code stringlengths 38 801k | repo_path stringlengths 6 263 |
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: MIR
# language: python
# name: mir
# ---
# # Evaluate
# In this notebook we evaluate the accuracy of the predicted alignments.
# %matplotlib inline
import numpy as np
import librosa as lb
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
import glob
import os.path
import pandas as pd
import pickle
##### Change this cell to suit your file structure #####
MAZURKAS_ROOT = Path('/data/Datasets/Chopin_Mazurkas') # Path to Mazurkas dataset root directory
OUT_ROOT = Path().absolute() # Output root directory (this is where features, paths, etc. will be saved)
########################################################
ANNOTATIONS_ROOT = MAZURKAS_ROOT / 'annotations_beat'
query_list = Path('cfg_files/query.test.list')
query_list_train = Path('cfg_files/query.train.list')
# ### Evaluate hypothesis directory
# First evaluate a single hypothesis directory.
def eval_dir(hypdir, querylist, hop_sec, savefile = None):
'''
Find errors for all alignment paths in a given directory
'''
allErrs = {}
cnt = 0
print(f'Processing {hypdir} ', end='')
with open(querylist, 'r') as f:
for line in f:
parts = line.strip().split()
assert len(parts) == 2
basename = os.path.basename(parts[0]) + '__' + os.path.basename(parts[1])
hypfile = hypdir / (basename + '.pkl')
if not os.path.exists(hypfile):
print("X", end='')
continue
allErrs[basename] = eval_file(hypfile, hop_sec)
cnt += 1
if cnt % 500 == 0:
print(".", end='')
print(' done')
if savefile:
os.makedirs(os.path.split(savefile)[0], exist_ok = True)
pickle.dump(allErrs, open(savefile, 'wb'))
return allErrs
def eval_file(hypfile, hop_sec):
'''
Find errors in a given file
'''
parts = os.path.basename(hypfile).split('__')
assert len(parts) == 2
piece = extractPieceName(parts[0])
annotfile1 = (ANNOTATIONS_ROOT / piece / parts[0]).with_suffix('.beat')
annotfile2 = (ANNOTATIONS_ROOT / piece / parts[1]).with_suffix('.beat')
gt1 = getTimestamps(annotfile1)
gt2 = getTimestamps(annotfile2)
hypalign = loadAlignment(hypfile) # warping path in frames
if hypalign is None:
err = [] # no valid path
else:
pred2 = np.interp(gt1, hypalign[0,:]*hop_sec, hypalign[1,:]*hop_sec)
err = pred2 - gt2
return err
def extractPieceName(fullpath):
basename = os.path.basename(fullpath) # e.g. Chopin_Op068No3_Sztompka-1959_pid9170b-21
parts = basename.split('_')
piece = '_'.join(parts[0:2]) # e.g. Chopin_Op068No3
return piece
def getTimestamps(annotfile):
df = pd.read_csv(annotfile, header=None, sep='\s+', skiprows=3)
return np.array(df[0])
def loadAlignment(hypfile):
with open(hypfile, 'rb') as f:
d = pickle.load(f)
return d
# Evaluate a single hypothesis directory.
hypdir = OUT_ROOT / 'experiments_test/clean/WSDTW_2'
savefile = OUT_ROOT / 'evaluations_test/clean/WSDTW_2_clean'
hop_sec = 512 * 1 / 22050
allErrs = eval_dir(hypdir, query_list, hop_sec, savefile)
hypdir = OUT_ROOT / 'experiments_test/clean/SSDTW_8'
savefile = OUT_ROOT / 'evaluations_test/clean/SSDTW_8.pkl'
hop_sec = 512 * 1 / 22050
allErrs = eval_dir(hypdir, query_list, hop_sec, savefile)
# Evaluate all hypothesis directories.
def eval_all_dirs(rootdir, querylist, hop_sec, outdir):
'''
Find errors for all alignments in all subdirectories of rootdir
'''
if not os.path.exists(outdir):
os.mkdir(outdir)
for hypdir in glob.glob(f'{str(rootdir)}/*'):
hypdirPath = Path(hypdir)
savefile = outdir / (os.path.basename(hypdir) + '.pkl')
allErrs = eval_dir(hypdirPath, querylist, hop_sec, savefile = savefile)
EXPERIMENTS_ROOT = OUT_ROOT / 'experiments_test/clean'
hop_sec = 512 * 1 / 22050
outdir = OUT_ROOT / 'evaluations_test/clean'
eval_all_dirs(EXPERIMENTS_ROOT, query_list, hop_sec, outdir)
# ### Plot error vs tolerance
def calc_error_rates(errFile, maxTol):
'''
Calculate the error rates at various error tolerances for a single error file
'''
# read from file
with open(errFile, 'rb') as f:
allErrs = pickle.load(f)
# collect all errors
errsFlat = []
for query in allErrs:
errs = np.array(allErrs[query])
errsFlat.append(errs)
errsFlat = np.concatenate(errsFlat)
# calculate error rates
errRates = np.zeros(maxTol+1)
for i in range(maxTol+1):
errRates[i] = np.mean(np.abs(errsFlat) > i/1000)
return errRates, errsFlat
def calc_error_rates_batch(indir, basenames, maxTol):
'''
Calculate the error rates at various error tolerances for all error files
'''
errRates = np.zeros((len(basenames), maxTol+1))
allErrVals = []
print('Computing error rates ', end='')
for i, basename in enumerate(basenames):
errFile = indir / (basename + '.pkl')
errRates[i,:], errors = calc_error_rates(errFile, maxTol)
allErrVals.append(errors)
print('.', end='')
print(' done')
return errRates, allErrVals
def plot_multiple_roc(errRates, basenames):
'''
Plot error tolerance vs error rate for multiple systems as lines
'''
numSystems = errRates.shape[0]
maxTol = errRates.shape[1] - 1
for i in range(numSystems):
plt.plot(np.arange(maxTol+1), errRates[i,:] * 100.0)
plt.legend(basenames, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('Error Tolerance (ms)')
plt.ylabel('Error Rate (%)')
plt.show()
return
# +
EVAL_ROOT_DIR = OUT_ROOT / 'evaluations_test/clean'
toPlot = ['DTW', 'FastDTW',
'NSDTW_2', 'NSDTW_4', 'NSDTW_8', 'NSDTW_16', 'NSDTW_32', \
'WSDTW_2', 'WSDTW_4', 'WSDTW_8', 'WSDTW_16', 'WSDTW_32', \
'SSDTW_2', 'SSDTW_4', 'SSDTW_8', 'SSDTW_16', 'SSDTW_32']
maxTol = 1000 # in msec
errRates, errVals = calc_error_rates_batch(EVAL_ROOT_DIR, toPlot, maxTol)
# -
plot_multiple_roc(errRates, toPlot)
# ### Histogram of selected error rates
def plot_grouped_histogram1(errRates_bars, SSDTW_errRates, NSDTW_errRates, basenames, tols, savefile = None):
'''
Create final plot of error rates of each system at multiple error tolerances
'''
# Histogram grouped by tolerance
# first construct DataFrame
data = []
for i, system in enumerate(basenames):
for tol in tols:
data.append((system, tol, errRates_bars[i,tol] * 100.0))
df = pd.DataFrame(data, columns = ['System', 'Tolerance', 'Error'])
# grouped barplot (DTW & WSDTW)
sns.barplot(x="Tolerance", y="Error", hue="System", data=df)
plt.xlabel("Tolerance (ms)", size=14)
plt.ylabel("Error Rate (%)", size=14)
plt.legend(loc='upper right')
# overlay dots for SSDTW results
if errRates_bars.shape[0] == 7:
width_bar = .116
else:
width_bar = .135
x_coords = []
y_coords = []
for i, tol in enumerate(tols):
for j in range(SSDTW_errRates.shape[0]):
if errRates_bars.shape[0] == 7:
x_coords.append(i+(-1+j)*width_bar)
else:
x_coords.append(i+(-1.5+j)*width_bar)
y_coords.append(SSDTW_errRates[j,tol] * 100.0)
plt.plot(x_coords, y_coords, 'ko', markersize=3)
# overlay dots for NSDTW results
x_coords = []
y_coords = []
for i, tol in enumerate(tols):
for j in range(NSDTW_errRates.shape[0]):
if errRates_bars.shape[0] == 7:
x_coords.append(i+(-1+j)*width_bar)
else:
x_coords.append(i+(-1.5+j)*width_bar)
y_coords.append(NSDTW_errRates[j,tol] * 100.0)
plt.plot(x_coords, y_coords, 'rx', markersize=3)
if savefile:
plt.savefig(savefile, bbox_inches = 'tight')
return
tols = [10, 20, 50, 100, 200, 500] # in msec
display_names = ['DTW', 'FastDTW', 'WSDTW-2', 'WSDTW-4', 'WSDTW-8', 'WSDTW-16','WSDTW-32']
savefile = OUT_ROOT / 'results.png'
barRates = np.zeros((7, errRates.shape[1]))
barRates[0:2,:] = errRates[0:2,:]
barRates[2:, :] = errRates[7:12,:]
NSDTW_errRates = errRates[2:7,:]
SSDTW_errRates = errRates[12:,:]
plot_grouped_histogram1(barRates, SSDTW_errRates, NSDTW_errRates, display_names, tols, savefile)
# ## Noisy Data Plot
SNR_Vals = [20, 15, 10, 5, 0, -5, -10]
for SNR in SNR_Vals:
EXPERIMENTS_ROOT = OUT_ROOT / ('experiments_test/noisy_%sdB' % str(SNR))
hop_sec = 512 * 1 / 22050
outdir = OUT_ROOT / ('evaluations_test/noisy_%sdB' % str(SNR))
if not os.path.exists(outdir):
os.mkdir(outdir)
eval_all_dirs(EXPERIMENTS_ROOT, query_list, hop_sec, outdir)
# +
toPlot = ["DTW", "FastDTW", "WSDTW_2", "WSDTW_4", "WSDTW_8", "WSDTW_16", "WSDTW_32"]
errRates100 = np.zeros((7, len(toPlot))) # Each row is a different SNR, each col is a different system
errRates20 = np.zeros((7, len(toPlot)))
errRates500 = np.zeros((7, len(toPlot)))
for i, SNR in enumerate(SNR_Vals):
EVAL_ROOT_DIR = OUT_ROOT / ('evaluations_test/noisy_%sdB' % str(SNR))
maxTol = 1000 # in msec
theseErrRates, _ = calc_error_rates_batch(EVAL_ROOT_DIR, toPlot, maxTol)
for j in range(len(toPlot)):
errRates100[i, j] = theseErrRates[j, 100]
errRates20[i, j] = theseErrRates[j, 20]
errRates500[i, j] = theseErrRates[j, 500]
# +
x_coords = []
y_coords20 = []
y_coords500 = []
for i in range(len(toPlot)):
width = 0.12
plt.bar(np.arange(7)+i * width, errRates100[:,i] * 100, width);
plt.ylim([0,100]);
plt.ylabel("Error Rate (%)")
plt.xlabel("SNR (dB)")
plt.xticks(np.arange(7) + 3 * width, SNR_Vals);
x_coords.append(np.arange(7) + (i - 0.1) * width)
y_coords20.append(errRates20[:,i] * 100)
y_coords500.append(errRates500[:,i] * 100)
labels = ["DTW", "FastDTW", "WSDTW-2", "WSDTW-4", "WSDTW-8", "WSDTW-16", "WSDTW-32"]
plt.legend(labels, loc = (1.05,0.55));
plt.plot(x_coords, y_coords20, 'k_', markersize=4);
plt.plot(x_coords, y_coords500, 'k_', markersize=4);
plt.savefig(OUT_ROOT / "SNR_results.png", bbox_inches = 'tight')
# -
# ### Runtime Analysis
dtw_runtimes, dtw_sizes = pickle.load(open(OUT_ROOT / 'profiles/dtw_prof.pkl', 'rb'))
pardtw_runtimes, pardtw_sizes = pickle.load(open(OUT_ROOT / 'profiles/pardtw_prof.pkl', 'rb'))
fastdtw_runtimes, fastdtw_sizes = pickle.load(open(OUT_ROOT / 'profiles/fastdtw_prof.pkl', 'rb'))
nsdtw_runtimes, nsdtw_segments, nsdtw_sizes = pickle.load(open(OUT_ROOT / 'profiles/nsdtw_prof.pkl', 'rb'))
wsdtw_runtimes, wsdtw_segments, wsdtw_sizes = pickle.load(open(OUT_ROOT / 'profiles/wsdtw_prof.pkl', 'rb'))
ssdtw_runtimes, ssdtw_segments, ssdtw_sizes = pickle.load(open(OUT_ROOT / 'profiles/ssdtw_prof.pkl', 'rb'))
# Numbers for runtime table
dtw_avgs = np.mean(np.sum(dtw_runtimes[::-1,:,:], axis=2), axis=1)
pardtw_avgs = np.mean(np.sum(pardtw_runtimes[::-1,:,:], axis=2), axis=1)
fastdtw_avgs = np.mean(fastdtw_runtimes[::-1,:], axis=1)
nsdtw_avgs = np.mean(np.sum(nsdtw_runtimes[:,::-1,:,:], axis=3), axis=2)
wsdtw_avgs = np.mean(np.sum(wsdtw_runtimes[:,::-1,:,:], axis=3), axis=2)
ssdtw_avgs = np.mean(np.sum(ssdtw_runtimes[:,::-1,:,:], axis=3), axis=2)
all_avgs = np.vstack((dtw_avgs.reshape((1,-1)), (pardtw_avgs.reshape((1,-1))), fastdtw_avgs, \
nsdtw_avgs, wsdtw_avgs, ssdtw_avgs))
# Make Runtime Table
# +
columns = ['1k', '2k', '5k', '10k', '20k', '50k']
rows = ["System",'DTW', 'ParDTW', 'FastDTW']
segment_algs = ['NSDTW', 'WSDTW', 'SSDTW']
num_segs = [2, 4, 8, 16, 32]
for alg_name in segment_algs:
for num_seg in num_segs:
rows.append(alg_name + '-' + str(num_seg))
cell_text = [columns]
for i in range(len(rows) - 1):
cell_text.append(['%1.3f' % x for x in all_avgs[i,:]])
plt.axis('off')
tab = plt.table(cellText=cell_text, rowLabels=rows, loc='center')
for key, cell in tab.get_celld().items():
if key[0] in [0,1,2,3,4,9,14]: #[0,1,2,7,12]:
cell.visible_edges = "TRL"
elif key[0] == 18:
cell.visible_edges = "BRL"
else:
cell.visible_edges = "RL"
tab.scale(1.5, 1.2);
plt.savefig(OUT_ROOT / 'runtime_table.png',
bbox_inches='tight',
dpi=150
)
plt.show()
# -
# Breakdown of runtime by component
# get DTW percent of total runtime by component
dtw_avgs = np.mean(dtw_runtimes, axis=1)
dtw_avgs = dtw_avgs / np.sum(dtw_avgs, axis=1, keepdims=True) * 100.0
dtw_avgs = dtw_avgs[::-1,:]
dtw_avgs = np.hstack((dtw_avgs, np.zeros((6,2)))) # order: cost, frm dp, frm back, seg dp, seg back
dtw_df = pd.DataFrame(dtw_avgs, columns=['Cost', 'Frm DP', 'Frm Back','Seg DP', 'Seg Back'], index=dtw_sizes[::-1])
np.mean(dtw_runtimes, axis=1)
# get NSDTW percent of total runtime by component
nsdtw_avgs = np.mean(nsdtw_runtimes, axis=2)
nsdtw_avgs = nsdtw_avgs / np.sum(nsdtw_avgs, axis=2, keepdims=True) * 100.0
nsdtw_avgs = nsdtw_avgs[4,::-1,:] # focus on K=32 segments
nsdtw_avgs = np.hstack((nsdtw_avgs, np.zeros((6,2)))) # order: cost, frm dp, frm back, seg dp, seg back
nsdtw_df = pd.DataFrame(nsdtw_avgs, columns=['Cost', 'Frm DP', 'Frm Back','Seg DP', 'Seg Back'], index=nsdtw_sizes[::-1])
# get WSDTW percent of total runtime by component
wsdtw_avgs = np.mean(wsdtw_runtimes, axis=2)
wsdtw_avgs = wsdtw_avgs / np.sum(wsdtw_avgs, axis=2, keepdims=True) * 100.0
wsdtw_avgs = wsdtw_avgs[4,::-1,:] # focus on K=32 segments
wsdtw_avgs = wsdtw_avgs[:,[0,1,4,2,3]] # original order: cost, frm dp, seg dp, seg back, frm back
wsdtw_df = pd.DataFrame(wsdtw_avgs, columns=['Cost', 'Frm DP', 'Frm Back','Seg DP', 'Seg Back'], index=wsdtw_sizes[::-1])
# get SSDTW percent of total runtime by component
ssdtw_avgs = np.mean(ssdtw_runtimes, axis=2)
ssdtw_avgs = ssdtw_avgs / np.sum(ssdtw_avgs, axis=2, keepdims=True) * 100.0
ssdtw_avgs = ssdtw_avgs[4,::-1,:] # focus on K=32 segments
#print(ssdtw_avgs)
ssdtw_avgs[:,2] = ssdtw_avgs[:,2] + ssdtw_avgs[:,5] # combine runtimes from both frame-level backtracking stages
ssdtw_avgs = ssdtw_avgs[:,0:5] # order: cost, frm dp, frm back, seg dp, seg back
ssdtw_df = pd.DataFrame(ssdtw_avgs, columns=['Cost', 'Frm DP', 'Frm Back','Seg DP', 'Seg Back'], index=ssdtw_sizes[::-1])
# Make Plot for Breakdown of Runtime
# +
fig, axes = plt.subplots(nrows=1, ncols=4)
# DTW plot
ax = dtw_df.plot(kind="bar", stacked=True, colormap="rainbow", ax=axes[0])
ax.set_title("DTW")
ax.set_ylabel("% Total Runtime", size=13),
ax.set_ylim(0, 100)
ax.set_yticks(range(0, 101, 10))
ax.xaxis.set_ticks_position('none')
ax.set_xticklabels(labels=['1k','2k','5k','10k','20k','50k'], rotation=90, minor=False)
ax.get_legend().remove()
# NSDTW plot
ax = nsdtw_df.plot(kind="bar", stacked=True, colormap="rainbow", ax=axes[1])
ax.set_title("NSDTW-32")
ax.set_xlabel("\nCost Matrix Size", size=13),
ax.set_ylim(0, 100)
ax.set_yticks([])
ax.xaxis.set_ticks_position('none')
ax.set_xticklabels(labels=['1k','2k','5k','10k','20k','50k'], rotation=90, minor=False)
ax.get_legend().remove()
# WSDTW plot
ax = wsdtw_df.plot(kind="bar", stacked=True, colormap="rainbow", ax=axes[2])
ax.set_title("WSDTW-32")
ax.set_ylim(0, 100)
ax.set_yticks([])
ax.xaxis.set_ticks_position('none')
ax.set_xticklabels(labels=['1k','2k','5k','10k','20k','50k'], rotation=90, minor=False)
ax.get_legend().remove()
# SSDTW plot
ax = ssdtw_df.plot(kind="bar", stacked=True, colormap="rainbow", ax=axes[3])
ax.set_title("SSDTW-32")
ax.set_ylim(0, 100)
ax.set_yticks([])
ax.xaxis.set_ticks_position('none')
ax.set_xticklabels(labels=['1k','2k','5k','10k','20k','50k'], rotation=90, minor=False)
ax.legend(bbox_to_anchor=(1, 1))
plt.savefig(OUT_ROOT / 'runtime_plot.png',
bbox_inches='tight',
dpi=150
)
plt.show()
# -
# ### Data Stats for paper
# Collecting some stats on the audio data
root_dir = MAZURKAS_ROOT / 'wav_22050_mono'
def printAudioStats(indir):
durs = []
for infile in glob.glob(f'{indir}/*.wav'):
y, sr = lb.load(infile)
durs.append(len(y)/sr)
durs = np.array(durs)
print(os.path.basename(indir))
print('---------')
print(f'Min: {np.min(durs)} s')
print(f'Max: {np.max(durs)} s')
print(f'Mean: {np.mean(durs)} s')
print(f'Std: {np.std(durs)} s')
for indir in glob.glob(f'{str(root_dir)}/*'):
printAudioStats(indir)
| 03_Evaluate.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Bruk av integrerte hastighetslover for å bestemme orden og hastighetskonstant
# (Denne oppgaven likner på oppgave 2 på eksamen, vår 2020.)
#
# Vi studerer hastigheten til reaksjonen,
#
# $$2 \text{C}_4 \text{H}_6\, (\text{g}) \to \text{C}_8 \text{H}_{12}\, (\text{g}),$$
#
# og vi har målt følgende konsentrasjoner ved ulike tidspunkt (og konstant temperatur):
#
# | \[C$_4$H$_6$\] (mol/L) | tid (s) |
# |------------------------|---------|
# | 0.01000 | 0 |
# | 0.00625 | 1000 |
# | 0.00476 | 1800 |
# | 0.00370 | 2800 |
# | 0.00313 | 3600 |
# | 0.00270 | 4400 |
# | 0.00241 | 5200 |
# | 0.00208 | 6200 |
#
# Vi vet at denne reaksjonen er enten av 1. orden eller av 2. orden. Vi skal nå bestemme
# hva reaksjonens orden er, og vi skal bestemme hastighetskonstanten.
#
# ## Reaksjonens orden
# Vi vet altså ikke hva reaksjonsordenen er, men vi vet at:
#
# - For 1. ordens reaksjon, så avhenger konsentrasjonen av tiden etter:
# $$\ln [\text{A}]_t = \ln [\text{A}]_0 - kt.$$
# Det betyr at logaritmen av konsentrasjonen endrer seg lineært med tiden.
# Dersom vi plotter logaritmen av de målte konsentrasjonene mot tiden, og vi får en rett linje, så
# tyder dette på at vi har en 1. ordens reaksjon.
# - For 2. ordens reaksjon, så avhenger konsentrasjonen av tiden etter:
# $$\frac{1}{[\text{A}]_t} = \frac{1}{[\text{A}]_0} + kt.$$
# Det betyr at den inverse konsentrasjonen ($\frac{1}{[\text{A}]_t}$) endrer seg lineært med tiden.
# Dersom vi plotter den inverse konsentrasjonen mot tiden, og vi får en rett linje, så tyder dette på
# at vi har en 2. ordens reaksjon.
#
# La oss nå plotte disse to alternative og sjekke i hvilket tilfelle vi får en rett linje.
# Begynn med å lage en tabell over konsentrasjonene:
import pandas as pd
tabell = pd.DataFrame(
[
(0.0100, 0),
(0.00625, 1000),
(0.00476, 1800),
(0.00370, 2800),
(0.00313, 3600),
(0.00270, 4400),
(0.00241, 5200),
(0.00208, 6200),
],
columns=['konsentrasjon', 'tid']
)
tabell
# Importer bibliotek vi trenger for plotting og numeriske operasjoner:
import numpy as np
from matplotlib import pyplot as plt
plt.style.use(['seaborn-notebook', '../kj1000.mplstyle'])
# %matplotlib notebook
# Lag plott av de målte verdiene:
konsentrasjon = tabell['konsentrasjon'].values
tid = tabell['tid'].values
figi, axes = plt.subplots(constrained_layout=True, ncols=2)
# Plott først logaritmen til konsentrasjonen mot tiden:
axes[0].plot(tid, np.log(konsentrasjon), marker='o', lw=3, ms=12)
axes[0].set(xlabel='tid / s', ylabel='$\ln [A]$')
axes[0].set_aspect(1 / axes[0].get_data_ratio())
# Plott så invers konsentrasjon:
axes[1].plot(tid, 1/konsentrasjon, marker='o', lw=3, ms=12)
axes[1].set(xlabel='tid / s', ylabel='1/[A] / L/mol');
axes[1].set_aspect(1 / axes[1].get_data_ratio())
# Når vi sammenlikner de to figurene, så ser vi at vi ikke har en rett linje når vi plotter logaritmen til konsentrasjonen, men vi har en rett linje når vi plotter invers konsentrasjon! Vi konkluderer derfor med at reaksjonen er av **2. orden**.
#
# Vi trenger så å finne hastighetskonstanten. Det kan vi gjøre ved å tilpasse en rett linje. For en 2. ordens
# reaksjon har vi den integrerte hastighetsloven:
#
# $$\frac{1}{[\text{A}]_t} = \frac{1}{[\text{A}]_0} + kt.$$
#
# Som tidligere nevnt gir dette en rett linje når vi plotter invers konsentrasjon mot tiden. Vi ser også at
# stigningstallet til den rette linjen blir lik $k$.
# Tilpass rett linje for å finne "k":
linje = np.polyfit(tid, 1/konsentrasjon, 1)
print(f'Hastighetskonstanten er: k = {linje[0]:.3g} L/(mol*s)')
# La oss sjekke hvor bra linjen er:
linje_y = np.polyval(linje, tid)
SSE = np.sum((1/konsentrasjon - linje_y)**2)
SST = np.sum((1/konsentrasjon - np.mean(1/konsentrasjon))**2)
R2 = 1 - SSE / SST
figi, axi = plt.subplots(constrained_layout=True)
axi.scatter(tid, 1/konsentrasjon, marker='o', label='Målepunkter', s=150, color='0.2')
axi.plot(tid, linje_y, label=f'Tilpasset linje: y = {linje[1]:.3g} + {linje[0]:.3g} * t\n(R² = {R2:.3f})', lw=3)
axi.set(xlabel='tid / s', ylabel='1/[A]')
axi.legend();
| jupyter/kinetikk/bestemmeorden.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
# # RCA
# +
# Load metrics
## Super resolution
rca_SR_n4_up3_k3_metrics = np.load('./../data/metrics/rca/rca_SR_shifts_n4_up3_k3_metrics.npy', allow_pickle=True)[()]
print('')
print('e1 RMSE: \t %.3e'% rca_SR_n4_up3_k3_metrics['metrics_dics'][3]['rmse_e1'])
print('e1 std: \t %.3e'% rca_SR_n4_up3_k3_metrics['metrics_dics'][3]['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% rca_SR_n4_up3_k3_metrics['metrics_dics'][3]['rmse_e2'])
print('e2 std: \t %.3e'% rca_SR_n4_up3_k3_metrics['metrics_dics'][3]['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% rca_SR_n4_up3_k3_metrics['metrics_dics'][3]['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% rca_SR_n4_up3_k3_metrics['metrics_dics'][3]['std_rmse_R2_meanR2'])
# -
# # PSFEx
# +
# Load metrics
## Super resolution
psfex_SR_metric_d3_path = './../data/metrics/psfex/psfex_SR_run_d3_metrics.npy'
psfex_SR_d3_metrics = np.load(psfex_SR_metric_d3_path, allow_pickle=True)[()]
print('')
print('e1 RMSE: \t %.3e'% psfex_SR_d3_metrics['metrics_dics'][3]['rmse_e1'])
print('e1 std: \t %.3e'% psfex_SR_d3_metrics['metrics_dics'][3]['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% psfex_SR_d3_metrics['metrics_dics'][3]['rmse_e2'])
print('e2 std: \t %.3e'% psfex_SR_d3_metrics['metrics_dics'][3]['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% psfex_SR_d3_metrics['metrics_dics'][3]['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% psfex_SR_d3_metrics['metrics_dics'][3]['std_rmse_R2_meanR2'])
# -
# # MCCD
# +
# Load metrics
## Super resolution
mccd_SR_metric_path = './../data/metrics/mccd/mccd_SR_id10_metrics.npy'
mccd_SR_metrics = np.load(mccd_SR_metric_path, allow_pickle=True)[()]
print('')
print('e1 RMSE: \t %.3e'% mccd_SR_metrics['metrics_dics'][3]['rmse_e1'])
print('e1 std: \t %.3e'% mccd_SR_metrics['metrics_dics'][3]['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% mccd_SR_metrics['metrics_dics'][3]['rmse_e2'])
print('e2 std: \t %.3e'% mccd_SR_metrics['metrics_dics'][3]['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% mccd_SR_metrics['metrics_dics'][3]['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% mccd_SR_metrics['metrics_dics'][3]['std_rmse_R2_meanR2'])
# -
# # Zernike 15
# +
# Load metrics
metrics_wf_inc15_2k_path = './../data/metrics/zernike_15/metrics-param_incomplete_15_sample_w_2k.npy'
metrics_wf_inc15_2k = np.load(metrics_wf_inc15_2k_path, allow_pickle=True)[()]
metrics = metrics_wf_inc15_2k
print('')
print('e1 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e1'])
print('e1 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e2'])
print('e2 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_R2_meanR2'])
# -
# # Zernike 40
# +
# Load metrics
metrics_wf_inc40_2k_path = './../data/metrics/zernike_40/metrics-param_incomplete_40_sample_w_bis1_2k.npy'
metrics_wf_inc40_2k = np.load(metrics_wf_inc40_2k_path, allow_pickle=True)[()]
metrics = metrics_wf_inc40_2k
print('')
print('e1 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e1'])
print('e1 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e2'])
print('e2 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_R2_meanR2'])
# -
# # WaveDiff-original
# +
# Load metrics
metrics_2k_path = './../data/metrics/wavediff-original/metrics-poly_sample_w_bis1_2k.npy'
wf_orifinal_metrics = np.load(metrics_2k_path, allow_pickle=True)[()]
metrics = wf_orifinal_metrics
print('')
print('e1 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e1'])
print('e1 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e2'])
print('e2 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_R2_meanR2'])
# -
# # WaveDiff-graph
# +
# Load metrics
metrics_2k_path = './../data/metrics/wavediff-graph/metrics-graph_sample_w_tunned_2k.npy'
wf_graph_metrics = np.load(metrics_2k_path, allow_pickle=True)[()]
metrics = wf_graph_metrics
print('')
print('e1 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e1'])
print('e1 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e2'])
print('e2 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_R2_meanR2'])
# -
# # WaveDiff-polygraph
# +
# Load metrics
metrics_2k_path = './../data/metrics/wavediff-polygraph/metrics-mccd_sample_w_bis2_2k.npy'
wf_polygraph_metrics = np.load(metrics_2k_path, allow_pickle=True)[()]
metrics = wf_polygraph_metrics
print('')
print('e1 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e1'])
print('e1 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e1'])
print('')
print('e2 RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_e2'])
print('e2 std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_e2'])
print('')
print('R2/<R2> RMSE: \t %.3e'% metrics['test_metrics']['shape_results_dict']['rmse_R2_meanR2'])
print('R2/<R2> std: \t %.3e'% metrics['test_metrics']['shape_results_dict']['std_rmse_R2_meanR2'])
# -
| papers/article_IOP/notebooks/table-shape-size-error-metrics.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Feature Engineering in Keras.
#
# Let's start off with the Python imports that we need.
import os, json, math
import numpy as np
import tensorflow as tf
try:
# necessary if we pip install tensorflow, but not if we have tensorflow 2.0
tf.enable_v2_behavior()
except:
pass
print(tf.__version__)
# + tags=["parameters"]
# Note that this cell is special. It's got a tag (you can view tags by clicking on the wrench icon on the left menu in Jupyter)
# These are parameters that we will configure so that we can schedule this notebook
DATADIR = '../data'
EXPORT_DIR = './export/savedmodel'
NBUCKETS = 10 # for feature crossing
TRAIN_BATCH_SIZE = 32
NUM_TRAIN_EXAMPLES = 10000 * 5 # remember the training dataset repeats, so this will wrap around
NUM_EVALS = 5 # evaluate this many times
NUM_EVAL_EXAMPLES = 10000 # enough to get a reasonable sample, but no so much that it slows down
# -
# ## Locating the CSV files
#
# We will start with the CSV files that we wrote out in the [first notebook](../01_explore/taxifare.iypnb) of this sequence. Just so you don't have to run the notebook, we saved a copy in ../data
if DATADIR[:5] == 'gs://':
# !gsutil ls $DATADIR/*.csv
else:
# !ls -l $DATADIR/*.csv
# ## Use tf.data to read the CSV files
#
# We wrote these cells in the [third notebook](../03_tfdata/input_pipeline.ipynb) of this sequence.
CSV_COLUMNS = ['fare_amount', 'pickup_datetime',
'pickup_longitude', 'pickup_latitude',
'dropoff_longitude', 'dropoff_latitude',
'passenger_count', 'key']
LABEL_COLUMN = 'fare_amount'
DEFAULTS = [[0.0],['na'],[0.0],[0.0],[0.0],[0.0],[0.0],['na']]
# +
def features_and_labels(row_data):
for unwanted_col in ['key']: # keep the pickup_datetime!
row_data.pop(unwanted_col)
label = row_data.pop(LABEL_COLUMN)
return row_data, label # features, label
# load the training data
def load_dataset(pattern, batch_size=1, mode=tf.estimator.ModeKeys.EVAL):
pattern = '{}/{}'.format(DATADIR, pattern)
dataset = (tf.data.experimental.make_csv_dataset(pattern, batch_size, CSV_COLUMNS, DEFAULTS)
.map(features_and_labels) # features, label
.cache())
if mode == tf.estimator.ModeKeys.TRAIN:
print("Repeating training dataset indefinitely")
dataset = dataset.shuffle(1000).repeat()
dataset = dataset.prefetch(1) # take advantage of multi-threading; 1=AUTOTUNE
return dataset
# -
import datetime
# Python 3.5 doesn't handle timezones of the form 00:00, only 0000
ts = datetime.datetime.strptime('2010-02-08 09:17:00+00:00'.replace(':',''), "%Y-%m-%d %H%M%S%z")
print(ts.weekday())
DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
print(DAYS[ts.weekday()])
# +
## Add transformations
def euclidean(params):
lon1, lat1, lon2, lat2 = params
londiff = lon2 - lon1
latdiff = lat2 - lat1
return tf.sqrt(londiff*londiff + latdiff*latdiff)
DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
def get_dayofweek(s):
# Python 3.5 doesn't handle timezones of the form 00:00, only 0000
ts = datetime.datetime.strptime(s.replace(':', ''), "%Y-%m-%d %H%M%S%z")
return DAYS[ts.weekday()]
def dayofweek(ts_in):
return tf.map_fn(
lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string),
ts_in
)
def transform(inputs, NUMERIC_COLS, STRING_COLS):
transformed = inputs.copy()
print("BEFORE TRANSFORMATION")
print("INPUTS:", inputs.keys())
feature_columns = {
colname: tf.feature_column.numeric_column(colname)
for colname in NUMERIC_COLS
}
# scale the lat, lon values to be in 0, 1
for lon_col in ['pickup_longitude', 'dropoff_longitude']: # in range -70 to -78
transformed[lon_col] = tf.keras.layers.Lambda(
lambda x: (x+78)/8.0,
name='scale_{}'.format(lon_col)
)(inputs[lon_col])
for lat_col in ['pickup_latitude', 'dropoff_latitude']: # in range 37 to 45
transformed[lat_col] = tf.keras.layers.Lambda(
lambda x: (x-37)/8.0,
name='scale_{}'.format(lat_col)
)(inputs[lat_col])
# add Euclidean distance. Doesn't have to be accurate calculation because NN will calibrate it
transformed['euclidean'] = tf.keras.layers.Lambda(euclidean, name='euclidean')([
inputs['pickup_longitude'],
inputs['pickup_latitude'],
inputs['dropoff_longitude'],
inputs['dropoff_latitude']
])
feature_columns['euclidean'] = tf.feature_column.numeric_column('euclidean')
# hour of day from timestamp of form '2010-02-08 09:17:00+00:00'
transformed['hourofday'] = tf.keras.layers.Lambda(
lambda x: tf.strings.to_number(tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32),
name='hourofday',
output_shape=()
)(inputs['pickup_datetime'])
feature_columns['hourofday'] = tf.feature_column.indicator_column(
tf.feature_column.categorical_column_with_identity('hourofday', num_buckets=24))
# day of week is hard because there is no TensorFlow function for date handling
transformed['dayofweek'] = tf.keras.layers.Lambda(
lambda x: tf.strings.substr(x, 0, 4), #dayofweek(x),
name='dayofweek',
output_shape=()
)(inputs['pickup_datetime'])
feature_columns['dayofweek'] = tf.feature_column.indicator_column(
tf.feature_column.categorical_column_with_vocabulary_list(
'dayofweek', vocabulary_list = DAYS))
# featurecross lat, lon into nxn buckets, then embed
nbuckets = NBUCKETS
latbuckets = np.linspace(0, 1, nbuckets).tolist()
lonbuckets = np.linspace(0, 1, nbuckets).tolist()
b_plat = tf.feature_column.bucketized_column(feature_columns['pickup_latitude'], latbuckets)
b_dlat = tf.feature_column.bucketized_column(feature_columns['dropoff_latitude'], latbuckets)
b_plon = tf.feature_column.bucketized_column(feature_columns['pickup_longitude'], lonbuckets)
b_dlon = tf.feature_column.bucketized_column(feature_columns['dropoff_longitude'], lonbuckets)
ploc = tf.feature_column.crossed_column([b_plat, b_plon], nbuckets * nbuckets)
dloc = tf.feature_column.crossed_column([b_dlat, b_dlon], nbuckets * nbuckets)
pd_pair = tf.feature_column.crossed_column([ploc, dloc], nbuckets ** 4 )
feature_columns['pickup_and_dropoff'] = tf.feature_column.embedding_column(pd_pair, 100)
print("AFTER TRANSFORMATION")
print("TRANSFORMED:", transformed.keys())
print("FEATURES", feature_columns.keys())
return transformed, feature_columns
def rmse(y_true, y_pred):
return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true)))
def build_dnn_model():
# input layer is all float except for pickup_datetime which is a string
STRING_COLS = ['pickup_datetime']
NUMERIC_COLS = set(CSV_COLUMNS) - set([LABEL_COLUMN, 'key']) - set(STRING_COLS)
print(STRING_COLS)
print(NUMERIC_COLS)
inputs = {
colname : tf.keras.layers.Input(name=colname, shape=(), dtype='float32')
for colname in NUMERIC_COLS
}
inputs.update({
colname : tf.keras.layers.Input(name=colname, shape=(), dtype='string')
for colname in STRING_COLS
})
# transforms
transformed, feature_columns = transform(inputs, NUMERIC_COLS, STRING_COLS)
dnn_inputs = tf.keras.layers.DenseFeatures(feature_columns.values())(transformed)
# two hidden layers of [32, 8] just in like the BQML DNN
h1 = tf.keras.layers.Dense(32, activation='relu')(dnn_inputs)
h2 = tf.keras.layers.Dense(8, activation='relu')(h1)
# final output would normally have a linear activation because this is regression
# However, we know something about the taxi problem (fares are +ve and tend to be below $60).
# Use that here. (You can verify by running this query):
# SELECT APPROX_QUANTILES(fare_amount, 100) FROM serverlessml.cleaned_training_data
fare_thresh = lambda x: 60 * tf.keras.activations.relu(x)
output = tf.keras.layers.Dense(1, activation=fare_thresh)(h2)
model = tf.keras.models.Model(inputs, output)
model.compile(optimizer='adam', loss='mse', metrics=[rmse, 'mse'])
return model
model = build_dnn_model()
print(model.summary())
# -
# ## Train model
#
# To train the model, call model.fit()
# +
trainds = load_dataset('taxi-train*', TRAIN_BATCH_SIZE, tf.estimator.ModeKeys.TRAIN)
evalds = load_dataset('taxi-valid*', 1000, tf.estimator.ModeKeys.EVAL).take(NUM_EVAL_EXAMPLES//10000) # evaluate on 1/10 final evaluation set
steps_per_epoch = NUM_TRAIN_EXAMPLES // (TRAIN_BATCH_SIZE * NUM_EVALS)
history = model.fit(trainds,
validation_data=evalds,
epochs=NUM_EVALS,
steps_per_epoch=steps_per_epoch)
# +
# plot
import matplotlib.pyplot as plt
nrows = 1
ncols = 2
fig = plt.figure(figsize=(10, 5))
for idx, key in enumerate(['loss', 'rmse']):
ax = fig.add_subplot(nrows, ncols, idx+1)
plt.plot(history.history[key])
plt.plot(history.history['val_{}'.format(key)])
plt.title('model {}'.format(key))
plt.ylabel(key)
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left');
# -
# ## Evaluate over full validation dataset
#
# Let's evaluate over the full validation dataset (provided the validation dataset is large enough).
evalds = load_dataset('taxi-valid*', 1000, tf.estimator.ModeKeys.EVAL).take(NUM_EVAL_EXAMPLES//1000)
model.evaluate(evalds)
# Yippee! We are now at under 4 dollars RMSE!
# ## Predict with model
#
# This is how to predict with this model:
# This doesn't work yet.
model.predict({
'pickup_longitude': tf.convert_to_tensor([-73.982683]),
'pickup_latitude': tf.convert_to_tensor([40.742104]),
'dropoff_longitude': tf.convert_to_tensor([-73.983766]),
'dropoff_latitude': tf.convert_to_tensor([40.755174]),
'passenger_count': tf.convert_to_tensor([3.0]),
'pickup_datetime': tf.convert_to_tensor(['2010-02-08 09:17:00+00:00'], dtype=tf.string),
})
# However, this is not realistic, because we can't expect client code to have a model object in memory. We'll have to export our model to a file, and expect client code to instantiate the model from that exported file.
# ## Export model
#
# Let's export the model to a TensorFlow SavedModel format. Once we have a model in this format, we have lots of ways to "serve" the model, from a web application, from JavaScript, from mobile applications, etc.
# +
# This doesn't work yet.
export_dir = os.path.join(EXPORT_DIR, datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
print(export_dir)
tf.keras.experimental.export_saved_model(model, export_dir)
# Recreate the exact same model
new_model = keras.experimental.load_from_saved_model(export_dir)
# try predicting with this model
new_model.predict({
'pickup_longitude': tf.convert_to_tensor([-73.982683]),
'pickup_latitude': tf.convert_to_tensor([40.742104]),
'dropoff_longitude': tf.convert_to_tensor([-73.983766]),
'dropoff_latitude': tf.convert_to_tensor([40.755174]),
'passenger_count': tf.convert_to_tensor([3.0]),
'pickup_datetime': tf.convert_to_tensor(['2010-02-08 09:17:00+00:00'], dtype=tf.string),
})
# -
# In this notebook, we have looked at how to implement a custom Keras model using feature columns.
# Copyright 2019 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| quests/serverlessml/06_feateng_keras/taxifare_fc.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
# #### Load header into string array
# +
# with open('/Users/rmueller/Projects/MIDOSS/results/MediumFloater/SOG_21nov17-28nov17_EvapExposureTest/resOilOutput.sro', 'r') as the_file:
# all_data = [line.strip() for line in the_file.readlines()]
# header = all_data[4]
# parse directory name to create output file names
# Assumes the last 3 directory names describe oil_type, location and date
input_dir = '/Users/rmueller/Projects/MIDOSS/results/OS2020/akns/SB/15jan2018/'
dir_str = input_dir.split('/')
ndirs = len(dir_str)
out_tag = test_split[ndirs-4] + '_' + test_split[ndirs-3] + '_' + test_split[ndirs-2]
# define input file name
input_file = input_dir + 'resOilOutput.sro'
with open(input_file, 'r') as the_file:
all_data = [line.strip() for line in the_file.readlines()]
header = all_data[4]
# Order header into list array by splitting up string
header_arr = []
header_arr = header.split(' ')
# Remove emtpy entries from list
header_arr = np.asarray([x for x in header_arr if x != ''])
# -
# #### Load data
data2D = np.genfromtxt(input_file, skip_header=6, skip_footer=4)
nrows,ncols = data2D.shape
# #### Create structured Array
# +
# define structure of structured array
dtype = [('Header',(np.str_,22)),('Values', np.float64)]
# create index list for for-loop over columns
header_range = range(header_arr.size)
data_range = range(nrows)
# Assign 2D data and header strings to structured array
massbalance = np.array([[(header_arr[hdr_index], data2D[data_index, hdr_index]) for hdr_index in header_range] for data_index in data_range], dtype=dtype)
# -
[data_len, ncols] = massbalance.shape
# #### define the array indices corresponding to mass balance numbers
# +
# mass
i_mevaporated = 15
i_mdispersed = 18
i_mdissolved = 24
i_mbio = 37
i_msedimented = 21
i_mwatercontent = 33
# volume
i_voloilbeached = 8
i_volumebeached = 9
i_volumeoil = 10
i_volume = 11
i_vwatercontent = 34
# oil properties
i_density = 35
i_viscosity = 36
# spill area
i_area = 12
i_theorical_area = 13
# analyte mass (I thought this was dissolved but the numbers are more reflective of dispersed)
i_analytemass0 = 42
i_analytemass1 = 43
i_analytemass2 = 44
i_analytemass3 = 45
i_analytemass4 = 46
# biodegredation
i_bio0 = 47
i_bio0 = 48
i_bio0 = 49
i_bio0 = 50
i_bio0 = 51
# -
# define output file names
o_massbalance = input_dir + 'massbalance.png'
o_volumebeached = input_dir + 'volumebeached.png'
o_volumefloating = input_dir + 'volumefloating.png'
o_massbalance_wtotal = input_dir + 'massbalance_wtotal.png'
o_density_viscosity = input_dir + 'density_viscosity.png'
o_analyte_mass = input_dir + 'analyte_mass.png'
o_analyte_bio = input_dir + 'analyte_bio.png'
o_spill_area = input_dir + 'spill_area.png'
o_mwatercontent = input_dir + 'mwater_content.png'
# #### Plot results
plot_data = [15,18,24,37]
header_arr[plot_data]
plot_data = [15,18,24,37]
#plt.plot([data2D[range(191), data_index] for data_index in plot_data])
plt.plot(data2D[range(data_len), plot_data[0]])
plt.plot(data2D[range(data_len), plot_data[1]])
plt.plot(data2D[range(data_len), plot_data[2]])
plt.plot(data2D[range(data_len), plot_data[3]])
plt.ylabel('Mass (Tonnes)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['Evaporated', 'Dispersed','Disolved','Biodegraded'])
plt.savefig(o_massbalance)
# ### plot volume oil beached
# indices of data_2D that correspond to VolOilBeached and VolumeBeached
plot_data = [8,9]
VolOilBeached = data2D[range(data_len), plot_data[0]]
VolumeBeached = data2D[range(data_len), plot_data[1]]
VolumeWaterBeached = VolumeBeached - VolOilBeached
#plt.plot([data2D[range(191), data_index] for data_index in plot_data])
plt.plot(VolOilBeached)
plt.plot(VolumeBeached)
plt.plot(VolumeWaterBeached)
plt.ylabel('Volume Beached (assumed m^3)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['VolOilBeached', 'VolumeBeached','VolumeBeached - VolOilBeached'])
plt.savefig(o_volumebeached)
# ### plot volume oil floating
plot_data = [10,11,34]
VolumeOil = data2D[range(data_len), plot_data[0]]
Volume = data2D[range(data_len), plot_data[1]]
VWaterContent = data2D[range(data_len), plot_data[2]]
VolumeWater = Volume - VolumeOil
#plt.plot([data2D[range(191), data_index] for data_index in plot_data])
plt.plot(VolumeOil)
plt.plot(Volume)
plt.plot(VolumeWater)
plt.plot(VWaterContent)
plt.ylabel('Volume Beached (assumed m^3)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['VolumeOil', 'Volume','Volume - Volume Oil', 'VWaterContent'],loc='upper right')
plt.savefig(o_volumefloating)
# +
# mass of floating oil
MassOil = data2D[range(data_len), 7]
Volume = data2D[range(data_len), 11]
Density = data2D[range(data_len), 35]
MOil = Volume * Density
# mass loss from weathering
plot_data = [15,18,24,33,37]
MEvaporated = data2D[range(data_len), plot_data[0]]
MDispersed = data2D[range(data_len), plot_data[1]]
MDissolved = data2D[range(data_len), plot_data[2]]
MWaterContent = data2D[range(data_len), plot_data[3]]
MBio = data2D[range(data_len), plot_data[4]]
MTotal = MOil - MEvaporated - MDispersed - MDissolved - MBio
plt.plot(MEvaporated)
plt.plot(MDispersed)
plt.plot(MDissolved)
plt.plot(MWaterContent)
plt.plot(MBio)
plt.plot(MTotal)
plt.ylabel('Mass (assumed kg)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['MEvaporated', 'MDispersed','MDissolved', 'MWaterContent', 'MBio', r'MTotal=$\rho V - \Sigma above$'],loc='upper right')
plt.savefig(o_massbalance_wtotal)
# -
plt.plot(MEvaporated)
plt.plot(MDispersed)
plt.plot(MDissolved)
plt.plot(MWaterContent)
plt.plot(MBio)
plt.ylabel('Mass (assumed kg)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['MEvaporated', 'MDispersed', 'MDissolved', 'MWaterContent', 'MBio'],loc='upper right')
plt.savefig('MassBalance.png')
# ### plot density and viscosity
plot_data = [35,36]
Density = data2D[range(data_len), plot_data[0]]
Viscosity = data2D[range(data_len), plot_data[1]]
# +
# create figure and axis objects with subplots()
fig,ax1 = plt.subplots()
ax1.plot(Density, color="blue")
ax1.set_ylabel('Density (kg/m^3)')
ax1.set_xlabel('Time after oil release (hours) ')
ax1.yaxis.label.set_color('blue')
ax1.tick_params(axis='y', colors='blue')
# twin object for two different y-axis on the sample plot
ax2=ax1.twinx()
ax2.plot(Viscosity, color="green")
ax2.yaxis.label.set_color('green')
ax2.tick_params(axis='y', colors='green')
ax2.set_ylabel('Viscosity (Pa s)')
plt.savefig('DensityViscosity.png')
# -
# ### plot Area and Teorical Area
plot_data = [12,13]
Area = data2D[range(data_len), plot_data[0]]
TeoricalArea = data2D[range(data_len), plot_data[1]]
plt.plot(Area)
plt.plot(TeoricalArea)
plt.ylabel('Area (assumed m^2)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['Area', 'Teorical Area'])
plt.savefig('SpillArea.png')
# ### plot AnalyteMass (Dispersed Oil?)
plot_data = [42,43,44,45,46]
m0 = data2D[range(data_len), plot_data[0]]
m1 = data2D[range(data_len), plot_data[1]]
m2 = data2D[range(data_len), plot_data[2]]
m3 = data2D[range(data_len), plot_data[3]]
m4 = data2D[range(data_len), plot_data[4]]
# +
plt.plot(m0)
plt.plot(m1)
plt.plot(m2)
plt.plot(m3)
plt.plot(m4)
plt.ylabel('Dispersed (?) mass (assumed kg)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['AnalyteMass1', 'AnalyteMass2', 'AnalyteMass3', 'AnalyteMass4', 'AnalyteMass5'])
plt.savefig('AnalyteMass.png')
# -
# ### plot AnalyteBio
plot_data = [47,48,49,50,51]
m0 = data2D[range(data_len), plot_data[0]]
m1 = data2D[range(data_len), plot_data[1]]
m2 = data2D[range(data_len), plot_data[2]]
m3 = data2D[range(data_len), plot_data[3]]
m4 = data2D[range(data_len), plot_data[4]]
# +
plt.plot(m0)
plt.plot(m1)
plt.plot(m2)
plt.plot(m3)
plt.plot(m4)
plt.ylabel('Biodegraded mass (assumed kg)')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['AnalyteBio1', 'AnalyteBio2', 'AnalyteBio3', 'AnalyteBio4', 'AnalyteBio5'])
plt.savefig('AnalyteBio.png')
# -
# I'm not yet sure what this is. Fraction of mass of particle containing water?
plt.plot(MWaterContent)
plt.ylabel('mass fraction?')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['MWaterContent'],loc='upper right')
plt.savefig(o_mwatercontent)
# I'm not yet sure what this is. Fraction of mass of particle containing water?
plt.plot(VWaterContent)
plt.ylabel('volume fraction?')
plt.xlabel('Time after oil release (hours) ')
plt.legend(['VWaterContent'],loc='upper right')
#plt.savefig(o_mwatercontent)
| notebooks/mass_balance/plot_massbalance_functiontest.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python3
# ---
# Universidade Federal do Rio Grande do Sul (UFRGS)
# Programa de Pós-Graduação em Engenharia Civil (PPGEC)
#
# # Project PETROBRAS (2018/00147-5):
# ## Attenuation of dynamic loading along mooring lines embedded in clay
#
# ---
# _Prof. <NAME>, Dr.techn._ [(ORCID)](https://orcid.org/0000-0001-5640-1020)
# Porto Alegre, RS, Brazil
# ___
#
# [1. Introduction](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/01_Introduction.ipynb?flush_cache=true)
# [2. Reduced model scaling](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/02_Reduced_model.ipynb?flush_cache=true)
# [3. Typical soil](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/03_Typical_soil.ipynb?flush_cache=true)
# [4. The R4 studless 120mm chain](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/04_R4_studless_chain.ipynb?flush_cache=true)
# [5. Dynamic load definition](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/05_Dynamic_load.ipynb?flush_cache=true)
# [6. Design of chain anchoring system](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/06_Chain_anchor.ipynb?flush_cache=true)
# [7. Design of uniaxial load cell with inclinometer](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/07_Load_cell.ipynb?flush_cache=true)
# [8. Location of experimental sites](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/08_Experimental_sites.ipynb?flush_cache=true)
#
# Importing Python modules required for this notebook
# (this cell must be executed with "shift+enter" before any other Python cell)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# ## 6. Design of chain anchoring system
#
# The bottom end of the chain under test must be anchored at the deepest
# segment of the CPT shaft. At the link point a load cell and an inclinometer
# will be installed, and the anchoring point must not undergo significant
# displacements.
#
# The idea is to design a modified CPT shaft segment provided with two welded steel
# fins, orthogonally disposed with respect to the loading direction, which must
# work mobilizing passive earth pressure as the chain is loaded.
# The figure below brings the initially proposed geometry for the fins:
#
# <img src="resources/Chain_anchoring.png" alt="Modified CPT rod segment" width="720">
#
# The scaled design load is defined in [section 5](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/05_Dynamic_load.ipynb?flush_cache=true) as approximatelly 7kN,
# to be applied with a maximum horizontal projection of approximatelly
# $F_{\rm H,max} \approx \cos(\pi/4) \cdot 7 \approx 5$kN (maximum chain leaning angle
# is $45^\circ$ ).
#
# The soil undrained shear resistance, $s_{\rm u}$, at the scaled depth of $z_{\rm max} = 3$m
# is given by $s_{\rm u} = 1.4z = 4.2$kPa, as presented in [section 3](https://nbviewer.jupyter.org/github/mmaiarocha/Attenuation/blob/master/03_Typical_soil.ipynb?flush_cache=true).
# The admissible soil resistance against the fins displacement may be understood as the
# resistance of a shallow foundation over clayed soil, given by:
#
# $$ F_{\rm H,adm} \approx N_{\rm c} A s_{\rm u} > F_{\rm H,max} $$
#
# with $A$ being the supporting surface and $N_{\rm c}$ conservatively taken as 5.
# Below is the calculation of $F_{\rm H,adm}$ for the proposed fin geometry:
#
# +
hs = 1.0 # shaft segment length (m)
de = 0.036 # CPT shaft external diameter (m)
di = 0.016 # CPT shaft internal diameter (m)
hf = 0.8 # mean fin height (m)
b = 0.2 # fin width (m)
t = 0.004 # fin thickness (m)
z = 3.0 # mean depth (m)
A = 2*hf*b + hs*de # total pressure surface (m²)
V = 2*hf*b*t + hs*np.pi*(de*de - di*di)/4 # total steel volume (m³)
W = 7850*V # total weight of modified segment (kg)
Nc = 5.14 # geometrical coefficient
su = 1.4*z # local undrained shear resistance (kPa)
Fadm = Nc*A*su # admissible fin supporting load (kN)
print('Total weight of modified segment is: {0:4.1f}kg'.format(W))
print('Admissible fin supporting load is: {0:4.1f}kN'.format(Fadm))
print('Resulting safety margin is: {0:4.1f} '.format(Fadm/5.0))
# -
# The calculation above shows that the proposed dimensions are enough for the design load,
# with a safety factor of approximatelly 1.5.
#
# Besides the soil resistance, the fins must also be designed for the resulting bending
# moments. Maximum moment amplitude will occur along the seam welding, such that the fins
# behave like cantilever plates fixed at the CPT shaft.
# Bending stresses are calculated below:
#
# +
E = 2.05e8 # steel Young's modulus (kPa)
I = (t**3)/12 # moment of inertia per unit length (m³)
fy = 250. # steel yielding stress
p = Nc*su # design pressure over the fins (kPa)
M = p*b*b/2000 # bending moment per unit lenght (MN)
σb = M*(t/2)/I # maximum bending stress (MPa)
print('Maximum bending stress is {0:3.0f}MPa'.format(σb))
print('Resulting safety margin is {0:3.1f} '.format(fy/σb))
# -
# From the calculations above, the global safety margin assigned to fins failure
# turns out to be $S = 1.5\times1.5 = 2.25$, hence above 2. The required steel plate
# thickness is 4mm and the modified CPT segment will weight approximately 17kg.
#
| 06_Chain_anchor.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.3 64-bit (''base'': conda)'
# metadata:
# interpreter:
# hash: b3ba2566441a7c06988d0923437866b63cedc61552a5af99d1f4fb67d367b25f
# name: 'Python 3.8.3 64-bit (''base'': conda)'
# ---
# # In this notebook the used threshold will be discussed and tested
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# %matplotlib qt
from pathlib import Path
import os
from pipeline import undistort_image
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
`vertices` should be a numpy array of integer points.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillConvexPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
# +
# Make a list of test images
images = glob.glob('../test_images/*.jpg')
output_dir = "../output_images/threshold/"
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Parameters to experiment #################
s_thresh=(150, 255)
sx_thresh=(23, 150)
############################################
for filename in images:
img = cv2.imread(filename)
# Undistort image with previously computes parameters
undst = undistort_image(img)
# Convert to HLS color space and separate the V channel
hls = cv2.cvtColor(undst, cv2.COLOR_RGB2HLS)
l_channel = hls[:,:,1]
s_channel = hls[:,:,2]
# Apply sobel x to l chanel
sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x
abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal
scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
# Threshold x gradient
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1
# Threshold color channel
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1
# Stack each channel
color_binary = np.dstack(( np.zeros_like(sxbinary), sxbinary, s_binary)) * 255
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(mpimg.imread(filename))
ax1.set_title('Original Image', fontsize=40)
ax2.imshow(color_binary)
ax2.set_title('Pipeline Result', fontsize=40)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
f.savefig(output_dir + os.path.basename(filename))
f.show()
# -
# ## Threshold conclusions:
#
# The images were succesfully transformed to a threshold image which indicates the position of the lanes. To make this image there are 2 contributions the x sobel derivate apply to the l chanel marked in green in the images, and the s chanel simply filtered with a threshold markes in blue. The obtained images can be found in output_images/threshold. For example:
#
# 
#
# 
#
# With this experiment the function threshold was implemented in pipeline.py
# +
# Testing threshold function
from pipeline import threshold
# Make a list of test images
images = glob.glob('../test_images/*.jpg')
for filename in images:
img = cv2.imread(filename)
# Undistort image with previously computes parameters
undst = undistort_image(img)
# Obtain bitmap
color_binary = threshold(undst)
# Stack each channel
color_binary_to_plot = np.dstack(( color_binary, color_binary, color_binary)) * 255
# Plot the result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(mpimg.imread(filename))
ax1.set_title('Original Image', fontsize=40)
ax2.imshow(color_binary_to_plot)
ax2.set_title('Pipeline Result', fontsize=40)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
f.show()
| pipeline/threshold.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %matplotlib inline
import stock_analysis
from stock_analysis.utils import group_stocks
start, end = '2019-01-01', '2020-12-31'
reader = stock_analysis.StockReader(start, end)
# get bitcoin data
bitcoin = reader.get_bitcoin_data('USD')
# get faang data
fb, aapl, amzn, nflx, goog = (
reader.get_ticker_data(ticker)
for ticker in ['FB', 'AAPL', 'AMZN', 'NFLX', 'GOOG']
)
# get S&P 500 data
sp = reader.get_index_data('S&P 500')
faang = group_stocks(
{
'Facebook': fb,
'Apple': aapl,
'Amazon': amzn,
'Netflix': nflx,
'Google': goog
}
)
# +
import itertools
def levels(analyzer, method):
return [getattr(analyzer, method)(i) for i in range(1, 4)]
# calculate support/resistance levels
nflx_analyzer = stock_analysis.StockAnalyzer(nflx)
support_levels, resistance_levels = (
levels(nflx_analyzer, metric) for metric in ['support', 'resistance']
)
nflx_viz = stock_analysis.StockVisualizer(nflx)
ax = nflx_viz.evolution_over_time('close', figsize=(15, 8), title='NFLX Closing Price')
for support, resistance, linestyle, level in zip(
support_levels, resistance_levels,
[':', '--', '-.'], itertools.count(1)
):
nflx_viz.add_reference_line(
ax,
y=support,
label=f'support level {level}',
color='green',
linestyle=linestyle
)
nflx_viz.add_reference_line(
ax,
y=resistance,
label=f'resistance level {level}',
color='red',
linestyle=linestyle
)
ax.get_legend().remove()
ax.set_ylabel('price ($)')
# -
stock_analysis.AssetGroupVisualizer(faang).after_hours_trades()
# +
from stock_analysis.utils import make_portfolio
stock_analysis.StockVisualizer(make_portfolio(faang)).after_hours_trades()
# +
from matplotlib.ticker import StrMethodFormatter
from stock_analysis.utils import make_portfolio
ax = stock_analysis.StockVisualizer(make_portfolio(faang)).open_to_close()
ax.yaxis.set_major_formatter(StrMethodFormatter('${x:,.0f}'))
# -
fbalx = reader.get_ticker_data('FBALX')
msft = reader.get_ticker_data('MSFT')
mutual_fund = group_stocks({
'0 - FBALX': fbalx,
'1 - Microsoft': msft,
'2 - Apple': aapl,
'3 - Amazon': amzn
})
stock_analysis.AssetGroupAnalyzer(mutual_fund).analyze('annualized_volatility')
# +
import pandas as pd
def metric_table(stock, index, r_f):
"""
Make a table of metrics for a stock.
Parameters:
- stock: The stock's dataframe.
- index: The dataframe for the index.
- r_f: Risk-free rate of return
Returns:
A `pandas.DataFrame` object with a single row of metrics
"""
return pd.DataFrame({
metric: getattr(
stock_analysis.StockAnalyzer(stock),
metric
)(**kwargs) \
for metric, kwargs in {
'alpha': {'index': index, 'r_f': r_f},
'beta': {'index': index},
'sharpe_ratio': {'r_f': r_f},
'annualized_volatility': {},
'is_bear_market': {},
'is_bull_market': {}
}.items()
}, index=range(1))
# test out the function
metric_table(fbalx, sp, r_f=reader.get_risk_free_rate_of_return())
# -
forex = reader.get_forex_rates('USD', 'JPY', api_key='<KEY>')
stock_analysis.StockVisualizer(forex).candlestick(date_range=slice('2019-02-01', '2021-01-31'), resample='1W')
| ch_07/HOMEWORK_ch7.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="-KDQ4GTf9pAB" colab_type="text"
# # Regressor (House selling price prediction)
# In this post, we will be covering some basics of data exploration and building a model with Keras in order to help us on predicting the selling price of a house in the Boston (MA) area. As an application of this model in the real world, you can think about being a real state agent looking for a tool to help you on your day-to-day duties, which for me, at least, sounds pretty good when compared to just gut-estimation.
#
# For this exercise, we will be using the Plotly library instead of the good ol' fashioned matplotlib, due to having more interactive plots, which for sure help in understanding the data. We will also use the Scikit-Learn and Keras for building the models, Pandas library to manipulate our data and the SHAP library to generate explanations for our trained model.
#
# + id="giQXZ85h9udT" colab_type="code" outputId="d07bac41-0b40-4110-b764-18e650599e57" executionInfo={"status": "ok", "timestamp": 1590922887755, "user_tz": -120, "elapsed": 1320, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 359}
from sklearn.datasets import load_boston
import pandas as pd
boston_dataset = load_boston()
df = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
df['MEDV'] = boston_dataset.target
df.head(n=10)
# + [markdown] id="8sFofWW9V6K6" colab_type="text"
# ## Dataset
# In this example, we wil be using the sklearn.datasets module, which contains the Boston dataset. You could also use the keras.datasets module, but this one does not contain the labels of the features, so we decided to use scikits one. Let's also convert it to a Pandas DataFrame and print it's head.
#
# The features can be summarized as follows:
# - CRIM: This is the per capita crime rate by town
# - ZN: This is the proportion of residential land zoned for lots larger than 25,000 sq.ft.
# - INDUS: This is the proportion of non-retail business acres per town.
# - CHAS: This is the Charles River dummy variable (this is equal to 1 if tract bounds river; 0 otherwise)
# - NOX: This is the nitric oxides concentration (parts per 10 million)
# - RM: This is the average number of rooms per dwelling
# - AGE: This is the proportion of owner-occupied units built prior to 1940
# - DIS: This is the weighted distances to five Boston employment centers
# - RAD: This is the index of accessibility to radial highways
# - TAX: This is the full-value property-tax rate per 10,000 dollars
# - PTRATIO: This is the pupil-teacher ratio by town
# - B: This is calculated as 1000(Bk — 0.63)², where Bk is the proportion of people of African American descent by town
# - LSTAT: This is the percentage lower status of the population
# - MEDV: This is the median value of owner-occupied homes in 1k dollars
# + [markdown] id="c5N4Wbyn74VT" colab_type="text"
# # Exploratory Data Analysis
# Making yourself comfortable and familiar with your dataset is a fundamental step to help you comprehend your data and draw better conclusions and explanations from your results.
#
# Initially, let's plot a few box plots, which will help us to better visualize anomalies and/or outliers in data distribution. If you are confused about what is a box plot and how it can help us to better visualize the distribution of our data, here is a brief description from Ross (1977):
#
# In descriptive statistics, a box plot is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending vertically from the boxes (whiskers) indicating variability outside the upper and lower quartiles, hence the terms box-and-whisker plot and box-and-whisker diagram. Outliers may be plotted as individual points.
#
# + id="cBALCbD18BpX" colab_type="code" outputId="eb3a4132-942d-4ef7-c1d6-5d77ff260914" executionInfo={"status": "ok", "timestamp": 1590922889922, "user_tz": -120, "elapsed": 3472, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 0}
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import math
total_items = len(df.columns)
items_per_row = 3
total_rows = math.ceil(total_items / items_per_row)
fig = make_subplots(rows=total_rows, cols=items_per_row)
cur_row = 1
cur_col = 1
for index, column in enumerate(df.columns):
fig.add_trace(go.Box(y=df[column], name=column), row=cur_row, col=cur_col)
if cur_col % items_per_row == 0:
cur_col = 1
cur_row = cur_row + 1
else:
cur_col = cur_col + 1
fig.update_layout(height=1000, width=550, showlegend=False)
fig.show()
# + [markdown] id="Ex0tktBR8Dtu" colab_type="text"
# These results do corroborate our initial assumptions about having outliers in some columns. Let's also plot some scatter plots for each feature and the target variable, as well as their intercept lines:
#
# + id="C1jMNAkl8OHL" colab_type="code" outputId="31677e26-aedc-4ea9-9ec1-a727d34d1025" executionInfo={"status": "ok", "timestamp": 1590922890684, "user_tz": -120, "elapsed": 4223, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 0}
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import math
import numpy as np
total_items = len(df.columns)
items_per_row = 3
total_rows = math.ceil(total_items / items_per_row)
fig = make_subplots(rows=total_rows, cols=items_per_row, subplot_titles=df.columns)
cur_row = 1
cur_col = 1
for index, column in enumerate(df.columns):
fig.add_trace(go.Scattergl(x=df[column],
y=df['MEDV'],
mode="markers",
marker=dict(size=3)),
row=cur_row,
col=cur_col)
intercept = np.poly1d(np.polyfit(df[column], df['MEDV'], 1))(np.unique(df[column]))
fig.add_trace(go.Scatter(x=np.unique(df[column]),
y=intercept,
line=dict(color='red', width=1)),
row=cur_row,
col=cur_col)
if cur_col % items_per_row == 0:
cur_col = 1
cur_row = cur_row + 1
else:
cur_col = cur_col + 1
fig.update_layout(height=1000, width=550, showlegend=False)
fig.show()
# + [markdown] id="7cGMHuAA8RzV" colab_type="text"
# From this initial data exploration, we can have two major conclusions:
#
# * There is a strong linear correlation between the RM (average number of rooms per dwelling) and LSTAT (% lower status of the population) with the target variable, being the RM a positive and the LSTAT a negative correlation.
# * There are some records containing outliers, which we could preprocess in order to input our model with more normalized data.
# + [markdown] id="LLjH9CjD8b64" colab_type="text"
# # Data Preprocessing
# Before we proceed into any data preprocessing, it's important to split our data into training and test sets. We should not apply any kind of preprocessing into our data without taking into account that we should not leak information from our test set. For this step, we can use the train_test_split method from scikit-learn. In this case, we will use a split of 70% of the data for training and 30% for testing. We also set a random_state seed, in order to allow reprocibility.
# + id="r9v71bQF8ouh" colab_type="code" colab={}
from sklearn.model_selection import train_test_split
X = df.loc[:, df.columns != 'MEDV']
y = df.loc[:, df.columns == 'MEDV']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=123)
# + [markdown] id="1pCC26wd8qsN" colab_type="text"
# In order to provide a standardized input to our neural network, we need the perform the normalization of our dataset. This can be seen as an step to reduce the differences in scale that may arise from the existent features. We perform this normalization by subtracting the mean from our data and dividing it by the standard deviation. One more time, this normalization should only be performed by using the mean and standard deviation from the training set, in order to avoid any information leak from the test set.
#
# + id="9ypAKDKg8tJL" colab_type="code" colab={}
mean = X_train.mean(axis=0)
std = X_train.std(axis=0)
X_train = (X_train - mean) / std
X_test = (X_test - mean) / std
# + [markdown] id="-O-e_qwr8wVn" colab_type="text"
# # Building the Model
# Due to the small amount of presented data in this dataset, we must be careful to not create an overly complex model, which could lead to overfitting our data. For this, we are going to adopt an architecture based on two Dense layers, the first with 128 and the second with 64 neurons, both using a ReLU activation function. A dense layer with a linear activation will be used as output layer.
#
# In order to allow us to know if our model is properly learning, we will use a mean squared error loss function and to report the performance of it we will adopt the mean average error metric.
#
# By using the summary method from Keras, we can see that we have a total of 10,113 parameters, which is acceptable for us.
# + id="1irL3xIW8vF5" colab_type="code" outputId="59a6c4e9-141f-44be-c70d-d9b6ef6dd3e2" executionInfo={"status": "ok", "timestamp": 1590922899976, "user_tz": -120, "elapsed": 13497, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 255}
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(128, input_shape=(13, ), activation='relu', name='dense_1'))
model.add(Dense(64, activation='relu', name='dense_2'))
model.add(Dense(1, activation='linear', name='dense_output'))
model.compile(
optimizer='adam',
loss='mse',
metrics=['mae']
)
model.summary()
# + [markdown] id="Rjz2fsJo807D" colab_type="text"
# # Training the Model
# This step is pretty straightforward: fit our model with both our features and their labels, for a total amount of 100 epochs, separating 10% of the samples (39 records) as validation set.
# + id="qT4X4J4y85ss" colab_type="code" outputId="18f91127-c608-4d68-838f-4fc39a61c679" executionInfo={"status": "ok", "timestamp": 1590922910653, "user_tz": -120, "elapsed": 24162, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 0} tags=["outputPrepend", "outputPrepend"]
epochs=150
validation_split = 0.10
history = model.fit(X_train, y_train, epochs=epochs, validation_split=validation_split)
# + [markdown] id="4EoQa94A87EI" colab_type="text"
#
# By plotting both loss and mean average error, we can see that our model was capable of learning patterns in our data without overfitting taking place (as shown by the validation set curves):
#
# + id="e4NZ0_OT9t4y" colab_type="code" outputId="7019351a-20ed-46d9-bd93-54b6dcc82bbe" executionInfo={"status": "ok", "timestamp": 1590922910654, "user_tz": -120, "elapsed": 24150, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 0}
fig = go.Figure()
fig.add_trace(go.Scattergl(y=history.history['loss'], name='Train'))
fig.add_trace(go.Scattergl(y=history.history['val_loss'], name='Valid'))
fig.update_layout(height=500, width=700,
xaxis_title='Epoch',
yaxis_title='Loss')
fig.show()
# + id="LbScGALI89px" colab_type="code" outputId="a0f595e8-490e-418a-9920-4ba4986350d7" executionInfo={"status": "ok", "timestamp": 1590922910655, "user_tz": -120, "elapsed": 24141, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 0}
fig = go.Figure()
fig.add_trace(go.Scattergl(y=history.history['mae'], name='Train'))
fig.add_trace(go.Scattergl(y=history.history['val_mae'], name='Valid'))
fig.update_layout(height=500, width=700,
xaxis_title='Epoch',
yaxis_title='Mean Absolute Error')
fig.show()
# + [markdown] id="CERqG5359-s1" colab_type="text"
# # Evaluating the Model
#
# Deep Learning: Neural Networks
# + id="3pU-tAtq-J-J" colab_type="code" outputId="37297993-42f5-4954-fdcc-0d7ba2369d70" executionInfo={"status": "ok", "timestamp": 1590922910656, "user_tz": -120, "elapsed": 24132, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 68}
mse_nn, mae_nn = model.evaluate(X_test, y_test, verbose=1)
print('Mean squared error on test data: ', mse_nn)
print('Mean absolute error on test data: ', mae_nn)
# + [markdown] id="O9aP3aEp-lSP" colab_type="text"
# Machine Learning: Linear Regression
# + id="pw56G2wO-pb8" colab_type="code" outputId="b33e1011-69b2-44b2-d447-6e10fdc7fdc7" executionInfo={"status": "ok", "timestamp": 1590922911115, "user_tz": -120, "elapsed": 24575, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)
y_pred_lr = lr_model.predict(X_test)
mse_lr = mean_squared_error(y_test, y_pred_lr)
mae_lr = mean_absolute_error(y_test, y_pred_lr)
print('Mean squared error on test data: ', mse_lr)
print('Mean absolute error on test data: ', mae_lr)
# + [markdown] id="DcLxf7-C_oB0" colab_type="text"
# Machine Learning: Decision Tree
# + id="HJCHdxTV_uW7" colab_type="code" outputId="814cfd51-d943-4784-a329-413ae54c5dc5" executionInfo={"status": "ok", "timestamp": 1590922911116, "user_tz": -120, "elapsed": 24561, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
tree = DecisionTreeRegressor()
tree.fit(X_train, y_train)
y_pred_tree = tree.predict(X_test)
mse_dt = mean_squared_error(y_test, y_pred_tree)
mae_dt = mean_absolute_error(y_test, y_pred_tree)
print('Mean squared error on test data: ', mse_dt)
print('Mean absolute error on test data: ', mae_dt)
# + [markdown] id="BcKbwLaR_7X4" colab_type="text"
# # Opening the Black Box (a.k.a. Explaining our Model)
# Sometimes just a good result is enough for most of the people, but there are scenarios where we need to explain what are the major components used by our model to perform its prediction. For this task, we can rely on the SHAP library, which easily allows us to create a summary of our features and its impact on the model output. I won't dive deep into the details of SHAP, but if you are intered on it, you can check their github page or even give a look at its paper].
#
# + id="haUYDanf9nOl" colab_type="code" outputId="7c9b3d93-57a5-44e3-8f54-7994714b12f0" executionInfo={"status": "ok", "timestamp": 1590922923257, "user_tz": -120, "elapsed": 36688, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgucoueHJYBt5Dz37rx5VyVbjjAbwPvFEYvjW6_=s64", "userId": "05706845498661238300"}} colab={"base_uri": "https://localhost:8080/", "height": 0}
# !pip install shap
import shap
shap.initjs()
explainer = shap.GradientExplainer(model, X_train[:150].values)
shap_values = explainer.shap_values(X_test[:150].values)
shap.summary_plot(shap_values, X_test, plot_type='bar')
# + [markdown] id="P-zMx1PJCeQ5" colab_type="text"
# From this simple plot, we can see that the major features that have an impact on the model output are:
#
# - LSTAT: % lower status of the population
# - RM: average number of rooms per dwelling
# - RAD: index of accessibility to radial highways
# - DIS: weighted distances to five Boston employment centres
# - NOX: nitric oxides concentration (parts per 10 million) - this may more likely be correlated with greenness of the area
# - CRIM: per capita crime rate by town
#
# From this plot, we can clearly corroborate our initial EDA analysis in which we point out the LSTAT and RM features as having a high correlation with the model outcome.
# + [markdown] id="23Va79aOCWnB" colab_type="text"
# # Conclusions
#
# In this post, we have showed that by using a Neural Network, we can easily outperform traditional Machine Learning methods by a good margin. We also show that, even when using a more complex model, when compared to other techniques, we can still explain the outcomes of our model by using the SHAP library.
#
# Furthermore, we need to have in mind that the explored dataset can be somehow outdated, and some feature engineering (such as correcting prices for inflaction) could be performed in order to better reflect current scenarios.
#
# The Jupyter notebook for this post can be found here.
#
# References
# Boston Dataset: https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html
#
# Plotly: https://plot.ly/python/
#
# ScikitLearn: https://scikit-learn.org/stable/
#
# Keras: https://keras.io/
#
# Pandas: https://pandas.pydata.org/
#
# SHAP Project Page: https://github.com/slundberg/shap
#
# SHAP Paper: https://papers.nips.cc/paper/7062-a-unified-approach-to-interpreting-model-predictions.pdf
#
# Introduction to probability and statistics for engineers and scientists. https://www.amazon.com.br/dp/B007ZBZN9U/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1
| 1 - Deep Learning - Regressor.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import plotting
# +
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
from matplotlib2tikz import save as tikz_save
# %matplotlib inline
# -
# ## Speedup as a function of the number of GPUs
def get_speedups(times):
t1 = times[0]
return [t1/t for t in times]
gpus = [1,2,4]
times = [356.420000, 212.990762, 76.724623]
speedups = get_speedups(times)
# +
n_nodes = gpus
lines = [speedups]
xlabel = 'Number of GPUs'
ylabel = 'speedup'
filename = 'strong-mpi.svg'
# +
import matplotlib.ticker as mtick
plt.figure(figsize=(12,8))
plt.grid()
# colormap
n_lines = len(lines)
line_colors = [plotting.colorblind_palette_dict[plotting.palette_order[i%plotting.n_colors]]
for i in range(n_lines)]
# plot lines
for i,tts in enumerate(lines):
plt.plot(n_nodes, tts,
color=line_colors[i], linestyle=plotting.linestyles[i%plotting.n_linestyles],
marker=plotting.markers[i%plotting.n_markers],
markerfacecolor=line_colors[i],
markersize=7)
plt.plot(n_nodes, n_nodes, color=plotting.ideal_color)
plt.text(n_nodes[-2]+1.4, n_nodes[-2]+1.2, 'ideal', fontsize='x-large')
# x-axis
plt.xscale('log', basex=2)
plt.xticks(n_nodes, fontsize='large')
plt.xlabel(xlabel, fontsize='x-large')
# y-axis
plt.yscale('log', basex=2)
plt.yticks(n_nodes)
plt.ylabel(ylabel, fontsize='x-large')
# ticks formatting
ax = plt.gca()
# ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.xaxis.set_major_formatter(ScalarFormatter())
# ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
# ax.yaxis.set_major_formatter(ScalarFormatter())
formatter = mtick.ScalarFormatter()
labels = [formatter(x) for x in [1,2,4]]
ax.set_yticklabels(labels)
# tikz_save(filename, figureheight='\\figureheight', figurewidth='\\figurewidth')
plt.savefig(filename)
plt.show()
# -
# ## Time to solution for a fixed problem for each implementation
machines = ['sequential', '1 processor - 1 GPU', '2 processors - 2 GPUs', '2 processors - 4 GPUs']
values = [180921.57, 356.42, 212.99, 76.72]
values_lists = [values]
xlabel = 'Machine'
ylabel = 'Time to solution [s]'
filename = 'strong-tts.svg'
# +
plt.figure(figsize=(12,8))
plt.grid()
# colormap
n_labels = 1
bar_colors = []
bar_colors = [plotting.colorblind_palette_dict[plotting.palette_order2[i%plotting.n_colors]]
for i in range(n_labels)]
# plot bars -- label by label
width = 0.35
n_machines = len(machines)
x_values = np.arange(1, n_machines+1)
max_value = max(values)
for i in range(1):
plt.bar(x_values+i*width, values, width, align='center', color=bar_colors[i])
for idx, v in enumerate(sorted(values_lists[i], reverse=True)):
plt.text(idx+1+i*width, 1.1*v, str(v), fontsize='large', horizontalalignment='center')
# x-axis
plt.xticks(x_values+(n_labels-1)*width/2, machines, fontsize='large')
plt.xlabel(xlabel, fontsize='x-large')
# y-axis
plt.yscale('log')
plt.yticks(fontsize='large')
plt.ylabel(ylabel, fontsize='x-large')
# ticks formatting
ax = plt.gca()
# ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
# ax.xaxis.set_major_formatter(ScalarFormatter())
# ax.yaxis.set_major_formatter(ScalarFormatter())
plt.savefig(filename)
plt.show()
| plots/StrongScaling.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
# +
import numpy as np
import argparse
import sys
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_svmlight_file
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.kernel_ridge import KernelRidge
from kernel_regression import KernelLogit
from ope_estimators import OPEestimators
# +
def data_generation(data_name, N):
X, Y = load_svmlight_file('data/{}'.format(data_name))
X = X.toarray()
maxX = X.max(axis=0)
maxX[maxX == 0] = 1
X = X / maxX
Y = np.array(Y, np.int64)
perm = np.random.permutation(len(X))
X, Y = X[perm[:N]], Y[perm[:N]]
if data_name == 'satimage':
Y = Y - 1
elif data_name == 'vehicle':
Y = Y - 1
elif data_name == 'mnist':
pca = PCA(n_components=100).fit(X)
X = pca.transform(X)
elif data_name == 'letter':
Y = Y - 1
elif data_name == 'Sensorless':
Y = Y - 1
elif data_name == 'connect-4':
Y = Y + 1
classes = np.unique(Y)
Y_matrix = np.zeros(shape=(N, len(classes)))
for i in range(N):
Y_matrix[i, Y[i]] = 1
return X, Y, Y_matrix, classes
def fit_logreg(X, Y):
return LogisticRegression(random_state=0, penalty='l2', C=0.1, solver='saga', multi_class='multinomial').fit(X, Y)
def create_policy(X, classes, classifier, alpha=0.7):
N = len(X)
num_class = len(classes)
predict = np.array(classifier.predict(X), np.int64)
pi_predict = np.zeros(shape=(N, num_class))
for i in range(N):
pi_predict[i, predict[i]] = 1
pi_random = np.random.uniform(size=(N, num_class))
pi_random = pi_random.T
pi_random /= pi_random.sum(axis=0)
pi_random = pi_random.T
policy = alpha * pi_predict + (1 - alpha) * pi_random
return policy
class Basic(object):
def __init__(self, num_arm, T):
self.num_arm = num_arm
self.sum_of_reward = np.zeros(num_arm)
self.num_of_trial = np.zeros(num_arm)
self.T = T
class UCB(Basic):
def __init__(self, num_arm, T, dim, sigma2_0=1, sigma2=1, alpha=1):
super().__init__(num_arm, T)
self.ucb_score = np.zeros(num_arm)
self.identity = np.identity(dim)
self.sigma2_0 = sigma2_0
self.sigma2 = sigma2
self.A_inv_array = [(self.sigma2_0/self.sigma2) *
self.identity for i in range(num_arm)]
self.b_array = [np.zeros((dim, 1)) for i in range(num_arm)]
self.alpha = alpha
def __call__(self, t, covariate):
alpha_t = self.alpha*np.sqrt(np.log(t+1))
for arm in range(self.num_arm):
theta = self.A_inv_array[arm].dot(self.b_array[arm])
m0 = covariate.T.dot(theta)
m1 = alpha_t * \
np.sqrt(
self.sigma2)*np.sqrt(covariate.T.dot(self.A_inv_array[arm]).dot(covariate))
self.ucb_score[arm] = m0 + m1
return np.argmax(self.ucb_score)
def update(self, arm, reward, covariate):
self.sum_of_reward[arm] += reward
self.num_of_trial[arm] += 1
A_inv_temp = self.A_inv_array[arm].copy()
A_inv_temp0 = A_inv_temp.dot(covariate).dot(
covariate.T).dot(A_inv_temp)
A_inv_temp1 = 1+covariate.T.dot(A_inv_temp).dot(covariate)
self.A_inv_array[arm] -= A_inv_temp0/A_inv_temp1
self.b_array[arm] += covariate*reward
class TS(Basic):
def __init__(self, num_arm, T, dim, sigma2_0=1, sigma2=1, alpha=1):
super().__init__(num_arm, T)
self.ucb_score = np.zeros(num_arm)
self.identity = np.identity(dim)
self.sigma2_0 = sigma2_0
self.sigma2 = sigma2
self.A_inv_array = [(self.sigma2_0/self.sigma2) *
self.identity for i in range(num_arm)]
self.b_array = [np.zeros((dim, 1)) for i in range(num_arm)]
self.alpha = alpha
def __call__(self, t, covariate):
for arm in range(self.num_arm):
mu = self.A_inv_array[arm].dot(self.b_array[arm])
theta = np.random.multivariate_normal(
mu.T[0], self.sigma2*self.A_inv_array[arm])
self.ucb_score[arm] = covariate.T.dot(theta)
return np.argmax(self.ucb_score)
def update(self, arm, reward, covariate):
self.sum_of_reward[arm] += reward
self.num_of_trial[arm] += 1
A_inv_temp = self.A_inv_array[arm].copy()
A_inv_temp0 = A_inv_temp.dot(covariate).dot(
covariate.T).dot(A_inv_temp)
A_inv_temp1 = 1+covariate.T.dot(A_inv_temp).dot(covariate)
self.A_inv_array[arm] -= A_inv_temp0/A_inv_temp1
self.b_array[arm] += covariate*reward
def create_bandit_policy(X, classes, Y, policy_type='RW', predct_alg='Logit', tau=0.7):
sample_size, dim = X.shape
num_actions = len(classes)
chosen_action_matrix = np.zeros(shape=(sample_size, num_actions))
observed_outcome_matrix = np.zeros(shape=(sample_size, num_actions))
if policy_type == 'UCB':
pi_behavior_array = np.zeros((sample_size, num_actions))
next_candidate = np.random.uniform(0.01, 0.99, size=(1, num_actions))
next_candidate = next_candidate/np.sum(next_candidate)
pi_behavior_array[0] = next_candidate
ucb = UCB(num_arm=num_actions, T=sample_size,
dim=dim, sigma2_0=5, sigma2=5)
for time in range(sample_size):
covariate_t = np.array([X[time]]).T
arm = ucb(time, covariate_t)
uni_rand = np.random.uniform(size=(num_actions))
uni_rand = uni_rand/np.sum(uni_rand)
prob = (1-tau)*uni_rand
prob[arm] += tau
pi_behavior_array[time] = prob
chosen_action = np.random.choice(
classes, p=pi_behavior_array[time])
observed_outcome = Y[time, chosen_action]
chosen_action_matrix[time, chosen_action] = 1
observed_outcome_matrix[time,
chosen_action] = observed_outcome
ucb.update(chosen_action,
observed_outcome, covariate_t)
if policy_type == 'TS':
pi_behavior_array = np.zeros((sample_size, num_actions))
next_candidate = np.random.uniform(0.01, 0.99, size=(1, num_actions))
next_candidate = next_candidate/np.sum(next_candidate)
pi_behavior_array[0] = next_candidate
ts = TS(num_arm=num_actions, T=sample_size,
dim=dim, sigma2_0=1, sigma2=1)
for time in range(sample_size):
covariate_t = np.array([X[time]]).T
arm = ts(time, covariate_t)
uni_rand = np.random.uniform(size=(num_actions))
uni_rand = uni_rand/np.sum(uni_rand)
prob = (1-tau)*uni_rand
prob[arm] += tau
pi_behavior_array[time] = prob
chosen_action = np.random.choice(
classes, p=prob)
observed_outcome = Y[time, chosen_action]
chosen_action_matrix[time, chosen_action] = 1
observed_outcome_matrix[time,
chosen_action] = observed_outcome
ts.update(chosen_action,
observed_outcome, covariate_t)
return pi_behavior_array, observed_outcome_matrix, chosen_action_matrix
def true_value(Y_matrix, pi_evaluation):
return np.sum(Y_matrix * pi_evaluation) / len(pi_evaluation)
def sample_by_behavior(Y_matrix, pi_behavior, classes):
sample_size = len(Y_matrix)
Y_observed_matrix = np.zeros(shape=(sample_size, len(classes)))
A_observed_matrix = np.zeros(shape=(sample_size, len(classes)))
for i in range(sample_size):
a = np.random.choice(classes, p=pi_behavior[i])
Y_observed_matrix[i, a] = Y_matrix[i, a]
A_observed_matrix[i, a] = 1
return Y_observed_matrix, A_observed_matrix
# +
KernelRidge_hyp_param = {'alpha': [0.01, 0.1, 1], 'gamma': [0.01, 0.1, 1]}
KernelLogit_sigma_list = np.array([0.01, 0.1, 1])
KernelLogit_lda_list = np.array([0.01, 0.1, 1])
def kernel_ridge_estimator(X, Y, Z, cv=5):
model = KernelRidge(kernel='rbf')
model = GridSearchCV(
model, {'alpha': [0.01, 0.1, 1], 'gamma': [0.01, 0.1, 1]}, cv=cv)
model.fit(X, Y)
return model.predict(Z)
def kernel_logit_estimator(X, Y, Z, cv=5):
model, KX, KZ = KernelLogit(X, Y, Z, folds=cv, num_basis=100,
sigma_list=KernelLogit_sigma_list,
lda_list=KernelLogit_lda_list, algorithm='Ridge')
model.fit(KX, Y)
return model.predict_proba(KZ)
class OPEestimators():
def __init__(self, classes, pi_evaluation, pi_behavior=None):
self.classes = classes
self.pi_behavior = pi_behavior
self.pi_evaluation = pi_evaluation
def fit(self, X, A, Y_matrix, est_type,
outcome_estimator=kernel_ridge_estimator,
policy_estimator=kernel_logit_estimator,
warning_samples=10):
self.X = X
self.N_hst, self.dim = X.shape
self.A = A
self.Y = Y_matrix
self.warning_samples = warning_samples
self.outcome_estimator = kernel_ridge_estimator
self.policy_estimator = kernel_logit_estimator
warnings.simplefilter('ignore')
if est_type == 'ipw':
theta, var = self.ipw()
if est_type == 'dm':
theta, var = self.dm()
if est_type == 'aipw':
theta, var = self.aipw()
if est_type == 'a2ipw':
theta, var = self.a2ipw()
if est_type == 'adr':
theta, var = self.adr()
if est_type == 'dr':
theta, var = self.dr()
if est_type == 'doublyrobust':
theta, var = self.doublyrobust()
return theta, var
def aipw(self, folds=2):
theta_list = []
cv_fold = np.arange(folds)
cv_split0 = np.floor(np.arange(self.N_hst)*folds/self.N_hst)
cv_index = cv_split0[np.random.permutation(self.N_hst)]
x_cv = []
a_cv = []
y_cv = []
pi_bhv_cv = []
pi_evl_cv = []
for k in cv_fold:
x_cv.append(self.X[cv_index == k])
a_cv.append(self.A[cv_index == k])
y_cv.append(self.Y[cv_index == k])
pi_bhv_cv.append(self.pi_behavior[cv_index == k])
pi_evl_cv.append(self.pi_evaluation[cv_index == k])
for k in range(folds):
count = 0
for j in range(folds):
if j == k:
x_te = x_cv[j]
a_te = a_cv[j]
y_te = y_cv[j]
pi_bhv_te = pi_bhv_cv[j]
pi_evl_te = pi_evl_cv[j]
if j != k:
if count == 0:
x_tr = x_cv[j]
a_tr = a_cv[j]
y_tr = y_cv[j]
pi_bhv_tr = pi_bhv_cv[j]
pi_evl_tr = pi_evl_cv[j]
count += 1
else:
x_tr = np.append(x_tr, x_cv[j], axis=0)
a_tr = np.append(a_tr, a_cv[j], axis=0)
y_tr = np.append(y_tr, y_cv[j], axis=0)
pi_bhv_tr = np.append(pi_bhv_tr, pi_bhv_cv[j], axis=0)
pi_evl_tr = np.append(pi_evl_tr, pi_evl_cv[j], axis=0)
densratio_matrix = pi_evl_te/pi_bhv_te
f_matrix = np.zeros(shape=(len(x_te), len(self.classes)))
for c in self.classes:
f_matrix[:, c] = self.outcome_estimator(
x_tr[a_tr[:, c] == 1], y_tr[:, c][a_tr[:, c] == 1], x_te)
# weight = np.ones(shape=a_te.shape)*np.sum(a_te/pi_bhv_te, axis=0)
weight = len(a_te)
theta = np.sum(a_te*(y_te-f_matrix)*densratio_matrix /
weight) + np.sum(f_matrix*pi_evl_te/weight)
theta_list.append(theta)
theta = np.mean(theta_list)
densratio_matrix = self.pi_evaluation/self.pi_behavior
f_matrix = np.zeros(shape=(self.N_hst, len(self.classes)))
for c in self.classes:
for t in range(self.N_hst):
if np.sum(self.A[:t, c] == 1) > self.warning_samples:
f_matrix[t, c] = self.outcome_estimator(
self.X[:t][self.A[:t, c] == 1],
self.Y[:t][:t, c][self.A[:t, c] == 1],
[self.X[t]])
else:
f_matrix[t, c] = 0
# weight = np.ones(shape=a_te.shape)*np.sum(a_te/pi_bhv_te, axis=0)
score = np.sum(self.A*(self.Y-f_matrix)*densratio_matrix, axis=1) + np.sum(f_matrix*self.pi_evaluation, axis=1)
var = np.mean((score - theta)**2)
return theta, var
def dr(self, folds=2):
theta_list = []
cv_fold = np.arange(folds)
cv_split0 = np.floor(np.arange(self.N_hst)*folds/self.N_hst)
cv_index = cv_split0[np.random.permutation(self.N_hst)]
x_cv = []
a_cv = []
y_cv = []
pi_evl_cv = []
for k in cv_fold:
x_cv.append(self.X[cv_index == k])
a_cv.append(self.A[cv_index == k])
y_cv.append(self.Y[cv_index == k])
pi_evl_cv.append(self.pi_evaluation[cv_index == k])
for k in range(folds):
count = 0
for j in range(folds):
if j == k:
x_te = x_cv[j]
a_te = a_cv[j]
y_te = y_cv[j]
pi_evl_te = pi_evl_cv[j]
if j != k:
if count == 0:
x_tr = x_cv[j]
a_tr = a_cv[j]
y_tr = y_cv[j]
pi_evl_tr = pi_evl_cv[j]
count += 1
else:
x_tr = np.append(x_tr, x_cv[j], axis=0)
a_tr = np.append(a_tr, a_cv[j], axis=0)
y_tr = np.append(y_tr, y_cv[j], axis=0)
pi_evl_tr = np.append(pi_evl_tr, pi_evl_cv[j], axis=0)
a_temp = np.where(a_tr == 1)[1]
pi_bhv_te = kernel_logit_estimator(
x_tr, a_temp, x_te)
densratio_matrix = pi_evl_te/pi_bhv_te
f_matrix = np.zeros(shape=(len(x_te), len(self.classes)))
for c in self.classes:
f_matrix[:, c] = self.outcome_estimator(
x_tr[a_tr[:, c] == 1], y_tr[:, c][a_tr[:, c] == 1], x_te)
# weight = np.ones(shape=a_te.shape)*np.sum(a_te/pi_bhv_te, axis=0)
weight = len(a_te)
theta = np.sum(a_te*(y_te-f_matrix)*densratio_matrix /
weight) + np.sum(f_matrix*pi_evl_te/weight)
theta_list.append(theta)
theta = np.mean(theta_list)
a_temp = np.where(self.A == 1)[1]
pi_behavior = kernel_logit_estimator(self.X, a_temp, self.X)
densratio_matrix = self.pi_evaluation/pi_behavior
f_matrix = np.zeros(shape=(self.N_hst, len(self.classes)))
for c in self.classes:
for t in range(self.N_hst):
if np.sum(self.A[:t, c] == 1) > self.warning_samples:
f_matrix[t, c] = self.outcome_estimator(
self.X[:t][self.A[:t, c] == 1],
self.Y[:t][:t, c][self.A[:t, c] == 1],
[self.X[t]])
else:
f_matrix[t, c] = 0
# weight = np.ones(shape=a_te.shape)*np.sum(a_te/pi_bhv_te, axis=0)
score = np.sum(self.A*(self.Y-f_matrix)*densratio_matrix, axis=1) + np.sum(f_matrix*self.pi_evaluation, axis=1)
var = np.mean((score - theta)**2)
return theta, var
def a2ipw(self):
densratio_matrix = self.pi_evaluation/self.pi_behavior
f_matrix = np.zeros(shape=(self.N_hst, len(self.classes)))
for c in self.classes:
for t in range(self.N_hst):
if np.sum(self.A[:t, c] == 1) > self.warning_samples:
f_matrix[t, c] = self.outcome_estimator(
self.X[:t][self.A[:t, c] == 1],
self.Y[:t][:t, c][self.A[:t, c] == 1],
[self.X[t]])
else:
f_matrix[t, c] = 0
# weight = np.ones(shape=a_te.shape)*np.sum(a_te/pi_bhv_te, axis=0)
score = np.sum(self.A*(self.Y-f_matrix)*densratio_matrix, axis=1) + np.sum(f_matrix*self.pi_evaluation, axis=1)
theta = np.mean(score)
var = np.mean((score - theta)**2)
return theta, var
def adr(self):
theta_list = []
pi_behavior = np.copy(self.pi_evaluation)
pi_behavior[:] = 0.5
for t in range(1, self.N_hst):
if all(np.sum(self.A[:t, :] == 1, axis=0) > self.warning_samples):
a_temp = np.where(self.A[:t] == 1)[1]
pi_behavior[t, :] = kernel_logit_estimator(
self.X[:t], a_temp, np.array([self.X[t]]))
else:
pi_behavior[t, :] = 0.5
densratio_matrix = self.pi_evaluation/pi_behavior
f_matrix = np.zeros(shape=(self.N_hst, len(self.classes)))
for c in self.classes:
for t in range(self.N_hst):
if np.sum(self.A[:t, c] == 1) > self.warning_samples:
f_matrix[t, c] = self.outcome_estimator(
self.X[:t][self.A[:t, c] == 1],
self.Y[:t][:t, c][self.A[:t, c] == 1],
[self.X[t]])
else:
f_matrix[t, c] = 0
# weight = np.ones(shape=a_te.shape)*np.sum(a_te/pi_bhv_te, axis=0)
score = np.sum(self.A*(self.Y-f_matrix)*densratio_matrix, axis=1) + np.sum(f_matrix*self.pi_evaluation, axis=1)
theta = np.mean(score)
var = np.mean((score - theta)**2)
return theta, var
def ipw(self):
if self.pi_behavior is None:
a_temp = np.where(self.A == 1)[1]
self.pi_behavior = kernel_logit_estimator(self.X, a_temp, self.X)
densratio = self.pi_evaluation/self.pi_behavior
# weight = np.ones(shape=self.A.shape)*np.sum(self.A/self.pi_behavior, axis=0)
weight = len(self.A)
score = np.sum(self.A*self.Y*densratio, axis=1)
theta = np.mean(score)
var = np.mean((score - theta)**2)
return theta, var
def doublyrobust(self):
a_temp = np.where(self.A == 1)[1]
pi_behavior = kernel_logit_estimator(self.X, a_temp, self.X)
densratio = self.pi_evaluation/pi_behavior
f_matrix = np.zeros(shape=(self.N_hst, len(self.classes)))
for c in self.classes:
f_matrix[:, c] = self.outcome_estimator(
self.X[self.A[:, c] == 1],
self.Y[:, c][self.A[:, c] == 1],
self.X)
# weight = np.ones(shape=self.A.shape)*np.sum(self.A/self.pi_behavior, axis=0)
score = np.sum(self.A*(self.Y-f_matrix)*densratio, axis=1) + np.sum(f_matrix*self.pi_evaluation, axis=1)
theta = np.mean(score)
var = np.mean((score - theta)**2)
return theta, var
def dm(self, method='Ridge'):
f_matrix = np.zeros(shape=(self.N_hst, len(self.classes)))
for c in self.classes:
f_matrix[:, c] = self.outcome_estimator(
self.X[self.A[:, c] == 1],
self.Y[:, c][self.A[:, c] == 1],
self.X)
score = np.sum(f_matrix*self.pi_evaluation, axis=1)
theta = np.mean(score)
var = np.mean((score - theta)**2)
return theta, var
# -
def data_generator(N=1000):
X = np.random.normal(size=(N, 10))
g0 = np.sum(X, axis=1)
g1 = np.sum(np.random.choice([-1, 1], size=(N, 10))*X**2, axis=1)
g2 = np.sum(np.random.choice([-1, 1], size=(N, 10))*np.abs(X), axis=1)
prob_array = np.zeros(shape=(N, 3))
prob_array[:, 0] = np.exp(g0)
prob_array[:, 1] = np.exp(g1)
prob_array[:, 2] = np.exp(g2)
prob_array = (prob_array.T/prob_array.sum(axis=1)).T
Y = np.zeros(shape=(N, 1))
for i in range(N):
Y[i] = np.random.choice([0, 1, 2], p=prob_array[i])
Y = np.array(Y, np.int64)
Y_matrix = np.zeros(shape=(N, 3))
for i in range(N):
Y_matrix[i, Y[i]] = 1
return X, Y, Y_matrix
# +
history_sample_size = 50
evaluation_policy_size = 100
policy_type = 'TS'
classes = [0, 1, 2]
num_trials = 1000
logit_model = LogisticRegression(random_state=0, C=0.1)
method_list = [logit_model]
true_list = []
est_ipw_list = []
est_dm_list = []
est_aipw_list = []
est_a2ipw_list = []
est_est_ipw_list = []
est_dr_list = []
est_doubly_robust_list = []
est_adr_list = []
for tr in range(num_trials):
print(tr)
X, Y_true, Y_true_matrix = data_generator(evaluation_policy_size + history_sample_size)
X_pre = X[:evaluation_policy_size]
Y_pre_true = Y_true[:evaluation_policy_size]
_ = Y_true_matrix[:evaluation_policy_size]
X_hist = X[evaluation_policy_size:]
_ = Y_true[evaluation_policy_size:]
Y_hist_true_matrix = Y_true_matrix[evaluation_policy_size:]
classifier = fit_logreg(X_pre, Y_pre_true)
pi_evaluation = create_policy(
X_hist, classes, classifier, alpha=0.9)
pi_behavior, Y_hist, A_hist = create_bandit_policy(
X_hist, classes, Y_hist_true_matrix, policy_type=policy_type, tau=0.7)
true_val = true_value(Y_hist_true_matrix, pi_evaluation)
OPE = OPEestimators( classes, pi_evaluation=pi_evaluation, pi_behavior=pi_behavior)
true_list.append(true_val)
est_ipw_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='ipw') )
est_dm_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='dm') )
est_aipw_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='aipw') )
est_a2ipw_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='a2ipw'))
OPE = OPEestimators( classes, pi_evaluation=pi_evaluation, pi_behavior=None)
est_est_ipw_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='ipw') )
est_dr_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='dr') )
est_doubly_robust_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='doublyrobust') )
est_adr_list.append(OPE.fit(X_hist, A_hist, Y_hist, est_type='adr'))
# -
num_trials
# +
true_list_array = np.array(true_list)
est_ipw_list_array = np.array(est_ipw_list)
est_dm_list_array = np.array(est_dm_list)
est_aipw_list_array = np.array(est_aipw_list)
est_a2ipw_list_array = np.array(est_a2ipw_list)
est_dr_list_array = np.array(est_dr_list)
est_adr_list_array = np.array(est_adr_list)
est_doubly_robust_list_array = np.array(est_doubly_robust_list)
# -
error0 = est_ipw_list_array[:, 0] - true_list_array
error1 = est_dm_list_array[:, 0] - true_list_array
error2 = est_aipw_list_array[:, 0] - true_list_array
error3 = est_a2ipw_list_array[:, 0]- true_list_array
error4 = est_dr_list_array[:, 0] - true_list_array
error5 = est_adr_list_array[:, 0] - true_list_array
error6 = est_doubly_robust_list_array[:, 0] - true_list_array
error0 = est_ipw_list_array[:, 0] - true_list_array
error1 = est_dm_list_array[:, 0] - true_list_array
error2 = est_aipw_list_array[:, 0] - true_list_array[:-1]
error3 = est_a2ipw_list_array[:, 0]- true_list_array[:-1]
error4 = est_dr_list_array[:, 0] - true_list_array[:-1]
error5 = est_adr_list_array[:, 0] - true_list_array[:-1]
error6 = est_doubly_robust_list_array[:, 0] - true_list_array[:-1]
# +
import numpy as np
from scipy.stats import gaussian_kde
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
limmin = -0.5
limmax = 0.5
ls = np.linspace(limmin, limmax, 1000)
kde = gaussian_kde(error0)
plt.plot(ls, kde(ls), label='ipw')
kde = gaussian_kde(error1)
plt.plot(ls, kde(ls), label='dm')
kde = gaussian_kde(error2)
plt.plot(ls, kde(ls), label='aipw')
kde = gaussian_kde(error3)
plt.plot(ls, kde(ls), label='a2ipw')
kde = gaussian_kde(error4)
plt.plot(ls, kde(ls), label='dr')
kde = gaussian_kde(error5)
plt.plot(ls, kde(ls), label='adr')
p = plt.vlines([0], 0, 8, "black", linestyles='dashed')
plt.xlabel('Errors', fontsize=30)
plt.yticks(fontsize=30)
plt.xticks([-0.5, -0.25, 0, 0.25, 0.5])
plt.xticks(fontsize=30)
plt.legend(fontsize=30)
# +
import numpy as np
from scipy.stats import gaussian_kde
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
limmin = -0.5
limmax = 0.5
ls = np.linspace(limmin, limmax, 1000)
kde = gaussian_kde(error1)
plt.plot(ls, kde(ls), label='all')
kde = gaussian_kde(error2[:20])
plt.plot(ls, kde(ls), label='early')
kde = gaussian_kde(error3[:30])
plt.plot(ls, kde(ls), label='last')
kde = gaussian_kde(error4[:40])
plt.plot(ls, kde(ls), label='a2ipw')
kde = gaussian_kde(error5[:50])
plt.plot(ls, kde(ls), label='dr')
kde = gaussian_kde(error6[:])
plt.plot(ls, kde(ls), label='adr')
p = plt.vlines([0], 0, 8, "black", linestyles='dashed')
plt.xlabel('Errors', fontsize=30)
plt.yticks(fontsize=30)
plt.xticks([-0.3, -0.25, 0, 0.25, 0.3])
plt.xticks(fontsize=30)
plt.legend(fontsize=30)
# -
error2
np.mean(error0)
np.mean(error0**2)
np.mean(error2)
np.mean(error3)
np.mean(error3**2)
np.mean(error4)
np.mean(error4**2)
np.mean(error5)
np.mean(error5**2)
np.mean(error1**2)
from scipy import stats
np.random.seed(12345678)
x = stats.norm.rvs(loc=5, scale=3, size=100)
stats.shapiro(x)
| bias.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Binary Search Trees continue
# ### Searching for an element in the tree
#
# Now that we have our BST structure, and a possibility to print out its content to see that it is behaving as intended. Let us now look at how to search the tree for a specific element based on its key. To do this, we again use the recursive nature of the tree, as well as it's search property: i.e., we only have to check the left subtree *or* the right subtree, but never both.
#
# ```C++
# public:
# bool contains(int x) {
# /* Check if the whole tree contains a given value */
# return contains(root, x);
# }
#
# private:
# bool contains(Node* subroot, int x) {
# /* Check if a given subtree contains a given value */
#
# // An empty subtree contains nothing
# if (subroot == nullptr) {
# return false;
# }
#
# if (subroot->key == x) {
# // Match found
# return true;
#
# } else if (x < subroot-> key) {
# // If match exists, it must be in left subtree
# return contains(subroot->left, x);
#
# } else {
# // If match exists, it must be in right subtree
# return contains(subroot->right, x);
# }
# }
# ```
# Testing our implementation
# ```C++
# BinarySearchTree tree({7, 4, 1, 3, 5, 6, 2, 9, 0, 8});
# cout << tree.contains(5) << endl;
# cout << tree.contains(20) << endl;
# ```
# This prints out
# ```
# 1
# 0
# ```
# Here, 1 means true, and 0 means false. This is how `cout` prints out boolean values. If we want it to actually print out true/false, we can use the `<iomanip>` header to impact this by setting the booleanalpha flag:
# ```C++
# BinarySearchTree tree({7, 4, 1, 3, 5, 6, 2, 9, 0, 8});
# cout << boolalpha;
# cout << tree.contains(5) << endl;
# cout << tree.contains(20) << endl;
# ```
# ```
# true
# false
# ```
#
# #### Why we call it the "key"
#
# We are now ready to explain why we call it the *key* of the node. A node can potentially contain any data, including a large amount of different data. A node could for example represent a person in a contact list, and contain various data fields such as the phone number, the email, and so forth. For a linked list, the contents of the node doesn't impact where it goes, so we just called it the "data" of the node.
#
# However, for our binary search tree, we need access to a *key* on which we check if it is smaller or larger than a given value. So the key must be a simple data type that is sortable, like an integer or a string (which can be sorted alphabetically). The node can still contain all the other data as well, but the *key* itself is the piece of information we use to structure our tree.
#
# For a contact list, the *key* would typically be the name. Thus every contact needs a name, which identifies them and sorts them, while all other pieces of information would be optional and just stored additionally, it wouldn't impact the binary search tree. In a larger data base, you might want to sort people by some sort of identity number instead, for example an employee number. Each node would contain this code as its key, but all the other information would also be stored in the node, it just wouldn't impact the placement within the tree.
#
# After having programmed Python for a while, you might naturally associate "keys" with dictionaries, which store items in key: value pairs. This is the exact same logic we are using now, in fact, binary search trees are a great underlying structure for implementing a dictionary class (altough, not the one Python uses, which is a different structure called a hash table).
#
# While implementing a dictionary class from the bottom-up on top of a binary search tree is a great exercise. We won't take the time to do it here. However, it could be a great exercise to learn more about data structures to do so yourself, if you have the time.
# ### Removing elements
#
# We now turn to removing elements from our BST based on key. If we want to remove elements with a given key, we first have to find the right node, and then somehow remove it without decoupling the entire tree, which can potentially be a bit tricky. In the process of trying to keep the tree in tact, we also have to be certain to keep the search property of the tree in tact as well.
#
# Once we have found the node to be removed, there are three possible cases: the node to be deleted can have (1) no children, i.e., it is a leaf node, (2) it can have one child, or (3) it chan have two children. Let us discuss these three cases seperately:
#
# **(1)** If the node has no children, deleting it is fairly trivial, just set the pointer of its parent to `nullptr` and you are done. This is the same as deleting the last element in a linked list.
#
# **(2)** If the node we are deleting has a single child, things are still fairly easy. We simply need to take the parent's point and point it at its "grandchild". This is like deleting an element from the middle of a linked list.
#
# **(3)** If there are two children, things get a bit more tricky. Imagine for example trying to remove the root of the whole tree, effectively we are cleaving the tree into two completely separated new trees—but we don't want this, we want to keep the remaining noded as a single tree. The challenge is then to find out what should become the *new root* of the tree.
#
# The way we handle this is to find the *inorder successor* of the node to be deleted, i.e., the element that would naturally follow it in a sorted list. The successor will always be found by first stepping a single time to the right (from the node to be deleted), and then stepping continiously to the left untill you reach a node with no left child. We then move the successor up to become the new root by first deleting it from its current location in the tree, and then replacing the node to be actually be deleted by it. As the inorder successor node has no left child (by definition), it has at most one child, and so deleting it will be fairly easy.
#
# This process is a lot easier to envision with an example, so let us draw a figure:
# <img src="fig/bst_removal.png" width=700>
# <center><b>Figure 5:</b> Removing a node from a BST can potentially be tricky. In the given example we want to remove the node with value `4`. However, this node has two children, and so we have to find a replacement for it, otherwise the tree would split into two. We choose the inorder succsessor, which in this case is the node with `5`. When we move this node up into the deleted nodes place, we have to be careful not to lose its child, `6` in the process!</center>
#
# In the given example, we wanted to remove the root of the whole tree. What happens if we want to remove a different node? Well, any node is the root of it's own subtree, and so you could simply perform the same process on that subtree.
# #### Implementing remove
#
# Before we implement the remove itself, we define a `find_min` function to help us find the in-order successor:
# ```C++
# Node* find_min(Node* subroot) {
# /* Find the smallest node of a given subtree */
# Node* minimum = subroot;
# while (minimum->left != nullptr) {
# minimum = minimum->left;
# }
# return minimum;
# }
# ```
# Now we turn to the actual removal method, which we again do recursively
# ***
# ```C++
# public:
# void remove(int x) {
# /* Remove node with key x from whole tree if present
#
# If the key is not present, we throw an error.
# */
# root = remove(root, x);
# count--;
# }
# ```
# ***
# ```C++
# private:
# Node* remove(Node* subroot, int x) {
# /* Remove node with key x from subtree if present */
# if (subroot == nullptr) {
# // Element is not contained in tree, cannot remove
# throw runtime_error("element not in tree");
# }
#
# if (x < subroot-> key) {
# // Keep searching left subtree
# subroot->left = remove(subroot->left, x);
# } else if (x > subroot-> key) {
# // Keep searching right subtree
# subroot->right = remove(subroot->right, x);
# } else {
# // We have found the node to be deleted
#
# if (subroot->left == nullptr and subroot->right == nullptr) {
# // 0 children
# delete subroot;
# return nullptr;
# } else if (subroot->left == nullptr) {
# // 1 child
# Node* child = subroot->right;
# delete subroot;
# return child;
# } else if (subroot->right == nullptr) {
# // 1 child
# Node* child = subroot->left;
# delete subroot;
# return child;
# } else {
# // 2 children
# Node* succsessor = find_min(subroot->right);
# subroot->key = successor->key;
# subroot->right = remove(subroot->right, successor->key);
# }
# }
# }
# ```
#
# This implementation quite a beast with several nested tests, and a recursive definition! But, when going through and implementing it yourself, just be thourough, and do it incremenetally, step by step, and it all works out in the end.
#
# Note also that we in this example use a slight hack on the 2 children solution. Instead of deleting the actual node, and then moving the successor up, we simply copy the succsessor's key, and then delete the succsessor. This works well if we only store the key. If we stored other information than the key, we would also need to copy that over. Copying these values over instead of moving the nodes around is not strictly speaking optimal, but it's a far easier way to implement it.
# #### Testing Remove
#
# Because there are the three different cases: removing a node with 0, 1, or 2 children, we should check all of them. We can use the same tree:
# ```C++
# BinarySearchTree tree({7, 4, 1, 3, 5, 6, 2, 9, 0, 8});
# ```
#
# We start by checking a node with no children. This could for example be the biggest node in the list: 9. We write the following thest snippet:
# ```C++
# cout << boolalpha;
# cout << "Before removal:" << endl;
# cout << "===============" << endl;
# cout << ".length(): " << tree.length() << endl;
# cout << ".contains(9): " << tree.contains(9) << endl;
# cout << ".print():" << endl;
# tree.print();
#
# tree.remove(9);
#
# cout << endl << "After removal:" << endl;
# cout << "===============" << endl;
# cout << ".length(): " << tree.length() << endl;
# cout << ".contains(9): " << tree.contains(9) << endl;
# cout << ".print():" << endl;
# tree.print();
# ```
#
# Which produces the output (with the print changed to be on a single line:
# ```
# Before removal:
# ===============
# .length(): 10
# .contains(9): true
# .print(): 0 1 2 3 4 5 6 7 8 9
#
# After removal:
# ===============
# .length(): 9
# .contains(9): false
# .print(): 0 1 2 3 4 5 6 7 8
# ```
#
# To check removal of a node with a single child, we simply change the example of 9, to for example 3, which has a single child. Try it yourself.
#
# Lastly, we must check the case of a node with two elements, here we can choose the root itself for example, which would be 7. Or a different node with two children, for example 4. Try it yourself, and verify that my, or your own, implementation is valid.
# ## Cost of operations
#
# We have now gone through and implemented a binary search tree class, and defined the most important operations, namely: `insert`, `remove`, `contains` and inorder traversal in the form of `print`. Let us now analyze the performance of our data structure. Let us start with the `contains` method, which is a simple search, as this was the original motivation for the search tree.
#
# So, how many operations does our `contains` use? First, let us look back to our implementation:
#
# ***
# ```C++
# public:
# bool contains(int x) {
# /* Check if the whole tree contains a given value */
# return contains(root, x);
# }
#
# private:
# bool contains(Node* subroot, int x) {
# /* Check if a given subtree contains a given value */
#
# // An empty subtree contains nothing
# if (subroot == nullptr) {
# return false;
# }
#
# if (subroot->key == x) {
# // Match found
# return true;
#
# } else if (x < subroot-> key) {
# // If match exists, it must be in left subtree
# return contains(subroot->left, x);
#
# } else {
# // If match exists, it must be in right subtree
# return contains(subroot->right, x);
# }
# }
# ```
# ***
#
# While this method might look very complicated, note that as we search for an element in the tree, we only ever move down from the root, never back up. For each step, we choose either the left or right branch, and stick with our decision. This works because of the tree's search property. If there is no match in our tree, then we need to keep looking untill we hit a leaf node in our tree. But how many operations is that? Well, that depends on the *height* of the tree. To understand the concept of height, we also need to discuss *balance*.
#
# #### Tree height and tree balance
#
# Earlier in the lecture, we explained that a tree does not remember its insertion order, but this doesn't mean that the insertion order is unimportant. Depending on the order elements are inserted in, a binary search tree can have a very different structure. We say that a tree is "balanced" if it's node spread out evenly across all branches. While if the nodes start clumping up towards one side of the tree, we say the tree becomes unbalanced.
#
# As an example, let us make two trees, both consisting of the numbers 1 through 7. But we build our trees by inserting the elements in different orders:
#
# 1. Insert in order: 4, 6, 5, 2, 1, 7, 3
# 2. Insert in order: 1, 2, 3, 4, 5, 6, 7
#
# If you go through with pen and paper and construct these two trees out, you will find that tree (1) becomes perfectly balanced, i.e., it fills up all layers perfectly. While (2) becomes "perfectly" unbalanced, with all nodes using the right branch. Because the left branch is never used, our structure doesn't branch at all, and we have effectively just made a linked list! I say "perfectly" in air quotes, because we *want* our tree to be balanced, so there is nothing perfect about this unbalanced tree.
#
# <img src="fig/bst_balance.png" width=600>
# <center><b>Figure 6:</b> Two trees consisting of the same elements, but with a different structure. On the left we see a perfectly balanced tree, meaning all branches are filled out at every level. On the right we have a very unbalaced tree, with only the right branches being used, and none of the left branches.</center>
#
# Now, what is the *height* of these two trees? First we need to define the height of a tree:
# > The height of a tree structure is the longest path from the top to bottom (root to a leaf) going only down.
#
# So counting, we see that the height of the balanced tree is 3, because there are three "layers", and it takes three steps to go from the root to the bottom. For the unbalanced tree however, the height is 7, as we have to step through all the nodes to reach the bottom of the tree.
#
# Now, let us extend this thinking to a larger, tree with $n$ nodes, what will the height of such a tree be if it is either balanced or unbalanced? The balanced tree will have a height on the order of $\log_2(n)$, because for each new layer we add to the tree, we can fit twice as many nodes, so because the structure is branching, the height grows less and less as the number of nodes increases. You will notice this quickly, try drawing a large balanced tree on a sheet of paper and you will run out of width long before you fill the height of the sheet. For an unbalanced tree however, the height will be on the order of $n$, because each new node you add to the tree adds to the height.
#
# Of course, most real binary search trees won't be perfectly balanced or unbalanced, but lie somewhere in between. Still, for most realistic use cases, the tree will actually turn out be quite well balanced, meaning its height grows as $\mathcal{O}(\log n)$ (Big Oh doesn't care about the base of the logarithm), though we should be careful using BSTs in situations where they might tend to become unbalanced due to the nature of a problem. So if we can assume that the input come in more or less random order, then the tree will be balanced.
# #### Cost of searching a BST
#
# So back to the question at hand. We asked:
# * How many operations to check whether our tree contains a given value?
#
# As our search algorithm only moves downward, and never back up in the tree, the *worst case* for our algorithm will be the height of the tree. If there is no match in the tree, the answer is still the height of the tree, as we only need to reach the bottom of the tree to know there is no match. So for a balanced tree, the worst case runtime of searching is $\mathcal{O}(\log n)$, much better than the $\mathcal{O}(n)$ of arrays and linked lists. The average case is also $\mathcal{O}(\log n)$ (why?).
#
# Now, we assumed that our tree was balanced, but this might not always be the case, so for a general BST we say that the worst case is that our tree is "perfectly" unbalanced, in which case it acts like a linked list with a cost of searching of $\mathcal{O}(n)$, but on average, a general tree will tend to be fairly balanced, so the average cose of a general BST is $\mathcal{O}(\log n)$.
#
# #### Cost of traversing the tree
#
# What about the cost of traversing the the elements of the tree, for example to print them out. While the algorithm to do so was a bit trickier than the ones for the linked list or the array, the fact is still that we visit each node of the tree exactly once when traversing it, so the cost of traversing a tree is $\mathcal{O}(n)$, same as for the array and linked list structures.
#
# #### Cost of inserting and deleting
#
# What about adding a new node to the tree? When we want to add a new node, we first have to find where it goes, which is effectively a *search* operation (why?), so first we have the cost of the search, and then adding the new node is $\mathcal{O}(1)$. So for a balanced tree the cost of an insert is $\mathcal{O(\log n)}$.
#
# Deleting a node is very similar, first we need to find the node to be deleted, and then we carry out a finite number of steps, meaning the removal itself is $\mathcal{O}(1)$, but the search is $\mathcal{O}(\log n)$, so removal is also $\mathcal{O}(\log n)$ in total. For an unbalanced tree however, the search becomes linear, so in those cases, we actually get a cost of $\mathcal{n}$.
#
# | Algorithm | Average Case | Worst case |
# | --------- | --------------------- | ---------------- |
# | Search | $\mathcal{O}(\log n)$ | $\mathcal{O}(n)$ |
# | Insert | $\mathcal{O}(\log n)$ | $\mathcal{O}(n)$ |
# | Delete | $\mathcal{O}(\log n)$ | $\mathcal{O}(n)$ |
# | Traverse | $\mathcal{O}(n)$ | $\mathcal{O}(n)$ |
#
# Now, looking at these costs, we see that there is a huge difference between a balanced tree, which generally has a scaling of $\mathcal{O}(\log n)$ and an unbalanced tree, which has a scaling of $\mathcal{O}(n)$. This is a big difference because a logarithmic growth is *much* slower than a linear growth.
#
# Put another way, for binary search trees to perform optimally, they have to be balanced. We will return to this point later, to show how we can ensure trees are balanced.
# ## Binary Search Tree Sort
#
# Now that we have implemented a BST, and analyzed its behavior, let us see a use case of a binary search tree—sorting data.
#
# Recall that when we printed the contents of our tree, it came out in sorted order, a natural consequence of the inorder traveersal we did. So if we have an unsorted list of numbers, we can effectively sort it by loading them into a BST, and reading them out again! This might sound like a horribly inefficient way to do things, but it turns out its actually quite efficient!
#
# Because our sorting is based on the binary search tree structure, we can refer to it as a binary search tree sort, or a BST sort for short.
#
# #### Implementing BST sort
# The first thing we want to to is add a method to our `BinarySearchTree` class to get the numbers stored in it, in an in-order output other than printing. We could for example add a method to read out the data stored in it as a vector:
# ```C++
# public:
# vector<int> get_vector() {
# /*Return all elements of tree in order as vector */
# vector<int> numbers;
# add_values(root, numbers);
# return numbers;
# }
#
# private:
# void add_values(Node* subroot, vector<int>& numbers) {
# // Add all keys in subtree to given vector
# if (subroot == nullptr) {
# return;
# }
#
# add_values(subroot->left, numbers);
# numbers.push_back(subroot->key);
# add_values(subroot->right, numbers);
# }
# ```
# This algorithm is exactly the same as our print method implemented earlier. We do in-order traversal of the tree. The only difference is that now we add the data of each node to the vector, instead of printing it out.
#
# With our `get_vector` implemented, we can now create a stand-alone function that sorts a list of numbers
# ***
# ```C++
# vector<int> bst_sort(vector<int> input) {
# BinarySearchTree bst(input);
# return bst.get_vector();
# }
# ```
# ***
#
# #### Cost of BST Sort
#
# What is the cost of our algorithm? Say we want to sort a list of $n$ numbers. To sort them, we do two steps:
# 1. Insert the $n$ elements into the tree
# 2. Traverse the tree to append the sorted numbers to a vector
#
# The first step is $n$ insertions into the BST, and in the average case, a single insertion costs $\mathcal{O}(\log n)$. The total cost of doing all the $n$ insertions is thus
# $$n \cdot \mathcal{O}(\log n) = \mathcal{O}(n\log n).$$
#
# The second step is doing an in-order traversal, in which case each node is visited exactly once, this means that the second step must be $\mathcal{O}(n)$.
#
# Adding the two steps together gives:
# $$\mathcal{O}(n\log n) + \mathcal{O}(n) = \mathcal{O}(n\log n).$$
#
# Recall from the previous lecture, where we discussed sorting algorithms, that having a cost of $\mathcal{O}(n\log n)$ as an average cost of a sorting algorithm is actually really good, and theoretically it cannot get any better! Thus, simply by creating a binary search tree, we have found a sorting algorithm that scales well, much better than both bubble sort and selection sort.
#
# #### What about the Worst case?
#
# In our analysis, we used the average case of $\mathcal{O}(\log n)$ for insertions to find the cost of inserting the elements into the tree. But, what if the tree becomes unbalanced while inserting? In that case, the cost of an insertion becomes $\mathcal{O}(n)$ per insertion, much like the linked list. And so the total cost of inserting $n$ elements becomes $n\cdot\mathcal{O}(n) = \mathcal{O}(n^2)$. This also means that our whole sorting algorithm becomes $\mathcal{O}(n^2)$, the same as bubble sort and selection sort.
#
# The trend that an unbalanced tree will perform poorly is starting to become a trend in this lecture. But for binary tree sorting especially, it turns out to become quite paradoxical. Recall from our example of the "perfectly" unbalanced tree, that we inserted the elements in sorted order into the tree, and this creates an unbalanced tree. In fact, our assumption of a balanced tree in the average case assumes the input data to be randomly ordered. This means that our binary search tree sort actually performs *best* on really well shuffled data, while if you hand it a sorted list, then it performs horribly.
# ## Self Balancing Trees
#
# The main problem we keep meeting with the binary search tree data structure is that it can become unbalanced if the inserts into the tree come in nearly sorted or sorted order. However, this problem can be fixed by making the tree *self-balance*. Such self-balancing trees are trees that act like normal binary search trees, but they also self-monitor. If we would insert or delete a node that would cause things to become unbalanced, they will shift their nodes around to correct this. Much like the "resizing" of dynamic arrays, this operation occurs completely hidden from the users view, and is only carried out when needed.
#
# The first self-balancing data structure was the AVL tree, which is just a specialized binary search tree. It is named after its inventor Adelson, Velskii and Landis. Other self-balancing trees have been invented since, for example splay trees, but AVL trees are still one of the simplest to implement and sees a lot of use. They published their data structre in the 1962 paper *An algorithm for the organization of information*. While self-balancing trees were a brand new concept in the sixties, today, almost any real-word use of binary search trees will be self-balancing, to ensure their performance.
#
# The idea behind AVL trees is fairly simple. We just add an additional step after inserting and deleting nodes, that checks if the tree is still balanced after the operation. It it isn't, we take the time to balance it out there and then. Because the balancing happens after each insertion or deletion, the balancing itself is still fairly easy to carry out. The [Wikipedia article on AVL trees](https://en.wikipedia.org/wiki/AVL_tree) shows a gif of this process, we'll link it below:
# <img src="fig/AVL_Tree_Example.gif">
# <center><b>Source:</b> Created by <a href="https://commons.wikimedia.org/wiki/File:AVL_Tree_Example.gif"><NAME></a> under a <a href"https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0 license</a>.</center>
#
# Implementing AVL trees is actually not that tricky, we could take the BST class we made, and just add a `self_balance` method to it, and we would be done. However, we have covered *a lot* on BSTs already, so we will skip this for now. If you are curious about AVL trees and want to implement the self-balancing aspect on your own, go for it! In that case, this [MIT 6.006 Lecture on AVL trees](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-6-avl-trees-avl-sort/) could be very helpful (the full lecture is about 50 minutes but also contains some review about BSTs).
# ### BST Sort with self-balancing trees
#
# If we had implemented a self-balancing tree, we would guarantee the performance of $\mathcal{O}(\log n)$ insertions, and followingly guaranteed a sorting algorithm of $\mathcal{O}(n\log n)$, also in the worst case. However, as we need to insert all $n$ elements, and write them out again, the best case is also $\mathcal{O}(n\log n)$. And so for "sorting" already sorted lists, bubble sort beats our BST sort.
#
# Looking back to the [Wikipedia Article on Sorting Algorithms](https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms). We see that the Binary Tree Sort entry indeed has a performance of $\mathcal{O}(n\log n)$ in the best, average and worst case. What it doesn't have good performance on however, is *memory*. Because, if we want to sort a list of numbers. Then doing BST sort on them, we have to first create a complete tree as well, this means we basically use twice the memory. If we are sorting extremely large lists, we do not want to do this, and we would much rather choose an algorithm that sorts in-place, so no extra memory is needed. Quicksort for example, does this.
#
# If you have a list of numbers you want to sort, BST sort isn't necessarily the best way to go about it. But if you need to store data, and often want to access it in a sorted manner, then storing it in a BST is probably better than a list. As we learned last week, appending elements to a list is $\mathcal{O}(1)$, but if you want to ensure it is sorted, this will cost you! For a BST, you pay the slightly higher price of $\mathcal{O}(\log n)$ for the insertion, but you don't have to sort it, you get that for free!
#
#
#
#
#
#
#
#
# ## Indexing Binary Search Trees
#
# One final thing to discuss before leaving BSTs and data structures behind for this time: indexing. So far, we have not discussed indexing a binary search tree, or implemented the `operator[]` method. Now, you might think we haven't done this, because the BST doesn't store data in a *sequence*. And while it is true that the BST doesn't store things in a sequence in the sense that it doesn't remember its insertion order, it is still stores $n$ elements in a given order, namely: sorted order. It is therefore possible to index elements by their position in the sorted order.
#
# To implement this, the most intuitive approach would probably be to simply do in-order traversal, like we for example do with printing, untill we have iterated through $i$ elements, in which case we can return the element at the correct index. This would work well, but would require traversing over $\mathcal{O}(i)$ steps, and so give a similar performance to indexing a linked list, i.e., $\mathcal{O}(n)$, a fairly bad scaling.
#
# However, there is another approach we can take if we want to implement indexing. In our `BinarySearchTree` class, we have kept count of the number of elements stored in the complete tree, however, a subtree doesn't know how many elements it has. We can change this by moving the `count` variable into each node. Thus, `root.count` would be the number of elements in the entire tree, but any subnode would also know how many elements there were in its own subtree.
#
# With this knowledge implemented at each node, and ensuring that we update the count of each node at each insertion and removal, an easy task with the recursive implementation, we could implement indexing by figuring if we had to follow the left or right branch at each node. For example, if the left branch contains a total of 10 nodes, and are trying to reach index 14, we would follow the right branch. This algorithm could thus only move down in the tree, unlike our traversal solution, and so the performance would be $\mathcal{O}(\log n)$.
#
# Thus, indexing a BST costs $\mathcal{O}(\log n)$, which is better than for a linked list, which was $\mathcal{O}(n)$, but worse than for dynamic arrays, where it is $\mathcal{O}(1)$. However, do remember that indexing means different things for the different structures. For the lists, it is getting the $i$'th element, based on insertion order. While for a BST, it means getting the $i$'th element in the sorted list, for example the $i$'th smallest element for a list of numbers.
#
#
#
# ## Wrapping up on Data Structures and Algorithms
#
# To wrap up our discussion on data structures in IN1910, let us list the analysis we did on our different data structures
#
# | Operation | Array | Dynamic Array | Linked List | Binary Search Tree$^{**}$ |
# |---------------------|------------------|--------------------|------------------|--------------------|
# | Indexing | $\mathcal{O}(1)$ | $\mathcal{O}(1)$ | $\mathcal{O}(n)$ | $\mathcal{O}(\log n)$ |
# | Insert at beginning | - | $\mathcal{O}(n)$ | $\mathcal{O}(1)$ | $\mathcal{O}(\log n)$ |
# | Insert at end | - | $\mathcal{O}(1)^*$ | $\mathcal{O}(1)$ | $\mathcal{O}(\log n)$ |
# | Insert in middle | - | $\mathcal{O}(n)$ | $\mathcal{O}(n)^{***}$ | $\mathcal{O}(\log n)$ |
# | Search | $\mathcal{O}(n)$ | $\mathcal{O}(n)$ | $\mathcal{O}(n)$ | $\mathcal{O}(\log n)$ |
#
# \*) Amortized/averaged cost \*\*) assuming balanced binary tree, also note that insertion is a single method on the BST, as the concept of "position" in the tree is different. \*\*\*) Insertion itself is $\mathcal{O}(1)$, but indexing into the list is $\mathcal{O}(n)$.
| book/docs/lectures/cpp/binary_search_trees_2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
import numpy as np
import tensorflow as tf
from data_utils import load_CIFAR10
#Load data
cifar10_dir = 'Dataset/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
#Display data dimensions
print 'Training data shape: ', X_train.shape
print 'Training labels shape: ', y_train.shape
print 'Test data shape: ', X_test.shape
print 'Test labels shape: ', y_test.shape
# Reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
print X_train.shape, X_test.shape
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=3072)]
# Define the classifier
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
hidden_units=[100, 200, 100],
n_classes=10,
model_dir="/tmp/iris_model")
# Define the training inputs
def get_train_inputs():
x = tf.constant(X_train)
y = tf.constant(y_train)
return x, y
# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)
| NeuralNetwork_Tensorflow.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # WUM
# ## Praca domowa nr 2
# ## Autor: <NAME>
# # Część 0
# # Biblioteki oraz załadowanie danych
import pandas as pd
import numpy as np
import sklearn
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
data = pd.read_csv('https://www.dropbox.com/s/360xhh2d9lnaek3/allegro-api-transactions.csv?dl=1')
data.head(3)
data.info()
# # Część 1
#
# # Kodowanie zmiennych kategorycznych
# #### Unikalne wartości
len(data['it_location'].unique())
len(data['it_location'].str.lower().unique())
# #### Dlaczego *target encoding* ma przewagę nad *OneHotEncoding*?
# Dla *OneHotEncodingu* zostałoby stworzone ponad dziesięć tysięcy nowy kolumn. W przypadku *Target Encodingu* jest tworzona tylko jedna dodatkowa kolumna. Na pewno jest to znaczące gdy mamy aż tak dużo unikalnych wartości
# ## Biblioteki
from category_encoders import TargetEncoder
# ## *Target encoding* zmiennej *it_location*
data['it_location'] = data['it_location'].str.lower()
data['it_location_en'] = TargetEncoder().fit_transform(data.it_location, data.price)
data[['item_id', 'it_location', 'it_location_en', 'price']].sample(4)
# ## Enkodowanie dla *main_category*
# ### Biblioteki
from category_encoders import BinaryEncoder
from category_encoders import BaseNEncoder
from sklearn.preprocessing import OneHotEncoder
# ### Zapoznanie z *main_category*
data['main_category'].unique()
len(data['main_category'].unique()) # lub .nunique() -> number of unique
# ### One-hot encoding
# ##### 1. sposób
data_out = pd.get_dummies(data, prefix=['main_cat'], columns=['main_category'])
data_out.sample(2)
# ##### 2. sposób
# +
data_oe = data.copy()
oe = OneHotEncoder(sparse=False)
data_out = oe.fit_transform(data_oe[['main_category']])
data_out = pd.DataFrame(data=data_out)
data_out.columns = oe.get_feature_names(['main_category'])
data_out=pd.concat([data_out, data_oe], axis=1)
data_out.sample(2)
# -
# ### Binary encoder
# #### Wyjaśnienie
#
# Kolejne wartości binarne (0001 - 1, 0010 - 2, 0011 - 3 itd.). Do i-tej pozycji liczby binarnej jest tworzona kolumna (tyle kolumn ile potrzeba liczb do zapisu liczby kategorii). Ogranicza to liczbę kolumn (jest ich po prostu mniej).
data_out = BinaryEncoder().fit_transform(data['main_category'], data['price'])
data_out.head()
# #### Ważne
#
# Należy tu dodać te ramki do Dataframe - concatenate (join z indeksami) - anlogicznie jak w przypadku *OneHotEncoding*.
#
# #### Komentarz
#
# Liczba kolumn rośnie, ale nie tak wyraźnie jak w *OneHotEncoder*. Zmienne zostały poprawnie zakodowane (jak opisane w Wyjaśnieniu).
# ### BaseN
# #### Wyjaśnienie
#
# Dla:
# 1. n = 1 to OneHotEncoding
# 2. n = 2 to BinaryEncoding
# 3. n > 2 to już enkodowanie o podstawie N
#
# Po prostu zmienne z enkodowane w danym sposobie zapisu liczby (znane są systemy dziesiątkowe, ósemkowe itd.)
# +
data_baseN = data.copy()
data_out = BaseNEncoder(base=8).fit_transform(data_baseN['main_category'])
data_out.head(10)
# -
# #### Ważne
#
# Należy tu dodać te ramki do Dataframe - concatenate (join z indeksami) - anlogicznie jak w przypadku *OneHotEncoding*.
#
# #### Komentarz
#
# Liczba kolumn rośnie, ale nie tak wyraźnie jak w *OneHotEncoder* (jest to zależne od N). Zmienne zostały poprawnie zakodowane (jak opisane w Wyjaśnieniu).
# # Cześć 2
#
# # Imputacja danych
# ## Losowe usunięcie (dodanie *np.NaN*) 10% wartości ze zmiennej *it_seller_rating*
from pandas import DataFrame
from typing import List
imputed_data = data[['it_seller_rating', 'it_quantity', 'price']]
imputed_data.head(3)
imputed_data.isnull().mean()
def make_NaN(data:DataFrame, ratio: float, cols: List) -> DataFrame:
imputed_data = data[['it_seller_rating', 'it_quantity', 'price']]
nan_idx = imputed_data.sample(frac=ratio).index
for i in cols:
imputed_data[i].iloc[nan_idx] = np.NaN
return imputed_data
make_NaN(data=data, ratio=0.1).isnull().mean()
# ## Nearest neighbors imputation
from sklearn.impute import KNNImputer
# ### Zbyt wolne - za dużo jest danych
#
# Z tego powodu skorzystałem z drugiego sposoby (opis niżej)
# ## Multivariate feature imputation
# #### Biblioteki
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.metrics import mean_squared_error
import statistics
# ### Brak danych w kolumnie *it_seller_rating*
# #### Obliczenie błędów
# +
rmse_error_list_1 = []
for i in range(10):
# zrobienie z danych 10% NaN
data_in = make_NaN(data=data, ratio=0.1, cols=['it_seller_rating'])
# imputacja
imp = IterativeImputer(max_iter=20)
data_out = imp.fit_transform(data_in[['it_seller_rating', 'it_quantity', 'price']])
df = pd.DataFrame(data=data_out, columns=['it_seller_rating', 'it_quantity', 'price'])
rmse_error_list_1.append(mean_squared_error(data[['it_seller_rating', 'it_quantity', 'price']], df, squared=False))
print(rmse_error_list_1)
print('==========')
print(data_in.isnull().mean())
print(df.isnull().mean())
# -
# #### Odchylenie standardowe
std_dev = statistics.stdev(rmse_error_list_1)
print(std_dev)
# ### Brak danych w kolumnach *it_seller rating* oraz *it_quantity*
# #### Obliczenie błędów
# +
rmse_error_list_2 = []
for i in range(10):
# zrobienie z danych 10% NaN
data_in = make_NaN(data=data, ratio=0.1, cols=['it_seller_rating', 'it_quantity'])
# imputacja
imp = IterativeImputer(max_iter=20)
data_out = imp.fit_transform(data_in[['it_seller_rating', 'it_quantity', 'price']])
df = pd.DataFrame(data=data_out, columns=['it_seller_rating', 'it_quantity', 'price'])
rmse_error_list_2.append(mean_squared_error(data[['it_seller_rating', 'it_quantity', 'price']], df, squared=False))
print(rmse_error_list_2)
print('==========')
print(data_in.isnull().mean())
print(df.isnull().mean())
# -
# #### Odchylenie standardowe
std_dev = statistics.stdev(rmse_error_list_2)
print(std_dev)
# ### Wykres
# +
data_to_plot = pd.DataFrame({"it_seller rating": rmse_error_list_1, "it_seller rating oraz it_quantity": rmse_error_list_2})
data_to_plot.plot()
# -
# #### Wnioski
#
# Błąd jest większy, gdy imputujemy do dwóch kolumn co wydaje się dość oczywiste (większe rozbieżności od normy). Odchylenie standardowe dla dwóch przypadków jest bardzo zbliżone.
| Prace_domowe/Praca_domowa2/Grupa1/SlapekMariusz/pd2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Analyzing results from hyperparameter tuning
# In this example, we will go through how you can use Ray AIR to run a distributed hyperparameter experiment to find optimal hyperparameters for an XGBoost model.
#
# What we'll cover:
# - How to load data from an Sklearn example dataset
# - How to initialize an XGBoost trainer
# - How to define a search space for regular XGBoost parameters and for data preprocessors
# - How to fetch the best obtained result from the tuning run
# - How to fetch a dataframe to do further analysis on the results
# We'll use the [Covertype dataset](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_covtype.html#sklearn-datasets-fetch-covtype) provided from sklearn to train a multiclass classification task using XGBoost.
#
# In this dataset, we try to predict the forst cover type (e.g. "lodgehole pine") from cartographic variables, like the distance to the closest road, or the hillshade at different times of the day. The features are binary, discrete and continuous and thus well suited for a decision-tree based classification task.
#
# You can find more information about the dataset [on the dataset homepage](https://archive.ics.uci.edu/ml/datasets/Covertype).
#
# We will train XGBoost models on this dataset. Because model training performance can be influenced by hyperparameter choices, we will generate several different configurations and train them in parallel. Notably each of these trials will itself start a distributed training job to speed up training. All of this happens automatically within Ray AIR.
#
# First, let's make sure we have all dependencies installed:
# !pip install -q "ray[all]" sklearn
# Then we can start with some imports.
# +
import pandas as pd
from sklearn.datasets import fetch_covtype
import ray
from ray import tune
from ray.air import RunConfig
from ray.air.train.integrations.xgboost import XGBoostTrainer
from ray.tune.tune_config import TuneConfig
from ray.tune.tuner import Tuner
# -
# We'll define a utility function to create a Ray Dataset from the Sklearn dataset. We expect the target column to be in the dataframe, so we'll add it to the dataframe manually.
# +
def get_training_data() -> ray.data.Dataset:
data_raw = fetch_covtype()
df = pd.DataFrame(data_raw["data"], columns=data_raw["feature_names"])
df["target"] = data_raw["target"]
return ray.data.from_pandas(df)
train_dataset = get_training_data()
# -
# Let's take a look at the schema here:
print(train_dataset)
# Since we'll be training a multiclass prediction model, we have to pass some information to XGBoost. For instance, XGBoost expects us to provide the number of classes, and multiclass-enabled evaluation metrices.
#
# For a good overview of commonly used hyperparameters, see [our tutorial in the docs](https://docs.ray.io/en/latest/tune/examples/tune-xgboost.html#xgboost-hyperparameters).
# XGBoost specific params
params = {
"tree_method": "approx",
"objective": "multi:softmax",
"eval_metric": ["mlogloss", "merror"],
"num_class": 8,
"min_child_weight": 2
}
# With these parameters in place, we'll create a Ray AIR `XGBoostTrainer`.
#
# Note a few things here. First, we pass in a `scaling_config` to configure the distributed training behavior of each individual XGBoost training job. Here, we want to distribute training across 2 workers.
#
# The `label_column` specifies which columns in the dataset contains the target values. `params` are the XGBoost training params defined above - we can tune these later! The `datasets` dict contains the dataset we would like to train on. Lastly, we pass the number of boosting rounds to XGBoost.
trainer = XGBoostTrainer(
scaling_config={"num_workers": 2},
label_column="target",
params=params,
datasets={"train": train_dataset},
num_boost_round=10,
)
# We can now create the Tuner with a search space to override some of the default parameters in the XGBoost trainer.
#
# Here, we just want to the XGBoost `max_depth` and `min_child_weights` parameters. Note that we specifically specified `min_child_weight=2` in the default XGBoost trainer - this value will be overwritten during tuning.
#
# We configure Tune to minimize the `train-mlogloss` metric. In random search, this doesn't affect the evaluated configurations, but it will affect our default results fetching for analysis later.
#
# By the way, the name `train-mlogloss` is provided by the XGBoost library - `train` is the name of the dataset and `mlogloss` is the metric we passed in the XGBoost `params` above. Trainables can report any number of results (in this case we report 2), but most search algorithms only act on one of them - here we chose the `mlogloss`.
tuner = Tuner(
trainer,
run_config=RunConfig(verbose=1),
param_space={
"params": {
"max_depth": tune.randint(2, 8),
"min_child_weight": tune.randint(1, 10),
},
},
tune_config=TuneConfig(num_samples=8, metric="train-mlogloss", mode="min"),
)
# Let's run the tuning. This will take a few minutes to complete.
results = tuner.fit()
# Now that we obtained the results, we can analyze them. For instance, we can fetch the best observed result according to the configured `metric` and `mode` and print it:
# +
# This will fetch the best result according to the `metric` and `mode` specified
# in the `TuneConfig` above:
best_result = results.get_best_result()
print("Best result error rate", best_result.metrics["train-merror"])
# -
# For more sophisticated analysis, we can get a pandas dataframe with all trial results:
df = results.get_dataframe()
print(df.columns)
# As an example, let's group the results per `min_child_weight` parameter and fetch the minimal obtained values:
# +
groups = df.groupby("config/params/min_child_weight")
mins = groups.min()
for min_child_weight, row in mins.iterrows():
print("Min child weight", min_child_weight, "error", row["train-merror"], "logloss", row["train-mlogloss"])
# -
# As you can see in our example run, the min child weight of `2` showed the best prediction accuracy with `0.196929`. That's the same as `results.get_best_result()` gave us!
# The `results.get_dataframe()` returns the last reported results per trial. If you want to obtain the best _ever_ observed results, you can pass the `filter_metric` and `filter_mode` arguments to `results.get_dataframe()`. In our example, we'll filter the minimum _ever_ observed `train-merror` for each trial:
df_min_error = results.get_dataframe(filter_metric="train-merror", filter_mode="min")
df_min_error["train-merror"]
# The best ever observed `train-merror` is `0.196929`, the same as the minimum error in our grouped results. This is expected, as the classification error in XGBoost usually goes down over time - meaning our last results are usually the best results.
# And that's how you analyze your hyperparameter tuning results. If you would like to have access to more analytics, please feel free to file a feature request e.g. [as a Github issue](https://github.com/ray-project/ray/issues) or on our [Discuss platform](https://discuss.ray.io/)!
| doc/source/ray-air/examples/analyze_tuning_results.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
### Train an RL agent using DQN architecture in a Unity environment (bananaModel)
# -
from unityagents import UnityEnvironment
import numpy as np
import matplotlib.pyplot as plt
from collections import deque, defaultdict
import time
import sys
from tqdm import tqdm
from dqnetwork import DQNetwork
from agent import Agent
import torch
import torch.nn as nn
import torch.nn.functional as F
env = UnityEnvironment(file_name="../unity/Banana.app")
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# ### Action space:
# - `0` - walk forward
# - `1` - walk backward
# - `2` - turn left
# - `3` - turn right
#
# ### State space:
# - `37` - dimensions.
# - some samples include the agent's velocity.
# - ray-based perception in the forward direction of the agent.
#
# ### Reward:
#
# - `+1` - Yellow Banana collected.
# - `-1` - Blue Banana collected.
# +
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector_observations[0]
print('States look like:', state)
state_size = len(state)
print('States have length:', state_size)
# -
# ### Implement DQN Agent
model = DQNetwork()
agent = Agent()
scores = [] # List with all scores per episode
score_d = deque(maxlen=100) #Last 100 episodes
NUM_EPISODES = 1000
ENV_SOLVED = 13 #How many Bananas must be collected to succeed?
# ## Train Agent
def get_epsilon_i(num_episode, epsilon_min = 0.01):
"""Simple Epsilon Decay over total number of episodes. Stochastic in nature when summed over"""
epsilon = 1.0/num_episode
return max(epsilon, epsilon_min)
for epoch in range(1, NUM_EPISODES+1):
env_info = env.reset(train_mode=True)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
i = 0
while True:
i += 1
epsilon = get_epsilon_i(epoch)
action = agent.get_action(state, epsilon) # select an action
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
transition = (state, action, reward, next_state, done) #set transition
agent.step(transition) # Train the model
score += reward # update the score
state = next_state # roll over the state to next time step
if done: # exit loop if episode finished
break
scores.append(score)
score_d.append(score)
if(epoch%50 == 0):#Print stats every 50 episodes
print(f"{epoch}: Score: {score}; Last 100 mean: {np.mean(score_d)}; Epsilon: {epsilon}")
if(np.mean(score_d) >= ENV_SOLVED):
print(f"Solved at episode {epoch} with score: {score}")
break
plt.plot(scores)
plt.xlabel("Episode #")
plt.ylabel("Score")
plt.show()
#Calculate rolling average
import pandas as pd
df = pd.DataFrame(scores)
df = df.rolling(window=100).mean()
df.plot()
plt.xlabel("Episode #")
plt.ylabel("Score")
plt.title("Rolling Score over episode number")
plt.legend()
plt.show()
# ## Test an Agent
import time
time.sleep(1)#human is slow
# +
env_info = env.reset(train_mode=False)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
i = 0
solved_at = False
while True:
i+=1
action = agent.get_action(state, epsilon) # select an action
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
score += reward # update the score
state = next_state # roll over the state to next time step
if(score >= ENV_SOLVED and solved_at == False):
solved_at = True
print(f"Solved at iteration: {i}")
if done: # exit loop if episode finished
break
print("Score: {}".format(score))
print("iterations:",i)
# -
# # Save model
#Save model:
torch.save(agent.qnetwork_local.state_dict(), '../model/local_model.pth')
#---OPTIONAL---
#Load model:
import os
# load the weights from file
agent.qnetwork_local.load_state_dict(torch.load( os.path.join('../model/local_model.pth'), map_location='cpu'))
agent.qnetwork_local.eval()
# ### The End!
| DQN/code/Navigation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#Part1_test
input_data1=open('input_D3_test.txt','r')
input_numbers=input_data1.read().strip().split('\n')
input_data1.close()
print(input_numbers)
gamma_rate=[]
epsilon_rate=[]
#Gamma
for column in range(0,5):
pos0_0=0
pos0_1=0
for i in input_numbers:
if i[column]=='0':
pos0_0+=1
else:
pos0_1+=1
print(pos0_0,pos0_1)
if pos0_0>pos0_1:
gamma_rate.append("0")
else:
gamma_rate.append('1')
gamma_rate =''.join(gamma_rate)
print(gamma_rate)
gamma_rate= int(gamma_rate, 2)
print(gamma_rate)
#Epsilon
for column in range(0,5):
pos0_0=0
pos0_1=0
for i in input_numbers:
if i[column]=='0':
pos0_0+=1
else:
pos0_1+=1
print(pos0_0,pos0_1)
if pos0_0>pos0_1:
epsilon_rate.append("1")
else:
epsilon_rate.append('0')
epsilon_rate =''.join(epsilon_rate)
print(epsilon_rate)
epsilon_rate= int(epsilon_rate, 2)
print(epsilon_rate)
power=gamma_rate*epsilon_rate
print('power:', power)
# +
#Part1
input_data1=open('input_D3.txt','r')
input_numbers=input_data1.read().strip().split('\n')
input_data1.close()
#print(input_numbers)
gamma_rate=[]
epsilon_rate=[]
#Gamma
for column in range(0,12):
pos0_0=0
pos0_1=0
for i in input_numbers:
if i[column]=='0':
pos0_0+=1
else:
pos0_1+=1
#print(pos0_0,pos0_1)
if pos0_0>pos0_1:
gamma_rate.append("0")
else:
gamma_rate.append('1')
gamma_rate =''.join(gamma_rate)
#print(gamma_rate)
gamma_rate= int(gamma_rate, 2)
print('gamma_rate:',gamma_rate)
#Epsilon
for column in range(0,12):
pos0_0=0
pos0_1=0
for i in input_numbers:
if i[column]=='0':
pos0_0+=1
else:
pos0_1+=1
#print(pos0_0,pos0_1)
if pos0_0>pos0_1:
epsilon_rate.append("1")
else:
epsilon_rate.append('0')
epsilon_rate =''.join(epsilon_rate)
#print(epsilon_rate)
epsilon_rate= int(epsilon_rate, 2)
print('epsilon_rate:',epsilon_rate)
power=gamma_rate*epsilon_rate
print('power:', power)
| Day3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/mkmritunjay/machineLearning/blob/master/ANNClassifier.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="aK-wmTVKoSaU" colab_type="text"
# # Neural Networks
#
# Neural Networks are a machine learning framework that attempts to mimic the learning pattern of natural biological neural networks. Biological neural networks have interconnected neurons with dendrites that receive inputs, then based on these inputs they produce an output signal through an axon to another neuron. We will try to mimic this process through the use of Artificial Neural Networks (ANN), which we will just refer to as neural networks from now on. The process of creating a neural network begins with the most basic form, a single perceptron.
#
# ---
# The Perceptron
#
# Let's start our discussion by talking about the Perceptron! A perceptron has one or more inputs, a bias, an activation function, and a single output. The perceptron receives inputs, multiplies them by some weight, and then passes them into an activation function to produce an output. There are many possible activation functions to choose from, such as the logistic function, a trigonometric function, a step function etc. We also make sure to add a bias to the perceptron, this avoids issues where all inputs could be equal to zero (meaning no multiplicative weight would have an effect).
#
#
# ---
# Once we have the output we can compare it to a known label and adjust the weights accordingly (the weights usually start off with random initialization values). We keep repeating this process until we have reached a maximum number of allowed iterations, or an acceptable error rate.
#
# To create a neural network, we simply begin to add layers of perceptrons together, creating a multi-layer perceptron model of a neural network. You'll have an input layer which directly takes in your feature inputs and an output layer which will create the resulting outputs. Any layers in between are known as hidden layers because they don't directly "see" the feature inputs or outputs.
#
# + [markdown] id="GBUse5bco5Lg" colab_type="text"
# ---
# Data
#
# We'll use SciKit Learn's built in Breast Cancer Data Set which has several features of tumors with a labeled class indicating whether the tumor was Malignant or Benign. We will try to create a neural network model that can take in these features and attempt to predict malignant or benign labels for tumors it has not seen before. Let's go ahead and start by getting the data!
# + id="09St20alp84B" colab_type="code" colab={}
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report,confusion_matrix
# + id="DSTE3mymoLee" colab_type="code" colab={}
# This object is like a dictionary, it contains a description of the data and the features and targets:
cancer = load_breast_cancer()
# + id="WV4R8i5HpJHW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c79ad2ce-dcea-4930-879e-e263f873952e"
cancer.keys()
# + id="4HLZNT4LpOmG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c1201624-e22d-48ec-b71a-7a0a154d1a15"
cancer['data'].shape
# + id="Qz7S6C09pTvi" colab_type="code" colab={}
X = cancer['data']
Y = cancer['target']
# + [markdown] id="okOZLQZRpfTQ" colab_type="text"
# ### Train Test Split
# + id="95ooBUZApecY" colab_type="code" colab={}
X_train, X_test, y_train, y_test = train_test_split(X, Y)
# + [markdown] id="X12PkI_cqXFa" colab_type="text"
# ### Data Preprocessing
#
# The neural network may have difficulty converging before the maximum number of iterations allowed if the data is not normalized. Multi-layer Perceptron is sensitive to feature scaling, so it is highly recommended to scale your data. Note that you must apply the same scaling to the test set for meaningful results. There are a lot of different methods for normalization of data, we will use the built-in StandardScaler for standardization.
# + id="8w-_8eREqP_u" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="d6bba499-551f-4499-99ae-bd9bdff37b1a"
scaler = StandardScaler()
# Fit only to the training data
scaler.fit(X_train)
# + id="P2O1wnfOqj5_" colab_type="code" colab={}
# Now apply the transformations to the data:
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# + [markdown] id="Yjov3FagrSaX" colab_type="text"
# ### Model Building
# + [markdown] id="vilxU6VOqxMe" colab_type="text"
# Now it's time to train our model. SciKit Learn makes this incredibly easy, by using estimator objects. In this case we will import our estimator (the Multi-Layer Perceptron Classifier model) from the neural_network library of SciKit-Learn!
#
# **from sklearn.neural_network import MLPClassifier**
#
# Next we create an instance of the model, there are a lot of parameters you can choose to define and customize here, we will only define the hidden_layer_sizes. For this parameter you pass in a tuple consisting of the number of neurons you want at each layer, where the nth entry in the tuple represents the number of neurons in the nth layer of the MLP model. There are many ways to choose these numbers, but for simplicity we will choose 3 layers with the same number of neurons as there are features in our data set.
# + id="7bVq_vPjqm8T" colab_type="code" colab={}
mlp = MLPClassifier(hidden_layer_sizes=(30,30,30))
# + [markdown] id="xMNkr-G-rJqY" colab_type="text"
# Now that the model has been made we can fit the training data to our model, remember that this data has already been processed and scaled.
# + id="HKYTiAlerG5o" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 153} outputId="d0b80ba3-7db6-4322-bb6c-2a88d0ad04fd"
mlp.fit(X_train,y_train)
# + [markdown] id="VOA0XgrIrZ5w" colab_type="text"
# ### Prediction and evaluation
#
# Now that we have a model it's time to use it to get predictions.
#
# We can do this simply with the predict() method off of our fitted model.
# + id="LgzYdWc3rVvL" colab_type="code" colab={}
predictions = mlp.predict(X_test)
# + id="WeZGuFuArsEw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 170} outputId="dafac788-497d-4987-f28d-84f41f8218a9"
print(classification_report(y_test,predictions))
# + [markdown] id="KbYW-DpBsAse" colab_type="text"
# With a 98% accuracy rate (as well as 98% precision and recall) this is pretty good considering how few lines of code we had to write. The downside however to using a Multi-Layer Preceptron model is how difficult it is to interpret the model itself. The weights and biases won't be easily interpretable in relation to which features are important to the model itself.
#
# However, if you do want to extract the MLP weights and biases after training your model, you use its public attributes coefs_ and intercepts_.
#
# coefs_ is a list of weight matrices, where weight matrix at index i represents the weights between layer i and layer i+1.
#
# intercepts_ is a list of bias vectors, where the vector at index i represents the bias values added to layer i+1.
# + id="gfU3fkS_rulJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="703e0502-55ff-4da4-fccf-34bf6fc908a0"
len(mlp.coefs_)
# + id="wzLvZMTpsaDe" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="5a65ccd8-bc84-47b2-84eb-8caecb539ee6"
len(mlp.coefs_[0])
# + id="l7ndMYtqscJ4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="381d6717-c5d3-48dc-fdf4-dceca13f93bc"
len(mlp.intercepts_[0])
# + [markdown] id="HbtPUh2itsHQ" colab_type="text"
# # HR case study
#
# Let's look into one more data set and build an artificial neural network.
# We will use same data set that we used for bagging and boosting.
# + id="vS7YEg9jsf4u" colab_type="code" colab={}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
import sklearn.neural_network as nn
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report, confusion_matrix
url = 'https://raw.githubusercontent.com/mkmritunjay/machineLearning/master/HR_comma_sep.csv'
# + id="5-gzA1pEuhiu" colab_type="code" colab={}
hr_df = pd.read_csv(url)
# + id="wmtsEnh7u9lA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 272} outputId="c17204b9-3482-40de-e35e-288e35a2a38d"
hr_df.info()
# + id="CscwvSkPvARY" colab_type="code" colab={}
# Encoding Categorical Features
numerical_features = ['satisfaction_level', 'last_evaluation', 'number_project',
'average_montly_hours', 'time_spend_company']
categorical_features = ['Work_accident','promotion_last_5years', 'department', 'salary']
# + id="0kledtFZvECd" colab_type="code" colab={}
# A utility function to create dummy variable
def create_dummies( df, colname ):
col_dummies = pd.get_dummies(df[colname], prefix=colname)
col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)
df = pd.concat([df, col_dummies], axis=1)
df.drop( colname, axis = 1, inplace = True )
return df
# + id="mhl1HuCQvGwi" colab_type="code" colab={}
for c_feature in categorical_features:
hr_df = create_dummies( hr_df, c_feature )
# + [markdown] id="K5K-V_mSveMA" colab_type="text"
# ### Train Test Split
# + id="d-J-da4nvL-7" colab_type="code" colab={}
feature_columns = hr_df.columns.difference( ['left'] )
# + id="LPnPAzc3viMd" colab_type="code" colab={}
train_X, test_X, train_y, test_y = train_test_split( hr_df[feature_columns],
hr_df['left'],
test_size = 0.2,
random_state = 42 )
# + id="nt9d862-vljE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="b3b2b971-d6cb-46bb-e3d4-6e459beea492"
scaler = StandardScaler()
# Fit only to the training data
scaler.fit(train_X)
# + id="QCiXJPPLvpQh" colab_type="code" colab={}
# Now apply the transformations to the data:
X_train = scaler.transform(train_X)
X_test = scaler.transform(test_X)
# + id="A9kYQCAvvtHf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="0de94dae-7334-42bc-f4a0-7da8d6aa90e7"
mlp = MLPClassifier(hidden_layer_sizes=(3,2), verbose=True)
mlp.fit(X_train,train_y)
# + id="nfzKDwNfvzmI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 408} outputId="34ef580f-b051-4a12-c183-801dd96668cd"
mlp.coefs_
# + id="JwkbK1bTv7_S" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="c8135155-cec9-435c-eb33-c807473896d5"
mlp.intercepts_
# + id="JpCx2upfv9xR" colab_type="code" colab={}
predictions = mlp.predict(X_test)
# + id="MsKc3IWzwEML" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="9af68df8-45e0-43eb-82b6-5efabacb6ad6"
print(confusion_matrix(test_y, predictions))
# + id="aSCC83PAwKmJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 170} outputId="6cf6f1bf-8125-4a97-c677-ce7e8549f5e9"
print(classification_report(test_y, predictions))
# + id="6Z4_qbRzwPgI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="fce4fd17-bda7-4cb8-e7c6-91eb9142650d"
print(len(mlp.coefs_))
print(len(mlp.coefs_[0]))
print(len(mlp.intercepts_[0]))
# + id="P26yVSxJwY0k" colab_type="code" colab={}
| ANNClassifier.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# # Data Containers, Lists, and Iterations
#
# 
# + [markdown] slideshow={"slide_type": "slide"}
# ## What you'll learn in this week's lesson (Learning Goals)
#
# - What a data structure is.
# - What is a Tuple, List, and Dictionary, their differences, and when to use them.
# - Mutability vs. Immutability.
# - Looping and Iterating using For and While Loops.
# - Finding items within a Data Structure.
# - Indexing and slicing.
# - Adding and removing elements.
# - Nesting, Copying, and Sorting elements.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Tuples
#
# - **Tuple:** A finite _ordered_ sequence of values.
# - Order is based on "insertion" (the order in which is was declared).
# - A comma (,) separated set of values.
# - Can contain any type of element (int, str, float, any objects)
# - Immutable. Order cannot change and elements cannot be added.
# - Strings are basically tuples but specifically for only characters.
# - **Iterable:** Capable of being iterated (looped) over.
# + slideshow={"slide_type": "subslide"}
# You create a tuple using comma separate elements
first_tuple = 1,'2', 3.0
print(first_tuple)
# + slideshow={"slide_type": "subslide"}
# It's common practice to surround the separated elements
# with ()
first_tuple = (1, '2', 3.0)
print(first_tuple)
# + slideshow={"slide_type": "subslide"}
# You can create an empty tuple, though this isn't very useful
empty_tuple = ()
print(empty_tuple)
print(type(empty_tuple))
# + slideshow={"slide_type": "subslide"}
# creating a single item tuple is a bit quirky. Remember that parenthesis
# DOES NOT create a tuple (except empty ones), but rather the comma.
single_item_tuple = (1)
print(single_item_tuple)
print(type(single_item_tuple))
# + slideshow={"slide_type": "subslide"}
# Here is the proper way to create a tuple.
single_item_tuple = (1,)
print(single_item_tuple)
print(type(single_item_tuple))
# + slideshow={"slide_type": "subslide"}
# Like int, str, and float, tuple have a constructor:
hello_tuple = tuple("Hello World")
print(hello_tuple)
# + slideshow={"slide_type": "subslide"}
# Similar to string, tuples have a length to them.
values = (1, 2, 3, 4, 5)
print(values)
print(len(values))
# + slideshow={"slide_type": "subslide"}
# And you can also index and slice into them
print(values[2:4])
print(values[1])
# + slideshow={"slide_type": "subslide"}
# They're also immutable like strings as well
values[2] = 6
# + slideshow={"slide_type": "subslide"}
# You can "unpack" tuples as well.
values = (1, '2', 3.0)
one, two, three = values
print(values)
print(one)
print(two)
print(three)
# + slideshow={"slide_type": "subslide"}
# You can check to see if a value is in a tuple.
3.0 in values
# + slideshow={"slide_type": "subslide"}
# you can find the first location of a value in the tuple using
# index
values.index(3.0)
# + slideshow={"slide_type": "subslide"}
# Finally, you can iterate over tuples
vowels = ('a', 'e', 'i', 'o', 'u')
for vowel in vowels:
print(vowel)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Loops
#
# 
#
# - **Loop:** A repeatable set of actions with a set of defined starting and closing actions.
# - **For Loop:** A type of loop that iterates over a sequence of objects.
# - **While Loop:** A type of loop that continually loops until a specific exit criteria is met.
# + [markdown] slideshow={"slide_type": "subslide"}
# ### While Loops
#
# - Uses the `while` keyword, followed by a test condition, ends with the colon (`:`).
# - Loop body contains the code to be repeated. This is indented by one indentation level.
# - Should be used when the sequences, or the number of loop operations isn't finite or known.
# - Infinite loops (no stopping) can be created.
# + slideshow={"slide_type": "subslide"}
i = 0
while i < len(vowels):
print(vowels[i])
i += 1
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Side-bar: Tabs vs. Spaces:
#
# 
# -
# - tabs or spaces can be used to mark indentation levels.
# - Python 3 will **not** allow mixture of the two.
# - PEP 8 (Python Standard guide) suggests 4 spaces (or tabs that render at 4 spaces)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Most Importantly, Don't let it ruin relationships:
# + slideshow={"slide_type": "-"}
from IPython.display import YouTubeVideo
YouTubeVideo('SsoOG6ZeyUI', width=800, height=400)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### The For Loop
#
# - Uses the `for` keyword followed by a membership expression and then finally the colon (`:`).
# - The loop body contains the code to be repeated. This is indented by one indentation level.
# - Should be used when iterating over known, finite sequences.
# + slideshow={"slide_type": "subslide"}
# To use the for loop
print(vowels)
for letter in vowels:
print(letter)
# + slideshow={"slide_type": "subslide"}
# the range built-in is a function that will return x sequential values
# where x is the max - 1 value you want starting at 0.
for i in range(10):
print(i)
# + slideshow={"slide_type": "subslide"}
# you can pass in two arguments where the first is the starting number,
# and the second is the max - 1 value you want.
for i in range(3, 10):
print(i)
# + slideshow={"slide_type": "subslide"}
# finally you can pass in three arguments where the first is the starting
# number, the second is the max - 1 value you want, and the third is the
# steps to take.
for i in range(2, 20, 2):
print(i)
# + slideshow={"slide_type": "subslide"}
# here's another example
for i in range(0, 100, 10):
print(i)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Nested Loops
#
# - You have the ability to nest loops within loops.
# - indentation is key here
# - Use caution when using nested loops, and try to limit them to as few as possible.
# + slideshow={"slide_type": "subslide"}
for i in range(5):
for j in range(5, 8):
print(f'i = {i}; j = {j}')
print('break!')
# + [markdown] slideshow={"slide_type": "subslide"}
# ### In-Class Exercise
#
# 1. Create a tuple named `pokemon` that holds the strings `'picachu'`, `'charmander'`, and `'bulbasaur'`.
# 1. Using index notation, `print()` the string that located at index 1 in `pokemon`
# 1. Unpack the values of `pokemon` into the following three new variables with names `starter1`, `starter2`, `starter3`.
# 1. Create a tuple using the `tuple()` built-in, that contains the letters of your name.
# 1. Check whether the character `i` is in your tuple representation of your name.
# 1. Write a `for` loop that prints out the integers 2 through 10, each on a new line, by using the `range()` function.
# 1. Use a `while` loop that prints out the integers 2 through 10.
# 1. Write a `for` loop that iterates over the string `'This is a simple string'` and prints each character.
# 1. Using a nested for loop, iterate over the following set `('this', 'is', 'a', 'simple', 'set')` and print each word, three times.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Lists
#
# 
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Lists
#
# - Is a sequence, just like a string or set.
# - created using square brackets and commas.
# - **mutable:** in place order and values can be changed.
# + slideshow={"slide_type": "subslide"}
# lists are created simply by wrapping muliple, comma separated objects with
# square brackets.
colors = ['red', 'yellow', 'green', 'blue']
print(colors)
print(type(colors))
# + slideshow={"slide_type": "subslide"}
# you can also use the list() builin on a string (or any other sequence)
# to create a list.
hello_list = list('hello')
print(hello_list)
# + slideshow={"slide_type": "subslide"}
# lists (like tuples), can have any type in object within, even other lists
random_list = ['hello', 1337, ['sub', 'list']]
print(random_list)
# + slideshow={"slide_type": "subslide"}
# Lists are iterable, meaning they can be looped over using a for loop
for element in random_list:
print(element)
# + slideshow={"slide_type": "subslide"}
# They're also mutable, meaning that changes can be made in-place
print(random_list)
random_list[2] = 'sublist'
print(random_list)
# + slideshow={"slide_type": "subslide"}
# lists can be sorted in place (be careful of mixing types with the list)
numbers = [3, 1, 19, -234]
print(numbers)
numbers.sort()
print(numbers)
# + slideshow={"slide_type": "subslide"}
# They can also be changed by adding elements to the list
numbers = []
for i in range(5):
numbers.append(i ** 2)
print(numbers)
# + slideshow={"slide_type": "subslide"}
# Elements within the list can be removed
num = numbers.pop()
print(num)
print(numbers)
# + slideshow={"slide_type": "subslide"}
# and put right back in
numbers.append(num)
print(num)
print(numbers)
# + slideshow={"slide_type": "subslide"}
# and again
numbers.append(num)
print(numbers)
# + slideshow={"slide_type": "subslide"}
# lists can be combined together using the + operator
list_one = list(range(3))
list_two = list(range(3, 6))
combo_list = list_one + list_two
print(list_one)
print(list_two)
print(combo_list)
# + slideshow={"slide_type": "subslide"}
# or one list can be combined with another list using the extend() method
print(combo_list)
combo_list.extend([10, 11, 12])
print(combo_list)
# + slideshow={"slide_type": "subslide"}
# lists can be indexed and sliced
numbers = list(range(10))
print(numbers)
print(numbers[8])
print(numbers[2:5])
# + slideshow={"slide_type": "subslide"}
# you calculate the length of the list using len()
len(numbers)
# + slideshow={"slide_type": "subslide"}
# you can find the max value of in a list using max()
max(numbers)
# + slideshow={"slide_type": "subslide"}
# you can find the minimum value in a list using min()
min(numbers)
# + slideshow={"slide_type": "subslide"}
# you can also take the sum of all the elements in the list using sum()
sum(numbers)
# + slideshow={"slide_type": "subslide"}
# here's a small example of what you can do with a while loop and some
# of these previously mentioned builtins.
numlist = []
while True:
inp = input('Enter a number: ')
# We haven't covered conditional statements yet,
# but this basically states that if the user enters
# `done` as the input, then stop the loop
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f'Average: {average}')
# + slideshow={"slide_type": "subslide"}
# Let's say you have a comma separated list of elements in a string
jedi = ('Obi-Wan,Anakin,Yoda,Mace Windu')
print(jedi)
print(type(jedi))
# + slideshow={"slide_type": "subslide"}
# you can convert that string into an actual Python list using the split()
# method.
jedi_list = jedi.split(',')
print(jedi_list)
print(type(jedi_list))
# -
# By default, split() assumes spaces as the delimeter
print("one two three four".split())
# + slideshow={"slide_type": "subslide"}
# you can check if a specific element is in a list.
print(jedi_list)
print('Anakin' in jedi_list)
# + slideshow={"slide_type": "subslide"}
# iterating over a list can easily be done using the for loop.
for jedi in jedi_list:
print(jedi)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### In-Class Exercises
# 1. Create a list named `food` with two elements `'rice'` and `'beans'`.
# 1. Append the string `'broccoli'` to `food` using `.append()`.
# 1. Add the strings `'bread'` and `'pizza'` to `food` using `.extend()`.
# 1. Print the first two item in the `food` list using `print()` and slicing notation.
# 1. Print the last item in food using `print()` and index notation.
# 1. Create a list called `breakfast` from the string `"eggs,fruit,orange juice"` using the `split()` method.
# 1. Verify that `breakfast` has 3 elements using the `len` built-in.
# 1. Write a script that prompts the user for a floating point value until they enter `stop`. Store their entries in a list, and then find the average, min, and max of their entries and print them those values.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Dictionaries
#
# 
# -
| Lecture Material/Week 04 - Data Containers, Loops, and Iterations/06 - Data Containers, Loops, and Iterations.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/ocalzada/DS-Unit-2-Regression-Classification/blob/master/module2/assignment_regression_classification_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="7IXUfiQ2UKj6" colab_type="text"
# Lambda School Data Science, Unit 2: Predictive Modeling
#
# # Regression & Classification, Module 2
#
# ## Assignment
#
# You'll continue to **predict how much it costs to rent an apartment in NYC,** using the dataset from renthop.com.
#
# - [X] Do train/test split. Use data from April & May 2016 to train. Use data from June 2016 to test.
# - [X] Engineer at least two new features. (See below for explanation & ideas.)
# - [X] Fit a linear regression model with at least two features.
# - [X] Get the model's coefficients and intercept.
# - [X] Get regression metrics RMSE, MAE, and $R^2$, for both the train and test data.
# - [X] What's the best test MAE you can get? Share your score and features used with your cohort on Slack!
# - [X] As always, commit your notebook to your fork of the GitHub repo.
#
#
# #### [Feature Engineering](https://en.wikipedia.org/wiki/Feature_engineering)
#
# > "Some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used." — Pedro Domingos, ["A Few Useful Things to Know about Machine Learning"](https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf)
#
# > "Coming up with features is difficult, time-consuming, requires expert knowledge. 'Applied machine learning' is basically feature engineering." — <NAME>, [Machine Learning and AI via Brain simulations](https://forum.stanford.edu/events/2011/2011slides/plenary/2011plenaryNg.pdf)
#
# > Feature engineering is the process of using domain knowledge of the data to create features that make machine learning algorithms work.
#
# #### Feature Ideas
# - Does the apartment have a description?
# - How long is the description?
# - How many total perks does each apartment have?
# - Are cats _or_ dogs allowed?
# - Are cats _and_ dogs allowed?
# - Total number of rooms (beds + baths)
# - Ratio of beds to baths
# - What's the neighborhood, based on address or latitude & longitude?
#
# ## Stretch Goals
# - [ ] If you want more math, skim [_An Introduction to Statistical Learning_](http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf), Chapter 3.1, Simple Linear Regression, & Chapter 3.2, Multiple Linear Regression
# - [ ] If you want more introduction, watch [<NAME>, Statistics 101: Simple Linear Regression](https://www.youtube.com/watch?v=ZkjP5RJLQF4)
# (20 minutes, over 1 million views)
# - [ ] Do the [Plotly Dash](https://dash.plot.ly/) Tutorial, Parts 1 & 2.
# - [ ] Add your own stretch goal(s) !
# + id="o9eSnDYhUGD7" colab_type="code" colab={}
# If you're in Colab...
import os, sys
in_colab = 'google.colab' in sys.modules
if in_colab:
# Install required python packages:
# pandas-profiling, version >= 2.0
# plotly, version >= 4.0
# !pip install --upgrade pandas-profiling plotly
# Pull files from Github repo
os.chdir('/content')
# !git init .
# !git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Regression-Classification.git
# !git pull origin master
# Change into directory for module
os.chdir('module1')
# + id="ipBYS77PUwNR" colab_type="code" colab={}
# Ignore this Numpy warning when using Plotly Express:
# FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning, module='numpy')
# + id="cvrw-T3bZOuW" colab_type="code" colab={}
import numpy as np
import pandas as pd
# Read New York City apartment rental listing data
df = pd.read_csv('../data/renthop-nyc.csv')
assert df.shape == (49352, 34)
# Remove the most extreme 1% prices,
# the most extreme .1% latitudes, &
# the most extreme .1% longitudes
df = df[(df['price'] >= np.percentile(df['price'], 0.5)) &
(df['price'] <= np.percentile(df['price'], 99.5)) &
(df['latitude'] >= np.percentile(df['latitude'], 0.05)) &
(df['latitude'] < np.percentile(df['latitude'], 99.95)) &
(df['longitude'] >= np.percentile(df['longitude'], 0.05)) &
(df['longitude'] <= np.percentile(df['longitude'], 99.95))]
# + id="aGfyX5tMdFsI" colab_type="code" outputId="a0cd8c79-30bb-4ef6-ca06-01abb2684cef" colab={"base_uri": "https://localhost:8080/", "height": 513}
df.head()
# + id="4iEk6CPjdaMQ" colab_type="code" outputId="d7ef881f-76b9-4479-e250-1f3eabf9c235" colab={"base_uri": "https://localhost:8080/", "height": 612}
# training data april & may
# test data june.
# first, must convert 'created' object into a datetime
import pandas as pd
df['created'] = pd.to_datetime(df['created'])
df.dtypes
# + id="pW34AIvlmpzO" colab_type="code" outputId="50e2e42b-2a82-4415-e9bc-ef2c92f3d3dc" colab={"base_uri": "https://localhost:8080/", "height": 513}
# created a month feature to then split my data by month
df['month_listed'] = df['created'].dt.month
df.head()
# + id="xejV4RCRtq-n" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="4b511740-d940-48bd-8223-48662fdf61f5"
df.query('month_listed ==4')
# + id="LR2dT5ADyvJB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 513} outputId="14e2b7c0-58a5-4b41-ece5-8e48d166c4e5"
df['total_rooms'] = df['bathrooms'] + df['bedrooms']
df.head()
# + id="ufnCiVDK0BSR" colab_type="code" colab={}
df['central_park'] = df['description'].str.contains('central park')
df['central_park'].value_counts()
df = df.dropna()
# + id="-J6poITzuFne" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="7e6dfc12-5dea-459e-a1cc-6df3b818f6f6"
# isolating April and May data to create my training dataset
mask = (df['month_listed'] >= 4) & (df['month_listed'] <=5)
mask.value_counts()
# + id="TobzKQJVunkW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 663} outputId="c327ecde-4e8c-47f4-ca3a-2cb336afd2bf"
train = df[mask]
train.isnull().sum()
# + id="09aM6-nzDzI4" colab_type="code" colab={}
# + id="9INaTarTvJ9p" colab_type="code" colab={}
mask2 = (df['month_listed']==6)
test = df[mask2]
test
# + id="oXB_XWaj1WW2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="697fdb5a-a9c0-4616-f6ce-21b7432a05ea"
# pick my model
from sklearn.linear_model import LinearRegression
#instantiate model
model = LinearRegression()
# pick features matrix and target vector
features = ['total_rooms', 'central_park']
target = 'price'
model.fit(train[features], train[target])
# + id="EPcqEeIWEhVt" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="82d5938c-4a44-48cf-c2f2-100b89d2491d"
# intercept
print('Intercept', model.intercept_)
# + id="25nowX4YEld6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="b8f5888f-14b1-4da1-8e86-9772e94720bf"
coefficients = pd.Series(model.coef_, features)
print(coefficients)
# + id="zkGv6LYUFRa9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="16de7a7b-36c8-4c4d-9198-3acff29ee3a8"
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
#calculate regression metrics for Training data
y = train[target]
y_pred = model.predict(train[features])
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('Mean Squared Error:', round(mse))
print('Root Mean Squared Error:', round(rmse))
print('Mean Absolute Error:', round(mae))
print('R^2:', r2)
# + id="jQTUYNTiH5vi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="84c406a6-665c-4fd2-e871-79631509a900"
#calculate regression metrics for testing data
y = test[target]
y_pred = model.predict(test[features])
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('Mean Squared Error:', round(mse))
print('Root Mean Squared Error:', round(rmse))
print('Mean Absolute Error:', round(mae))
print('R^2:', r2)
# + id="rzCjuDHRLr7S" colab_type="code" colab={}
# Read New York City apartment rental listing data
df = pd.read_csv('../data/renthop-nyc.csv')
assert df.shape == (49352, 34)
# Remove the most extreme prices,
# the most extreme latitudes, &
# the most extreme longitudes
df = df[(df['price'] >= np.percentile(df['price'], 0.5)) &
(df['price'] <= np.percentile(df['price'], 90.0)) &
(df['latitude'] >= np.percentile(df['latitude'], 0.05)) &
(df['latitude'] < np.percentile(df['latitude'], 90.00)) &
(df['longitude'] >= np.percentile(df['longitude'], 0.05)) &
(df['longitude'] <= np.percentile(df['longitude'], 90.00))]
# + id="8WjpD75hMX9H" colab_type="code" colab={}
import pandas as pd
#convert created object into datetime
df['created'] = pd.to_datetime(df['created'])
#split dataset into train and test sets
df['month_listed'] = df['created'].dt.month
#train data == april & may
mask = (df['month_listed'] >= 4) & (df['month_listed'] <=5)
train = df[mask]
# test data == june
mask2 = (df['month_listed']==6)
test = df[mask2]
# + id="Y9ZKpoHjNbWU" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="64a8a99f-6c2d-4dee-80cc-e4fd44edd500"
# pick features matrix and target vector
features = ['bedrooms', 'bathrooms']
target = 'price'
model.fit(train[features], train[target])
y = train[target]
y_pred = model.predict(train[features])
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('Mean Squared Error:', round(mse))
print('Root Mean Squared Error:', round(rmse))
print('Mean Absolute Error:', round(mae))
print('R^2:', r2)
# + id="HFYUCF0yOSwO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="089e8f8a-df97-4856-f750-20946dcda371"
y = test[target]
y_pred = model.predict(test[features])
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y, y_pred)
r2 = r2_score(y, y_pred)
print('Mean Squared Error:', round(mse))
print('Root Mean Squared Error:', round(rmse))
print('Mean Absolute Error:', round(mae))
print('R^2:', r2)
# + id="0lzzJfF7Q_VV" colab_type="code" colab={}
# tinkering with data to obtain better testing MAE
#bedrooms, dogs_allowed
#bedrooms, longitude
#bedrooms, bathrooms
| module2/assignment_regression_classification_2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# This notebook takes a model trained on CIFAR-10 and gets ROC curve for OOD detection assuming SVHN to be the OOD dataset.
import os
import sys
cwd = os.getcwd()
module_path = "/".join(cwd.split('/')[0:-1])
if module_path not in sys.path:
sys.path.append(module_path)
import torch
import random
import matplotlib.pyplot as plt
import torch.backends.cudnn as cudnn
# Import dataloaders
import Data.cifar10 as cifar10
import Data.svhn as svhn
# Import network architectures
from Net.resnet import resnet50, resnet110
from Net.wide_resnet import wide_resnet_cifar
from Net.densenet import densenet121
# Import metrics to compute
from Metrics.ood_test_utils import get_roc_auc
# Import plot related libraries
import seaborn as sb
import matplotlib.pyplot as plt
# +
# Dataset params
dataset_num_classes = {
'cifar10': 10,
'svhn': 10
}
dataset_loader = {
'cifar10': cifar10,
'svhn': svhn
}
# -
# Mapping model name to model function
models = {
'resnet50': resnet50,
'resnet110': resnet110,
'wide_resnet': wide_resnet_cifar,
'densenet121': densenet121,
}
# +
# Checking if GPU is available
cuda = False
if (torch.cuda.is_available()):
cuda = True
# Setting additional parameters
torch.manual_seed(1)
device = torch.device("cuda" if cuda else "cpu")
# -
class args:
data_aug = True
gpu = device == "cuda"
train_batch_size = 128
test_batch_size = 128
# +
dataset = 'cifar10'
ood_dataset = 'svhn'
num_classes = dataset_num_classes[dataset]
train_loader, val_loader = dataset_loader[dataset].get_train_valid_loader(
batch_size=args.train_batch_size,
augment=args.data_aug,
random_seed=1,
pin_memory=args.gpu
)
test_loader = dataset_loader[dataset].get_test_loader(
batch_size=args.test_batch_size,
pin_memory=args.gpu
)
ood_train_loader, ood_val_loader = dataset_loader[ood_dataset].get_train_valid_loader(
batch_size=args.train_batch_size,
augment=args.data_aug,
random_seed=1,
pin_memory=args.gpu
)
ood_test_loader = dataset_loader[ood_dataset].get_test_loader(
batch_size=args.test_batch_size,
pin_memory=args.gpu
)
# +
# Taking input for the model
print ('Enter the model: ')
model_name = input()
print ('Enter saved model name: ')
saved_model_name = input()
model = models[model_name]
# +
net = model(num_classes=num_classes, temp=1.0)
net.cuda()
net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
net.load_state_dict(torch.load('./' + str(saved_model_name)))
(fpr_entropy, tpr_entropy, thresholds_entropy), (fpr_confidence, tpr_confidence, thresholds_confidence), auc_entropy, auc_confidence = get_roc_auc(net, test_loader, ood_test_loader, device)
# +
clrs = ['#1f77b4','#ff7f0e', '#2ca02c','#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22','#17becf']
plt.figure()
plt.rcParams["figure.figsize"] = (10, 8)
sb.set_style('whitegrid')
plt.plot(fpr_entropy, tpr_entropy, color=clrs[0], linewidth=5, label='ROC')
plt.xticks(fontsize=30)
plt.yticks(fontsize=30)
plt.xlabel('FPR', fontsize=30)
plt.ylabel('TPR', fontsize=30)
plt.legend(fontsize=28)
print ('AUROC entropy: ' + str(auc_entropy))
| Experiments/.ipynb_checkpoints/evaluate_single_model_ood-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 0.6.0
# language: julia
# name: julia-0.6
# ---
# Setting up a custom stylesheet in IJulia
# New in 0.6
file = open("style.css") # A .css file in the same folder as this notebook file
styl = readstring(file) # Read the file
HTML("$styl") # Output as HTML
# # Functions in Julia II
# <h2>In this lecture</h2>
#
# - [Outcome](#Outcome)
# - [One-line function definition](#One-line-function-definition)
# - [Multi-line function definition](#Multi-line-function-definition)
# - [Functions with multiple methods](#Functions-with-multiple-methods)
#
# <hr>
# <h2>Outcome</h2>
#
# After this lecture, you will be able to:
#
# - Define a function using the "functionname(varlist) = ..." one-line syntax
# - Define a function using the "function name(varlist) ... end" multiline syntax
# - Define an additional method for an existing user-defined function
# - Specify types for input values in a user-defined function
# - Use workspace() to clear the notebook of all values so that function signatures can be redefined.
# [Back to the top](#In-this-lecture)
# <h2>One-line function definition</h2>
#
# This has an extremely simple form. For example:
myfunc(firstvar) = 20*firstvar
# The rules are for defining one-line function are:
# - the name of the function must be a valid variable name (in this case "myfunc" is the name)
# - the arguments of the function must be valid variable names
# - the argument must be in parentheses (and as we'll see, multiple arguments must be separated by values)
# - the name, with arguments in parentheses goes on the left of an assignment
# - the code for evaluating the function goes on the right.
#
# By the way, it's not quite accurate that the code must always fit on one line---it must be a single statement, but so-called compound statements are often written with line breaks, to help the human reader. We will not be using compound statements in one-line functions in this course.
myfunc(333.2222) # then we just call it like any other function
# Here is an illustration of a two-argument function:
addxtoy(x,y) = x + y # not supposed to be useful! it just shows how the job is done
addxtoy(33, -22.2) # mixed types: illustrates that for quick and dirty code, we can (mostly) ignore types
# [Back to the top](#In-this-lecture)
# <h2>Multi-line function definition</h2>
#
# Let's face it, computing should not be all be done with one-liners. Julia supplies the following syntax for functions that take up multiple lines:
function nextfunc(a, b, c) # this line names your function and specifies the inputs
a*b + c # here go your (usually quite a few) lines
# ... just illustrating the possiblity of using white space and additional comments
end
nextfunc(7,5,3) # again, just call it like any other function
# To illustrate multi-line functions a bit more, here's a useful device for debugging: a line inside a function that gives you the value and the type of a variable.
#
# It relies on the escape character "$" in strings, which you recall DOESN'T create a dollar sign, but instead modifies how the string is built.
#
function showdebugprintln(testvar)
println("inside the showdebugprint() now") #this line announces where the report is coming from
println("The type of testvar is $(typeof(testvar)) and the value of testvar is $testvar")
# and this line reports what value, and hence what type, testvar actually has here
end
a = ['1',2.]
showdebugprintln(a)
# [Back to the top](#In-this-lecture)
# <h2>Functions with multiple methods</h2>
#
# As we saw in Lecture 8, many code bodies can share one function name. Julia knows which of them is relevant via the type signature. The type signature is simply the list of types of all the variables that are used to call the function.
#
# Here is a function that basically parallels the cos function.
mycos(x) = cos(x)
mycos(.7) # standard value of cos (angle in radians, of course)
# Now we extend mycos() by providing a function for computing the cosine from the hypotenuse and adjacent side:
mycos(adj, hyp) = adj/hyp
mycos(12, 13) # the cosine of the larger angle in a standard 5, 12, 13 triangle
methods(mycos) #Check this carefully!
# Again, methods() is your friend. Note especially that each method is given in terms of its input variables.
# As with every user-defined function, it is easy for these to go wrong. Suppose we want to make sure the mycos(x) is never called for integer values. We can require the input to be Float64 as follows:
mycos(thet::Float64) = cos(thet) # note the use of :: to force Julia to check the type
# However, there are now three methods, and integers can still be passed (check this for yourself). We actually intended to replace mycos(x) with mycos(thet::Float64). To do so, first we must clear the old version. Unfortunately, the only way to clear a notebook is to clear everything, by using workspace().
#
# Everything is cleared, so we have to redefine not only mycos(x) but also mycos(adj, hyp):
workspace() # no argument, please!
# ... clears all the results
mycos(thet::Float64) = cos(thet) # so passing mycos() an integer will now cause Julia to throw an error
mycos(hyp, adj) = adj/hyp
mycos(1) # ... this shouldn't work now ...
# [Back to the top](#In-this-lecture)
| Julia Scientific Programming - University of Cape Town/JuliaCourseNotebooks/Week1_9-Functions2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # General Assignment Rubric
#
# All assignments will be graded according to the following grading scheme.
#
# ## Completeness - 3 marks
#
# The completeness of the assignment will be graded out of 3 marks. Marks will be awarded based on the following descriptions:
#
# - 3 = all questions are answered and all code is complete
# - 2 = all questions are attempted but code and/or assignment responses are not complete
# - 1 = some questions and/or portions of the code are not attempted
# - 0 = more than half of questions are not attempted and/or significant portions of the code are not attempted
#
# ## Written Interpretations - 4 marks
#
# The written interpretations and accuracy will be graded out of 4 marks. Marks will be awarded based on the following descriptions:
#
# - 4 = written interpretations clearly and unambiguously explain the results of the code
# - 3 = written interpretations explain the results of the code, but may contain some innaccuracies and/or may be lacking some detail
# - 2 = written interpretations explain the results of the code, but may contain significant innaccuracies and/or may be lacking significant detail
# - 1 = written interpretations do not explain all of the results of the code and/or contain multiple significant errors
# - 0 = written interpratations are not clear and/or contain many errors and/or are incomplete
#
# ## Code Quality/Accuracy - 2 marks
#
# The code quality and accuracy will be graded out of 2 marks. Marks will be awarded based on the following descriptions:
#
# - 2 = code is clearly written and is completely correct
# - 1 = code is not clearly written and/or has some errors
# - 0 = code is poorly written and/or has many errors
#
# ## Use of Git - 1 mark
#
# - 1 = suffieient commits (>3) have been made with clear commit messages
# - 0 = insufficient commits (<3) have been made and/or commit messages are vague/incorrect
#
| cfdcourse/Assignments/AssignmentRubric.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [Root]
# language: python
# name: Python [Root]
# ---
# # Analysis of WWW dataset
# WWW dataset is identified as the most sparse graph in C&F paper. In this notebook, we will compute an empirical growth rate of edges w.r.t the number of nodes, and fit two different curves to this empirical growth.
# +
import os
import pickle
import time
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse import csc_matrix, csr_matrix, dok_matrix
from scipy.optimize import curve_fit
# %matplotlib inline
# -
# ### Load WWW dataset with sparse matrices
# +
n_e = 325729
def getWWWdataset(n_e = 325729, shuffle=True):
if shuffle:
node_idx = np.arange(n_e)
np.random.shuffle(node_idx)
node_dic = {i:node_idx[i] for i in range(n_e)}
else:
node_dic = {i:i for i in range(n_e)}
row_list = list()
col_list = list()
with open('../data/www/www.dat.txt', 'r') as f:
for line in f.readlines():
row, col = line.split()
row = int(row.strip())
col = int(col.strip())
row_list.append(node_dic[row])
col_list.append(node_dic[col])
return row_list, col_list
# -
# ## Compute growth rate of WWW dataset with varying size of nodes
# +
if not os.path.exists('www_growth.pkl'):
n_e = 325729
n_link = defaultdict(list)
n_samples = 10
for si in range(n_samples):
row_list, col_list = getWWWdataset()
www_row = csr_matrix((np.ones(len(row_list)), (row_list, col_list)), shape=(n_e, n_e))
www_col = csc_matrix((np.ones(len(row_list)), (row_list, col_list)), shape=(n_e, n_e))
n_link[0].append(0)
for i in range(1, n_e):
# counting triples by expanding tensor
cnt = 0
cnt += www_row.getrow(i)[:,:i].nnz
cnt += www_col.getcol(i)[:i-1,:].nnz
n_link[i].append(cnt + n_link[i-1][-1])
pickle.dump(n_link, open('www_growth.pkl', 'wb'))
else:
n_link = pickle.load(open('www_growth.pkl', 'rb'))
avg_cnt = [np.mean(n_link[i]) for i in range(n_e)]
# -
# ### Fit the growth curve
# +
def func(x, a, b, c):
return c*x**a + b
def poly2(x, a, b, c):
return c*x**2 + b*x + a
popt, pcov = curve_fit(func, np.arange(n_e), avg_cnt)
fitted_t = func(np.arange(n_e), *popt)
popt2, pcov2 = curve_fit(poly2, np.arange(n_e), avg_cnt)
fitted_t2 = poly2(np.arange(n_e), *popt2)
# -
# ### Plot the empirical and fitted growth curves
# +
plt.figure(figsize=(16,6))
plt.subplot(1,2,1)
plt.plot(avg_cnt, label='empirical')
plt.plot(fitted_t, label='$y=%.5f x^{%.2f} + %.2f$' % (popt[2], popt[0], popt[1]))
plt.plot(fitted_t2, label='$y=%.5f x^2 + %.5f x + %.2f$' % (popt2[2], popt2[1], popt2[0]))
plt.legend(loc='upper left')
plt.title('# of nodes vs # of links')
plt.xlabel('# nodes')
plt.ylabel('# links')
plt.subplot(1,2,2)
plt.plot(avg_cnt, label='empirical')
plt.plot(fitted_t, label='$y=%.5f x^{%.2f} + %.2f$' % (popt[2], popt[0], popt[1]))
plt.plot(fitted_t2, label='$y=%.5f x^2 + %.5f x + %.2f$' % (popt2[2], popt2[1], popt2[0]))
plt.legend(loc='upper left')
plt.title('# of nodes vs # of links (Magnified)')
plt.xlabel('# nodes')
plt.ylabel('# links')
plt.axis([100000,150000,100000,350000])
# +
row_list, col_list = getWWWdataset()
www_row = csr_matrix((np.ones(len(row_list)), (row_list, col_list)), shape=(n_e, n_e))
www_col = csc_matrix((np.ones(len(row_list)), (row_list, col_list)), shape=(n_e, n_e))
entity_degree = (www_row.sum(1) + www_col.sum(0).T).tolist()
e_list = np.arange(n_e)
np.random.shuffle(e_list)
one_entity = [entity_degree[ei][0] == 1 for ei in e_list]
cumsum = np.cumsum(one_entity)
plt.figure(figsize=(8,6))
plt.plot(cumsum)
plt.xlabel('# of entities')
plt.ylabel('# of entities of degree one')
plt.title('# of entities of degree one in WWW')
plt.axis([0, n_e, 0, n_e])
# -
| notebooks/AnalysisWWWdataset.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from gs_quant.session import GsSession, Environment
from gs_quant.instrument import EqOption, OptionType, OptionStyle
from gs_quant.backtests.strategy import Strategy
from gs_quant.backtests.triggers import *
from gs_quant.backtests.actions import *
from gs_quant.backtests.equity_vol_engine import *
from gs_quant.target.common import UnderlierType
from datetime import date
# external users should substitute their client id and secret; please skip this step if using internal jupyterhub
GsSession.use(Environment.PROD, client_id=None, client_secret=None, scopes=('run_analytics',))
# + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"}
# Define backtest dates
start_date = date(2019, 9, 4)
end_date = date(2020, 9, 4)
# + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"}
# Define instrument for strategy. EqOption or EqVarianceSwap are supported
# Equity Option
instrument = EqOption('SX5E', underlier_type=UnderlierType.BBID, expirationDate='3m', strikePrice='ATM', optionType=OptionType.Call, optionStyle=OptionStyle.European)
# Uncomment to backtest Equity Variance Swap
# instrument = EqVarianceSwap('.STOXX50E', expirationDate='3m', strikePrice='ATM')
# + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"}
# Define a periodic trigger and action. Trade and roll the option instrument every 1m
trade_action = EnterPositionQuantityScaledAction(priceables=instrument, trade_duration='1m', trade_quantity=1000, trade_quantity_type=BacktestTradingQuantityType.quantity)
trade_trigger = PeriodicTrigger(trigger_requirements=PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency='1m'), actions=trade_action)
# -
# Create strategy
strategy = Strategy(initial_portfolio=None, triggers=[trade_trigger])
# Run backtest
backtest = EquityVolEngine.run_backtest(strategy, start=start_date, end=end_date)
# Plot the performance
pnl = backtest.get_measure_series(FlowVolBacktestMeasure.PNL)
pnl.plot(legend=True, label='PNL')
| gs_quant/documentation/04_backtesting/examples/02_EquityVolEngine/040200_strategy_simple.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Chernoff Faces
#
# This notebook is the start of three in total to understand if transforming numerical data to images would improve classification tasks through deep learning techniques such as convolutional neural networks (CNNs). This notebook creates 4 data sets sampled from multi-level gaussian models, and each data point is then mapped to a visual representation in the form of a [Chernoff face](https://en.wikipedia.org/wiki/Chernoff_face). The output of this notebook are both images and numerical data. The images are fed to a CNN for classification task in the notebook [chernoff-deeplearning.ipynb](chernoff-deeplearning.ipynb), and the numerical data are fed into numerical classification models such as logistic regression and random forest in the notebook [chernoff-classification.ipynb](chernoff-classification.ipynb).
#
# ## Models
#
# We have 4 data sets that we sample, each composed of 18 variables. Each observation is then mapped to a Chernoff face. The models used to generate each sample is as follows.
#
# * $X_0 = 0.9$
# * $X_1 \sim \mathcal{N}(R, 0.1)$, where $R \in [0, 1]$ but constant per model
# * $X_2 \sim \mathcal{N}(0.3 x_1, 0.1)$
# * $X_3 \sim \mathcal{N}(0.25 x_1, 0.1)$
# * $X_4 \sim \mathcal{N}(0.25 x_2 + 0.33 x_3, 0)$
# * $X_5 \sim \mathcal{N}(0.77 x_4, 0.1)$
# * $X_6 \sim \mathcal{N}(0.66 x_4, 0.2)$
# * $X_7 \sim \mathcal{N}(0.33 x_4, 0.02)$
# * $X_8 \sim \mathcal{N}(0.2 x_5 + 0.32 x_6 + 0.18 x_7, 0.1)$
# * $X_9 \sim \mathcal{N}(0.5 x_8, 0.03)$
# * $X_{10} \sim \mathcal{N}(0.2 x_9, 0.05)$
# * $X_{11} \sim \mathcal{N}(0.3 x_9 + 0.4 x_{10}, 0.03)$
# * $X_{12} \sim \mathcal{N}(0.4 x_{10} + 0.25 x_{11}, 0.08)$
# * $X_{13} \sim \mathcal{N}(0.2 x_{10} + 0.2 x_{11} + 0.12 x_{12}, 0)$
# * $X_{14} \sim \mathcal{N}(0.5 x_{13}, 0.01)$
# * $X_{15} \sim \mathcal{N}(0.5 x_{14}, 0.01)$
# * $X_{16} \sim \mathcal{N}(0.5 x_{15}, 0.01)$
# * $X_{17} \sim \mathcal{N}(0.5 x_{16}, 0.01)$
#
# Note that the coefficients and standard deviations are very small, since the values (per observation) are required to be in $[0, 1]$. In some cases, negative values may occur, and a normalization of the values back to the domain of $[0, 1]$ is made. The graphical representation looks like the following.
# +
# %matplotlib inline
import warnings
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
np.random.seed(37)
G = nx.DiGraph()
G.add_edges_from([
(1, 2),
(1, 3),
(2, 4), (3, 4),
(4, 5),
(4, 6),
(4, 7),
(5, 8), (6, 8), (7, 8),
(8, 9),
(9, 10),
(9, 11), (10, 11),
(10, 12), (11, 12),
(10, 13), (11, 13), (12, 13),
(13, 14),
(14, 15),
(15, 16),
(16, 17)
])
with warnings.catch_warnings(record=True):
fig, ax = plt.subplots(figsize=(10, 15))
options = {
'node_color': 'red',
'node_size': 400,
'width': 1,
'alpha': 0.8
}
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw(G, with_labels=True, ax=ax, pos=pos, **options)
ax.set_title('Graphical Representation of Models')
plt.axis('off')
plt.show()
# -
# ## Sampling
#
# The sampling is performed below.
# +
from matplotlib.patches import Ellipse, Arc
import pandas as pd
import os
class Face():
def __init__(self, coef=None):
if coef is None:
self.coef_ = np.insert(np.random.rand(17), 0, 0.9)
else:
self.coef_ = coef
def next(self, N=1):
x0 = np.full((1, N), self.coef_[0])
x1 = np.random.normal(self.coef_[1], 0.1, N)
x2 = np.random.normal(0.3 * x1, 0.1, N)
x3 = np.random.normal(0.25 * x1, 0.1, N)
x4 = np.random.normal(0.25 * x2 + 0.33 * x3, 0.2, N)
x5 = np.random.normal(0.77 * x4, 0.1, N)
x6 = np.random.normal(0.66 * x4, 0.2, N)
x7 = np.random.normal(0.33 * x4, 0.02, N)
x8 = np.random.normal(0.20 * x5 + 0.32 * x6 + 0.18 * x7, 0.1, N)
x9 = np.random.normal(0.5 * x8, 0.03, N)
x10 = np.random.normal(0.2 * x9, 0.05, N)
x11 = np.random.normal(0.3 * x9 + 0.4 * x10, 0.03, N)
x12 = np.random.normal(0.4 * x10 + 0.25 * x11, 0.08, N)
x13 = np.random.normal(0.2 * x10 + 0.02 * x11 + 0.12 * x12, 0.05, N)
x14 = np.random.normal(0.5 * x13, 0.01, N)
x15 = np.random.normal(0.5 * x14, 0.01, N)
x16 = np.random.normal(0.5 * x15, 0.01, N)
x17 = np.random.normal(0.5 * x16, 0.01, N)
a = np.vstack([x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17]).T
b = (a - np.min(a))/np.ptp(a)
return b
def cface(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,width=3,height=3,odir=None,ofile=None,ax=None):
# x1 = height of upper face
# x2 = overlap of lower face
# x3 = half of vertical size of face
# x4 = width of upper face
# x5 = width of lower face
# x6 = length of nose
# x7 = vertical position of mouth
# x8 = curvature of mouth
# x9 = width of mouth
# x10 = vertical position of eyes
# x11 = separation of eyes
# x12 = slant of eyes
# x13 = eccentricity of eyes
# x14 = size of eyes
# x15 = position of pupils
# x16 = vertical position of eyebrows
# x17 = slant of eyebrows
# x18 = size of eyebrows
# transform some values so that input between 0,1 yields variety of output
x3 = 1.9*(x3-.5)
x4 = (x4+.25)
x5 = (x5+.2)
x6 = .3*(x6+.01)
x8 = 5*(x8+.001)
x11 /= 5
x12 = 2*(x12-.5)
x13 += .05
x14 += .1
x15 = .5*(x15-.5)
x16 = .25*x16
x17 = .5*(x17-.5)
x18 = .5*(x18+.1)
if ax is None:
fig = plt.figure(frameon=False)
fig.set_size_inches(width, height)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# top of face, in box with l=-x4, r=x4, t=x1, b=x3
e = Ellipse( (0,(x1+x3)/2), 2*x4, (x1-x3), fc='blue', linewidth=10)
ax.add_artist(e)
# bottom of face, in box with l=-x5, r=x5, b=-x1, t=x2+x3
e = Ellipse( (0,(-x1+x2+x3)/2), 2*x5, (x1+x2+x3), fc='blue', linewidth=10)
ax.add_artist(e)
# cover overlaps
e = Ellipse( (0,(x1+x3)/2), 2*x4, (x1-x3), fc='white', ec='none')
ax.add_artist(e)
e = Ellipse( (0,(-x1+x2+x3)/2), 2*x5, (x1+x2+x3), fc='white', ec='none')
ax.add_artist(e)
# draw nose
ax.plot([0,0], [-x6/2, x6/2], 'k')
# draw mouth
p = Arc( (0,-x7+.5/x8), 1/x8, 1/x8, theta1=270-180/np.pi*np.arctan(x8*x9), theta2=270+180/np.pi*np.arctan(x8*x9))
ax.add_artist(p)
# draw eyes
p = Ellipse( (-x11-x14/2,x10), x14, x13*x14, angle=-180/np.pi*x12, facecolor='yellow')
ax.add_artist(p)
p = Ellipse( (x11+x14/2,x10), x14, x13*x14, angle=180/np.pi*x12, facecolor='green')
ax.add_artist(p)
# draw pupils
p = Ellipse( (-x11-x14/2-x15*x14/2, x10), .05, .05, facecolor='black')
ax.add_artist(p)
p = Ellipse( (x11+x14/2-x15*x14/2, x10), .05, .05, facecolor='black')
ax.add_artist(p)
# draw eyebrows
ax.plot([-x11-x14/2-x14*x18/2,-x11-x14/2+x14*x18/2],[x10+x13*x14*(x16+x17),x10+x13*x14*(x16-x17)],'k')
ax.plot([x11+x14/2+x14*x18/2,x11+x14/2-x14*x18/2],[x10+x13*x14*(x16+x17),x10+x13*x14*(x16-x17)],'k')
ax.axis([-1.2,1.2,-1.2,1.2])
ax.set_xticks([])
ax.set_yticks([])
if odir is not None and ofile is not None:
opath = '{}/{}'.format(odir, ofile)
fig.savefig(opath, quality=100, optimize=True)
def plot(X):
fig = plt.figure(figsize=(11,11))
for i in range(X.shape[0]):
ax = fig.add_subplot(5,5,i+1,aspect='equal')
cface(*X[i], ax=ax)
fig.subplots_adjust(hspace=0, wspace=0)
plt.tight_layout()
plt.show()
def save_plots(X, offset=0, width=3, height=3, odir=None):
for i in range(X.shape[0]):
num = f'{i+offset:03}'
ofile = '{}.jpg'.format(num)
cface(*X[i], width=width, height=height, odir=odir, ofile=ofile)
plt.close()
def make_dirs(num_clazzes, root_path='./faces'):
tr_path = '{}/train'.format(root_path)
te_path = '{}/test'.format(root_path)
va_path = '{}/valid'.format(root_path)
dir_paths = [tr_path, te_path, va_path]
for dir_path in dir_paths:
for i in range(num_clazzes):
num = f'{i:02}'
subfolder_path = '{}/{}'.format(dir_path, num)
if not os.path.exists(subfolder_path):
os.makedirs(subfolder_path)
print('creating {}'.format(subfolder_path))
else:
print('{} already exists'.format(subfolder_path))
# +
f0 = Face()
f1 = Face()
f2 = Face()
f3 = Face()
X0 = f0.next(250)
X1 = f1.next(250)
X2 = f2.next(75)
X3 = f3.next(75)
faces = [X0, X1, X2, X3]
tr_indices = [(0, 200), (0, 200), (0, 25), (0, 25)]
te_indices = [(200, 225), (200, 225), (25, 50), (25, 50)]
va_indices = [(225, 250), (225, 250), (50, 75), (50, 75)]
make_dirs(len(faces))
# -
# ## Create the faces
#
# Each data point (observation of 18 variables) is then used to create a Chernoff face and saved.
for clazz, (X, tr, te, va) in enumerate(zip(faces, tr_indices, te_indices, va_indices)):
X_tr = X[tr[0]:tr[1], :]
X_te = X[te[0]:te[1], :]
X_va = X[va[0]:va[1], :]
num = f'{clazz:02}'
dir_tr = './faces/train/{}'.format(num)
dir_te = './faces/test/{}'.format(num)
dir_va = './faces/valid/{}'.format(num)
save_plots(X_tr, offset=tr[0], odir=dir_tr)
save_plots(X_te, offset=te[0], odir=dir_te)
save_plots(X_va, offset=va[0], odir=dir_va)
print('done!')
# ### Faces in class 0
plot(X0[0:25,:])
# ### Faces in class 1
plot(X1[0:25,:])
# ### Faces in class 2
plot(X2[0:25,:])
# ### Faces in class 3
plot(X3[0:25,:])
# ## Export raw data
#
# The numerical data is also exported.
# +
TR = []
VA = []
for clazz, (X, tr, te, va) in enumerate(zip(faces, tr_indices, te_indices, va_indices)):
X_tr = X[tr[0]:tr[1], :]
X_va = X[va[0]:va[1], :]
X = X_tr
y = np.full((X.shape[0], 1), clazz, dtype=np.int)
data = np.hstack([X, y])
TR.append(data)
X = X_va
y = np.full((X.shape[0], 1), clazz, dtype=np.int)
data = np.hstack([X, y])
VA.append(data)
TR = np.vstack(TR)
VA = np.vstack(VA)
print(TR.shape)
print(VA.shape)
cols = ['x{}'.format(i) if i < TR.shape[1] - 1 else 'y' for i in range(TR.shape[1])]
tr_df = pd.DataFrame(TR, columns=cols)
va_df = pd.DataFrame(VA, columns=cols)
tr_df = tr_df.astype({'y': 'int32'})
va_df = va_df.astype({'y': 'int32'})
tr_df.to_csv('./faces/data-train.csv', index=False, header=True)
va_df.to_csv('./faces/data-valid.csv', index=False, header=True)
# -
tr_df.dtypes
va_df.dtypes
| sphinx/datascience/source/chernoff-faces.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Przydatne linki
# ### bit.ly/symulator-kod
#
# ### bit.ly/symulator-model
# +
from flask import Flask
from io import BytesIO
import eventlet.wsgi
import eventlet
import socketio
import base64
from PIL import Image
import numpy as np
import keras
from keras.models import load_model
import matplotlib.pyplot as plt
# -
"""korzystamy z wyuczonego modelu"""
model = load_model('input/my_model_2.h5')
model.summary()
"""serwer web do odbierania zapytan z symulatora"""
sio = socketio.Server()
app = Flask(__name__)
"""funkcja wysylajaca rozkazy do symulatora"""
def send_control(steering_angle, throttle):
sio.emit("steer", data={'steering_angle': str(steering_angle),
'throttle': str(throttle) }, skip_sid=True)
# +
""" funkcja pomocnicza - zmienia rozmiar obrazu wejsciowiego na 60 x 80 x 3"""
def process_image(img):
return img[10:130:2 , fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, : ]
@sio.on('telemetry')
def telemetry(sid, data):
if data:
speed = float(data["speed"])
image_str = data["image"]#obraz jak string
#print(data.keys())# 4 wymiary aktualny skręt, polozenie pedalu gazu, prędkosc, obraz - dane z symulatora
#print(type(image_str))#obraz jako string
#decodowanie obrazu
decoded = base64.b64decode(image_str)
#konwertujemy do obrazu
image = Image.open(BytesIO(decoded))
#obraz konwertujemy do macierzy
imgae_array = np.asarray(image)
#print(imgae_array.shape)#obraz o wymiarach 160 wysokosc x 320 szerokosc x 3 kanały (RGB)
#model input 60x80x3
#plt.imshow(imgae_array)
#plt.show()
#zmniejszamy obraz
img = process_image(imgae_array)
img_batch = np.expand_dims(img,axis = 0)#dodanie 4 wymiaru , 1 zdjecie
#predykcja modelu i zmiana na float - skret kierownicy
steering_angle = float(model.predict(img_batch))
#print(steering_angle)
#steering_angle = 0.0 #kat skretu watosci -1..1 (-1 -lewo, 1 -prawo)
throttle = 0.1 #wcisniecie gazu wartosci 0..1 wartosci, -1..0 oznacza hamowanie
#print(throttle,steering_angle)
if speed < 10:
throttle = 0.6
if speed > 17:
throttle = -0.1
send_control(steering_angle, throttle)
else:
sio.emit('manual', data={}, skip_sid=True)
##uruchamia serwer i blokuje komórke
app = socketio.Middleware(sio, app)
eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
# -
| part3/day2/day2_part3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# +
#notebook for testing version control on Albacore data.
from __future__ import print_function
import sys
import h5py
from itertools import islice
TEMPLATE_BASECALL_KEY_0 = "/Analyses/Basecall_1D_001" #latest basecalled name (001)
TWOD_BASECALL_KEY_0 = "/Analyses/Basecall_2D_000"
VERSION_KEY = "version"
SUPPORTED_1D_VERSIONS = ("1.2.1") #version of the current albacore data
class NanoporeRead(object):
def __init__(self, fast_five_file, twoD=False):
# load the fast5
self.filename = fast_five_file # fast5 file path
self.is_open = self.open() # bool, is the member .fast5 open?
self.read_label = "" # read label, template read by default
self.alignment_table_sequence = "" # the sequence made by assembling the alignment table
self.template_events = [] # template event sequence
self.complement_events = [] # complement event sequence
self.template_read = "" # template strand base (from fastq) sequence
self.complement_read = "" # complement strand base (from fastq) sequence
self.template_strand_event_map = [] # map of events to kmers in the 1D template read
self.complement_strand_event_map = [] # map of events to kmers in the 1D complement read
self.template_event_map = [] # map of template events to kmers in 2D read
self.complement_event_map = [] # map of complement events to kmers in 2D read
self.stay_prob = 0 # TODO, do I need this?
self.template_model_name = "" # legacy, for reads base-called by a specific model (template)
self.complement_model_name = "" # legacy, for reads base-called by a specific model (complement)
self.template_scale = 1 # initial values for scaling parameters
self.template_shift = 1 #
self.template_drift = 0 # Template Parameters
self.template_var = 1 #
self.template_scale_sd = 1 #
self.template_var_sd = 1 # --------------------------------------
self.complement_scale = 1 #
self.complement_shift = 1 # Complement Parameters
self.complement_drift = 0 #
self.complement_var = 1 #
self.complement_scale_sd = 1 #
self.complement_var_sd = 1 #
self.twoD = twoD # 2D read flag, necessary right now, and the client should know
def open(self):
try:
self.fastFive = h5py.File(self.filename, 'r')
return True
except Exception, e:
self.close()
print("Error opening file {filename}, {e}".format(filename=self.filename, e=e), file=sys.stderr)
return False
def get_latest_basecall_edition(self, address):
highest = 0
while(highest < 10):
if address.format(highest) in self.fastFive:
highest += 1
continue
else:
return address.format(highest - 1) # the last base-called version we saw
def Initialize(self, parent_job):
print("Initialize")
if not self.is_open:
ok = self.open()
if not ok:
self.logError("[NanoporeRead:Initialize]ERROR opening %s" % self.filename, parent_job)
self.close()
return False
if self.twoD:
print("self.twoD is used in nanoporeRead")
ok = self._initialize_twoD(parent_job)
else:
print("self.twoD is not used in nanoporeRead")
ok = self._initialize(parent_job)
return ok
def _initialize(self, parent_job):
"""Routine setup 1D NanoporeReads, returns false if basecalled with upsupported
version or is not base-called
"""
#print("setup 1D NanoporeReads with _initialize")
if TEMPLATE_BASECALL_KEY_0 not in self.fastFive: # not base-called
self.logError("[NanoporeRead:_initialize]ERROR %s not basecalled" % self.filename, parent_job)
self.close()
return False
oneD_root_address = self.get_latest_basecall_edition("/Analyses/Basecall_1D_00{}")
if VERSION_KEY not in self.fastFive[oneD_root_address].attrs.keys():
self.logError("[NanoporeRead:_initialize]ERROR %s missing version" % self.filename, parent_job)
self.close()
return False
self.version = self.fastFive[oneD_root_address].attrs["version"]
if self.version not in SUPPORTED_1D_VERSIONS:
self.logError("[NanoporeRead:_initialize]ERROR %s unsupported version %s " % (self.filename, self.version),
parent_job)
self.close()
return False
self.template_event_table_address = "%s/BaseCalled_template/Events" % oneD_root_address
self.template_model_address = "%s/BaseCalled_template/Model" % oneD_root_address
self.template_model_id = None
fastq_sequence_address = "%s/BaseCalled_template/Fastq" % oneD_root_address
if fastq_sequence_address not in self.fastFive:
self.logError("[NanoporeRead:_initialize]ERROR %s missing fastq" % self.filename, parent_job)
self.close()
return False
self.template_read = self.fastFive[fastq_sequence_address][()].split()[2]
self.read_label = self.fastFive[fastq_sequence_address][()].split()[0][1:]
self.kmer_length = len(self.fastFive[self.template_event_table_address][0][4])
self.template_read_length = len(self.template_read)
if self.template_read_length <= 0 or not self.read_label or self.kmer_length <= 0:
self.logError("[NanoporeRead:_initialize]ERROR %s illegal read parameters "
"template_read_length: %s, read_label: %s, kmer_length: %s"
% (self.template_read_length, self.read_label, self.kmer_length), parent_job)
self.close()
return False
return True
def _initialize_twoD(self, parent_job=None):
self.has2D = False
self.has2D_alignment_table = False
if TWOD_BASECALL_KEY_0 not in self.fastFive:
self.close()
return False
twoD_address = self.get_latest_basecall_edition("/Analyses/Basecall_2D_00{}")
if twoD_address not in self.fastFive:
self.logError("[NanoporeRead::initialize_twoD] Didn't find twoD address, looked here %s " % twoD_address,
parent_job)
self.close()
return False
self.version = self.fastFive[twoD_address].attrs["dragonet version"]
supported_versions = ["1.15.0", "1.19.0", "1.20.0", "1.22.2", "1.22.4", "1.23.0"]
if self.version not in supported_versions:
self.logError("[NanoporeRead::initialize_twoD]Unsupported Version {} (1.15.0, 1.19.0, 1.20.0, "
"1.22.2, 1.22.4, 1.23.0 supported)".format(self.version), parent_job)
self.close()
return False
if self.version == "1.15.0":
oneD_address = self.get_latest_basecall_edition("/Analyses/Basecall_2D_00{}")
else:
oneD_address = self.get_latest_basecall_edition("/Analyses/Basecall_1D_00{}")
twoD_alignment_table_address = twoD_address + "/BaseCalled_2D/Alignment"
if twoD_alignment_table_address in self.fastFive:
self.twoD_alignment_table = self.fastFive[twoD_alignment_table_address]
if len(self.twoD_alignment_table) > 0:
self.has2D_alignment_table = True
self.kmer_length = len(self.twoD_alignment_table[0][2])
twoD_read_sequence_address = twoD_address + "/BaseCalled_2D/Fastq"
if twoD_read_sequence_address in self.fastFive:
self.has2D = True
self.twoD_read_sequence = self.fastFive[twoD_read_sequence_address][()].split()[2]
self.read_label = self.fastFive[twoD_read_sequence_address][()].split()[0:2][0][1:]
# initialize version-specific paths
if self.version == "1.15.0":
self.template_event_table_address = twoD_address + '/BaseCalled_template/Events'
self.template_model_address = twoD_address + "/BaseCalled_template/Model"
self.template_model_id = self.get_model_id(twoD_address + "/Summary/basecall_1d_template")
self.template_read = self.fastFive[twoD_address + "/BaseCalled_template/Fastq"][()].split()[2]
self.complement_event_table_address = twoD_address + '/BaseCalled_complement/Events'
self.complement_model_address = twoD_address + "/BaseCalled_complement/Model"
self.complement_model_id = self.get_model_id(twoD_address + "/Summary/basecall_1d_complement")
self.complement_read = self.fastFive[twoD_address + "/BaseCalled_complement/Fastq"][()].split()[2]
return True
elif self.version == "1.19.0" or self.version == "1.20.0":
self.template_event_table_address = oneD_address + '/BaseCalled_template/Events'
self.template_model_address = oneD_address + "/BaseCalled_template/Model"
self.template_model_id = self.get_model_id(oneD_address + "/Summary/basecall_1d_template")
self.template_read = self.fastFive[oneD_address + "/BaseCalled_template/Fastq"][()].split()[2]
self.complement_event_table_address = oneD_address + '/BaseCalled_complement/Events'
self.complement_model_address = oneD_address + "/BaseCalled_complement/Model"
self.complement_model_id = self.get_model_id(oneD_address + "/Summary/basecall_1d_complement")
self.complement_read = self.fastFive[oneD_address + "/BaseCalled_complement/Fastq"][()].split()[2]
return True
elif self.version == "1.22.2" or self.version == "1.22.4" or self.version == "1.23.0":
self.template_event_table_address = oneD_address + '/BaseCalled_template/Events'
self.template_model_address = ""
self.template_model_id = None
self.template_read = self.fastFive[oneD_address + "/BaseCalled_template/Fastq"][()].split()[2]
self.complement_event_table_address = oneD_address + '/BaseCalled_complement/Events'
self.complement_model_address = ""
self.complement_model_id = None
self.complement_read = self.fastFive[oneD_address + "/BaseCalled_complement/Fastq"][()].split()[2]
return True
else:
self.logError("Unsupported Version (1.15.0, 1.19.0, 1.20.0, 1.22.2, 1.22.4 supported)", parent_job)
return False
def assemble_2d_sequence_from_table(self):
"""The 2D read sequence contains kmers that may not map to a template or complement event, which can make
mapping difficult downstream. This function makes a sequence from the 2D alignment table, which is usually
pretty similar to the 2D read, except it is guaranteed to have an event map to every position.
returns: sequence made from alignment table
"""
def find_kmer_overlap(k_i, k_j):
""" finds the overlap between two non-identical kmers.
k_i: one kmer
k_j: another kmer
returns: The number of positions not matching
"""
for i in xrange(1, len(k_i)):
sk_i = k_i[i:]
sk_j = k_j[:-i]
if sk_i == sk_j:
return i
return len(k_i)
self.alignment_table_sequence = ''
self.alignment_table_sequence = self.twoD_alignment_table[0][2]
p_kmer = self.twoD_alignment_table[0][2]
# iterate through the k-mers in the alignment table
for t, c, kmer in self.twoD_alignment_table:
# if we're at a new 6-mer
if kmer != p_kmer:
# find overlap, could move up to len(k-mer) - 1 bases
i = find_kmer_overlap(p_kmer, kmer)
# append the suffix of the new 6-mer to the sequence
self.alignment_table_sequence += kmer[-i:]
# update
p_kmer = kmer
else:
continue
return
def init_1d_event_maps(self):
"""Maps the events from the template and complement strands to their base called kmers the map
generated by this function is called the "strand_event_map" because it only works for mapping the
strand read (1D read) to to it's events. Uses the same fields as 'get_twoD_event_map' below.
"""
def make_map(events):
event_map = [0]
previous_prob = 0
for i, line in islice(enumerate(events), 1, None):
move = line['move']
this_prob = line['p_model_state']
if move == 1:
event_map.append(i)
if move > 1:
for skip in xrange(move - 1):
event_map.append(i - 1)
event_map.append(i)
if move == 0:
if this_prob > previous_prob:
event_map[-1] = i
previous_prob = this_prob
final_event_index = [event_map[-1]]
padding = final_event_index * (self.kmer_length - 1)
event_map = event_map + padding
return event_map
self.template_strand_event_map = make_map(self.template_events)
assert len(self.template_strand_event_map) == len(self.template_read)
if self.twoD:
self.complement_strand_event_map = make_map(self.complement_events)
assert len(self.complement_strand_event_map) == len(self.complement_read)
return True
def get_twoD_event_map(self):
"""Maps the kmers in the alignment table sequence read to events in the template and complement strand reads
"""
def kmer_iterator(dna, k):
for i in xrange(len(dna)):
kmer = dna[i:(i + k)]
if len(kmer) == k:
yield kmer
# initialize
alignment_row = 0
prev_alignment_kmer = ''
nb_template_gaps = 0
previous_complement_event = None
previous_template_event = None
#twoD_init = self.initialize_twoD()
#if twoD_init is False:
# return False
if not self.has2D_alignment_table:
print("{file} doesn't have 2D alignment table".format(file=self.filename))
return False
self.assemble_2d_sequence_from_table()
# go thought the kmers in the read sequence and match up the events
for i, seq_kmer in enumerate(kmer_iterator(self.alignment_table_sequence, self.kmer_length)):
# assign the current row's kmer
current_alignment_kmer = self.twoD_alignment_table[alignment_row][2]
# in the situation where there is a repeat kmer in the alignment then
# we want to pick the best event to kmer alignment, TODO implement this
# right now we just use the first alignment
while current_alignment_kmer == prev_alignment_kmer:
alignment_row += 1
current_alignment_kmer = self.twoD_alignment_table[alignment_row][2]
# a match
if seq_kmer == current_alignment_kmer:
template_event = self.twoD_alignment_table[alignment_row][0]
complement_event = self.twoD_alignment_table[alignment_row][1]
# handle template event
# if there is a gap, count it and don't add anything to the map
if template_event == -1:
nb_template_gaps += 1
# if there is an aligned event
if template_event != -1:
# if it is an aligned event and there are no gaps, add it to the map
if nb_template_gaps == 0:
self.template_event_map.append(template_event)
# update
previous_template_event = template_event
# if there were gaps in the alignment we have to add 'best guess'
# event alignments to the map which is the current aligned event
if nb_template_gaps > 0:
self.template_event_map += [template_event] * (nb_template_gaps + 1)
# reset template gaps
nb_template_gaps = 0
# update
previous_template_event = template_event
# handle complement event
# if there is a gap, add the last aligned complement event to the map
if complement_event == -1:
self.complement_event_map.append(previous_complement_event)
# if there is an aligned complement event add it to the map
if complement_event != -1:
self.complement_event_map.append(complement_event)
# update the most recent aligned complement event
previous_complement_event = complement_event
# update previous alignment kmer and increment alignment row
prev_alignment_kmer = current_alignment_kmer
alignment_row += 1
continue
# not a match, meaning that this kmer in the read sequence is not
# in the event alignment but we need to assign an event to it so
# we use the heuristic that we use the alignment of the most
# recent aligned events to this base
if seq_kmer != current_alignment_kmer:
self.template_event_map.append(previous_template_event)
self.complement_event_map.append(previous_complement_event)
continue
# fill in the final events for the partial last kmer
for _ in xrange(self.kmer_length - 1):
self.template_event_map += [previous_template_event] * (nb_template_gaps + 1)
self.complement_event_map.append(previous_complement_event)
nb_template_gaps = 0
# check that we have mapped all of the bases in the 2D read
assert(len(self.template_event_map) == len(self.alignment_table_sequence))
assert(len(self.complement_event_map) == len(self.alignment_table_sequence))
return True
def get_template_events(self):
if self.template_event_table_address in self.fastFive:
self.template_events = self.fastFive[self.template_event_table_address]
return True
if self.template_event_table_address not in self.fastFive:
return False
def get_complement_events(self):
if self.complement_event_table_address in self.fastFive:
self.complement_events = self.fastFive[self.complement_event_table_address]
return True
if self.complement_event_table_address not in self.fastFive:
return False
def get_template_model_adjustments(self):
if self.template_model_address in self.fastFive:
self.has_template_model = True
self.template_scale = self.fastFive[self.template_model_address].attrs["scale"]
self.template_shift = self.fastFive[self.template_model_address].attrs["shift"]
self.template_drift = self.fastFive[self.template_model_address].attrs["drift"]
self.template_var = self.fastFive[self.template_model_address].attrs["var"]
self.template_scale_sd = self.fastFive[self.template_model_address].attrs["scale_sd"]
self.template_var_sd = self.fastFive[self.template_model_address].attrs["var_sd"]
if self.template_model_address not in self.fastFive:
self.has_template_model = False
return
def get_complement_model_adjustments(self):
if self.complement_model_address in self.fastFive:
self.has_complement_model = True
self.complement_scale = self.fastFive[self.complement_model_address].attrs["scale"]
self.complement_shift = self.fastFive[self.complement_model_address].attrs["shift"]
self.complement_drift = self.fastFive[self.complement_model_address].attrs["drift"]
self.complement_var = self.fastFive[self.complement_model_address].attrs["var"]
self.complement_scale_sd = self.fastFive[self.complement_model_address].attrs["scale_sd"]
self.complement_var_sd = self.fastFive[self.complement_model_address].attrs["var_sd"]
if self.complement_model_address not in self.fastFive:
self.has_complement_model = False
return
def get_model_id(self, address):
if address in self.fastFive:
model_name = self.fastFive[address].attrs["model_file"]
model_name = model_name.split('/')[-1]
return model_name
else:
return None
def Write(self, parent_job, out_file, initialize=True):
if initialize:
ok = self.Initialize(parent_job)
if not ok:
self.close()
return False
if self.twoD:
twoD_map_check = self.get_twoD_event_map()
complement_events_check = self.get_complement_events()
else:
twoD_map_check = True
complement_events_check = True
template_events_check = self.get_template_events()
oneD_event_map_check = self.init_1d_event_maps()
ok = False not in [twoD_map_check, template_events_check, complement_events_check, oneD_event_map_check]
if not ok:
self.close()
return False
# get model params
self.get_template_model_adjustments()
if self.twoD:
self.get_complement_model_adjustments()
# Make the npRead
# line 1 parameters
print(len(self.alignment_table_sequence), end=' ', file=out_file) # 0alignment read length
print(len(self.template_events), end=' ', file=out_file) # 1nb of template events
print(len(self.complement_events), end=' ', file=out_file) # 2nb of complement events
print(len(self.template_read), end=' ', file=out_file) # 3length of template read
print(len(self.complement_read), end=' ', file=out_file) # 4length of complement read
print(self.template_scale, end=' ', file=out_file) # 5template scale
print(self.template_shift, end=' ', file=out_file) # 6template shift
print(self.template_var, end=' ', file=out_file) # 7template var
print(self.template_scale_sd, end=' ', file=out_file) # 8template scale_sd
print(self.template_var_sd, end=' ', file=out_file) # 9template var_sd
print(self.template_drift, end=' ', file=out_file) # 0template_drift
print(self.complement_scale, end=' ', file=out_file) # 1complement scale
print(self.complement_shift, end=' ', file=out_file) # 2complement shift
print(self.complement_var, end=' ', file=out_file) # 3complement var
print(self.complement_scale_sd, end=' ', file=out_file) # 4complement scale_sd
print(self.complement_var_sd, end=' ', file=out_file) # 5complement var_sd
print(self.complement_drift, end=' ', file=out_file) # 6complement_drift
print((1 if self.twoD else 0), end='\n', file=out_file) # has 2D
# line 2 alignment table sequence
print(self.alignment_table_sequence, end='\n', file=out_file)
# line 3 template read
print(self.template_read, end='\n', file=out_file)
# line 4 template strand map
for _ in self.template_strand_event_map:
print(_, end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 5 complement read
print(self.complement_read, end='\n', file=out_file)
# line 6 complement strand map
for _ in self.complement_strand_event_map:
print(_, end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 7 template 2D event map
for _ in self.template_event_map:
print(_, end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 8 template events
template_start_time = self.template_events[0]['start']
for mean, stdev, length, start in self.template_events['mean', 'stdv', 'length', 'start']:
print(mean, stdev, length, (start - template_start_time), sep=' ', end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 9 complement 2D event map
for _ in self.complement_event_map[::-1]:
print(_, end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 10 complement events
if self.twoD:
complement_start_time = self.complement_events[0]['start']
for mean, stdev, length, start in self.complement_events['mean', 'stdv', 'length', 'start']:
print(mean, stdev, length, (start - complement_start_time), sep=' ', end=' ', file=out_file)
else:
pass
print("", end="\n", file=out_file)
# line 11 model_state (template)
for _ in self.template_events['model_state']:
print(_, sep=' ', end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 12 p(model) (template)
for _ in self.template_events['p_model_state']:
print(_, sep=' ', end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 13 model_state (complement)
if self.twoD:
for _ in self.complement_events['model_state']:
print(_, sep=' ', end=' ', file=out_file)
print("", end="\n", file=out_file)
# line 14 p(model) (complement)
if self.twoD:
for _ in self.complement_events['p_model_state']:
print(_, sep=' ', end=' ', file=out_file)
print("", end="\n", file=out_file)
return True
def close(self):
self.fastFive.close()
@staticmethod
def logError(message, parent_job=None):
if parent_job is None:
print(message, file=sys.stderr)
else:
parent_job.fileStore.logToMaster(message)
# -
d = NanoporeRead(fast_five_file= "../albacore/albacore-data/DEAMERNANOPORE_20161206_FNFAB49164_MN16450_sequencing_run_MA_821_R9_4_NA12878_12_06_16_71094_ch83_read186_strand.fast5", twoD= False)
d.Initialize(parent_job= None)
fh = open("../fh.txt", "w")
d.Write(parent_job=None, out_file= fh, initialize=True)
d.get_latest_basecall_edition("/Analyses/Basecall_1D_00{}")
d.get_template_events()
d.init_1d_event_maps()
fastFive = h5py.File("../albacore/albacore-data/DEAMERNANOPORE_20161206_FNFAB49164_MN16450_sequencing_run_MA_821_R9_4_NA12878_12_06_16_71094_ch83_read186_strand.fast5", 'r')
TEMPLATE_BASECALL_KEY_0 = "/Analyses/Basecall_1D_001"
TEMPLATE_BASECALL_KEY_0 in fastFive
oneD_root_address = d.get_latest_basecall_edition("/Analyses/Basecall_1D_00{}")
oneD_root_address
VERSION_KEY = "version"
VERSION_KEY in fastFive[oneD_root_address].attrs.keys()
version = d.fastFive[oneD_root_address].attrs["version"]
version
SUPPORTED_1D_VERSIONS = ("1.2.1")
version in SUPPORTED_1D_VERSIONS
template_event_table_address = "%s/BaseCalled_template/Events" % oneD_root_address
template_model_address = "%s/BaseCalled_template/Model" % oneD_root_address
template_model_id = None
template_event_table_address
template_model_address
fastq_sequence_address = "%s/BaseCalled_template/Fastq" % oneD_root_address
fastq_sequence_address
fastq_sequence_address in fastFive
template_read= fastFive[fastq_sequence_address][()].split()[2]
template_read
read_label= fastFive[fastq_sequence_address][()].split()[0][1:]
read_label
kmer_length= len(fastFive[template_event_table_address][0][4])
kmer_length
template_read_length = len(template_read)
template_read_length
| notebook/version1.2.1-control-albacore.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="htWoJBWIGGg0"
# # Functional Programming
#
# Playground notebook with notes and examples taken while studying the
# report
# [Functional Programming in Python](https://www.oreilly.com/library/view/functional-programming-in/9781492048633/)
# by <NAME>.
# + [markdown] id="ifSJIqowMgND"
# ## Closure
#
# - **Class** *«Data with operations attached*».
# - **Closure** *«operations with data attached»*.
# + id="cQcEKRh9GFTb" outputId="ff64ef12-9cb9-4d40-b8ea-1e1482f85c9d" colab={"base_uri": "https://localhost:8080/"}
def make_adder(n):
def adder(m):
return n + m
return adder
# Create and call the closure
adder_1 = make_adder(1)
print(adder_1(5))
print(adder_1(1))
# + [markdown] id="gV2uTgxSSoIV"
# ## Resources
#
# - [Functional Programming HOWTO](https://docs.python.org/3/howto/functional.html).
| notebooks/Functional_programming.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import math
import sys
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import matplotlib.cm as plt_cm
from PIL import Image
from skimage.filters import gaussian, sobel
from skimage.feature import canny
from skimage.transform import hough_line, hough_line_peaks, probabilistic_hough_line, resize
# Load image
print("Loading images")
raw_img = Image.open('./test.jpg').convert('L')
img = np.asarray(raw_img)
resize_fact = 8
img = resize(img, (math.floor(img.shape[0]/resize_fact), math.floor(img.shape[1]/resize_fact)),
mode='reflect',
anti_aliasing=False)
# Apply filters
print("Applying filters")
# ... Gaussian Blur
print(" Gaussian blur")
gaussian_img = gaussian(img,
sigma=1.0)
# ... Sobel Edge
print(" Sobel edge detect")
sobel_img = sobel(gaussian_img)
# ... Hough Line
print(" Hough line detect")
hough_lines = probabilistic_hough_line(sobel_img,
threshold=100,
line_length=5,
line_gap=0)
print(" Found {}".format(len(hough_lines)))
# Show images
print("Plotting")
fig, axes = plt.subplots(nrows=4,
ncols=1,
figsize=(15, 15))
# ... Original
print(" Original image")
orig_ax = axes[0]
orig_ax.imshow(img,
cmap=plt_cm.gray)
orig_ax.set_title('Original')
# ... Gaussian
print(" Gaussian blurred image")
gauss_ax = axes[1]
gauss_ax.imshow(gaussian_img,
cmap=plt_cm.gray)
gauss_ax.set_title('Gaussian')
# ... Sobel
print(" Sobel edge detected image")
sobel_ax = axes[2]
sobel_ax.imshow(sobel_img,
cmap=plt_cm.gray)
sobel_ax.set_title('Sobel')
# ... Hough
print(" Hough detected lines")
hough_ax = axes[3]
"""
for _, angle, dist in zip(*hough_line_peaks(hspace, hangles, hdists)):
y0 = (dist * np.cos(angle)) / np.sin(angle)
y1 = (dist - img.shape[1] * np.cos(angle)) / np.sin(angle)
hough_ax.plot((0, img.shape[1]),
(y0, y1),
color='red',
alpha=0.3)
"""
hough_ax.imshow(sobel_img)
sys.stdout.write(" ")
i = 0
for line in hough_lines:
p0, p1 = line
hough_ax.plot((p0[0], p1[0]),
(p0[1], p1[1]),
alpha=0.5)
#color='red',
#alpha=0.3)
if i % 100 == 0:
sys.stdout.write(".")
sys.stdout.flush()
i += 1
print()
hough_ax.set_title('Hough')
hough_ax.set_xlim((0, img.shape[1]))
hough_ax.set_ylim((img.shape[0], 0))
print("Calling show")
plt.show()
# -
| .ipynb_checkpoints/main-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Ridge and LAsso Regression implementation
from sklearn.datasets import load_boston
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=load_boston()
df
dataset = pd.DataFrame(df.data)
print(dataset.head())
dataset.columns=df.feature_names
dataset.head()
df.target.shape
dataset["Price"]=df.target
dataset.head()
X=dataset.iloc[:,:-1] ## independent features
y=dataset.iloc[:,-1] ## dependent features
# ## Linear Regression
#
# +
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
lin_regressor=LinearRegression()
mse=cross_val_score(lin_regressor,X,y,scoring='neg_mean_squared_error',cv=5)
mean_mse=np.mean(mse)
print(mean_mse)
# -
# ## Ridge Regression
# +
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
ridge=Ridge()
parameters={'alpha':[1e-15,1e-10,1e-8,1e-3,1e-2,1,5,10,20,30,35,40,45,50,55,100]}
ridge_regressor=GridSearchCV(ridge,parameters,scoring='neg_mean_squared_error',cv=5)
ridge_regressor.fit(X,y)
# -
print(ridge_regressor.best_params_)
print(ridge_regressor.best_score_)
# ## Lasso Regression
# +
from sklearn.linear_model import Lasso
from sklearn.model_selection import GridSearchCV
lasso=Lasso()
parameters={'alpha':[1e-15,1e-10,1e-8,1e-3,1e-2,1,5,10,20,30,35,40,45,50,55,100]}
lasso_regressor=GridSearchCV(lasso,parameters,scoring='neg_mean_squared_error',cv=5)
lasso_regressor.fit(X,y)
print(lasso_regressor.best_params_)
print(lasso_regressor.best_score_)
# -
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
prediction_lasso=lasso_regressor.predict(X_test)
prediction_ridge=ridge_regressor.predict(X_test)
# +
import seaborn as sns
sns.distplot(y_test-prediction_lasso)
# +
import seaborn as sns
sns.distplot(y_test-prediction_ridge)
# -
| new_learning/Ridge_and_Lasso_Regression.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Make 3D mixed shape training data with boundary interior methods¶
# Loop into the directory Documents/unet/data/cellmodeller_simulation/to_use_GT/mix_label
# Inputs are 3D sub tif images for each class.
# Outputs are binary label image,
# and corresponding five class: 1 being the background, 2/3 being the interior/boundary of the first class,
# and 4/5 being the interior/boundary of the second class.
import os
import numpy as np
from skimage.io import imsave, imread
from skimage.segmentation import find_boundaries
import time, datetime
#save as .nii file
import nibabel as nib
import pathlib
# Here: specify the two classes you want to input. Class 1 is either bend or sphere: class 2 is always rod
class1 = 'sphere' # change to bend if needed
class2 = 'rod'
nameIDX = -(len(class1) + 6)
def get_boundaryInterior(image):
image_size_x, image_size_y = image[1].shape
# make a semantic mask
semantic_masks = np.zeros(( len(image), image_size_x, image_size_y)) #, dtype = K.floatx())
# print(semantic_masks.shape)
# print(images.shape)
edges = find_boundaries(image, mode = 'thick')
interior = 2*(image > 0)
semantic_mask = edges + interior
semantic_mask[semantic_mask == 3] = 1
# Swap category names - edges category 2, interior category 1, background category 0
semantic_mask_temp = np.zeros(semantic_mask.shape, dtype = 'int')
semantic_mask_temp[semantic_mask == 1] = 2
semantic_mask_temp[semantic_mask == 2] = 1
semantic_mask = semantic_mask_temp
print(semantic_masks.shape)
# save as nii
binary_seg = np.transpose(semantic_mask)
return binary_seg
# change image directory as needed
mix_dir = os.path.join('data', 'mixShape')
today = datetime.date.today()
todaystr = today.isoformat()
output_path= os.path.join('output', 'boundary_interior_output', todaystr)
pathlib.Path(output_path).mkdir(parents=True, exist_ok=True) # create directory if neccessary
# +
for img in os.listdir(mix_dir):
if img.find(class1) != -1:
img_sphere = imread(os.path.join(mix_dir, img))
# result = find(img,'_')
name, ext = os.path.splitext(img)
img_rod = imread(os.path.join(mix_dir, name[0:nameIDX] + 'rod_Label' + ext))
print(img_sphere.shape)
print(img_rod.shape)
binarySeg_sphere = get_boundaryInterior(img_sphere)
binarySeg_rod = get_boundaryInterior(img_rod)
binarySeg_rod[binarySeg_rod == 1] = 3
binarySeg_rod[binarySeg_rod == 2] = 4
#combine
binary_seg = binarySeg_rod + binarySeg_sphere
# have problems sometimes output larger than '5' when overlap
binary_seg[binary_seg > 4] = 4
# make and save nifty images
bseg = nib.Nifti1Image(binary_seg.astype(np.uint16), affine=np.eye(4))
# make a new directory to save
new_name = img.replace('_' + class1 + '_Label.tif','')
# change the saved file names
nib.nifti1.save(bseg, os.path.join(output_path, new_name + '_Label.nii'))
| trainingDataGenerate/trainingDataGenerate_mixShape.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Ruby 2.4.1
# language: ruby
# name: ruby
# ---
require 'daru/view'
Daru::View.plotting_library = :googlecharts
data_str = 'https://docs.google.com/spreadsheets/d/1aXns2ch8y_rl9ZLxSYZIU5ewUB1ZNAg5O6iPLZLApZI/gviz/tq?header=1&tq='
table = Daru::View::Table.new(data_str, width: 500)
table.show_in_iruby
plot = Daru::View::Plot.new(data_str, {type: :bar, width: 800})
plot.show_in_iruby
query1 = 'SELECT C, sum(B) group by C'
table = Daru::View::Table.new(data_str + query1, width: 800)
table.show_in_iruby
query2 = 'SELECT * WHERE A > 1'
data_str << query2
table = Daru::View::Table.new(data_str, width: 800)
table.show_in_iruby
plot = Daru::View::Plot.new(data_str, {type: :line})
plot.show_in_iruby
query_string = 'SELECT A, H, O, Q, R, U LIMIT 5 OFFSET 8'
data_spreadsheet = 'https://docs.google.com/spreadsheets/d/1XWJLkAwch5GXAt_7zOFDcg8Wm8Xv29_8PWuuW15qmAE/gviz/tq?gid=0&headers=1&tq='
table_spreadsheet = Daru::View::Table.new(data_spreadsheet + query_string, width: 800)
table_spreadsheet.show_in_iruby
plot_spreadsheet = Daru::View::Plot.new(data_spreadsheet + query_string, {type: :area, width: 800})
plot_spreadsheet.show_in_iruby
plot_sheet = Daru::View::Plot.new(data_spreadsheet + query_string, {type: :column, width: 800})
plot_sheet.show_in_iruby
query = 'SELECT H, O, Q, R WHERE O > 1'
plot_sheet = Daru::View::Plot.new(data_spreadsheet + query)
plot_sheet.show_in_iruby
| spec/dummy_iruby/Google Chart | Data from google spreadsheet.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Companion code for "Persistent homology based computed tomography measurements of fibrosis and emphysema in lung diseases"
#
# - Input data file: volume data should be prepared in the dicom format or the numpy format (.npz)
# -- the npz file should be placed under the directory specified by root_npy
# -- the dicom series should be placed under a single directory under the directory specified by root_npy
#install necessary packages only if you do not have them yet
# !pip install persim ipywidgets
# !pip install git+https://github.com/shizuo-kaji/CubicalRipser_3dim
# +
## This program requires a lot of (GPU) memory.
## Restart the kernel when you get "out of memory" errors.
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
from mpl_toolkits.mplot3d import Axes3D
import os,time,subprocess,glob,re,pandas
from scipy.ndimage.filters import convolve
import ipywidgets as ipyw
import k3d
import seaborn as sns
from lung_whole_batch import *
np.set_printoptions(precision=5,suppress=True)
# -
# ## Setting
# +
## characteristic cycles
# cycles of 'dim' with birth time between b0 through b1, death time between d0 through d1, lifetime between l0 through l1 will be counted
# and those voxels with density higher than th will be visualized
cond = [
{'name': 'fib', 'dim': 0, 'b0':-1260, 'b1':-380, 'd0': -5000, 'd1': 5000, 'l0': 360, 'l1': 5000, 'th': 1},
{'name': 'emp', 'dim': 2, 'b0':-1020, 'b1':-900, 'd0': -5000, 'd1': 5000, 'l0': 20, 'l1': 90, 'th': 8.3},
]
th_def = [f['th'] for f in cond]
## GPU
gpu_id = 0 ## use the first gpu on the system
#gpu_id = -1 ## in case you do not have GPU
## the directory containing all data files
root_npy = os.path.expanduser("~/ipf/npy/")
## filename and the z-slice to be focused
name, init_z="PD20813300segmentedfinal", 381
#name, init_z="R135000_009", 0
## labelling (optional)
data_fn = "idlist.csv"
if os.path.isfile(data_fn):
dat = pandas.read_csv(data_fn,header=0)
names = dat['name'].tolist()
label = dat.at[names.index(name),'label']
else:
label = "unknown"
## gaussian kernel parameter
sigma, h = 10.0, 12
## filename for cache for cycle_norm
# change this everytime you change either sigma, h, cond
cycle_data_suffix = "_cyc200930.npz"
## focus on a spefic z-range for efficiency
#z_crop = (init_z-2*h, init_z+2*h)
z_crop = None # process the whole volume
## flag to recompute characteristic cycles based on "cond"
recompute_cycle_norm = False
print("characteristic cycles: ",cond)
if not os.path.isdir(root_npy):
print("set root_npy correctly!")
print("npy dir: ",root_npy)
# -
# ## Main
# +
## load/compute volume (vol), persistent homology (pd), cycle density (cycle_norm)
## results will be cached under root_npy. remove the cache files if you want to recompute.
print("loading... {}, label {}, z_crop {}".format(name, label, z_crop))
base_fn = os.path.join(root_npy,name)
# load volume from a cached npz file. If not present, load from DICOM files and save to a npz file
vol = load_vol(base_fn+".npz",z_crop=z_crop, save_npz=True)
# load persistet diagram from a cached npz file. If not present, compute from the volume and save to a npz file
pd = load_pd(base_fn,vol=vol,z_crop=z_crop)
# load segmented volume for comparison (optional)
nn_vol = load_vol(base_fn+"_NN1.npz",z_crop=z_crop)
if nn_vol is None:
nn_vol = np.zeros_like(vol)
else:
nn_vol = nn_vol.astype(np.float32)
print("Volume: ",vol.shape," PD: ",pd.shape)
# compute cycle norm (density of characteristic cycles specified by 'cond')
# the result will be saved in the file "*+cycle_data_suffix".
# cycle norm should be recomputed everytime any of 'cond', 'h', 'sigma' is changed.
recompute_data = {'vol': vol, 'pd': pd, 'cond': cond, 'h':h, 'sigma':sigma, 'gpu_id': gpu_id, 'force': recompute_cycle_norm}
cycle_norm = load_cyc(base_fn+cycle_data_suffix,recompute=recompute_data,z_crop=z_crop,verbose=True)
# print some statistics
stats = volume_stat(vol,cycle_norm, th_def)
st = ["vol",cond[0]['name'],cond[1]['name'],cond[0]['name']+"_ratio",cond[1]['name']+"_ratio",cond[0]['name']+"_99%",cond[1]['name']+"_99%",
cond[0]['name']+"%>th",cond[1]['name']+"%>th","HAA%","LAA%"]
for s,ff in zip(st,stats):
print(s,"\t\t",ff)
#stats = volume_stat(vol,nn_vol, [0.5,0.5])
#st = ["fib_NN_ratio","emp_NN_ratio","fib_NN_99%","fib_NN_99%","emp_NN%>0.5","emp_NN%>0.5"]
#for s,ff in zip(st,stats[3:-2]):
# print(s,"\t\t",ff)
# -
# persistence diagram
PDView(pd,cond,save_fn="PD_"+name+".jpg")
#PDView(pd,cond,zmin=init_z-20,zmax=init_z+20)
# +
# persistence image plot
import persim
min_birth, max_death = -1000,1000
pdl = [np.clip(pd[pd[:,0]==i,1:3],min_birth, max_death) for i in range(3)]
pimgr = persim.PersistenceImager(pixel_size=50, birth_range=(min_birth,max_death), pers_range=(0,max_death-min_birth), kernel_params={'sigma': [[1000.0, 0.0], [0.0, 1000.0]]})
pimgr.fit(pdl, skew=True)
pimgs = pimgr.transform(pdl, skew=True,n_jobs=-1)
print(pimgr)
## alternative: this can be faster
#import PersistenceImages.persistence_images as pimg
#h = 30
#pimgr = pimg.PersistenceImager(birth_range=(min_birth, max_death), pers_range=(0,max_death-min_birth),pixel_size=(max_death-min_birth)/h)
#pimgs = [pim.transform(pdl[i]) for i in range(3)]
plt.figure(figsize=(10,5))
for i in range(3):
ax = plt.subplot(1,3,i+1)
pimgr.plot_image(pimgs[i], ax)
plt.title("persistence image of H_{}".format(i))
# +
## 3D visualisation (computationally demanding)
## requires k3d: install it by `pip install k3d`
ct_min, ct_max = -1000,500
th_nn = [0.5,0.5]
th = th_def
volume = k3d.volume(
((np.clip(vol,ct_min,ct_max)-ct_min)/(ct_max-ct_min)).astype(np.float32),
# alpha_coef=1000,
# samples=600,
color_range=[0,1],
color_map=np.array(k3d.colormaps.matplotlib_color_maps.gray).astype(np.float32),
# color_map=np.array(k3d.colormaps.matplotlib_color_maps.Gist_heat).reshape(-1,4).astype(np.float32),
compression_level=1
)
fib_mask = k3d.volume((cycle_norm[0]>th[0]).astype(np.float16), color_range=[0,1],
color_map=np.array(k3d.colormaps.matplotlib_color_maps.Reds),
)
emp_mask = k3d.volume((cycle_norm[1]>th[1]).astype(np.float16), color_range=[0,1],
color_map=np.array(k3d.colormaps.matplotlib_color_maps.Blues),
)
plot = k3d.plot(grid_visible=False)
plot += volume
plot += fib_mask
plot += emp_mask
plot.lighting = 2
plot.display()
# +
# visualise pixels above/below threshold values (overlay)
print(name,label)
red,blue = 500, 1000
th_nn = [0.5,0.5]
th = th_def
if z_crop:
zz = (z_crop[1]-z_crop[0])//2
else:
zz = init_z
_ = ImageSliceViewer3D([ np.stack([vol,vol,vol]), # original CT
np.stack([vol+red*(cycle_norm[0]>th[0]),vol,vol+blue*(cycle_norm[1]>th[1])*(cycle_norm[0]<=th[0])]), # PH
np.stack([vol+red*(nn_vol[0]>th_nn[0]),vol,vol+blue*(nn_vol[1]>th_nn[1])]), ## NN
np.stack([vol+red*(vol>-200),vol,vol+blue*(-2048<vol)*(vol<-950)]), ## LAA/HAA
],colour=True,
title=["CT","PH","NN","AA"],
init_z=zz, vmin=[-1000],vmax=[500],save="{}_z{}.jpg".format(name,init_z)
)
# +
# visualise a single slice
th = th_def
print(name,label, "z={}".format(init_z))
if z_crop:
zz = (z_crop[1]-z_crop[0])//2
else:
zz = init_z
v=vol[:,:,[zz]]
_ = ImageSliceViewer3D([np.stack([v,v,v]),
np.stack([v+red*(cycle_norm[0,:,:,zz:(zz+1)]>th[0]),v,v+blue*(cycle_norm[1,:,:,zz:(zz+1)]>th[1])*(cycle_norm[0,:,:,zz:(zz+1)]<=th[0])]),
np.stack([v+red*(nn_vol[0,:,:,zz:(zz+1)]>th_nn[0]),v,v+blue*(nn_vol[1,:,:,zz:(zz+1)]>th_nn[1])]), ## NN
np.stack([v+red*(v>-200),v,v+blue*(-2048<v)*(v<-950)]),
], title=["CT","PH","NN","AA"],
vmin=[-1000],vmax=[500],colour=True)
# +
# visualise pixels above/below threshold values (replace)
base_vol = (np.clip(np.stack([vol,vol,vol]),-1000,500)+1000)/1500
PHmarked_vol = np.stack([cycle_norm[0]>th[0],np.zeros_like(cycle_norm[0]),cycle_norm[1]>th[1]])
PHmarked_vol = np.where(np.max(PHmarked_vol,axis=0)>0, PHmarked_vol, base_vol)
HUmarked_vol = np.stack([vol>-200,np.zeros_like(cycle_norm[0]),np.logical_and(-2048<vol,vol<-950)])
HUmarked_vol = np.where(np.max(HUmarked_vol,axis=0)>0, HUmarked_vol, base_vol)
_ = ImageSliceViewer3D([base_vol,PHmarked_vol,HUmarked_vol],init_z=init_z, colour=True)
# -
# visualise pixel values (separately)
# set vmin and vmax for viewing level window
# choose cmap from https://matplotlib.org/examples/color/colormaps_reference.html
_ = ImageSliceViewer3D([vol,cycle_norm[0],cycle_norm[1]],vmin=[-1000,0,0,0],title=["CT","fib","emp"],
init_z=init_z,cmap=['gray','Reds','Reds'])
# histgram of cycle density
in_cycle = cycle_norm[:,vol>-2048]
plt.figure(figsize=(12,4))
for i,a in enumerate(in_cycle):
ax = plt.subplot(1,len(in_cycle),i+1)
ax.hist(a.flatten(),bins=20, log=True)
ax.set_title(cond[i]['name'])
print("99 percentile: ", np.percentile(a, 99))
# ## Comparison of segmentation
# +
## visualise and compute Dice for segmentation of emphysema and fibrosis
from sklearn.metrics import jaccard_score
from PIL import Image
root_label ="label_image/final_label"
root_manual2 ="label_image/shima_label"
models = {"Manual2": None, "PH25": None,"PH50": None,"NN1": None, "AA": None, "AAconv": None}
models = {"Manual2": None}
names = [os.path.splitext(os.path.splitext(fname)[0])[0] for fname in sorted(os.listdir(root_label)) if fname.endswith(".tif") or fname.endswith(".npy")]
#names = ["IPF144segmentedfinal_405","PD20813300segmentedfinal_382"] ## for figure in the paper
## computation for DICE
# names = ["IPF030segmentedfinal_438","IPF035segmentedfinal_436","IPF083segmentedfinal_480","IPF109segmentedfinal_457","IPF144segmentedfinal_405",
# "IPF147segmentedfinal_431","IPF148segmentedfinal_377","IPF153segmentedfinal_474","IPF179segmentedfinal_495","MD003001segmentedfinal_405",
# "MD004202segmentedfinal_485","MD006001segmentedfinal_262","MD006901segmentedfinal_343","PD20613093segmentedfinal_317",
# "PD20813300segmentedfinal_382","IPF027segmentedfinal_421","IPF028segmentedfinal_385","IPF029segmentedfinal_344","IPF054segmentedfinal_482",
# "IPF118segmentedfinal_428","IPF133segmentedfinal_529","IPF136segmentedfinal_239","MD000902segmentedfinal_292",
# "MD001601segmentedfinal_413","MD002902segmentedfinal_154"]
n_class=3
print("#Slices: ",len(names))
root_save = "label_image/comparison"
os.makedirs(root_save, exist_ok=True)
save_figure = True
th25 = th_def # ROI25
th50 = [0.4,40] # ROI50
th_nn = [0.5,0.5] # NN
th_aa = [700,2200] # convoluted HAA/LAA
h, sigma = 12, 10
df = pandas.DataFrame.from_dict({'name': names})
for k,fns in enumerate(names):
print(k,fns)
fn = fns[:-4]
init_z = int(fns[-3:])
z_crop = (init_z-int(1.3*h), init_z+int(1.3*h))
zz = (z_crop[1]-z_crop[0])//2
# load volume
base_fn=os.path.join(root_npy,fn)
vol = load_vol(base_fn+".npz",z_crop=z_crop)
v = vol[:,:,[zz]]
print("Volume: ",v.shape)
# load segmentations
if os.path.isfile(os.path.join(root_label,fns)+".npy"):
manual = np.load(os.path.join(root_label,fns)+".npy")[:,:,np.newaxis]
elif os.path.isfile(os.path.join(root_label,fns)+".tif"):
manual = np.array(Image.open(os.path.join(root_label,fns)+".tif").convert('L'))[:,:,np.newaxis]
else:
manual = np.loadtxt(os.path.join(root_label,fns)+".txt")[:,:,np.newaxis]
if "Manual2" in models.keys():
bfn = os.path.join(root_manual2,fns)
if os.path.isfile(bfn+".npy"):
MAN2 = np.load(bfn+".npy")[:,:,np.newaxis]
elif os.path.isfile(bfn+".dcm"):
import pydicom as dicom
ref_dicom_in = dicom.read_file(bfn+".dcm", force=True)
MAN2 = ref_dicom_in.pixel_array+ref_dicom_in.RescaleIntercept
elif os.path.isfile(bfn+".tif"):
MAN2 = np.array(Image.open(bfn+".tif").convert('L'))[:,:,np.newaxis]
elif os.path.isfile(bfn+".txt"):
MAN2 = np.loadtxt(bfn+".txt")[:,:,np.newaxis]
else:
print("not found!")
models["Manual2"] = MAN2
if "PH25" in models.keys():
cycle_25 = load_cyc(base_fn+"_cyc200930.npz",z_crop=z_crop)[:,:,:,[zz]]
PH25 = np.zeros_like(v)
PH25[cycle_25[1,:,:]>th25[1]] = 1 ## class 1 is emp
PH25[cycle_25[0,:,:]>th25[0]] = 2 ## class 2 is fib
models["PH25"] = PH25
if "PH50" in models.keys():
cycle_50 = load_cyc(base_fn+"_cyc200922.npz",z_crop=z_crop)[:,:,:,[zz]]
PH50 = np.zeros_like(v)
PH50[cycle_50[1,:,:]>th50[1]] = 1
PH50[cycle_50[0,:,:]>th50[0]] = 2
models["PH50"] = PH50
if "NN1" in models.keys():
nn_vol = load_vol(base_fn+"_NN1.npz",z_crop=z_crop)[:,:,:,[zz]].astype(np.float32)
NN1 = np.zeros_like(v)
NN1[nn_vol[1,:,:]>th_nn[1]] = 1
NN1[nn_vol[0,:,:]>th_nn[0]] = 2
models["NN1"] = NN1
if "AA" in models.keys():
AA = np.zeros_like(v)
AA[(-2048<v)*(v<-950)] = 1
AA[(v>-200)] = 2
models["AA"] = AA
if "AAconv" in models.keys():
AAconv = np.zeros_like(v)
kernel = gaussian(h,sigma)
aa = conv_channel(np.stack([(v>-200),(-2048<v)*(v<-950)]).astype(np.float32), vol, kernel,verbose=False)[:,:,:,[zz]]
AAconv[aa[1]>th_aa[1]] = 1
AAconv[aa[0]>th_aa[0]] = 2
models["AAconv"] = AAconv
if save_figure:
print("saving figures...")
save_fn = os.path.join(root_save,"{}_{}.jpg".format(fn,init_z))
_ = ImageSliceViewer3D([np.stack([v+500*(manual==2),v,v+800*(manual==1)])]+[
np.stack([v+500*(lb==2),v,v+800*(lb==1)]) for lb in models.values()
],
title=["Manual"]+list(models.keys()),
vmin=[-1000]*8,vmax=[500]*8,
figsize=(120,20),colour=True,save=save_fn,save_exit=True)
if len(names)>3:
plt.close()
print("computing metrics...")
t_label = manual[v>-2048].flatten()
for j,c in enumerate(["nor","emp","fib"]):
df.loc[k,"manual_ratio_{}".format(c)] = sum(t_label==j)/len(t_label)
for dn in models.keys():
l_flatten = models[dn][v>-2048].flatten()
for j,c in enumerate(["nor","emp","fib"]):
df.loc[k,dn+"_dice_{}".format(c)] = jaccard_score(t_label==j,l_flatten==j)
df.loc[k,dn+"_ratio_{}".format(c)] = sum(l_flatten==j)/len(l_flatten)
#print(df.iloc[k])
## write dice scores to file
dice_fname="dice_NN210505b.csv"
df.to_csv(dice_fname,index=False)
# +
# compute Dice for Lung region segmentations
import pydicom as dicom
root_label = "segmentation_image/manual"
root_manual2 ="segmentation_image/NN"
names = [os.path.splitext(os.path.splitext(fname)[0])[0] for fname in sorted(os.listdir(root_label)) if fname.endswith(".txt")]
df = pandas.DataFrame.from_dict({'name': names})
for k,fns in enumerate(names):
print(k,fns)
# load segmentations
if os.path.isfile(os.path.join(root_label,fns)+".npy"):
manual = np.load(os.path.join(root_label,fns)+".npy")[:,:,np.newaxis]
elif os.path.isfile(os.path.join(root_label,fns)+".tif"):
manual = np.array(Image.open(os.path.join(root_label,fns)+".tif").convert('L'))[:,:,np.newaxis]
else:
manual = np.loadtxt(os.path.join(root_label,fns)+".txt")[:,:,np.newaxis]
ref_dicom_in = dicom.read_file(os.path.join(root_manual2,fns)+".dcm", force=True)
NN = ref_dicom_in.pixel_array+ref_dicom_in.RescaleIntercept
t_label = (manual>0).flatten()
l_flatten = (NN>-2048).flatten()
for j,c in enumerate(["in","out"]):
df.loc[k,"manual_vol".format(c)] = sum(t_label)/len(t_label)
df.loc[k,"seg_dice".format(c)] = jaccard_score(t_label,l_flatten)
df.loc[k,"seg_vol".format(c)] = sum(l_flatten)/len(l_flatten)
#print(df.iloc[k])
## write dice scores to file
dice_fname="segment_NN210504.csv"
df.to_csv(dice_fname,index=False)
# +
dice_fname="dice_NN210506.csv"
df = pandas.read_csv(dice_fname, header=0)
models = {"Manual2": None, "PH25": None,"PH50": None,"NN1": None, "AA": None, "AAconv": None}
## plot dice
for t in ["dice","ratio"]:
fig = plt.figure(figsize=(14,5))
plt.subplots_adjust(wspace=1.0, hspace=0.6)
for i,c in enumerate(["nor","emp","fib"]):
ax = fig.add_subplot(1, n_class, i+1)
keys = list(models.keys())
if t=="ratio":
keys = ['manual']+keys
ax.violinplot([df.loc[df.loc[:,dn+"_{}_{}".format(t,c)]>0,dn+"_{}_{}".format(t,c)] for dn in keys])
ax.set_xticks([k+1 for k in range(len(keys))])
ax.set_xticklabels(keys, rotation=45)
ax.set_xlabel('Method')
ax.set_ylabel('{} for label {}'.format(t,c))
ax.set_ylim(0, 1)
plt.savefig("comp_shima_{}.jpg".format(t))
# -
# regression analysis for volume %
import statsmodels.api as sm
res = []
for dn in models.keys():
for i,c in enumerate(["nor","emp","fib"]):
regr = sm.OLS(df.loc[:,dn+"_ratio_{}".format(c)], sm.add_constant(df.loc[:,"manual_ratio_{}".format(c)])).fit()
#print(regr.summary())
res.append({"model": dn, "label": c, "r": np.sqrt(regr.rsquared), "p": regr.pvalues[1]})
res = pandas.DataFrame.from_dict(res)
res.to_csv("volume_analysis.csv",index=False)
# ## Utility
## Gaussian kernel visualisation
h, sigma=12, 9.0
g= gaussian(h,sigma)
print(g.shape, g[h,0,h],g[h,h,h],np.sum(g))
mappable = plt.imshow(g[:,:,h])
plt.colorbar(mappable)
## show memory usage
import psutil
mem = psutil.virtual_memory()
print(mem.used/(1024**2),mem.total/(1024**2),mem.available/(1024**2))
# ## Experimental
# +
## tensorflow vs cupy
## currently, cupy is much faster
import time
import cupy as cp
from cupyx.scipy.ndimage import convolve
kernel = gaussian(h,sigma)
cc = cycle_count(vol,pd,cond,conv=False)
print(cc.shape)
start = time.time()
cp.cuda.Device(gpu_id).use()
cn2 = np.stack([ cp.asnumpy(convolve(cp.asarray(cc[i]),cp.asarray(kernel))) for i in range(len(cc))])
print(cn2.shape)
print ("elapsed_time:{} sec".format(time.time() - start))
start = time.time()
cn = convolve_tf(cc, kernel)
print(cn.shape)
print ("elapsed_time:{} sec".format(time.time() - start))
print(np.allclose(cn,cn2))
| Lung_whole.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.9.2 64-bit
# name: python392jvsc74a57bd0aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49
# ---
# +
#Source : http://www.laalmanac.com/employment/em12c.php#:~:text=Median%20Household%20Income%20in%20Past%2012%20Months%2C%202019%2A,%20%20%2449%2C675%20%2032%20more%20rows%20
# -
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import base64
CSV_FILE = 'census_income_zip'
with open('dataRaw/'+ CSV_FILE +'.csv') as f:
df=pd.read_csv(f, delimiter=';')
df.to_csv('dataClean/'+ CSV_FILE +'.csv', index=False)
| census_internet.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: pymedphys-master
# language: python
# name: pymedphys-master
# ---
# %load_ext autoreload
# %autoreload 2
# +
import pathlib
import json
import IPython.display
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.interpolate
import scipy.signal
import pymedphys
import pymedphys._wlutz.bbpredict
import pymedphys._wlutz.pylinac
import pymedphys._wlutz.iview
import pymedphys._wlutz.imginterp
import pymedphys._wlutz.findfield
import pymedphys._wlutz.findbb
import pymedphys._wlutz.reporting
# -
working_dir = pathlib.Path(r"S:\Physics\RCCC Specific Files\Linac Beam Data Record\Synergy 2619\QA\20200107_6MV_profiler_baselining\Ballbearing")
output_dir = working_dir.joinpath('results')
output_dir.mkdir(exist_ok=True)
cache_path = working_dir.joinpath("cache.json")
# +
penumbra = 2
edge_lengths = [20, 24]
initial_rotation = 0
bb_diameter = 8
bb_predictor_tol = 0.2
pd.set_option("display.max_rows", 101)
# -
clockwise_string = "00_CW"
counter_clockwise_string = "01_CC"
directions_map = {
clockwise_string: "clockwise",
counter_clockwise_string: "counter-clockwise"
}
frame_paths_list = list(working_dir.joinpath("frames").glob("**/*.ppm"))
# frame_paths_list
# +
frame = [path.stem.split('_')[1] for path in frame_paths_list]
timestamps = [path.parent.stem for path in frame_paths_list]
directions = [directions_map[path.parent.parent.stem] for path in frame_paths_list]
beams = [path.parent.parent.parent.stem for path in frame_paths_list]
keys = list(zip(beams, directions, timestamps, frame))
image_paths = {
key: path for key, path in zip(keys, frame_paths_list)
}
# +
# image_paths
# +
key_map = {
key: '-'.join(key) for key in keys
}
inv_key_map = {
item: key for key, item in key_map.items()
}
# -
movie_keys = list({
key[0:3] for key in keys
})
# +
movie_output_dirs = {}
for key in movie_keys:
movie_output_dirs[key] = output_dir.joinpath(f"{key[0]} {key[1]} {key[2]}")
movie_output_dirs[key].mkdir(exist_ok=True)
movie_output_dirs[key].joinpath('images').mkdir(exist_ok=True)
# -
data = {}
try:
with open(cache_path, 'r') as a_file:
data_string_keys = json.load(a_file)
data = {
inv_key_map[key]: item for key, item in data_string_keys.items()
}
except FileNotFoundError:
data = {}
def plot_pylinac_comparison(field, bb_diameter, edge_lengths, penumbra, field_centre, field_rotation, pylinac):
bb_centre = pymedphys._wlutz.findbb.optimise_bb_centre(
field, bb_diameter, edge_lengths, penumbra, field_centre, field_rotation, pylinac_tol=np.inf
)
fig = pymedphys._wlutz.reporting.image_analysis_figure(
x,
y,
img,
bb_centre,
field_centre,
field_rotation,
bb_diameter,
edge_lengths,
penumbra,
)
plt.title('PyMedPhys Basinhopping Method')
fig = pymedphys._wlutz.reporting.image_analysis_figure(
x,
y,
img,
pylinac['v2.2.6']['bb_centre'],
pylinac['v2.2.6']['field_centre'],
field_rotation,
bb_diameter,
edge_lengths,
penumbra,
)
plt.title('Pylinac v2.2.6 Filter and Profile Method')
fig = pymedphys._wlutz.reporting.image_analysis_figure(
x,
y,
img,
pylinac['v2.2.7']['bb_centre'],
pylinac['v2.2.7']['field_centre'],
field_rotation,
bb_diameter,
edge_lengths,
penumbra,
)
plt.title('Pylinac v2.2.7 Filter and Scikit-Image Method')
plt.show()
for key, image_path in image_paths.items():
try:
this_data = data[key]
pymedphys_data = this_data['pymedphys']
except KeyError:
this_data = {}
pymedphys_data = {}
this_data['pymedphys'] = pymedphys_data
data[key] = this_data
try:
pymedphys_data['field_centre']
pymedphys_data['field_rotation']
this_data['pylinac']
pymedphys_data['bb_centre']
except KeyError:
print(key)
x, y, img = pymedphys._wlutz.iview.iview_image_transform(image_path)
field = pymedphys._wlutz.imginterp.create_interpolated_field(x, y, img)
initial_centre = pymedphys._wlutz.findfield.get_centre_of_mass(x, y, img)
try:
pymedphys_data['field_centre']
pymedphys_data['field_rotation']
except KeyError:
try:
pymedphys_data['field_centre'], pymedphys_data['field_rotation'] = pymedphys._wlutz.findfield.field_centre_and_rotation_refining(
field, edge_lengths, penumbra, initial_centre, initial_rotation=initial_rotation
)
except ValueError as e:
print(e)
continue
pymedphys_data['field_centre'] = pymedphys_data['field_centre']
pymedphys_data['field_rotation'] = pymedphys_data['field_rotation']
try:
this_data['pylinac']
except KeyError:
try:
this_data['pylinac'] = pymedphys._wlutz.pylinac.run_wlutz(
field, edge_lengths, penumbra, pymedphys_data['field_centre'], pymedphys_data['field_rotation'])
except Exception as e:
print(e)
pass
try:
pymedphys_data['bb_centre']
except KeyError:
try:
pymedphys_data['bb_centre'] = pymedphys._wlutz.findbb.optimise_bb_centre(
field, bb_diameter, edge_lengths, penumbra, pymedphys_data['field_centre'], pymedphys_data['field_rotation']
)
except pymedphys._wlutz.pylinac.PylinacComparisonDeviation as e:
print(e)
plot_pylinac_comparison(
field, bb_diameter, edge_lengths, penumbra, pymedphys_data['field_centre'], pymedphys_data['field_rotation'],
this_data['pylinac']
)
continue
except ValueError as e:
print(e)
continue
pymedphys_data['bb_centre'] = pymedphys_data['bb_centre']
# +
data_for_json = {
key_map[key]: item for key, item in data.items()
}
with open(cache_path, 'w') as a_file:
json.dump(data_for_json, a_file, indent=2)
# +
# data.keys()
# +
# key_map
# -
# +
movie_data_dicts = {
movie_key: {
int(key[3]): item for key, item in data.items()
if key[0:3] == movie_key
}
for movie_key in movie_keys
}
# -
for key, item in movie_data_dicts.items():
assert list(sorted(item.keys())) == list(range(len(item.keys())))
movie_data = {
movie_key: [item[frame_key] for frame_key in sorted(item.keys())]
for movie_key, item in movie_data_dicts.items()
}
def extract_data(keys, data, lookup_func):
result = {}
for key in keys:
result[key] = []
for item in data[key]:
try:
result[key].append(lookup_func(item))
except KeyError:
result[key].append(np.nan)
result[key] = np.array(result[key])
return result
pymedphys_field_rotations = extract_data(movie_keys, movie_data, lambda x: x['pymedphys']['field_rotation'])
def determine_gantry_angle(direction_key, rotation):
not_nan = np.invert(np.isnan(rotation))
nan_removed_rotation = rotation[not_nan]
if direction_key == 'clockwise':
diff = np.diff(np.concatenate([[-180], nan_removed_rotation]))
diff[diff > 0] = diff[diff > 0] - 180
gantry = -180 - np.cumsum(diff * 2)
elif direction_key == 'counter-clockwise':
diff = np.diff(np.concatenate([[0], nan_removed_rotation]))
diff[diff < 0] = diff[diff < 0] + 180
gantry = 180 - np.cumsum(diff * 2)
else:
raise ValueError("Expected one of 'clockwise' or 'counter-clockwise'")
gantry_with_nans = np.ones_like(rotation) * np.nan
out_of_bounds = np.logical_or(gantry < -180, gantry > 180)
gantry[out_of_bounds] = np.nan
gantry_with_nans[not_nan] = gantry
return gantry_with_nans
# +
gantry_angles = {}
for key in movie_keys:
direction_key = key[1]
rotation = pymedphys_field_rotations[key]
gantry_angles[key] = determine_gantry_angle(direction_key, rotation)
# -
columns=[
'Image Frame', 'Gantry Angle (deg)', 'Field x (mm)', 'Field y (mm)', 'BB x (mm)', 'BB y (mm)'
]
# +
prep_for_dataframe = [
gantry_angles,
extract_data(movie_keys, movie_data, lambda x: x['pymedphys']['field_centre'][0]),
extract_data(movie_keys, movie_data, lambda x: x['pymedphys']['field_centre'][1]),
extract_data(movie_keys, movie_data, lambda x: x['pymedphys']['bb_centre'][0]),
extract_data(movie_keys, movie_data, lambda x: x['pymedphys']['bb_centre'][1]),
]
dataframes = {}
for key in movie_keys:
prepped_data = [item[key] for item in prep_for_dataframe]
frames = [list(range(len(prepped_data[0])))]
dataframe_data = np.vstack(frames + prepped_data).T
dataframe = pd.DataFrame(
columns=columns,
data=dataframe_data
)
dataframe['Image Frame'] = dataframe['Image Frame'].astype(np.int64)
dataframe = dataframe.set_index('Image Frame')
dataframes[key] = dataframe
# +
# dataframes[key]
# +
bb_x_predictor_data = [
dataframes[key]['BB x (mm)'] for key in movie_keys
]
bb_y_predictor_data = [
dataframes[key]['BB y (mm)'] for key in movie_keys
]
gantry_predictor_data = [
gantry_angles[key] for key in movie_keys
]
direction_predictor_data = [key[1] for key in movie_keys]
predict_bb = pymedphys._wlutz.bbpredict.create_bb_predictor(
bb_x_predictor_data, bb_y_predictor_data, gantry_predictor_data, direction_predictor_data, default_tol=bb_predictor_tol)
predict_bb([0, 2], 'clockwise')
# -
gantry_i = np.linspace(-180, 180, 401)
# +
plt.figure(figsize=(12,10))
for g, x, key in zip(gantry_predictor_data, bb_x_predictor_data, movie_keys):
if key[1] == 'clockwise':
prop = '-'
else:
prop = '--'
plt.plot(g, x, prop, alpha=0.5, label=key[0:2])
plt.plot(gantry_i, predict_bb(gantry_i, 'clockwise')[0], 'k')
plt.plot(gantry_i, predict_bb(gantry_i, 'counter-clockwise')[0], 'k--')
plt.legend()
plt.title("Absolute BB iView x position predictor")
plt.xlabel("Gantry Angle (deg)")
plt.ylabel("iView absolute x-position (mm)")
plt.savefig(output_dir.joinpath("Absolute BB x position predictor.png"))
# +
plt.figure(figsize=(12,10))
for g, y, key in zip(gantry_predictor_data, bb_y_predictor_data, movie_keys):
if key[1] == 'clockwise':
prop = '-'
else:
prop = '--'
plt.plot(g, y, prop, alpha=0.5, label=key[0:2])
plt.plot(gantry_i, predict_bb(gantry_i, 'clockwise')[1], 'k')
plt.plot(gantry_i, predict_bb(gantry_i, 'counter-clockwise')[1], 'k--')
plt.legend()
plt.title("Absolute BB iView y position predictor")
plt.xlabel("Gantry Angle (deg)")
plt.ylabel("iView absolute y-position (mm)")
plt.savefig(output_dir.joinpath("Absolute BB y position predictor.png"))
# -
for key in movie_keys:
bb_x = dataframes[key]['BB x (mm)'].copy()
bb_y = dataframes[key]['BB y (mm)'].copy()
gantry = dataframes[key]['Gantry Angle (deg)']
direction = key[1]
isnan = np.isnan(bb_x)
assert np.all(isnan == np.isnan(bb_y))
bb_x_prediction, bb_y_prediction = predict_bb(gantry[isnan], direction)
bb_x[isnan] = bb_x_prediction
bb_y[isnan] = bb_y_prediction
dataframes[key]['BB x [with predictions] (mm)'] = bb_x
dataframes[key]['BB y [with predictions] (mm)'] = bb_y
# +
pylinac_columns = [
'Pylinac Field x (mm)', 'Pylinac Field y (mm)',
'Pylinac v2.2.6 BB x (mm)', 'Pylinac v2.2.6 BB y (mm)',
'Pylinac v2.2.7 BB x (mm)', 'Pylinac v2.2.7 BB y (mm)'
]
pylinac_data_extract = [
extract_data(movie_keys, movie_data, lambda x: x['pylinac']['v2.2.7']['field_centre'][0]),
extract_data(movie_keys, movie_data, lambda x: x['pylinac']['v2.2.7']['field_centre'][1]),
extract_data(movie_keys, movie_data, lambda x: x['pylinac']['v2.2.6']['bb_centre'][0]),
extract_data(movie_keys, movie_data, lambda x: x['pylinac']['v2.2.6']['bb_centre'][1]),
extract_data(movie_keys, movie_data, lambda x: x['pylinac']['v2.2.7']['bb_centre'][0]),
extract_data(movie_keys, movie_data, lambda x: x['pylinac']['v2.2.7']['bb_centre'][1]),
]
for key in movie_keys:
for column, pylinac_data in zip(pylinac_columns, pylinac_data_extract):
dataframes[key][column] = pylinac_data[key]
# -
for key in movie_keys:
dataframes[key]['Field - BB x (mm)'] = dataframes[key]['Field x (mm)'] - dataframes[key]['BB x [with predictions] (mm)']
dataframes[key]['Field - BB y (mm)'] = dataframes[key]['Field y (mm)'] - dataframes[key]['BB y [with predictions] (mm)']
def plot_enery_axis(energy, axis, dataframes):
plt.figure(figsize=(12,10))
for key in movie_keys:
if energy in key[0]:
if key[1] == 'clockwise':
prop = '-'
else:
prop = '--'
plt.plot(
dataframes[key]['Gantry Angle (deg)'],
dataframes[key][f'Field - BB {axis} (mm)'],
prop, label=key[0:2], alpha=0.8)
x = np.linspace(-180, 180)
if axis == 'y':
plt.plot(x, 0.6*np.cos(x*np.pi/180), 'k', label='"Ideal"')
plt.plot(x, 0.6*np.cos(x*np.pi/180)-0.5, 'r', label='0.5 mm "bounds"', alpha=0.2)
plt.plot(x, 0.6*np.cos(x*np.pi/180)+0.5, 'r', alpha=0.2)
elif axis == 'x':
plt.plot(x, np.zeros_like(x), 'k', label='"Ideal"')
plt.plot(x, np.zeros_like(x)-0.5, 'r', label='0.5 mm "bounds"', alpha=0.2)
plt.plot(x, np.zeros_like(x)+0.5, 'r', alpha=0.2)
plt.legend()
plt.title(f"{energy} | iView panel {axis}-axis")
plt.xlabel('Gantry (deg)')
plt.ylabel(f'Field centre {axis} - BB centre {axis} (mm)')
# +
energies = ['06MV', '10MV', '06FFF', '10FFF']
axes = ['x', 'y']
for energy in energies:
for axis in axes:
plot_enery_axis(energy, axis, dataframes)
plt.savefig(output_dir.joinpath(f"{energy}_{axis}-axis.png"))
# -
for key in movie_keys:
print(key)
IPython.display.display(dataframes[key])
dataframes[key].round(2).to_csv(movie_output_dirs[key].joinpath('raw_results.csv'))
# +
# try:
# with open('session_cache.json', 'r') as a_file:
# data_string_keys = json.load(a_file)
# data = {
# inv_key_map[key]: item for key, item in data_string_keys.items()
# }
# except FileNotFoundError:
# data = {}
# +
# for key, image_path in image_paths.items():
# images_dir = movie_output_dirs[key[0:3]].joinpath('images')
# try:
# this_data = data[key]
# pymedphys_data = this_data['pymedphys']
# except KeyError:
# continue
# x, y, img = pymedphys._wlutz.iview.iview_image_transform(image_path)
# try:
# pymedphys_data['bb_centre']
# continue
# except KeyError:
# pass
# try:
# fig = pymedphys._wlutz.reporting.image_analysis_figure(
# x,
# y,
# img,
# None,
# pymedphys_data['field_centre'],
# pymedphys_data['field_rotation'],
# bb_diameter,
# edge_lengths,
# penumbra,
# )
# plt.title('PyMedPhys Basinhopping Method')
# plt.tight_layout()
# filepath = images_dir.joinpath(f"frame_{key[3]}_PyMedPhys_field_only.png")
# plt.savefig(filepath)
# print(f"Saved {filepath}")
# plt.close()
# except KeyError:
# pass
# -
# +
for key, image_path in image_paths.items():
print(key)
images_dir = movie_output_dirs[key[0:3]].joinpath('images')
try:
this_data = data[key]
pymedphys_data = this_data['pymedphys']
except KeyError:
continue
x, y, img = pymedphys._wlutz.iview.iview_image_transform(image_path)
try:
fig = pymedphys._wlutz.reporting.image_analysis_figure(
x,
y,
img,
pymedphys_data['bb_centre'],
pymedphys_data['field_centre'],
pymedphys_data['field_rotation'],
bb_diameter,
edge_lengths,
penumbra,
)
plt.title('PyMedPhys Basinhopping Method')
plt.tight_layout()
plt.savefig(images_dir.joinpath(f"frame_{key[3]}_PyMedPhys.png"))
plt.close()
except KeyError:
pass
try:
pylinac = this_data['pylinac']
except KeyError:
continue
fig = pymedphys._wlutz.reporting.image_analysis_figure(
x,
y,
img,
pylinac['v2.2.6']['bb_centre'],
pylinac['v2.2.6']['field_centre'],
pymedphys_data['field_rotation'],
bb_diameter,
edge_lengths,
penumbra,
)
plt.title('Pylinac v2.2.6 Filter and Profile Method')
plt.tight_layout()
plt.savefig(images_dir.joinpath(f"frame_{key[3]}_Pylinac_v2.2.6.png"))
plt.close()
fig = pymedphys._wlutz.reporting.image_analysis_figure(
x,
y,
img,
pylinac['v2.2.7']['bb_centre'],
pylinac['v2.2.7']['field_centre'],
pymedphys_data['field_rotation'],
bb_diameter,
edge_lengths,
penumbra,
)
plt.title('Pylinac v2.2.7 Filter and Scikit-Image Method')
plt.tight_layout()
plt.savefig(images_dir.joinpath(f"frame_{key[3]}_Pylinac_v2.2.7.png"))
plt.close()
| examples/site-specific/cancer-care-associates/production/Winston Lutz/prototyping/arc_analysis/003_run_arc_image_analysis.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Making Objects Callable
# We can make instances of our classes callables by implementing the `__call__` method.
# Let's first see a simple example:
class Person:
def __call__(self):
print('__call__ called...')
p = Person()
# And now we can use `p` as a callable too:
type(p)
p()
# This is actually quite useful, and is widely used by Python itself.
# For example, the `functools` module has a `partial` function that we can use to create partial functions, like this:
from functools import partial
def my_func(a, b, c):
return a, b, c
# We can call this function with three arguments, but we could also create a partial function that essentially pre-sets some of the positional arguments:
partial_func = partial(my_func, 10, 20)
# And now we can (indirectly) call `my_func` using `partial_func` using only an argument for `c`, with `a` and `b` pre-set to `10` and `20` respectively:
partial_func(30)
# So I referred to `partial` as a function, but in reality it's just a callable (and this is why in Python we generally refer to things as callables, not just functions, because an object might be callable without being an actual function). In fact, we've seen this before with properties - these are callables, but they are not functions!
# Back to `partial`, you'll notice that the `type` of `partial` is not a `function` at all!
type(partial)
# So the type is `type` which means `partial` is actually a class, not a function.
#
# We can easily re-create a simplified approximation of `partial` ourselves using the `__call__` method in a custom class.
class Partial:
def __init__(self, func, *args):
self._func = func
self._args = args
def __call__(self, *args):
return self._func(*self._args, *args)
partial_func = Partial(my_func, 10, 20)
type(partial_func)
partial_func(30)
# Many such "functions" in Python are actually just general callables. The distinction is often not important.
# There is a built-in function in Python, `callable` that can be used to determine if an object is callable:
callable(print)
callable(partial)
callable(partial_func)
# As you can see our `Partial` class **instance** is callable, but the `Person` class instances will not be (the class itself is callable of course):
class Person:
def __init__(self, name):
self.name = name
callable(Person)
p = Person('Alex')
callable(p)
# #### Example: Cache with a cache-miss counter
# Let's take a look at another example. I want to implement a dictionary to act as a cache, but I also want to keep track of the cache misses so I can later evaluate if my caching strategy is effective or not.
# The `defaultdict` class can be useful as a cache.
#
# Recall that I can specify a default callable to use when requesting a non-existent key from a `defaultdict`:
from collections import defaultdict
def default_value():
return 'N/A'
d = defaultdict(default_value)
d['a']
d.items()
# Now, I want to use this `default_value` callable to keep track of the number of times it has been called - this will tell me how may times a non-existent key was requested from my `defaultdict`.
# I could try to create a global counter, and use that in my `default_value` function:
miss_counter = 0
def default_value():
global miss_counter
miss_counter += 1
return 'N/A'
# And now we can use it this way:
d = defaultdict(default_value)
d['a'] = 1
d['a']
d['b']
d['c']
miss_counter
# This works, but is not very good - the `default_value` function **relies** on us having a global `miss_counter` variable - if we don't have it our function won't work. Additionally we cannot use it to keep track of different cache instances since they would all use the same instance of `miss_counter`.
del miss_counter
d = defaultdict(default_value)
try:
d['a']
except NameError as ex:
print(ex)
# So nmaybe we can just pass in the counter (defined in our current scope) we want to use to the `default_value` function:
def default_value(counter):
counter += 1
return 'N/A'
# But this **won't work**, because counter is now local to the function so the local `counter` will be incremented, not the `counter` from the outside scope.
# Instead, we could use a class to maintain both a counter state, and return the default value for a cache miss:
class DefaultValue:
def __init__(self):
self.counter = 0
def __iadd__(self, other):
if isinstance(other, int):
self.counter += other
return self
raise ValueError('Can only increment with an integer value.')
# So we can use this class a a counter:
default_value_1 = DefaultValue()
default_value_1 += 1
default_value_1.counter
# So this works as a counter, but `default_value_1` is not callable, which is what we need to the `defaultdict`.
#
# So let's make it callable, and implement the behavior we need:
class DefaultValue:
def __init__(self):
self.counter = 0
def __iadd__(self, other):
if isinstance(other, int):
self.counter += other
return self
raise ValueError('Can only increment with an integer value.')
def __call__(self):
self.counter += 1
return 'N/A'
# And now we can use this as our default callable for our default dicts:
def_1 = DefaultValue()
def_2 = DefaultValue()
cache_1 = defaultdict(def_1)
cache_2 = defaultdict(def_2)
cache_1['a'], cache_1['b']
def_1.counter
cache_2['a']
def_2.counter
# As one last little enhancement, I'm going to make the returned default value an instance attribute for more flexibility:
class DefaultValue:
def __init__(self, default_value):
self.default_value = default_value
self.counter = 0
def __iadd__(self, other):
if isinstance(other, int):
self.counter += other
return self
raise ValueError('Can only increment with an integer value.')
def __call__(self):
self.counter += 1
return self.default_value
# And now we could use it this way:
# +
cache_def_1 = DefaultValue(None)
cache_def_2 = DefaultValue(0)
cache_1 = defaultdict(cache_def_1)
cache_2 = defaultdict(cache_def_2)
# -
cache_1['a'], cache_1['b'], cache_1['a']
cache_def_1.counter
cache_2['a'], cache_2['b'], cache_2['c']
cache_def_2.counter
# So the `__call__` method can essentially be used to make **instances** of our classes callable.
#
# This is also very useful to create **decorator** classes.
#
# Often we just use closures to create decorators, but sometimes it is easier to use a class instead, or if we want our class to provide functionality beyond just being used as a decorator.
# Let's look at an example.
# #### Example: Profiling Functions
# For simplicity I will assume here that we only want to decorate functions defined at the module level. For creating a decorator that also works for methods (bound functions) we have to do a bit more work and will need to understand descriptors - more on descriptors later.
# So we want to easily be able to keep track of how many times our functions are called and how long they take to run on average.
# Although we could cretainly implement code directly inside our function to do this, it becomes repetitive if we need to do it for multiple functions - so a decorator is ideal for that.
#
# Let's look at how we can use a decorator class to keep track of how many times our function is called and also keep track of the time it takes to run on average.
# We could certainly try a closure-based approach, maybe something like this:
# +
from time import perf_counter
from functools import wraps
def profiler(fn):
counter = 0
total_elapsed = 0
avg_time = 0
@wraps(fn)
def inner(*args, **kwargs):
nonlocal counter
nonlocal total_elapsed
nonlocal avg_time
counter += 1
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
total_elapsed += (end - start)
avg_time = total_elapsed / counter
return result
# we need to give a way to our users to look at the
# counter and avg_time values - spoiler: this won't work!
inner.counter = counter
inner.avg_time = avg_time
return inner
# -
# So, we added `counter` and `avg_time` as attributes to the `inner` function (the decorated function) - that works but looks a little weird - also notice that we calculate `avg_time` every time we call our decorated fuinction, even though the user may never request it - seems wasteful.
# +
from time import sleep
import random
random.seed(0)
@profiler
def func1():
sleep(random.random())
# -
func1(), func1()
func1.counter
# Hmm, that's weird - `counter` still shows zero. This is because we have to understand what we did in the decorator - we made `inner.counter` the value of `counter` **at the time the decorator function was called** - this is **not** the counter value that we keep updating!!
# So instead we could try to fix it this way:
# +
from time import perf_counter
from functools import wraps
def profiler(fn):
_counter = 0
_total_elapsed = 0
_avg_time = 0
@wraps(fn)
def inner(*args, **kwargs):
nonlocal _counter
nonlocal _total_elapsed
nonlocal _avg_time
_counter += 1
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
_total_elapsed += (end - start)
return result
# we need to give a way to our users to look at the
# counter and avg_time values - but we need to make sure
# it is using a cell reference!
def counter():
# this will now be a closure with a cell pointing to
# _counter
return _counter
def avg_time():
return _total_elapsed / _counter
inner.counter = counter
inner.avg_time = avg_time
return inner
# -
@profiler
def func1():
sleep(random.random())
func1(), func1()
func1.counter()
func1.avg_time()
# OK, so that works, but it's a little convoluted. In this case a decorator class will be much easier to write and read!
# +
class Profiler:
def __init__(self, fn):
self.counter = 0
self.total_elapsed = 0
self.fn = fn
def __call__(self, *args, **kwargs):
self.counter += 1
start = perf_counter()
result = self.fn(*args, **kwargs)
end = perf_counter()
self.total_elapsed += (end - start)
return result
@property
def avg_time(self):
return self.total_elapsed / self.counter
# -
# So we can now use `Profiler` as a decorator!
@Profiler
def func_1(a, b):
sleep(random.random())
return (a, b)
func_1(1, 2)
func_1.counter
func_1(2, 3)
func_1.counter
func_1.avg_time
# And of course we can use it for other functions too:
@Profiler
def func_2():
sleep(random.random())
func_2(), func_2(), func_2()
func_2.counter, func_2.avg_time
# As you can see, it was much easier to implement this more complex decorator using a class and the `__call__` method than using a purely function approach. But of course, if the decorator is simple enough to implement using a functional approach, that's my preferred way of doing things!
#
# Just because I have a hammer does not mean everything is a nail!!
| dd_1/Part 4/Section 04 - Polymorphism and Special Methods/06 - Callables.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
import math
# +
# this whole method is from https://blog.csdn.net/guduruyu/article/details/70313176
# some question need log functions to be fitted, I take log of inputs and do linear fit after
def n_3(x, A):
return A*x*x*x
def n_1(x, A):
return A*x
# -
x_1 = [8, 32, 128, 512, 1024]
x_2 = [8, 32, 128, 512, 1024, 4096, 4192, 8192]
y_1 = np.loadtxt('./navie_run_time.txt')
y_2 = np.loadtxt('./binary_run_time.txt')
for x in range(len(x_2)):
x_2[x] = x_2[x]*x_2[x]*math.log(x_2[x],2)
a_1 = optimize.curve_fit(n_3, x_1, y_1)[0]
a_2 = a_1 *1.01
x_3 = np.arange(1, 1100, 1)
y_3 = a_2*x_3*x_3*x_3
naive_fit = [y_3[8], y_3[32], y_3[128], y_3[512], y_3[1024]]
np.savetxt('./naive fit.txt', naive_fit, fmt='%f')
print(a_1, a_2)
plt.figure()
plt.scatter(x_1, y_1, 25, 'r', label = 'test point')
plt.plot(x_3, y_3, 'g', label = 'fitted curve')
plt.legend(loc='upper left')
plt.title('naive method fit')
plt.xlabel('input number')
plt.ylabel('time cost (s)')
plt.savefig('./naive method fit.jpg')
plt.show()
b_1 = optimize.curve_fit(n_1, x_2, y_2)[0]
b_2 = b_1 * 1.08
print(b_1, b_2)
x_4 = np.arange(1, 8200, 1)
y_4 = np.zeros(len(x_4))
for x in range(len(x_4)):
y_4[x] = (b_2*(x_4[x]**2)*math.log(x_4[x],2))
#print(x_4)
binary_fit = [y_4[8], y_4[32], y_4[128], y_4[512], y_4[1024], y_4[4096], y_4[4192], y_4[8192]]
np.savetxt('./binary fit.txt', binary_fit, fmt='%f')
x_5 = [8, 32, 128, 512, 1024, 4096, 4192, 8192]
plt.figure()
plt.scatter(x_5, y_2, 25, 'r', label = 'test point')
plt.plot(x_4, y_4, 'g', label = 'fitted curve')
plt.legend(loc='upper left')
plt.title('binary method fit')
plt.xlabel('input number')
plt.ylabel('time cost (s)')
plt.savefig('./binary method fit.jpg')
plt.show()
find_input = [8, 32, 128, 512, 1024, 4096, 8192]
union_input = [8, 32, 128, 512, 1024, 4096, 8192]
weighted_input = [8, 32, 128, 512, 1024, 4096, 8192]
weighted_input_2 = [8, 32, 128, 512, 1024, 4096, 8192]
find_result = np.loadtxt('./quick find runtime.txt')
union_result = np.loadtxt('./quick union runtime.txt')
weighted_result = np.loadtxt('./weighted union runtime.txt')
for x in range(len(weighted_input)):
weighted_input_2[x] = math.log(weighted_input[x],2)
find_c = optimize.curve_fit(n_1, find_input, find_result)[0]
find_c_2 = find_c * 1.1
find_x = np.arange(1, 8200, 1)
find_y = find_c_2*find_x
find_fit = [find_y[8], find_y[32], find_y[128], find_y[512], find_y[1024], find_y[4096], find_y[8192]]
np.savetxt('./find fit.txt', find_fit, fmt='%f')
print(find_c, find_c_2)
plt.figure()
plt.scatter(find_input, find_result, 25, 'r', label = 'test point')
plt.plot(find_x, find_y, 'g', label = 'fitted curve')
plt.legend(loc='upper left')
plt.title('quick find fit')
plt.xlabel('input number')
plt.ylabel('time cost (s)')
plt.savefig('./find fit.jpg')
plt.show()
union_c = optimize.curve_fit(n_1, union_input, union_result)[0]
union_c_2 = union_c * 1.1
union_x = np.arange(1, 8200, 1)
union_y = union_c_2*union_x
union_fit = [union_y[8], union_y[32], union_y[128], union_y[512], union_y[1024], union_y[4096], union_y[8192]]
np.savetxt('./union fit.txt', union_fit, fmt='%f')
print(union_c, union_c_2)
plt.figure()
plt.scatter(union_input, union_result, 25, 'r', label = 'test point')
plt.plot(union_x, union_y, 'g', label = 'fitted curve')
plt.legend(loc='upper left')
plt.title('quick union fit')
plt.xlabel('input number')
plt.ylabel('time cost (s)')
plt.savefig('./union fit.jpg')
plt.show()
weighted_c = optimize.curve_fit(n_1, weighted_input_2, weighted_result)[0]
weighted_c_2 = weighted_c * 1.3
weighted_x = np.arange(1, 8200, 1)
weighted_y = np.zeros(len(weighted_x))
for x in range(len(weighted_x)):
weighted_y[x] = (weighted_c_2*math.log(weighted_x[x],2))
weighted_fit = [weighted_y[8], weighted_y[32], weighted_y[128], weighted_y[512], weighted_y[1024], weighted_y[4096], weighted_y[8192]]
np.savetxt('./weighted fit.txt', weighted_fit, fmt='%f')
print(weighted_c, weighted_c_2)
plt.figure()
plt.scatter(weighted_input, weighted_result, 25, 'r', label = 'test point')
plt.plot(weighted_x, weighted_y, 'g', label = 'fitted curve')
plt.legend(loc='upper left')
plt.title('weighted union fit')
plt.xlabel('input number')
plt.ylabel('time cost (s)')
plt.savefig('./weighted fit.jpg')
plt.show()
| HW1/Q3/Q3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# HIDDEN
from datascience import *
from prob140 import *
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# %matplotlib inline
import math
from scipy import stats
from scipy import misc
# ## Prediction and Estimation ##
# One way to think about the SD is in terms of errors in prediction. Suppose I am going to generate a value of the random variable $X$, and I ask you to predict the value I am going to get. What should you use as your predictor?
#
# A natural choice is $\mu_X$, the expectation of $X$. But you could choose any number $c$. The error that you will make is $X - c$. About how big is that? For most reasonable choices of $c$, the error will sometimes be positive and sometimes negative. To find the rough size of this error, we will avoid cancellation as before, and start by calculating the *mean squared error* $E[(X-c)^2]$.
#
# Because we have guessed that $\mu_X$ might be a good choice, we will organize the algebra around that value. The mean squared error using $c$ as your predictor is
#
# $$
# \begin{align*}
# E\big{[}(X - c)^2\big{]} &= E\big{[} \big{(} (X - \mu_X) + (\mu_X - c) \big{)}^2 \big{]} \\
# &= E\big{[} (X - \mu_X)^2 \big{]} +2(\mu_X - c)E\big{[} (X-\mu_X) \big{]} + (\mu_X -c)^2 \\
# &= \sigma_X^2 + 0 + (\mu_X -c)^2 \\
# &\ge \sigma_X^2
# \end{align*}
# $$
#
# with equality if and only if $c = \mu_X$.
# ### The Mean as a Least Squares Predictor ###
# What we have shown is the predictor $\mu_X$ has the smallest mean squared error among all choices $c$. That smallest mean squared error is the variance of $X$, and hence the smallest root mean squared error is the SD $\sigma_X$.
#
# This is why a common approach to prediction is, "My guess is the mean, and I'll be off by about an SD."
# ### Comparing Estimates ###
# If we have two competing estimators of a parameter, we can use expected values and SDs to compare them.
#
# As an example, recall the German warplanes example of Data 8. The model was that we were observing $X_1, X_2, \ldots , X_n$, which are $n$ draws made at random with replacement from $1, 2, \ldots , N$. The goal was to estimate $N$, the total number of warplanes.
#
# One natural estimate is $M = \max(X_1, X_2, \ldots , X_n)$. The other, developed more carefully earlier in this text than in Data 8, is $2A - 1$
# where
#
# $$
# A = \frac{X_1 + X_2 + \ldots + X_n}{n}
# $$
#
# is the sample average.
#
# Here is the simulation we did in Data 8, using a sample of size 30 to estimate $N$ which we had taken to be 300.
# +
N = 300
n = 30
serial_nos = np.arange(1, N+1)
repetitions = 10000
maxes = make_array()
double_means = make_array()
for i in range(repetitions):
sample = np.random.choice(serial_nos, size=n)
maxes = np.append(maxes, np.max(sample))
double_means = np.append(double_means, 2*np.mean(sample)-1)
results = Table().with_columns(
'M', maxes,
'2A - 1', double_means
)
# -
every_ten = np.arange(1, N+101, 10)
results.hist(bins=every_ten)
# We constructed the estimator $2A - 1$ to be unbiased, and indeed its empirical distribution is symmetric around the parameter 300. The estimator $M$ is clearly biased: it can never be larger than $N$ but it can be smaller. If we just compare expectations, then $E(2A-1) = 300$ while $E(M) \ne 300$, so it seems as though $2A-1$ is the better estimate.
#
# But the graph tells a different story, because the graph also shows the spread in each of the two distributions. The distribution of $2A-1$ is much more spread out than the distribution of $M$. The two empirical SDs differ by a factor of around 3.5:
np.std(maxes)
np.std(double_means)
# This tells us that though $M$ is typically going to be below 300, it won't be below by much, whereas $2A-1$ can be quite far away from 300, underestimating about as often as it overestimates.
#
# Perhaps now you'd prefer to use $M$ instead of $2A-1$.
#
# This is an example of the *bias-variance tradeoff* that is common in estimation. Both expectation and SD are important in choosing one estimator over another. As in this example, the choice isn't always clear. But if the estimator with the lower SD also happens to be unbiased, then you can declare it the winner.
| content/Chapter_12/02_Prediction_and_Estimation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Prueba Linkedin
# #### <NAME> y <NAME>
# Importo Beautiful Soup
from bs4 import BeautifulSoup
# Importo requests para pillar el código html de donde quiera
import requests
web = requests.get('https://es.linkedin.com/jobs/search?keywords=inform%C3%A1tica&location=Madrid%2C%2BComunidad%2Bde%2BMadrid%2C%2BEspa%C3%B1a&trk=homepage-jobseeker_jobs-search-bar_search-submit&f_TP=1&sortBy=DD&f_PP=103374081&redirect=false&position=1&pageNum=0')
print(web.content)
soup = BeautifulSoup(web.content, 'html.parser')
print(soup.prettify())
for job in soup.find_all('a'):
if job.get('class') == ['result-card__full-card-link']:
print(job.get('href'))
for job in soup.find_all('a'):
if job.get('class') == ['result-card__full-card-link']:
j = requests.get(job.get('href'))
s = BeautifulSoup(j.content, 'html.parser')
print(job.get_text())
print(job.get('href'))
for des in s.find_all('h3'):
if des.get('class') == ['job-criteria__subheader']:
print(des.get_text())
for des in s.find_all('span'):
if des.get('class') == ['job-criteria__text', 'job-criteria__text--criteria']:
print(des.get_text())
# +
todayJobs = []
for job in soup.find_all('a'):
if job.get('class') == ['result-card__full-card-link']:
oneJob = []
j = requests.get(job.get('href'))
s = BeautifulSoup(j.content, 'html.parser')
oneJob.append(job.get_text())
oneJob.append(job.get('href'))
for des in s.find_all('h3'):
if des.get('class') == ['job-criteria__subheader']:
oneJob.append(des.get_text())
for des in s.find_all('span'):
if des.get('class') == ['job-criteria__text', 'job-criteria__text--criteria']:
oneJob.append(des.get_text())
todayJobs.append(oneJob)
# -
print(todayJobs)
for job in todayJobs:
print('Nombre:', job[0])
print(job[2] + ':', job[6])
print(job[3] + ':', job[7])
print(job[4] + ':', job[8])
print(job[5] + ':', job[9] + '...')
print('Link:', job[1])
print('\n\n\n')
| WebScrapingLinkedin.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Scientific libraries
import numpy as np
import scipy as sp
import pandas as pd
import json
import missingno as msno
# Loading Plotting Modules
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
import chart_studio.plotly as py
import plotly.figure_factory as ff
import plotly.graph_objects as go
import plotly.express as px
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import os
import gc
# +
# Setting Data Frame Options
pd.set_option('display.max_rows', 150)
pd.set_option('display.max_columns', 50)
pd.set_option('display.width', 100)
pd.set_option('display.max_colwidth', 100)
# Setting Plot Configuration
sns.set(rc={'figure.figsize':(19,11)}, style = 'white')
# -
train = pd.read_csv('../../data/train.csv')
m, n = train.shape
print('Data Frame: {} x {}'.format(m,n))
train.head()
test = pd.read_csv('../../data/test.csv')
m, n = test.shape
print('Data Frame: {} x {}'.format(m,n))
test.head()
df = train.append(test, ignore_index=True)
df
from missingpy import MissForest
df_new = df.copy()
df.drop(['galaxy', 'galactic year', 'y'], axis=1, inplace=True)
# +
# %%time
params = dict(
max_iter=20,
decreasing=False,
missing_values=np.nan,
copy=True,
n_estimators=200,
criterion=('mse',
'gini'),
max_depth=None,
min_samples_split=5,
min_samples_leaf=2,
min_weight_fraction_leaf=0.0,
max_features='auto',
max_leaf_nodes=None,
min_impurity_decrease=0.0,
bootstrap=True,
oob_score=False,
n_jobs=-1,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None
)
miss_forest = MissForest(**params)
imputed_df = miss_forest.fit_transform(df)
imputed_df = pd.DataFrame(imputed_df, columns=df.columns)
imputed_df.head()
# -
imputed_df['galactic year'] = df_new['galactic year']
imputed_df['galaxy'] = df_new['galaxy']
imputed_df['y'] = df_new['y']
# +
# imputed_df.sort_values(by=['galactic year', 'galaxy'], ascending=True, inplace=True)
# imputed_df.reset_index(drop=True, inplace=True)
# -
imputed_df.head()
os.makedirs('./outputs', exist_ok=True)
imputed_df.to_csv('./outputs/miss_forest_complete_data2.csv')
msno.matrix(df)
msno.matrix(imputed_df)
imputed_df[imputed_df.y.isna()]
imputed_train = imputed_df[imputed_df.y.notna()].reset_index(drop=True).copy()
imputed_test = imputed_df[imputed_df.y.isna()].reset_index(drop=True).copy()
del imputed_test['y']
imputed_train.to_csv('./outputs/imputed_train_mfc2.csv', index=False)
imputed_test.to_csv('./outputs/imputed_test_mfc2.csv', index=False)
| notebooks/eda/handling_missing_miss_forest2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="UEBilEjLj5wY"
# Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.
# - Author: <NAME>
# - GitHub Repository: https://github.com/rasbt/deeplearning-models
# + colab={"autoexec": {"startup": false, "wait_interval": 0}, "base_uri": "https://localhost:8080/", "height": 119} colab_type="code" executionInfo={"elapsed": 536, "status": "ok", "timestamp": 1524974472601, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-cxK6yOSQ6uE/AAAAAAAAAAI/AAAAAAAAIfw/P9ar_CHsKOQ/s50-c-k-no/photo.jpg", "userId": "118404394130788869227"}, "user_tz": 240} id="GOzuY8Yvj5wb" outputId="c19362ce-f87a-4cc2-84cc-8d7b4b9e6007"
# %load_ext watermark
# %watermark -a '<NAME>' -v -p torch
# + [markdown] colab_type="text" id="rH4XmErYj5wm"
# # DenseNet-121 CIFAR-10 Image Classifier
# -
# ### Network Architecture
# The network in this notebook is an implementation of the DenseNet-121 [1] architecture on the MNIST digits dataset (http://yann.lecun.com/exdb/mnist/) to train a handwritten digit classifier.
#
# The following figure illustrates the main concept of DenseNet: within each "dense" block, each layer is connected with each previous layer -- the feature maps are concatenated.
#
#
# 
#
# Note that this is somewhat related yet very different to ResNets. ResNets have skip connections approx. between every other layer (but don't connect all layers with each other). Also, ResNets skip connections work via addition
#
# $$\mathbf{x}_{\ell}=H_{\ell}\left(\mathbf{X}_{\ell-1}\right)+\mathbf{X}_{\ell-1}$$,
#
# whereas $H_{\ell}(\cdot)$ can be a composite function of operations such as Batch Normalization (BN), rectified linear units (ReLU), Pooling, or Convolution (Conv).
#
# In DenseNets, all the previous feature maps $\mathbf{X}_{0}, \dots, \mathbf{X}_{\ell}-1$ of a feature map $\mathbf{X}_{\ell}$ are concatenated:
#
# $$\mathbf{x}_{\ell}=H_{\ell}\left(\left[\mathbf{x}_{0}, \mathbf{x}_{1}, \ldots, \mathbf{x}_{\ell-1}\right]\right).$$
#
# Furthermore, in this particular notebook, we are considering the DenseNet-121, which is depicted below:
#
#
#
# 
# **References**
#
# - [1] <NAME>., <NAME>., <NAME>., & <NAME>. (2017). Densely connected convolutional networks. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 4700-4708), http://openaccess.thecvf.com/content_cvpr_2017/html/Huang_Densely_Connected_Convolutional_CVPR_2017_paper.html
#
# - [2] http://yann.lecun.com/exdb/mnist/
# + [markdown] colab_type="text" id="MkoGLH_Tj5wn"
# ## Imports
# + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="ORj09gnrj5wp"
import os
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Subset
from torchvision import datasets
from torchvision import transforms
import matplotlib.pyplot as plt
from PIL import Image
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
# -
import matplotlib.pyplot as plt
# %matplotlib inline
# + [markdown] colab_type="text" id="I6hghKPxj5w0"
# ## Model Settings
# + colab={"autoexec": {"startup": false, "wait_interval": 0}, "base_uri": "https://localhost:8080/", "height": 85} colab_type="code" executionInfo={"elapsed": 23936, "status": "ok", "timestamp": 1524974497505, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-cxK6yOSQ6uE/AAAAAAAAAAI/AAAAAAAAIfw/P9ar_CHsKOQ/s50-c-k-no/photo.jpg", "userId": "118404394130788869227"}, "user_tz": 240} id="NnT0sZIwj5wu" outputId="55aed925-d17e-4c6a-8c71-0d9b3bde5637"
##########################
### SETTINGS
##########################
# Hyperparameters
RANDOM_SEED = 1
LEARNING_RATE = 0.001
BATCH_SIZE = 128
NUM_EPOCHS = 20
# Architecture
NUM_CLASSES = 10
# Other
DEVICE = "cuda:0"
GRAYSCALE = False
# -
# ### CIFAR-10 Dataset
# +
train_indices = torch.arange(0, 48000)
valid_indices = torch.arange(48000, 50000)
train_and_valid = datasets.CIFAR10(root='data',
train=True,
transform=transforms.ToTensor(),
download=True)
train_dataset = Subset(train_and_valid, train_indices)
valid_dataset = Subset(train_and_valid, valid_indices)
test_dataset = datasets.CIFAR10(root='data',
train=False,
transform=transforms.ToTensor(),
download=False)
train_loader = DataLoader(dataset=train_dataset,
batch_size=BATCH_SIZE,
num_workers=4,
shuffle=True)
valid_loader = DataLoader(dataset=valid_dataset,
batch_size=BATCH_SIZE,
num_workers=4,
shuffle=False)
test_loader = DataLoader(dataset=test_dataset,
batch_size=BATCH_SIZE,
num_workers=4,
shuffle=False)
# +
device = torch.device(DEVICE)
torch.manual_seed(0)
for epoch in range(2):
for batch_idx, (x, y) in enumerate(train_loader):
print('Epoch:', epoch+1, end='')
print(' | Batch index:', batch_idx, end='')
print(' | Batch size:', y.size()[0])
x = x.to(device)
y = y.to(device)
break
# +
# Check that shuffling works properly
# i.e., label indices should be in random order.
# Also, the label order should be different in the second
# epoch.
for images, labels in train_loader:
pass
print(labels[:10])
for images, labels in train_loader:
pass
print(labels[:10])
# +
# Check that validation set and test sets are diverse
# i.e., that they contain all classes
for images, labels in valid_loader:
pass
print(labels[:10])
for images, labels in test_loader:
pass
print(labels[:10])
# +
##########################
### MODEL
##########################
# The following code cell that implements the DenseNet-121 architecture
# is a derivative of the code provided at
# https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from collections import OrderedDict
def _bn_function_factory(norm, relu, conv):
def bn_function(*inputs):
concated_features = torch.cat(inputs, 1)
bottleneck_output = conv(relu(norm(concated_features)))
return bottleneck_output
return bn_function
class _DenseLayer(nn.Sequential):
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, memory_efficient=False):
super(_DenseLayer, self).__init__()
self.add_module('norm1', nn.BatchNorm2d(num_input_features)),
self.add_module('relu1', nn.ReLU(inplace=True)),
self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *
growth_rate, kernel_size=1, stride=1,
bias=False)),
self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)),
self.add_module('relu2', nn.ReLU(inplace=True)),
self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,
kernel_size=3, stride=1, padding=1,
bias=False)),
self.drop_rate = drop_rate
self.memory_efficient = memory_efficient
def forward(self, *prev_features):
bn_function = _bn_function_factory(self.norm1, self.relu1, self.conv1)
if self.memory_efficient and any(prev_feature.requires_grad for prev_feature in prev_features):
bottleneck_output = cp.checkpoint(bn_function, *prev_features)
else:
bottleneck_output = bn_function(*prev_features)
new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))
if self.drop_rate > 0:
new_features = F.dropout(new_features, p=self.drop_rate,
training=self.training)
return new_features
class _DenseBlock(nn.Module):
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=False):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer(
num_input_features + i * growth_rate,
growth_rate=growth_rate,
bn_size=bn_size,
drop_rate=drop_rate,
memory_efficient=memory_efficient,
)
self.add_module('denselayer%d' % (i + 1), layer)
def forward(self, init_features):
features = [init_features]
for name, layer in self.named_children():
new_features = layer(*features)
features.append(new_features)
return torch.cat(features, 1)
class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features):
super(_Transition, self).__init__()
self.add_module('norm', nn.BatchNorm2d(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,
kernel_size=1, stride=1, bias=False))
self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))
class DenseNet121(nn.Module):
r"""Densenet-BC model class, based on
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
Args:
growth_rate (int) - how many filters to add each layer (`k` in paper)
block_config (list of 4 ints) - how many layers in each pooling block
num_init_featuremaps (int) - the number of filters to learn in the first convolution layer
bn_size (int) - multiplicative factor for number of bottle neck layers
(i.e. bn_size * k features in the bottleneck layer)
drop_rate (float) - dropout rate after each dense layer
num_classes (int) - number of classification classes
memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,
but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_
"""
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),
num_init_featuremaps=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False,
grayscale=False):
super(DenseNet121, self).__init__()
# First convolution
if grayscale:
in_channels=1
else:
in_channels=3
self.features = nn.Sequential(OrderedDict([
('conv0', nn.Conv2d(in_channels=in_channels, out_channels=num_init_featuremaps,
kernel_size=7, stride=2,
padding=3, bias=False)), # bias is redundant when using batchnorm
('norm0', nn.BatchNorm2d(num_features=num_init_featuremaps)),
('relu0', nn.ReLU(inplace=True)),
('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
]))
# Each denseblock
num_features = num_init_featuremaps
for i, num_layers in enumerate(block_config):
block = _DenseBlock(
num_layers=num_layers,
num_input_features=num_features,
bn_size=bn_size,
growth_rate=growth_rate,
drop_rate=drop_rate,
memory_efficient=memory_efficient
)
self.features.add_module('denseblock%d' % (i + 1), block)
num_features = num_features + num_layers * growth_rate
if i != len(block_config) - 1:
trans = _Transition(num_input_features=num_features,
num_output_features=num_features // 2)
self.features.add_module('transition%d' % (i + 1), trans)
num_features = num_features // 2
# Final batch norm
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
# Linear layer
self.classifier = nn.Linear(num_features, num_classes)
# Official init from torch repo.
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.constant_(m.bias, 0)
def forward(self, x):
features = self.features(x)
out = F.relu(features, inplace=True)
out = F.adaptive_avg_pool2d(out, (1, 1))
out = torch.flatten(out, 1)
logits = self.classifier(out)
probas = F.softmax(logits, dim=1)
return logits, probas
# + colab={"autoexec": {"startup": false, "wait_interval": 0}} colab_type="code" id="_lza9t_uj5w1"
torch.manual_seed(RANDOM_SEED)
model = DenseNet121(num_classes=NUM_CLASSES, grayscale=GRAYSCALE)
model.to(DEVICE)
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
# + [markdown] colab_type="text" id="RAodboScj5w6"
# ## Training
# -
def compute_acc(model, data_loader, device):
correct_pred, num_examples = 0, 0
model.eval()
for i, (features, targets) in enumerate(data_loader):
features = features.to(device)
targets = targets.to(device)
logits, probas = model(features)
_, predicted_labels = torch.max(probas, 1)
num_examples += targets.size(0)
assert predicted_labels.size() == targets.size()
correct_pred += (predicted_labels == targets).sum()
return correct_pred.float()/num_examples * 100
# + colab={"autoexec": {"startup": false, "wait_interval": 0}, "base_uri": "https://localhost:8080/", "height": 1547} colab_type="code" executionInfo={"elapsed": 2384585, "status": "ok", "timestamp": 1524976888520, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-cxK6yOSQ6uE/AAAAAAAAAAI/AAAAAAAAIfw/P9ar_CHsKOQ/s50-c-k-no/photo.jpg", "userId": "118404394130788869227"}, "user_tz": 240} id="Dzh3ROmRj5w7" outputId="5f8fd8c9-b076-403a-b0b7-fd2d498b48d7"
start_time = time.time()
cost_list = []
train_acc_list, valid_acc_list = [], []
for epoch in range(NUM_EPOCHS):
model.train()
for batch_idx, (features, targets) in enumerate(train_loader):
features = features.to(DEVICE)
targets = targets.to(DEVICE)
### FORWARD AND BACK PROP
logits, probas = model(features)
cost = F.cross_entropy(logits, targets)
optimizer.zero_grad()
cost.backward()
### UPDATE MODEL PARAMETERS
optimizer.step()
#################################################
### CODE ONLY FOR LOGGING BEYOND THIS POINT
################################################
cost_list.append(cost.item())
if not batch_idx % 150:
print (f'Epoch: {epoch+1:03d}/{NUM_EPOCHS:03d} | '
f'Batch {batch_idx:03d}/{len(train_loader):03d} |'
f' Cost: {cost:.4f}')
model.eval()
with torch.set_grad_enabled(False): # save memory during inference
train_acc = compute_acc(model, train_loader, device=DEVICE)
valid_acc = compute_acc(model, valid_loader, device=DEVICE)
print(f'Epoch: {epoch+1:03d}/{NUM_EPOCHS:03d}\n'
f'Train ACC: {train_acc:.2f} | Validation ACC: {valid_acc:.2f}')
train_acc_list.append(train_acc)
valid_acc_list.append(valid_acc)
elapsed = (time.time() - start_time)/60
print(f'Time elapsed: {elapsed:.2f} min')
elapsed = (time.time() - start_time)/60
print(f'Total Training Time: {elapsed:.2f} min')
# + [markdown] colab_type="text" id="paaeEQHQj5xC"
# ## Evaluation
# + colab={"autoexec": {"startup": false, "wait_interval": 0}, "base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 6514, "status": "ok", "timestamp": 1524976895054, "user": {"displayName": "<NAME>", "photoUrl": "//lh6.googleusercontent.com/-cxK6yOSQ6uE/AAAAAAAAAAI/AAAAAAAAIfw/P9ar_CHsKOQ/s50-c-k-no/photo.jpg", "userId": "118404394130788869227"}, "user_tz": 240} id="gzQMWKq5j5xE" outputId="de7dc005-5eeb-4177-9f9f-d9b5d1358db9"
plt.plot(cost_list, label='Minibatch cost')
plt.plot(np.convolve(cost_list,
np.ones(200,)/200, mode='valid'),
label='Running average')
plt.ylabel('Cross Entropy')
plt.xlabel('Iteration')
plt.legend()
plt.show()
# +
plt.plot(np.arange(1, NUM_EPOCHS+1), train_acc_list, label='Training')
plt.plot(np.arange(1, NUM_EPOCHS+1), valid_acc_list, label='Validation')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# +
with torch.set_grad_enabled(False):
test_acc = compute_acc(model=model,
data_loader=test_loader,
device=DEVICE)
valid_acc = compute_acc(model=model,
data_loader=valid_loader,
device=DEVICE)
print(f'Validation ACC: {valid_acc:.2f}%')
print(f'Test ACC: {test_acc:.2f}%')
# -
# %watermark -iv
| pytorch_ipynb/cnn/cnn-densenet121-cifar10.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA,TruncatedSVD,NMF
from sklearn.preprocessing import Normalizer
import argparse
import time
import dask
import pickle as pkl
import dask.dataframe as dd
import numba
pd.set_option('display.float_format', lambda x: '%.3f' % x)
pd.options.mode.chained_assignment = None
from functools import reduce
import matplotlib
#matplotlib.use('agg')
matplotlib.style.use('ggplot')
from matplotlib import pyplot as plt
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
br_to_us=pd.read_excel("Book.xlsx",skiprows=[0])
br_to_us_dict=dict(zip(br_to_us.UK.tolist(),br_to_us.US.tolist()))
spelling_replacement={'modifier':br_to_us_dict,'head':br_to_us_dict}
def lemma_maker(x, y):
#print(lemmatizer(x,y)[0])
return lemmatizer(x,y)[0]
heads=pd.read_pickle("/data/dharp/compounding/datasets/heads_CompoundAware_0_20_300.pkl")
#heads.reset_index(inplace=True)
#heads=heads.drop(['decade'],axis=1).groupby(['head']).mean()
#heads=heads+1
#heads.index.set_names('time', level=1,inplace=True)
heads.info()
heads.head()
modifiers=pd.read_pickle("/data/dharp/compounding/datasets/modifiers_CompoundAware_0_20_300.pkl")
#heads.reset_index(inplace=True)
#heads=heads.drop(['decade'],axis=1).groupby(['head']).mean()
#modifiers=modifiers+1
#modifiers.index.set_names('time', level=1,inplace=True)
modifiers.info()
modifiers.head()
compounds=pd.read_pickle("/data/dharp/compounding/datasets/compounds_CompoundAware_0_20_300.pkl")
#heads.reset_index(inplace=True)
#heads=heads.drop(['decade'],axis=1).groupby(['head']).mean()
#compounds.index.set_names('time', level=2,inplace=True)
compounds.drop(['common'],axis=1,inplace=True)
#compounds=compounds+1
#compounds.reset_index(inplace=True)
compounds.info()
compounds.head()
compounds.xs('best_noun', level=1, drop_level=False)
heads.reindex(compounds.index,level=1)
# +
constituent_sim=compounds.reset_index()[['modifier','head']].merge(modifiers.reset_index(),how='left',on=['modifier'])
constituent_sim.set_index(['modifier','head'],inplace=True)
constituent_sim=constituent_sim.multiply(heads.reindex(constituent_sim.index, level=1).ffill()).sum(axis=1).to_frame()
constituent_sim.columns=['sim_bw_constituents']
constituent_sim.sim_bw_constituents.describe()
# -
compound_decade_counts=compounds.drop(['modifier','head'],axis=1).groupby('time').sum().sum(axis=1).to_frame()
compound_decade_counts.columns=['N']
compound_decade_counts
compounds = dd.from_pandas(compounds, npartitions=30)
# +
XY=compounds.groupby(['modifier','head','time']).sum().sum(axis=1).to_frame()
XY=XY.compute()
XY.columns=['a']
X_star=compounds.groupby(['modifier','time']).sum().sum(axis=1).to_frame()
X_star=X_star.compute()
X_star.columns=['x_star']
Y_star=compounds.groupby(['head','time']).sum().sum(axis=1).to_frame()
Y_star=Y_star.compute()
Y_star.columns=['star_y']
merge1=pd.merge(XY.reset_index(),X_star.reset_index(),on=['modifier','time'])
information_feat=pd.merge(merge1,Y_star.reset_index(),on=['head','time'])
information_feat=dd.from_pandas(information_feat, npartitions=30)
information_feat['b']=information_feat['x_star']-information_feat['a']
information_feat['c']=information_feat['star_y']-information_feat['a']
information_feat=information_feat.compute()
information_feat=pd.merge(information_feat,compound_decade_counts.reset_index(),on=['time'])
information_feat=dd.from_pandas(information_feat, npartitions=30)
information_feat['d']=information_feat['N']-(information_feat['a']+information_feat['b']+information_feat['c'])
information_feat['x_bar_star']=information_feat['N']-information_feat['x_star']
information_feat['star_y_bar']=information_feat['N']-information_feat['star_y']
#information_feat['LR']=-2*np.sum(information_feat['a']*np.log2((information_feat['a']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y'])))
information_feat=information_feat.compute()
information_feat.set_index(['modifier','head','time'],inplace=True)
information_feat.replace(0,0.0001,inplace=True)
information_feat['log_ratio']=2*(information_feat['a']*np.log((information_feat['a']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y']))+\
information_feat['b']*np.log((information_feat['b']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y_bar']))+\
information_feat['c']*np.log((information_feat['c']*information_feat['N'])/(information_feat['x_bar_star']*information_feat['star_y']))+\
information_feat['d']*np.log((information_feat['d']*information_feat['N'])/(information_feat['x_bar_star']*information_feat['star_y_bar'])))
information_feat['ppmi']=np.log2((information_feat['a']*information_feat['N'])/(information_feat['x_star']*information_feat['star_y']))
information_feat['local_mi']=information_feat['a']*information_feat['ppmi']
information_feat.ppmi.loc[information_feat.ppmi<=0]=0
information_feat.drop(['a','x_star','star_y','b','c','d','N','d','x_bar_star','star_y_bar'],axis=1,inplace=True)
information_feat.info()
information_feat.head()
# -
modifier_denom=np.square(modifiers).sum(axis=1)**0.5
modifier_denom=modifier_denom.to_frame()
modifier_denom.columns=['modifier_denom']
modifier_denom.info()
modifier_denom.head()
head_denom=np.square(heads).sum(axis=1)**0.5
head_denom=head_denom.to_frame()
head_denom.columns=['head_denom']
head_denom.info()
head_denom.head()
compound_denom=np.square(compounds.set_index(['modifier','head','time'])).sum(axis=1)**0.5
compound_denom=compound_denom.to_frame()
compound_denom.columns=['compound_denom']
compound_denom.info()
compound_denom.head()
#compounds.drop('head',axis=1).set_index(['modifier','time']).multiply(modifiers)
compound_modifier_sim=compounds.multiply(modifiers.drop('mod_count',axis=1).reindex(compounds.index, method='ffill')).sum(axis=1).to_frame()
compound_modifier_sim.columns=['sim_with_modifier']
compound_modifier_sim.info()
compound_modifier_sim.head()
_=compound_modifier_sim.hist(column ='sim_with_modifier', figsize=(10, 10),bins=100,sharex=True,sharey=True,density=True,range=(-0.1,1.1))
compound_head_sim=compounds.multiply(heads.reindex(compounds.index, method='ffill')).sum(axis=1).to_frame()
compound_head_sim.columns=['sim_with_head']
compound_head_sim.info()
compound_head_sim.head()
compound_head_sim.sim_with_head.describe()
_=compound_head_sim.hist(column ='sim_with_head', figsize=(10, 10),bins=100,sharex=True,sharey=True,density=True,range=(-0.1,1.1))
constituent_sim=compounds.reset_index()[['modifier','head','time']].merge(modifiers.reset_index(),how='left',on=['modifier','time'])
constituent_sim.set_index(['modifier','head','time'],inplace=True)
constituent_sim=constituent_sim.multiply(heads.reindex(constituent_sim.index, method='ffill')).sum(axis=1).to_frame()
constituent_sim.columns=['sim_bw_constituents']
constituent_sim.sim_bw_constituents.describe()
_=constituent_sim.hist(column ='sim_bw_constituents', figsize=(10, 10),bins=100,sharex=True,sharey=True,density=True,range=(-0.1,1.1))
# +
dfs = [constituent_sim, compound_head_sim, compound_modifier_sim, information_feat]
compounds_final = reduce(lambda left,right: pd.merge(left,right,left_index=True, right_index=True), dfs)
compounds_final=pd.pivot_table(compounds_final.reset_index(), index=['modifier','head'], columns=['time'])
compounds_final.fillna(0,inplace=True)
compounds_final -= compounds_final.min()
compounds_final /= compounds_final.max()
compounds_final_1=compounds_final.columns.get_level_values(0)
compounds_final_2=compounds_final.columns.get_level_values(1)
cur_year=0
new_columns=[]
for year in compounds_final_2:
new_columns.append(str(year)+"_"+compounds_final_1[cur_year])
cur_year+=1
compounds_final.columns=new_columns
compounds_final
# -
reddy11_study=pd.read_csv("/data/dharp/compounding/datasets/ijcnlp_compositionality_data/MeanAndDeviations.clean.txt",sep="\t")
#print(reddy11_study.columns)
reddy11_study.columns=['compound','to_divide']
reddy11_study['modifier_mean'],reddy11_study['modifier_std'],reddy11_study['head_mean'],reddy11_study['head_std'],reddy11_study['compound_mean'],reddy11_study['compound_std'],_=reddy11_study.to_divide.str.split(" ",7).str
reddy11_study['modifier'],reddy11_study['head']=reddy11_study['compound'].str.split(" ",2).str
reddy11_study.modifier=reddy11_study.modifier.str[:-2]
reddy11_study['head']=reddy11_study['head'].str[:-2]
reddy11_study.drop(['compound','to_divide'],axis=1,inplace=True)
reddy11_study['modifier']=np.vectorize(lemma_maker)(reddy11_study['modifier'],'noun')
reddy11_study['head']=np.vectorize(lemma_maker)(reddy11_study['head'],'noun')
reddy11_study.replace(spelling_replacement,inplace=True)
reddy11_study['modifier']=reddy11_study['modifier']+"_n"
reddy11_study['head']=reddy11_study['head']+"_n"
reddy11_study=reddy11_study.apply(pd.to_numeric, errors='ignore')
#reddy11_study.set_index(['modifier','head'],inplace=True)
reddy11_study.info()
reddy11_study.head()
merge_df=reddy11_study.merge(compounds_final.reset_index(),on=['modifier','head'],how='inner')
merge_df.set_index(["modifier", "head"], inplace = True)
merge_df.info()
merge_df.head()
merge_df.to_csv("/data/dharp/compounding/datasets/trial.csv",sep='\t')
| novel_compound_predictor/FeatureExtractor_Dense.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="h82nkWUDkWxy" colab_type="code" colab={}
# #!pip install datadotworld
# #!pip install datadotworld(pandas)
# + [markdown] id="Wwa6FXhSl-_k" colab_type="text"
#
# + id="ChXi88B-lz3K" colab_type="code" colab={}
# #!dw configure
# + id="2yp-bBoymZp3" colab_type="code" colab={}
from google.colab import drive
# + id="Nbg_7QOzlnm_" colab_type="code" colab={}
import pandas as pd
import numpy as np
# + id="MsEF2N0Olumb" colab_type="code" colab={}
import datadotworld as dw
# + id="JRy7V1kemqlj" colab_type="code" colab={}
#drive.mount('/content/drive')
# + id="b6Aa3-N-m0Lv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="0ddef6b5-08ae-41c3-c23c-3083226c61fb" executionInfo={"status": "ok", "timestamp": 1581535653077, "user_tz": -60, "elapsed": 1871, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# ls
# + id="0-2tTulbm2W8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="a5c2e034-b30b-4190-c795-eb0edb5e77a1" executionInfo={"status": "ok", "timestamp": 1581535659869, "user_tz": -60, "elapsed": 589, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# cd 'drive/My Drive/Colab Notebooks/dw_matrix'
# + id="WRUn9zKlnBif" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="fd509c67-3dc1-4af4-b710-f18e29cf5d10" executionInfo={"status": "ok", "timestamp": 1581535665623, "user_tz": -60, "elapsed": 1756, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# ls
# + id="WWfgXhXXnInu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="96df1d91-5fac-49a6-8ba5-5bd6ac9fbb1b" executionInfo={"status": "ok", "timestamp": 1581535674718, "user_tz": -60, "elapsed": 1834, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# ls matrix_one
# + id="_rQXBwtfxYeb" colab_type="code" colab={}
# !mkdir data
# + id="3l43kiBFnXl1" colab_type="code" colab={}
# !echo 'data' > .gitignore #ignot chanes in folder data to not oublist source data
# + id="mVQugbkxnnSn" colab_type="code" colab={}
# !git add .gitignore
# + id="9cnJVgLxnt8X" colab_type="code" colab={}
data = dw.load_dataset('datafiniti/mens-shoe-prices')
# + id="UF0I1UaC4wYH" colab_type="code" colab={}
df = data.dataframes
# + id="Ixw06A-QnLzZ" colab_type="code" colab={}
#df = data.dataframes['7004_1']
# + id="r73eSIdRxizE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="cc0f1bf2-1c79-4150-cf9c-39b2d8d845b4" executionInfo={"status": "ok", "timestamp": 1581536037244, "user_tz": -60, "elapsed": 620, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df.shape
# + id="AhOtPrAuxmoR" colab_type="code" colab={}
#df.sample(5)
# + id="48fbNIQqxr6D" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="63947c6c-8632-48e9-e703-8368e7ff7ac0" executionInfo={"status": "ok", "timestamp": 1581536044608, "user_tz": -60, "elapsed": 597, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df.columns
# + id="WUEh676AxuP1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 102} outputId="cd6e0c03-5a37-471d-ea28-cc5c79feeb89" executionInfo={"status": "ok", "timestamp": 1581536107303, "user_tz": -60, "elapsed": 589, "user": {"displayName": "<NAME>anska", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df.prices_currency.unique()
# + id="D8Tv_T3Gx2-T" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 255} outputId="e99d46bd-e4fc-4cdf-eef3-18610d2df46d" executionInfo={"status": "ok", "timestamp": 1581536124707, "user_tz": -60, "elapsed": 658, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df.prices_currency.value_counts()
# + id="RzlebVOpyBr6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 255} outputId="dd89b1e7-5129-4c32-8943-64d8612d0625" executionInfo={"status": "ok", "timestamp": 1581536180128, "user_tz": -60, "elapsed": 692, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df.prices_currency.value_counts(normalize=True)
# + id="6DGtKSiqyHOA" colab_type="code" colab={}
df_usd = df[df.prices_currency == 'USD'].copy()
# + id="H7ao0SW3yW0a" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="089cbde3-130a-4372-b0c4-cf0c1e16b607" executionInfo={"status": "ok", "timestamp": 1581536258735, "user_tz": -60, "elapsed": 690, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df_usd.shape
# + id="jt352rfiylxp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 119} outputId="76a3b362-aa55-4f51-ec24-bc088fbe6604" executionInfo={"status": "ok", "timestamp": 1581536262393, "user_tz": -60, "elapsed": 636, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df_usd.prices_amountmin.head()
# + id="y_Jhvl42zapv" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="64374c1f-32b5-4bed-d826-2d5dd835c6f8" executionInfo={"status": "ok", "timestamp": 1581536361717, "user_tz": -60, "elapsed": 695, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
#df_usd.prices_amountmin.float()
df_usd.prices_amountmin.astype(np.float)
# + id="Nh56MKNazf09" colab_type="code" colab={}
df_usd['prices_amountmin'] = df_usd.prices_amountmin.astype(np.float)
# + id="EDHJ9svxz40h" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="78e373c2-fc95-4746-d505-d8d1f2988c4c" executionInfo={"status": "ok", "timestamp": 1581536386233, "user_tz": -60, "elapsed": 642, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/<KEY>TP93A=s64", "userId": "06224752077255072397"}}
df_usd['prices_amountmin'].hist()
# + id="zzu6iM2ez-iY" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="d3e7ef6d-2350-4542-c193-2ec84fefafef" executionInfo={"status": "ok", "timestamp": 1581536465418, "user_tz": -60, "elapsed": 552, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
np.percentile(df_usd['prices_amountmin'],99) #usuwanie danych odstajacych
# + id="UI67rpC60Td6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="b3a55c8c-88ae-4e29-af0c-8ac7c6b503f6" executionInfo={"status": "ok", "timestamp": 1581536473994, "user_tz": -60, "elapsed": 604, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
filter_max = np.percentile(df_usd['prices_amountmin'],99)
filter_max
# + id="CJ96QLCi0i6-" colab_type="code" colab={}
df_usd_filter = df_usd[df_usd['prices_amountmin'] <filter_max]
# + id="ARh9ln1R0yo1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="8238fdb4-4263-4f12-acc2-e731d43211f9" executionInfo={"status": "ok", "timestamp": 1581536514008, "user_tz": -60, "elapsed": 729, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df_usd_filter.prices_amountmin.hist()
# + id="FE4zsXyk1C2-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="76313326-c06d-420c-ad27-51433eec25c2" executionInfo={"status": "ok", "timestamp": 1581536563761, "user_tz": -60, "elapsed": 903, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
df_usd_filter.prices_amountmin.hist(bins = 100)
# + id="v3Knp1CR7nd0" colab_type="code" colab={}
df.to_csv('data/shoes_prices.csv', index = False)
# + id="UEdEZiI078C9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="dd569e3a-d29d-4498-c6a9-07362aad8a90" executionInfo={"status": "ok", "timestamp": 1581536958704, "user_tz": -60, "elapsed": 2307, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# ls
# + id="5dWn6pRV1T2_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="2d6ee042-607f-4d4a-9b46-3f532a0a3817" executionInfo={"status": "ok", "timestamp": 1581536970719, "user_tz": -60, "elapsed": 1935, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# ls matrix_one
# + id="XOEASd_61sws" colab_type="code" colab={}
# !git add matrix_one/Day3.ipynb
# + id="kPHAtdYD1zYq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="a53acef7-f07d-4c52-c725-648dbec24dac" executionInfo={"status": "ok", "timestamp": 1581537524199, "user_tz": -60, "elapsed": 1989, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# !git commit -m "Read Man's Shoes Pricess dataset from data.world"
# + id="1ePCY8pY2CTq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="f7973446-fe40-46c5-fd79-b412fdd90d13" executionInfo={"status": "ok", "timestamp": 1581537274067, "user_tz": -60, "elapsed": 1921, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# !git commit -m "Read Man's Shoes Pricess dataset from data.world"
# + id="DGfop_uG-69u" colab_type="code" colab={}
@git config --global user.email "<EMAIL>"
git config --global user.name "<NAME>"
# + id="XXYAnU4V2jdq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 136} outputId="44394e5e-ea05-4491-c336-e6841d756e7a" executionInfo={"status": "ok", "timestamp": 1581537503162, "user_tz": -60, "elapsed": 2221, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# !git commit -m "Read Man's Shoes Pricess dataset from data.world"
# + id="gp-o_F6i-JEs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="eab9a13a-dc2a-456c-f01f-97f797c87ea7" executionInfo={"status": "ok", "timestamp": 1581537483770, "user_tz": -60, "elapsed": 1845, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCvk0YgF9_b80mKca0iNGm7BCAhoiUq6jtFtTP93A=s64", "userId": "06224752077255072397"}}
# !git push -u origin master
# + id="I8nSzymN-Xvj" colab_type="code" colab={}
| matrix_one/Day3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import matplotlib.pyplot as plt
import mmcv
from mmcv.parallel import collate, scatter
import numpy as np
from skimage.draw import rectangle_perimeter
from matplotlib.pyplot import figure
import matplotlib.image as mpimg
import mmcv
from mmcv.parallel import collate, scatter
from mmdet.datasets.pipelines import Compose
from mmcv.runner import load_checkpoint
from mmdet.apis import inference_detector, init_detector
from mmdet.models.detectors import BaseDetector
from skimage import data, io, filters
import pickle
from mmdet.datasets.pipelines import Compose
from mmdet.apis import show_result_pyplot
from evaluator import *
from glob import glob
import pandas as pd
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from skimage import data, io, filters
import os
# +
classes = {"Yeast White": 0, "Budding White": 1, "Yeast Opaque": 2,
"Budding Opaque":3,"Yeast Gray": 4, "Budding Gray": 5,
"Shmoo":6,"Artifact": 7, "Unknown ": 8,
"Pseudohyphae": 9, "Hyphae": 10,
"H-junction": 11, "P-junction":12,
"P-Start":13,"H-Start":14}
model.CLASSES = [i for i in classes]
def show_images(images, cols = 1, titles = None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np.ceil(n_images/float(cols))).
titles: List of titles corresponding to each image. Must have
the same length as titles.
"""
assert((titles is None)or (len(images) == len(titles)))
n_images = len(images)
if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(images, titles)):
a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
a.set_title(title)
fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
plt.savefig("validation.png")
plt.show()
# +
numba = "_exp0_test_"
exp = "exp0"
thresh = 0.2
target_file_location = "/home/data/refined/deep-microscopy/train-data/final-test/"
image_dir = "/home/data/refined/deep-microscopy/vaes/" + "test_object_" + numba + "_thresh_" + str(thresh) +"/"
performance_save = "/home/data/refined/deep-microscopy/performance/" + exp + "_results/"
print("/home/data/refined/deep-microscopy/output/final_experiment/" + exp + ".py")
model = init_detector("/home/data/refined/deep-microscopy/output/final_experiment/" + exp + "/" + exp + ".py",
"/home/data/refined/deep-microscopy/output/final_experiment/" + exp + "/" + "latest.pth")
model.__dict__
# -
# This is a bit of a hack at the moment for drawing the bounding boxes with labels.
from os import listdir
target_file_names = listdir(target_file_location)
print(target_file_names)
# +
tot = 0
all_events = pd.DataFrame( index=np.arange(0, len(target_file_names)),
columns = ['event', 'filename', 'index', 'experiment', 'grade', 'threshold', 'bbox_1', 'bbox_2','bbox_3','bbox_4', 'gt_class', 'dt_class' ] )
for f in target_file_names:
img_orig = target_file_location + f
actual_img = mpimg.imread(img_orig)
res = inference_detector(model, img_orig)
img = BaseDetector.show_result(img=img_orig,
result=res,
self=model,
#class_names =[i for i in classes],
#bbox_color = (72,101,241),
#text_color = "blue",
score_thr=0.3,
wait_time=0,
show=False,
#thickness=3,
#font_size =20,
out_file= None)
for i in range(0, len(model.CLASSES)):
current = res[i]
for j in range(0, len(current)):
if (current[j][4] > thresh):
new_image = resize(actual_img[int(current[j][1]):int(current[j][3]),int(current[j][0]):int(current[j][2])],(128,128,3))
mpimg.imsave(image_dir + str(tot) + "_" + model.CLASSES[i] + "_" + f, new_image )
all_events.loc[tot] = [
'predict',
f,
tot,
exp,
np.nan,
thresh,
int(current[j][0]),
int(current[j][1]),
int(current[j][2]),
int(current[j][3]),
np.nan,
model.CLASSES[i]]
print(tot)
tot += 1
all_events.to_csv(performance_save + "test_events_" + numba + "_thresh_" + str(thresh) + ".csv")
#io.imshow(new_image)
# -
# This loops over a set of validation images to see how the model does.
# +
performance_save = "/home/data/refined/deep-microscopy/performance/" + exp + "_results/"
all_events.to_csv(performance_save + "test_events_" + numba + "_thresh_" + str(thresh) + ".csv")
# -
| src/performance/.ipynb_checkpoints/test_set-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from deeptables.models import deeptable,deepnets,modelset
from tensorflow import keras
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255
conf = deeptable.ModelConfig(
nets=['dnn_nets'],
metrics=['AUC'],
optimizer=keras.optimizers.RMSprop(),
)
dt = deeptable.DeepTable(config=conf)
model, history = dt.fit(x_train, y_train, epochs=10)
dt.evaluate(x_train, y_train, batch_size=512, verbose=0)
| examples/dt_multiclass.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Example
# - rating dataset
# - https://www.kaggle.com/rounakbanik/the-movies-dataset/data
# - ratings_small.csv
import recommend
rating_df = pd.read_csv("ratings_small.csv")
rating_df["movieId"] = rating_df["movieId"].astype("str") # 숫자인 컬럼을 문자열로 형변환해줘야함.
rating_df.tail()
unique_user = rating_df["userId"].unique()
unique_movie = rating_df["movieId"].unique()
unique_rating = rating_df["rating"].unique()
unique_rating = sorted(unique_rating)
print("sorted rating : {}".format(unique_rating))
print(
"user:", len(unique_user),
"movie:", len(unique_movie),
"rating:", len(unique_rating),
)
# - 별점 분포
rating_df.groupby("rating").size().reset_index(name='rating_counts')
user_counts_df = rating_df.groupby("userId").size().reset_index(name='user_rating_count')
user_counts_df = user_counts_df.sort_values(by=['user_rating_count'], ascending=False)
user_counts_df.tail()
movie_counts_df = rating_df.groupby("movieId").size().reset_index(name='movie_rating_count')
movie_counts_df = movie_counts_df.sort_values(by=['movie_rating_count'], ascending=False)
movie_counts_df.tail()
# - preprocessing dataframe
user_limit, movie_limit = 200, 100
# user_limit번 이상 평가한 UserId
filtered_userId = list(user_counts_df[user_counts_df["user_rating_count"] > user_limit]["userId"])
len(filtered_userId)
# movie_limit개 이상 평가 받은 movieId
filtered_movieId = list(movie_counts_df[movie_counts_df["movie_rating_count"] > movie_limit]["movieId"])
len(filtered_movieId)
# +
# filtering userId
filterd_df = rating_df[rating_df['userId'].isin(filtered_userId)]
# filtering movieId
filterd_df = filterd_df[filterd_df['movieId'].isin(filtered_movieId)]
print(len(filterd_df))
filterd_df.tail()
# -
filterd_df["movieId"] = filterd_df["movieId"].astype("str")
user_df = filterd_df.pivot_table(values="rating", index=["userId"], columns=["movieId"],\
aggfunc=np.average, fill_value=0, dropna=False)
user_df.tail()
DR = recommend.DssRecommend(user_df)
euclidean_sm = DR.similarity_matrix("euclidean")
euclidean_sm.head()
euclidean_sm = DR.similarity_matrix("cosin")
euclidean_sm.head()
DR.auto()
DR.recommand_matrix().head()
DR.recommand_user(4)[:5]
DR.evaluate()
# +
# find variable
# -
DR = recommend.DssRecommend(user_df)
# +
similarity_list = ["euclidean", "cosin"]
close_counts = range(5,10)
for similarity in similarity_list:
for close_count in close_counts:
DR.pred_matrix(similarity, close_count)
print(similarity, close_count, DR.evaluate())
# -
| recommed_System/06_kaggle_exam.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Now You Code 2: Indigo Montoya
#
# [The Pricess Bride](https://www.rottentomatoes.com/m/princess_bride/) is an adventure film from the 80's, a true cult classic. One of the many notable scenes involves a character Indigo Montoya who explains his character's motivation for revenge through the catch-phase:
#
# "Hello. My name is <NAME>. You killed my father. Prepare to die!"
#
# You can watch the clip here: [https://www.youtube.com/watch?v=YY4cnMmo9qw](https://www.youtube.com/watch?v=YY4cnMmo9qw)
#
# Write a program in Python which asks the user to enter **your name**, a **relative** and an **past-tense action**. For example if you enter "Indigo Montoya", "Father" and "killed", the program will then output:
#
# "Hello. My name is <NAME>. You killed my father. Prepare to die!"
#
# Or you could input "<NAME>", "Uncle" and "Tickled" to get:
#
# "Hello. My name is <NAME>. You Tickled my Uncle. Prepare to die!"
#
# ## Step 1: Problem Analysis
#
# Inputs:
#
# Outputs:
#
# Algorithm (Steps in Program):
name = input ("enter your name")
relative = input("enter a relative")
action = input("enter a past-tence action")
print("Hello. my name is", name, "you", action, "my", relative, "Prepare to die!")
# ## Step 3: Questions
#
# 1. What happens when neglect the instructions and enter a past-tense action instead of a name? Does the code still run? Why? It justs reads the whole code as a string
# 2. What type of error it when the program runs but does not handle bad input? logical error
# 3. Is there anything you can do in code to correct this type of error? Why or why not? no
# ## Reminder of Evaluation Criteria
#
# 1. What the problem attempted (analysis, code, and answered questions) ?
# 2. What the problem analysis thought out? (does the program match the plan?)
# 3. Does the code execute without syntax error?
# 4. Does the code solve the intended problem?
# 5. Is the code well written? (easy to understand, modular, and self-documenting, handles errors)
#
| content/lessons/02/Now-You-Code/NYC2-Indigo-Montoya.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 1. Exercícios - tatiane
#
# Este é um exercício opcional para testar sua compreensão do básico do Python. Se você acha isso extremamente desafiador, provavelmente ainda não está pronto para o restante desta disciplina e não possui experiência em programação suficiente para continuar.
# ## Exercícios
#
# Responda às perguntas ou conclua as tarefas descritas em negrito abaixo, use o método específico descrito, se aplicável.
# **What is 7 to the power of 4?**
print(7 ** 4)
# **Split this string:**
#
# s = "<NAME> Sam!"
#
# **into a list.**
s = '<NAME> Sam!'
list= s.split()
list
# **Given the variables:**
#
# planet = "Earth"
# diameter = 12742
#
# **Use .format() to print the following string:**
#
# The diameter of Earth is 12742 kilometers.
planet = "Earth"
diameter = 12742
print('The diameter of {} is {} kilometers'.format(planet,diameter))
# **Given this nested list, use indexing to grab the word "hello"**
lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7]
lst[3][1][2]
# **Given this nested dictionary grab the word "hello". Be prepared, this will be annoying/tricky**
d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}
print (d['k1'][3]['tricky'][3]['target'][3])
# **What is the main difference between a tuple and a list?**
# +
# Tuple is immutable
# -
# **Create a function that grabs the email website domain from a string in the form:**
#
# <EMAIL>
#
# **So for example, passing "<EMAIL>" would return: domain.com**
def domainGet(site):
s= site.split('@')
print(s[1])
domainGet('<EMAIL>')
# **Create a basic function that returns True if the word 'dog' is contained in the input string. Don't worry about edge cases like a punctuation being attached to the word dog, but do account for capitalization.**
def findDog(d):
if('dog' in d):
return True
else:
return False
findDog('Is there a dog here?')
# **Create a function that counts the number of times the word "dog" occurs in a string. Again ignore edge cases.**
def countDog(d):
return(d.count('dog'))
countDog('This dog runs faster than the other dog dude!')
# **Use lambda expressions and the filter() function to filter out words from a list that don't start with the letter 's'. For example:**
#
# seq = ['soup','dog','salad','cat','great']
#
# **should be filtered down to:**
#
# ['soup','salad']
seq = ['soup','dog','salad','cat','great']
a = (list(filter(lambda y : 's' in y, seq)))
print(a)
# ### Final Problem
# **You are driving a little too fast, and a police officer stops you. Write a function
# to return one of 3 possible results: "No ticket", "Small ticket", or "Big Ticket".
# If your speed is 60 or less, the result is "No Ticket". If speed is between 61
# and 80 inclusive, the result is "Small Ticket". If speed is 81 or more, the result is "Big Ticket". Unless it is your birthday (encoded as a boolean value in the parameters of the function) -- on your birthday, your speed can be 5 higher in all
# cases.**
def caught_speeding(speed, is_birthday):
aux = 1
if is_birthday:
aux = 10
if speed < 60 or speed == 60:
return "No Ticket"
elif speed > 61 + aux and speed < 80 + aux:
return "Small Ticket"
else:
return "Big Ticket"
caught_speeding(81,True)
caught_speeding(91,False)
# # Great job!
| 12-Exercicios.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Hadoop/MapReduce -- WordCount en Python (Implementación eficiente)
# ===
# ## Definición del problema
#
# Se desea contar la frecuencia de ocurrencia de palabras en un conjunto de documentos. Debido a los requerimientos de diseño (gran volúmen de datos y tiempos rápidos de respuesta) se desea implementar una arquitectura Big Data. Se desea implementar una **solución computacional eficiente** en **Python**.
# A continuación se generarán tres archivos de prueba para probar el sistema.
## Se crea el directorio de entrada
# !rm -rf input output
# !mkdir input
# +
# %%writefile input/text0.txt
Analytics is the discovery, interpretation, and communication of meaningful patterns
in data. Especially valuable in areas rich with recorded information, analytics relies
on the simultaneous application of statistics, computer programming and operations research
to quantify performance.
Organizations may apply analytics to business data to describe, predict, and improve business
performance. Specifically, areas within analytics include predictive analytics, prescriptive
analytics, enterprise decision management, descriptive analytics, cognitive analytics, Big
Data Analytics, retail analytics, store assortment and stock-keeping unit optimization,
marketing optimization and marketing mix modeling, web analytics, call analytics, speech
analytics, sales force sizing and optimization, price and promotion modeling, predictive
science, credit risk analysis, and fraud analytics. Since analytics can require extensive
computation (see big data), the algorithms and software used for analytics harness the most
current methods in computer science, statistics, and mathematics.
# -
# %%writefile input/text1.txt
The field of data analysis. Analytics often involves studying past historical data to
research potential trends, to analyze the effects of certain decisions or events, or to
evaluate the performance of a given tool or scenario. The goal of analytics is to improve
the business by gaining knowledge which can be used to make improvements or changes.
# %%writefile input/text2.txt
Data analytics (DA) is the process of examining data sets in order to draw conclusions
about the information they contain, increasingly with the aid of specialized systems
and software. Data analytics technologies and techniques are widely used in commercial
industries to enable organizations to make more-informed business decisions and by
scientists and researchers to verify or disprove scientific models, theories and
hypotheses.
# ## Solución
# A continuación se presenta una implementación eficiente en Python para el problema.
# ### Paso 1
#
# Implementación del `mapper`.
# +
# %%writefile mapper.py
# #! /usr/bin/env python
##
## Esta es la función que mapea la entrada a parejas (clave, valor)
##
import sys
##
## Se usa una clase iterable para implementar el mapper.
##
class Mapper:
def __init__(self, stream):
##
## almacena el flujo de entrada como una
## variable del objeto
##
self.stream = stream
def emit(self, key, value):
##
## escribe al flujo estándar de salida
##
sys.stdout.write("{}\t{}\n".format(key, value))
def status(self, message):
##
## imprime un reporte en el flujo de error
## no se debe usar el stdout, ya que en este
## unicamente deben ir las parejas (key, value)
##
sys.stderr.write('reporter:status:{}\n'.format(message))
def counter(self, counter, amount=1, group="ApplicationCounter"):
##
## imprime el valor del contador
##
sys.stderr.write('reporter:counter:{},{},{}\n'.format(group, counter, amount))
def map(self):
word_counter = 0
##
## imprime un mensaje a la entrada
##
self.status('Iniciando procesamiento ')
for word in self:
##
## cuenta la cantidad de palabras procesadas
##
word_counter += 1
##
## por cada palabra del flujo de datos
## emite la pareja (word, 1)
##
self.emit(key=word, value=1)
##
## imprime un mensaje a la salida
##
self.counter('num_words', amount=word_counter)
self.status('Finalizadno procesamiento ')
def __iter__(self):
##
## itera sobre cada linea de código recibida
## a través del flujo de entrada
##
for line in self.stream:
##
## itera sobre cada palabra de la línea
## (en los ciclos for, retorna las palabras
## una a una)
##
for word in line.split():
##
## retorna la palabra siguiente en el
## ciclo for
##
yield word
if __name__ == "__main__":
##
## inicializa el objeto con el flujo de entrada
##
mapper = Mapper(sys.stdin)
##
## ejecuta el mapper
##
mapper.map()
# -
# ### Paso 2
## El programa anterior se hace ejecutable
# !chmod +x mapper.py
## la salida de la función anterior es:
# !cat ./input/text*.txt | ./mapper.py | head
# ### Paso 3
# El reducer recibe las parejas (key, value) a través del flujo de salida. En los ejemplos anteriores, el reducer verifica si la clave cambia de un elemento al siguiente. Sin embargo, resulta más eficiente que se pueda iterar directamente sobre elementos consecutivos que tienen la misma clave. La función `groupby` de la librería `itertools` permite hacer esto. Dicha función recibe como argumentos los datos y una función que genera la clave para cada dato. Retorna una tupla con la clave y los elementos consecutivos que contienen la misma clave. El siguiente ejemplo permite clarificar su operación.
# +
import itertools
## la letra es la clave y los números son los valores
data = [('A', 1), ('B', 10), ('A', 2), ('A', 3), ('A', 4) , ('B', 20)]
## retorna la parte correspondiente a la clave
def keyfun(x):
k, v = x
return k
## itera sobre la clave y los elementos que contiene
## la misma clave
for key, group in itertools.groupby(data, keyfun):
print(key)
for g in group:
print(' ', g)
# -
# A continuación se modifica el reducer para incoporar el uso de clases y de la función `groupby`.
# +
# %%writefile reducer.py
# #!/usr/bin/env python
import sys
import itertools
class Reducer:
def __init__(self, stream):
self.stream = stream
def emit(self, key, value):
sys.stdout.write("{}\t{}\n".format(key, value))
def reduce(self):
##
## Esta función reduce los elementos que
## tienen la misma clave
##
for key, group in itertools.groupby(self, lambda x: x[0]):
total = 0
for _, val in group:
total += val
self.emit(key=key, value=total)
def __iter__(self):
for line in self.stream:
##
## Lee el stream de datos y lo parte
## en (clave, valor)
##
key, val = line.split("\t")
val = int(val)
##
## retorna la tupla (clave, valor)
## como el siguiente elemento del ciclo for
##
yield (key, val)
if __name__ == '__main__':
reducer = Reducer(sys.stdin)
reducer.reduce()
# -
# ### Paso 4
## Se hace ejecutable el archivo
# !chmod +x reducer.py
# ### Paso 5
#
# Se prueba la implementación localmente.
## La función sort hace que todos los elementos con
## la misma clave queden en lineas consecutivas.
## Hace el papel del módulo Shuffle & Sort
# !cat ./input/text*.txt | ./mapper.py | sort | ./reducer.py | head
# ### Paso 6 (solo en modo pseudo-distribuido)
#
# Una vez se tienen las versiones anteriores funcionando, se puede proceder a ejecutar la tarea directamente en Hadoop. Si Hadoop se ejecuta en modo pseudo-distribuido, será necesario ejecutar los siguientes comandos para copiar los datos al HDFS.
#
# $HADOOP_HOME/bin/hadoop fs -mkdir input
#
# $HADOOP_HOME/bin/hadoop fs -put input/* input
#
# $HADOOP_HOME/bin/hadoop fs -ls input/*
# ### Paso 7
##
## Se ejecuta en Hadoop.
## -input: archivo de entrada
## -output: directorio de salida
## -maper: programa que ejecuta el map
## -reducer: programa que ejecuta la reducción
##
# !$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/share/hadoop/tools/lib/hadoop-streaming-*.jar -input input -output output -mapper mapper.py -reducer reducer.py
## contenido del directorio con los
## resultados de la corrida
# !$HADOOP_HOME/bin/hadoop fs -ls output
## se visualiza el archivo con los
## resultados de la corrida
# !$HADOOP_HOME/bin/hadoop fs -cat output/part-00000 | head
# ### Limpieza
# !rm reducer.py mapper.py
# !rm -rf input output
# ---
| 04-WordCount-python-efficient.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Week 1, Day 2 Exercises
# <hr/>
# ### Problem 1: Lists
# __(a)__ Here are data on the number of cells found in a set of brain regions in the human brain.
#
#
# Retina: 29,100,000
# Prefrontal cortex: 1,322,782,000
# Dorsal striatum: 114,890,000
# Thalamus: 51,800,000
# Amygdala: 13,128,000
# Hippocampus: 41,255,000
# Substantia nigra: 708,000
# Primary visual cortex: 142,300,000
# Cerebellum: 101,096,000,000
#
# The data in this list are given in anatomical order, from anterior (front of brain) to posterior (back of brain).
#
# Create two lists: one containing the names of the brain structures, and a second containing the cell counts in the same order.
# +
structure_names = ['Retina', 'Prefrontal cortex', 'Dorsal striatum',
'Thalamus', 'Amygdala', 'Hippocampus',
'Substantia nigra', 'Primary visual cortex', 'Cerebellum']
structure_sizes = [29100, 1322782, 114890,
51800, 13128, 41255,
708, 142300, 101096000]
structure_sizes = [size * 1000 for size in structure_sizes]
# -
# __(b)__ Given an index `i` stored in an integer variable, print out a sentence indicating the name of brain region `i` and its associated cell count.
# +
i = 4 # ensure your solution works for any value of i
for i in range(len(structure_names)):
print(i, structure_names[i], structure_sizes[i])
# -
# __(c)__ Determine:
# (i) the number of brain structures in the list that lie anterior to region `i`
# (ii) the number of brain structures in the list that lie posterior to region `i`
# (iii) whether or not region `i` is anterior to more brain regions than it is posterior to
#
# Print out the results.
# +
print('Index', 'Name', '# Anterior', '# Posterior', 'More anterior?')
n = len(structure_names)
for i in range(n):
# at the i'th position, exactly i regions lie anterior (since we start at zero)
num_anterior = i
# at the i'th position, n - i - 1 lie posterior (since we exclude i itself)
# where n is the length of the list
num_posterior = n - i - 1
# more anterior is a comparison between the two
more_anterior = num_anterior > num_posterior
print(i, structure_names[i], num_anterior, num_posterior, more_anterior)
# -
# __(d)__ We just received data from a new study in which 3 new brain regions were discovered. The data are listed below.
#
# Nucleus accumbens, directly anterior to dorsal striatum, 7,290,000 neurons
# Inferior olive, directly anterior to cerebellum, 718,000 neurons
# Olfactory bulb, directly posterior to retina, 5,110,000 neurons
#
# Update your lists to include these data, and print out the final dataset.
# +
# the .index method returns the current index of whatever we ask it for
# which is the index we would insert to if we want to insert it before
# remember that thte list from from anterior to posterior,
# so directly anterior = right before
nucleus_accumbens_index = structure_names.index('Dorsal striatum')
structure_names.insert(nucleus_accumbens_index, 'Nucleus accumbens')
structure_sizes.insert(nucleus_accumbens_index, 7290000)
inferior_olive_index = structure_names.index('Cerebellum')
structure_names.insert(inferior_olive_index, 'Inferior olive')
structure_sizes.insert(inferior_olive_index, 718000)
# adding one since this is posterior
olfactory_bulb_index = structure_names.index('Retina') + 1
structure_names.insert(olfactory_bulb_index, 'Olfactory bulb')
structure_sizes.insert(olfactory_bulb_index, 5110000)
print(structure_names)
print(structure_sizes)
# -
# <hr/>
# ### Problem 2: `if` statements
#
# Consider 3 brain regions: region `i`, the region directly anterior to region `i`, and the region directly posterior to region `i`.
#
# Which has the largest number of cells? Which has the smallest number of cells? Print out the answers.
# +
i = 4
# Please, for the love of all that is holy, never write code like this
if structure_sizes[i] < structure_sizes[i + 1] and \
structure_sizes[i] < structure_sizes[i - 1]:
print('i is the smallest')
if structure_sizes[i - 1] < structure_sizes[i + 1] and \
structure_sizes[i - 1] < structure_sizes[i]:
print('i - 1 is the smallest')
if structure_sizes[i + 1] < structure_sizes[i] and \
structure_sizes[i + 1] < structure_sizes[i - 1]:
print('i + 1 is the smallest')
if structure_sizes[i] > structure_sizes[i + 1] and \
structure_sizes[i] > structure_sizes[i - 1]:
print('i is the largest')
if structure_sizes[i - 1] > structure_sizes[i + 1] and \
structure_sizes[i - 1] > structure_sizes[i]:
print('i - 1 is the largest')
if structure_sizes[i + 1] > structure_sizes[i] and \
structure_sizes[i + 1] > structure_sizes[i - 1]:
print('i + 1 is the largest')
# -
# <hr/>
# ### Problem 3: `while` loops
#
# __(a)__ Compute the total number of cells in all the brain regions of your dataset.
# +
i = 0
total_size = 0
while i < len(structure_sizes):
# this is the same as total_size = total_size + structure_sizes[i]
total_size += structure_sizes[i]
i += 1
print('The total size is', total_size)
# -
# __(b)__ Compute the average number of cells in a brain region.
print('The average size is', total_size / len(structure_sizes))
# __(c)__ Determine the brain region with
# (i) the largest number of cells
# (ii) the smallest number of cells
#
# Print out the results.
# +
i = 0
largest_index = None
largest_size = 0
smallest_index = None
smallest_size = 1e25
while i < len(structure_sizes):
current_size = structure_sizes[i]
if current_size > largest_size:
largest_size = current_size
largest_index = i
if current_size < smallest_size:
smallest_size = current_size
smallest_index = i
i += 1
print(f'The largest region is {structure_names[largest_index]} with {largest_size} neurons')
print(f'The smallest region is {structure_names[smallest_index]} with {smallest_size} neurons')
# -
# <hr/>
# ### Problem 4: `if` statements and loops
# For every brain region in your dataset:
#
# Print a string that indicates which category the brain region falls into:
# Category 1: the region with the longest name or the largest number of cells
# Category 2: the region with the shortest name or the smallest number of cells
# Category 3: a region with more than double the number of cells found in the smallest brain region
# Category 4: a region with more cells than the average cell count, and with a name shorter than the average name
# Category 5: none of the above
# +
largest_size = max(structure_sizes)
smallest_size = min(structure_sizes)
average_size = sum(structure_sizes) / len(structure_sizes)
# Let's compute the average name length for the fourth category
total_name_length = 0
for name in structure_names:
total_name_length += len(name)
average_name_length = total_name_length / len(structure_names)
for i in range(len(structure_names)):
name = structure_names[i]
size = structure_sizes[i]
if size == largest_size:
print(f'The {name} region is the largest in the brain with {size} neurons (1)')
elif size == smallest_size:
print(f'The {name} region is the smallest in the brain with {size} neurons (2)')
elif size > 2 * smallest_size:
print(f'The {name} region has more than double the neurons of the smallest region (3)')
elif size > average_size and len(name) < average_name_length:
print(f'The {name} region has above average size and shorter than average name (4)')
else:
print(f'The {name} regions falls into none of the above classifications (5)')
# -
# <hr/>
# ### Problem 5: `for` loops
# __(a)__ Print out your whole dataset with one line per brain structure, formatted as `"Structure #X: Structure_name, contains N cells."`
#
# For example, the first line might be: `"Structure #0: Retina, contains 29,100,100 cells."`
for i in range(len(structure_names)):
print(f'Structure #{i}: {structure_names[i]}, contains {structure_sizes[i]:,} cells.')
# __(b)__ Given a list of integer indices called `idxs`, modify the name of the brain structure at every index in `idxs` to be all capital letters.
#
# *Hint: my_string.upper() returns an upper-case version of my_string.*
# +
idxs = [3, 5, 10] # ensure your solution works for any number of indices in this list
# the syntax list[:] creates a copy of the list
# (think about it as a slice from the start to the end)
capitalized_structure_names = structure_names[:]
for i in idxs:
capitalized_structure_names[i] = capitalized_structure_names[i].upper()
print(capitalized_structure_names)
# -
# <hr/>
# ### Problem 6: Synapses
# Let's assume that the neurons in every brain region are "fully connected" – this means that any given neuron makes a synaptic connection with every other neuron in that region.
#
# Furthermore, let's assume that each of these connections consists of exactly one synapse.
#
# For example, if a brain region has 500 cells, then each cell in that region makes 499 connections: one connection with each other cell in the region.
# __(a)__ For every brain region, calculate the *total* number of synapses in that region. Store the results in a new list called `synapse_counts`, with the same length as your other 2 lists.
# +
# for each region, each neuron connects to every other one
# so naively it would be n * (n - 1)
# however, this counts each synapse twice, so let's divide by two:
synapse_counts = []
for size in structure_sizes:
synapse_counts.append(size * (size - 1) / 2)
print(synapse_counts)
# -
# __(b)__ We want to study the 4 brain regions with the fewest number of synapses. Create a new list that contains 4 elements. Each element consists of one of these brain regions, represented by a list with 4 elements: the index of that region, the name of that region, the number of cells in that region, and the number of synapses in that region.
# +
sorted_synapse_counts = sorted(synapse_counts)
# sorted goes from smallest to largest
smallest_four_synapse_counts = sorted_synapse_counts[:4]
# create a list to store my smallest regions
small_regions = []
# loop through each count
for synapse_count in smallest_four_synapse_counts:
# grab the index in the lists of the current synapse count
index = synapse_counts.index(synapse_count)
small_regions.append([index, structure_names[index],
structure_sizes[index], synapse_count])
for region in small_regions:
print(region)
# -
# __(c)__ For each of the 4 regions, determine how many synapses it would take to connect every neuron in that region with all neurons in another region. For each of the 4 regions, perform this calculation for *all* of the other 3 remaining regions.
#
# Store the results in a dictionary: each region will constitute a single key-value pair in the dictionary, where the key is the region name, and the value is a 3-item list containing the number of synapses required to connect the region to each other region.
# +
connection_requirements = {}
for source_index in range(len(small_regions)):
source_region_results = {}
for target_index in range(len(small_regions)):
if source_index == target_index:
continue
# compute the number of required connections
required_connections = small_regions[source_index][2] * small_regions[target_index][2]
# save the results for this target region
source_region_results[target_index] = required_connections
connection_requirements[source_index] = source_region_results
# -
# __(d)__ Print out the results line by line, indicating the two regions being connected, and the number of synapses required to connect them.
# loop through all keys in the top level dictionary
for source_index in connection_requirements:
# grab the results for this source region
source_results = connection_requirements[source_index]
# loop through the keys of the results for this source region
for target_index in source_results:
# grab the names of both regions
source_name = small_regions[source_index][1]
target_name = small_regions[target_index][1]
# grab the number of synapses required
required_connections = source_results[target_index]
print(f'To connect {source_name} <=> {target_name}, we need {required_connections} synapses')
# <hr/>
# ### Problem 7: More file names
# __(a)__ Suppose you have collected a set of brain images using an imaging device. You collected 1000 images, each stored in its own 'tif' file.
#
# The names of the image files are like this: `'SubjectX_TrialY_ImageZ_Timestamp.tif'`, where X is the integer subject ID, Y is the integer trial number, Z is the integer image index, and Timestamp is a floating point number with 3 decimal points indicating the time of the image acquisition. For example, a file name might be `'Subject3_Trial22_Image71_3456324.784.tif'`.
#
# Given 4 lists, consisting of subject ID's, trial numbers, image indices, and timestamps, create a 5th list, `filenames`, consisting of the file names for all your data.
# Let's create some sample data
subject_ids = [123, 456, 789]
trial_numbers = [11, 22, 33]
image_indices = [100, 101, 102]
timesteamps = [0.007, 0.008, 0.009]
# +
filenames = []
for i in range(len(subject_ids)):
filename = f'Subject{subject_ids[i]}_Trial{trial_numbers[i]}'
filename += f'_Image{image_indices[i]}_{timesteamps[i]:.3f}.tif'
filenames.append(filename)
print(filenames)
# -
# __(b)__ Now suppose these files are located in a folder on your computer, `'/Home/My/Data/'`. Adjust the contents of `filenames` to complete the full path to each file name.
# +
folder = '/Home/My/Data/'
full_paths = []
for filename in filenames:
full_paths.append(f'{folder}{filename}')
print(full_paths)
# -
# __(c)__ Given your list of paths to data files, write code to *parse* them–i.e., retrieve the subject name, trial number, image index, and timestamp from every file name.
for full_path in full_paths:
# First, let's only take the part after the folder ends
filename = full_path[len(folder):]
# Second, let's remove the file extension
filename_no_ext = filename[:-1 * len('.tif')]
# Third, let's split by underscores, to get each part separately
filename_parts = filename_no_ext.split('_')
# Let's recover the part we care about from each section
subject_id = filename_parts[0][len('Subject'):]
trial_id = filename_parts[1][len('Trial'):]
image_id = filename_parts[2][len('Image'):]
timestamp = filename_parts[3]
print(subject_id, trial_id, image_id, timestamp)
| Week1_Python/Day2/Week1Day2_Exercises-Answers.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
import statsmodels as sm
from linearmodels import PanelOLS
from linearmodels import RandomEffects
df = pd.read_csv("individual_african_countries.csv")
df.dtypes
df.describe()
data = df.set_index(['country_name','year'])
mod1 = PanelOLS(data.pov_320, data[['credit','edu','fdi','gdp','inflation','infrastructure','inst','trade_free']], time_effects = True, entity_effects=True)
res1 = mod1.fit(cov_type='clustered', cluster_entity=True)
res1
from linearmodels import BetweenOLS
data = df.set_index(['country_name','year'])
mod2 = BetweenOLS(data.pov_190, data[['credit','edu','inflation','inst','ln_gdp','trade_free']])
res2 = mod2.fit(cov_type='robust')
# + active=""
# res2
# -
df.fdi.min()
df[(df.fdi < 0)]
df[(df.country_name == 'Ghana')]
| latest/Africa April 2020.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.11 64-bit (''dvs_pose'': conda)'
# name: python3
# ---
import sys
sys.path.append('../scripts')
import experimenting
import event_library as el
import torch
from matplotlib import pyplot as plt
from experimenting.utils.visualization import plot_skeleton_2d, plot_skeleton_3d
from experimenting.utils.skeleton_helpers import Skeleton
import numpy as np
from experimenting.dataset.factory import Joints3DConstructor
import experimenting.utils.visualization as viz
import experimenting
from experimenting.utils import utilities
hw = el.utils.get_hw_property('dvs')
# +
# Wrapper for Events-H3m
# h3mcore = experimenting.dataset.HumanCore('test', '/data/gscarpellini/dataset/human3.6m/constant_count', '/data/gscarpellini/dataset/human3.6m/constant_count/gt.npz', 'cross-view', 1, test_cams=[1, 3], test_subjects=[6, 7])
# -
# Wrapper for DHP19
# dhpcore = experimenting.dataset.DHP19Core('test', base_path='/data/gscarpellini/dhp19/time_count_dataset', data_dir='/data/gscarpellini/dhp19/time_count_dataset/movements_per_frame', joints_dir='/data/gscarpellini/dhp19/time_count_dataset/labels_full_joints', hm_dir="", labels_dir="", preload_dir="", n_joints=13, n_classes=33, partition='cross-subject', n_channels=1, cams=[1, 3], movements=None, test_subjects=[6, 7])
dhpcore = experimenting.dataset.DHP19Core('test', base_path=r'D:\Dataset\DVS\dhp19\time_count_dataset', data_dir=r'D:\Dataset\DVS\dhp19\time_count_dataset\frames', joints_dir=r'D:\Dataset\DVS\dhp19\time_count_dataset\labels', hm_dir="", labels_dir="", preload_dir="", n_joints=13, n_classes=33, partition='cross-subject', n_channels=1, cams=[1, 3], movements=None, test_subjects=[3,4])
hasattr(dhpcore, 'n_channels')
# +
# Example using H3m
# +
# idx = 10
# print(h3mcore.frames_info[idx+1])
# sk, intr, extr = h3mcore.get_joint_from_id(idx)
# frame = h3mcore.get_frame_from_id(idx)
# joints = sk.get_2d_points(260, 346, intrinsic_matrix=intr, extrinsic_matrix=extr)
# plot_skeleton_3d(sk)
# plot_skeleton_2d(frame.squeeze(), joints)
# -
# ## Evaluate a model
#
# ### H3m
#
path = "/home/gianscarpe/dev/event-based-monocular-hpe/h3m_constantcount/exps_MargiposeEstimator/cross-view/03-18-08-22_exp_resnet50_pretrained_True/checkpoints"
model = utilities.load_model(path, "MargiposeEstimator", core=h3mcore).double()
factory = Joints3DConstructor()
factory.set_dataset_core(h3mcore)
train, val, test = factory.get_datasets({'apply':{}}, {'apply':{}})
loader = iter(torch.utils.data.DataLoader(test, batch_size=1, shuffle=True))
viz.plot_skeleton_2d(b_x[0].squeeze(),b_y['2d_joints'][0], pred_sk.get_2d_points(260, 346, extrinsic_matrix=b_y['M'][0], intrinsic_matrix=b_y['camera'][0]))
# ### DHP19
#
# path = "/home/gianscarpe/dev/event-based-monocular-hpe/timecount_dhp19/exps_MargiposeEstimator/cross-subject/03-20-08-54_exp_resnet50_pretrained_True_stages_3/checkpoints/"
path = r'D:\Dataset\DVS\dhp19\pretrained_model\dhp19_constantcount\checkpoints'
model = utilities.load_model(path, "MargiposeEstimator", core=dhpcore).eval().double().cuda()
factory = Joints3DConstructor()
factory.set_dataset_core(dhpcore)
train, val, test = factory.get_datasets({'apply':{}}, {'apply':{}})
np.random.seed(100)
loader = iter(torch.utils.data.DataLoader(val, batch_size=1, shuffle=True))
# for i in range(1000):
b_x, b_y = next(loader)
# +
# print(b_y['M'])
# print(b_y['camera'])
# print(b_y['z_ref'])
# print(b_y['mask'])
# print(b_y['skeleton'])
# print(b_y['normalized_skeleton'])
# print(b_y['2d_joints'])
bykeys = b_y.keys()
print(f'Keys: {bykeys}')
for k in bykeys:
print(f'{k}: {b_y[k]}\n')
# -
counter=0
def plot_next(loader):
b_x, b_y = next(loader)
sk_label = Skeleton(b_y['xyz'][0])
preds, outs = model(b_x.permute(0, -1, 1, 2).cuda())
preds = preds.cpu()
pred_sk = Skeleton(preds[0].detach().numpy()).denormalize(260, 346, camera=b_y['camera'][0], z_ref=b_y['z_ref'][0]).reproject_onto_world(b_y['M'][0])
plot_skeleton_3d(sk_label, pred_sk)
gt_joints = torch.stack([b_y['2d_joints'][0][:, 0], b_y['2d_joints'][0][:, 1]], 1)
pred_joints = pred_sk.get_2d_points(260, 346, extrinsic_matrix=b_y['M'][0], intrinsic_matrix=b_y['camera'][0])
plt.savefig(f'results/3D/{counter}.png')
plt.close('all')
pred_joints = np.stack([pred_joints[:, 0], pred_joints[:, 1]], 1)
plot_skeleton_2d(b_x[0].squeeze(), gt_joints, pred_joints)
plt.savefig(f'results/2D/{counter}.png')
# plt.cla()
plt.close('all')
return sk_label, pred_sk
# sk_label, pred_sk = plot_next(loader=loader)
for i in range(100):
plot_next(loader=loader)
counter += 1
print(sk_label.left_elbow_point, pred_sk.left_elbow_point)
# +
b_x, b_y = next(loader)
preds, outs = model(b_x.permute(0, -1, 1, 2).cuda())
preds = preds.cpu()
pred_sk = Skeleton(preds[0].detach().numpy()).denormalize(260, 346, camera=b_y['camera'][0], z_ref=b_y['z_ref'][0]).reproject_onto_world(b_y['M'][0])
plot_skeleton_3d(Skeleton(b_y['xyz'][0]), pred_sk)
gt_joints = torch.stack([b_y['2d_joints'][0][:, 0], b_y['2d_joints'][0][:, 1]], 1)
pred_joints = pred_sk.get_2d_points(260, 346, extrinsic_matrix=b_y['M'][0], intrinsic_matrix=b_y['camera'][0])
pred_joints = np.stack([pred_joints[:, 0], pred_joints[:, 1]], 1)
plot_skeleton_2d(b_x[0].squeeze(), gt_joints, pred_joints)
# -
lb = np.load(r'J:\datasets\DVS\dhp19\time_count_dataset\labels\S10_session_1_mov_1_frame_10_cam_1_2dhm.npz')
print(list(lb.keys()))
lb.get('camera')
lb.get('M')
lb.get('xyz')
gt_joints
fms = np.load(r'J:\datasets\DVS\dhp19\time_count_dataset\frames\S10_session_1_mov_2_frame_11_cam_2.npy')
print(fms.shape)
from mlib import mcv
mcv.imshow(fms, multiply=255)
set(fms.flatten().tolist())
| notebooks/Tutorial_train_test_visualize_dhp19_h3m.ipynb |
% ---
% jupyter:
% jupytext:
% text_representation:
% extension: .m
% format_name: light
% format_version: '1.5'
% jupytext_version: 1.14.4
% kernelspec:
% display_name: Octave
% language: octave
% name: octave
% ---
% # Assignment for GE Linear Algebra
% Submitted by <NAME> to the Department of Mathematics, University of Delhi
pkg load symbolic
syms A B beta
% ## Part One
% Consider the linear transformation $L:\mathbb{R}^3\to\mathbb{R}^4$ given by $L(\vec{v})=A\vec{v}$ where $A = \begin{bmatrix} 4 & -2 & 8 \\ 7 & 1 & 5 \\ -2 & -1 & 0 \\ 3 & -2 & 7 \end{bmatrix}$
% - Find $ker(L)$ and $range(L)$
% - Verify the Dimension Theorem
% #### Solution
% Consider $B$ to be the reduced row echelon form of $A$ and let the columns of A denote the variables $x_1$, $x_2$, and $x_3$.
A = sym([4 -2 8;7 1 5;-2 -1 0;3 -2 7])
B = rref(A)
% From $B$, we see that the third column has no pivot entry and thus $x_3$ is independent. Let $x_3=c\in\mathbb{R}$.
%
% We get the following system for $BX=0$, $\begin{cases}x_1-x_3=0 \\ x_2-2x_3=0 \end{cases}$
%
% Now as $x_3=c\in\mathbb{R}$, $x_1=c$ and $x_2=-2c$ i.e. $X = c \begin{bmatrix} 1 \\ -2 \\ 1 \end{bmatrix}$
%
% $\therefore ker(L) = \Bigg\{ c \begin{bmatrix} 1 \\ -2 \\ 1 \end{bmatrix} \;\Bigg|\; c \in \mathbb{R} \Bigg\}$
%
% $\ \Rightarrow ker(L) = span\;(\Bigg\{ \begin{bmatrix} 1 \\ -2 \\ 1 \end{bmatrix} \Bigg\})$
null(B)
% Now, $range(L)$ is spanned by linearly independent columns of $A$. From $B$, we know that $x_1$ and $x_2$ are linearly independent.
%
% $\therefore range(L) = span\;(\Bigg\{ \begin{bmatrix} 4 \\ 7 \\ -2 \\ 3 \end{bmatrix},\ \begin{bmatrix} -2 \\ 1 \\ -1 \\ -2 \end{bmatrix} \Bigg\})$
% Now, according to the Dimension Theorem, $\dim(ker(L)) + \dim(range(L)) = \dim(V)$ for a linear transformation $L : V \to W$
%
% For **RHS**,
%
% For $\mathbb{R}^3$, $\dim(\mathbb{R}^3) = 3$ $\quad(\because \dim(\mathbb{R}^n) = n)$
%
% For **LHS**,
%
% As $\dim(ker(L)) = 1$ and $\dim(range(L)) = 2$,
%
% $\ \Rightarrow \dim(ker(L)) + \dim(range(L)) = 1 + 2 = 3$
%
% $\therefore \dim(ker(L)) + \dim(range(L)) = \dim(\mathbb{R}^3)$
%
% As **LHS** = **RHS**, the Dimension Theorem is verified.
% ## Part Two
% Consider $L : \mathbb{P}_2 \to \mathbb{R}^2$ given by $L(p) = \begin{bmatrix} p(1) \\ p'(1) \end{bmatrix}$ for some $p \in \mathbb{P}_2$. Verify the Dimension Theorem.
% #### Solution
% For $L : \mathbb{P}_2 \to \mathbb{R}^2$, consider some $p \in \mathbb{P}_2$ as $p = a^2 + bx + c$.
%
% $\Rightarrow L(p) = \begin{bmatrix} a + b + c \\ 2a + b \end{bmatrix}$
%
% Consider the standard bases for $\mathbb{P}_2$ and $\mathbb{R}^2$ as $B = \langle x^2, x, 1 \rangle$ and $C = \langle e_1, e_2 \rangle$ respectively.
%
% We get the transformation matrix $A_{BC}$ for $L$ as $A_{BC} = \begin{bmatrix} 1 && 1 && 1 \\ 2 && 1 && 0 \end{bmatrix}$
A = sym([1 1 1;2 1 0])
% Row reducing $A_{BC}$ and let $\beta = rref(A_{BC})$,
beta = rref(A)
% From $\beta$, we see that the third column has no pivot entry and thus the constant term is independent. Let the constant be some $\alpha\in\mathbb{R}$.
%
% We get the following system for $\beta X=0$, $\begin{cases}x^2-1=0 \\ x+2=0 \end{cases}$
%
% Now as constant is $\alpha\in\mathbb{R}$, we get $x^2=\alpha$ and $x=-2\alpha$ i.e. $X = \alpha \begin{bmatrix} 1 \\ -2 \\ 1 \end{bmatrix}$
%
% $\therefore ker(L) = \Bigg\{ \alpha \begin{bmatrix} 1 \\ -2 \\ 1 \end{bmatrix} \;\Bigg|\; \alpha \in \mathbb{R} \Bigg\}$
%
% $\ \Rightarrow ker(L) = span\;(\Bigg\{ \begin{bmatrix} 1 \\ -2 \\ 1 \end{bmatrix} \Bigg\})$
null(beta)
% From $\beta$, $x^2$ and $x$ columns are independent.
%
% $\therefore range(L) = span\;(\Bigg\{ \begin{bmatrix} 1 \\ 2 \end{bmatrix},\ \begin{bmatrix} 1 \\ 1 \end{bmatrix} \Bigg\})$
% Now, according to the Dimension Theorem, $\dim(ker(L)) + \dim(range(L)) = \dim(V)$ for a linear transformation $L : V \to W$
%
% For **RHS**,
%
% For $\mathbb{P}_2$, $\dim(\mathbb{P}_2) = 3$ $\quad(\because \dim(\mathbb{P}_n) = n + 1)$
%
% For **LHS**,
%
% As $\dim(ker(L)) = 1$ and $\dim(range(L)) = 2$,
%
% $\ \Rightarrow \dim(ker(L)) + \dim(range(L)) = 1 + 2 = 3$
%
% $\therefore \dim(ker(L)) + \dim(range(L)) = \dim(\mathbb{P}_2)$
%
% As **LHS** = **RHS**, the Dimension Theorem is verified.
% ## Part Three
% Consider $L : \mathcal{M}_{2 2} \to \mathcal{M}_{3 2}$ given by $L(\begin{bmatrix} a_{1 1} && a_{1 2} \\ a_{2 1} && a_{2 2} \end{bmatrix}) = \begin{bmatrix} 0 && -a_{1 2} \\ -a_{2 1} && 0 \\ 0 && 0 \end{bmatrix}$. Find $ker(L)$ and $range(L)$.
% #### Solution
% Consider the standard bases for $\mathcal{M}_{2 2}$ be $B = \Bigg\langle \begin{bmatrix} 1 && 0 \\ 0 && 0 \end{bmatrix},\ \begin{bmatrix} 0 && 1 \\ 0 && 0 \end{bmatrix},\ \begin{bmatrix} 0 && 0 \\ 1 && 0 \end{bmatrix},\ \begin{bmatrix} 0 && 0 \\ 0 && 1 \end{bmatrix} \Bigg\rangle$ and that for $\mathcal{M}_{3 2}$ be $C$ respectively.
%
% The transition matrix $A_{BC}$ is given by $A_{BC} = \begin{bmatrix} 0 && 0 && 0 && 0 \\ 0 && -1 && 0 && 0 \\ 0 && 0 && -1 && 0 \\ 0 && 0 && 0 && 0 \\ 0 && 0 && 0 && 0 \\ 0 && 0 && 0 && 0 \end{bmatrix}$
A = sym([0 0 0 0;0 -1 0 0;0 0 -1 0;0 0 0 0;0 0 0 0;0 0 0 0])
% Row reducing $A_{BC}$ and let $\beta = rref(A_{BC})$,
beta = rref(A)
% In $\beta$, first and fourth columns are independent. Let $a_{1 1}$ and $a_{2 2}$ $\in \mathbb{R}$.
%
% For the system $\beta X = 0$ i.e. $\beta \begin{bmatrix} a_{1 1} && a_{1 2} \\ a_{2 1} && a_{2 2} \end{bmatrix} = \begin{bmatrix} 0 && 0 \\ 0 && 0 \end{bmatrix}$, we get $a_{1 2} = 0$ and $a_{2 1} = 0$.
%
% That is, $X = \Bigg\{ \begin{bmatrix} a && 0 \\ 0 && b \end{bmatrix} \;\bigg|\; a, b \in \mathbb{R} \Bigg\}$
%
% $\therefore ker(L) = span\;(\Bigg\{ \begin{bmatrix} 1 && 0 \\ 0 && 0 \end{bmatrix},\ \begin{bmatrix} 0 && 0 \\ 0 && 1 \end{bmatrix} \Bigg\})$
null(A)
% From $\beta$, the second and third columns have pivot entries,
%
% $\therefore range(L) = span\;(\Bigg\{ \begin{bmatrix} 0 && -1 \\ 0 && 0 \\ 0 && 0 \end{bmatrix},\ \begin{bmatrix} 0 && 0 \\ -1 && 0 \\ 0 && 0 \end{bmatrix} \Bigg\})$
% ## Part Four
% Verify that $\mathbb{P}_3 \cong \mathbb{R}^4$ as $L : \mathbb{P}_3 \to \mathbb{R}^4$ given by $L(p) = \begin{bmatrix} p(-1) \\ p(0) \\ p(1) \\ p(2) \end{bmatrix}$ for some $p \in \mathbb{P}_3$.
% #### Solution
% In order to show that $\mathbb{P}_3 \cong \mathbb{R}^4$, we must show that $L$ is an isomorphism from $\mathbb{P}_3$ to $\mathbb{R}^4$. To show that $L$ is an isomorphism, we must also show the following:
% - $L$ is a linear transformation.
% - $L$ is one-one.
% - $L$ is onto.
%
% Consider $L : \mathbb{P}_3 \to \mathbb{R}^4$ given by $L(p) = \begin{bmatrix} p(-1) \\ p(0) \\ p(1) \\ p(2) \end{bmatrix}$ for some $p = ax^3 + bx^2 + cx + d \in \mathbb{P}_3$.
%
% $\Rightarrow L(p) = \begin{bmatrix} -a+b-c+d \\ d \\ a+b+c+d \\ 8a+4b+2c+d \end{bmatrix} $
% Consider the standard bases for $\mathbb{P}_3$ and $\mathbb{R}^4$ as $B = \langle x^3, x^2, x, 1 \rangle$ and $C = \langle e_1, e_2, e_3, e_4 \rangle$ respectively.
%
% We get the transformation matrix $A_{BC}$ for $L$ as $A_{BC} = \begin{bmatrix} -1 && 1 && -1 && 1 \\ 0 && 0 && 0 && 1 \\ 1 && 1 && 1 && 1 \\ 8 && 4 && 2 && 1 \end{bmatrix}$
A = sym([-1 1 -1 1;0 0 0 1;1 1 1 1;8 4 2 1])
% Also, $\det(A_{BC}) = 12 \neq 0$ $\Rightarrow A_{BC}$ is invertible $\Rightarrow A_{BC}^{-1}$ exists $\Rightarrow L^{-1}$ is possible.
det(A)
% ##### To Show: **$L$** is a Linear Transformation
% Suppose $L$ is a linear transformation, then the following properties must hold:
% * $L(p_1,p_2) = L(p_1) + L(p_2)$
% * $L(\alpha p) = \alpha L(p)$
%
% ###### Proving **$L(p_1,p_2) = L(p_1) + L(p_2)$**
% Consider $p_1 = a_1x^3 + b_1x^2 + c_1x + d_1$ and $p_2 = a_2x^3 + b_2x^2 + c_2x + d_2$ $\in \mathbb{P}_3$.
%
% For **LHS**,
%
% $L(p_1+p_2)$
%
% $\; \Rightarrow L((a_1 + a_2)x^3 + (b_1 + b_2)x^2 + (c_1 + c_2)x + (d_1 + d_2))$
%
% $\; \Rightarrow L(p) = \begin{bmatrix} -(a_1 + a_2)+(b_1 + b_2)-(c_1 + c_2)+(d_1 + d_2) \\ (d_1 + d_2) \\ (a_1 + a_2)+(b_1 + b_2)+(c_1 + c_2)+(d_1 + d_2) \\ 8(a_1 + a_2)+4(b_1 + b_2)+2(c_1 + c_2)+(d_1 + d_2) \end{bmatrix} $
%
% For **RHS**.
%
% $L(p_1) + L(p_2)$
%
% $\; \Rightarrow L(a_1x^3 + b_1x^2 + c_1x + d_1) + L(a_2x^3 + b_2x^2 + c_2x + d_2)$
%
% $\; \Rightarrow \begin{bmatrix} -a_1+b_1-c_1+d_1 \\ d_1 \\ a_1+b_1+c_1+d_1 \\ 8a_1+4b_1+2c_1+d_1 \end{bmatrix} + \begin{bmatrix} -a_2+b_2-c_2+d_2 \\ d_2 \\ a_2+b_2+c_2+d_2 \\ 8a_2+4b_2+2c_2+d_2 \end{bmatrix}$
%
% $\; \Rightarrow \begin{bmatrix} -(a_1 + a_2)+(b_1 + b_2)-(c_1 + c_2)+(d_1 + d_2) \\ (d_1 + d_2) \\ (a_1 + a_2)+(b_1 + b_2)+(c_1 + c_2)+(d_1 + d_2) \\ 8(a_1 + a_2)+4(b_1 + b_2)+2(c_1 + c_2)+(d_1 + d_2) \end{bmatrix} $
%
% As **LHS** = **RHS**, it is shown that $L(p_1,p_2) = L(p_1) + L(p_2)$
%
% ###### Proving **$L(\alpha p) = \alpha L(p)$**
% Consider some $\alpha \in \mathbb{R}$ and $p = ax^3 + bx^2 + cx + d \in \mathbb{P}_3$.
%
% For **LHS**,
%
% $L(\alpha p)$
%
% $\; \Rightarrow L((\alpha a)x^3 + (\alpha b)x^2 + (\alpha c)x + (\alpha d))$
%
% $\; \Rightarrow \begin{bmatrix} -(\alpha a)+(\alpha b)-(\alpha c)+(\alpha d) \\ (\alpha d) \\ (\alpha a)+(\alpha b)+(\alpha c)+(\alpha d) \\ 8(\alpha a)+4(\alpha b)+2(\alpha c)+(\alpha d) \end{bmatrix} $
%
% For **RHS**.
%
% $\alpha L(p)$
%
% $\; \Rightarrow \alpha \; \begin{bmatrix} -a+b-c+d \\ d \\ a+b+c+d \\ 8a+4b+2c+d \end{bmatrix} $
%
% $\; \Rightarrow \begin{bmatrix} -(\alpha a)+(\alpha b)-(\alpha c)+(\alpha d) \\ (\alpha d) \\ (\alpha a)+(\alpha b)+(\alpha c)+(\alpha d) \\ 8(\alpha a)+4(\alpha b)+2(\alpha c)+(\alpha d) \end{bmatrix} $
%
% As **LHS** = **RHS**, it is shown that $L(\alpha p) = \alpha L(p)$
%
% $\therefore L$ is a linear transformation.
% ##### To Show: **$L$** is one-one
% $L$ is one-one $\iff$ $L(p_1) = L(p_2) \to p_1 = p_2$
%
% Suppose $L$ is one-one.
%
% $\; \Rightarrow L(p_1) = L(p_2)$
%
% $\; \Rightarrow A_{BC} \; p_1 = A_{BC} \; p_2$
%
% $\; \Rightarrow A_{BC}^{-1} \; A_{BC} \; p_1 = A_{BC}^{-1} \; A_{BC} \; p_2$ $\quad$ ($\because \det(A_{BC}) \neq 0$)
%
% $\; \Rightarrow p_1 = p_2$
%
% As $L(p_1) = L(p_2) \to p_1 = p_2$,
%
% $\therefore L$ is one-one.
% ##### To Show: **$L$** is onto
% $L$ is one-one $\iff$ $\dim(range(L)) = \dim(\mathbb{R}^4)$
%
% Row reducing $A_{BC}$,
rref(A)
% In $rref(A)$, all columns have pivot entries.
%
% $\ \Rightarrow range(L) = span\;(\Bigg\{ \begin{bmatrix} -1 \\ 0 \\ 1 \\ 8 \end{bmatrix},\ \begin{bmatrix} 1 \\ 0 \\ 1 \\ 4 \end{bmatrix},\ \begin{bmatrix} -1 \\ 0 \\ 1 \\ 2 \end{bmatrix},\ \begin{bmatrix} 1 \\ 1 \\ 1 \\ 1 \end{bmatrix} \Bigg\})$
%
% Now $\dim(range(L)) = 4$ and $\dim(\mathbb{R}^4) = 4$, therefore $\dim(range(L)) = \dim(\mathbb{R}^4)$.
%
% $\therefore L$ is onto.
% As $L$ is a linear transformation, is one-one and is onto, it implies that $L$ is an isomorphism from $\mathbb{P}_3$ to $\mathbb{R}^4$.
%
% $\therefore \mathbb{P}_3 \cong \mathbb{R}^4$
% ## Part Five
% Consider the linear transformation $L : \mathbb{P}_3 \to \mathbb{R}^3$ given by $L(dx^3+cx^2+bx+d) = \begin{bmatrix} a+b \\ 2c \\ d-a \end{bmatrix}$.
%
% Find $A_{BC}$ where $B$ and $C$ are the standard bases for $\mathbb{P}_3$ and $\mathbb{R}^3$ respectively.
%
% Find $A_{DE}$ where $D$ and $E$ are the ordered bases $D = \langle x^3+x^2, x^2+x, x+1, 1 \rangle$ and $E = \Bigg\langle \ \begin{bmatrix} -2 \\ 1 \\ 3 \end{bmatrix},\ \begin{bmatrix} 1 \\ -3 \\ 0 \end{bmatrix},\ \begin{bmatrix} 3 \\ -6 \\ 2 \end{bmatrix} \ \Bigg\rangle$
% #### Solution
% Standard bases for $\mathbb{P}_3$ and $\mathbb{R}^3$ are $B = \langle x^3, x^2, x, 1 \rangle$ and $C = \langle e_1, e_2, e_3 \rangle$.
%
% Therefore, the transformation matrix $A_{BC}$ is given by $A_{BC} = \begin{bmatrix} 0 && 0 && 1 && 1 \\ 0 && 2 && 0 && 0 \\ 1 && 0 && 0 && -1 \end{bmatrix}$
A = sym([0 0 1 1;0 2 0 0;1 0 0 -1])
% Now, $A_{DE} = Q_{E \leftarrow C} A_{BC} P_{B \leftarrow D}$.
%
% Using Change of Basis formula to find $Q_{E \leftarrow C}$ and $P_{B \leftarrow D}$,
%
% Row reducing
% $
% \left [
% \begin{array}{r|r} E & C \end{array}
% \right ] = \left [
% \begin{array}{rrr|rrr}
% -2 & 1 & 3 & 1 & 0 & 0 \\ 1 & -3 & -6 & 0 & 1 & 0 \\ -3 & 0 & 2 & 0 & 0 & 1
% \end{array}
% \right ]
% $
% and $\left [ \begin{array}{r|r} B & D \end{array} \right ]= \left [ \begin{array}{rrrr|rrrr} 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 1 & 1 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 1 & 1 \end{array}\right ]$ to get $\left [ \begin{array}{r|r} I_3 & Q_{E \leftarrow C} \end{array} \right ]$ and $\left [ \begin{array}{r|r} I_4 & P_{B \leftarrow D} \end{array} \right ]$
E_aug_C = sym([-2 1 3 1 0 0;1 -3 -6 0 1 0;-3 0 2 0 0 1])
B_aug_D = sym([1 0 0 0 1 0 0 0;0 1 0 0 1 1 0 0;0 0 1 0 0 1 1 0;0 0 0 1 0 0 1 1])
I_aug_Q = rref(E_aug_C)
I_aug_P = rref(B_aug_D)
% We get $Q_{E \leftarrow C} = \begin{bmatrix} -6 & -2 & 3 \\ 16 & 5 & -9 \\ -9 & -3 & 5 \end{bmatrix}$ and $P_{B \leftarrow D} = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 \end{bmatrix}$
Q = sym([-6 -2 3;16 5 -9;-9 -3 5])
P = sym([1 0 0 0;1 1 0 0;0 1 1 0;0 0 1 1])
% Computing $A_{DE} = Q_{E \leftarrow C} A_{BC} P_{B \leftarrow D} =
% \begin{bmatrix} -6 & -2 & 3 \\ 16 & 5 & -9 \\ -9 & -3 & 5 \end{bmatrix}
% \begin{bmatrix} 0 & 0 & 1 & 1 \\ 0 & 2 & 0 & 0 \\ 1 & 0 & 0 & -1 \end{bmatrix}
% \begin{bmatrix} 1 & 0 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 \end{bmatrix}$
Q * A * P
% $\therefore A_{DE} = \begin{bmatrix} -1 & -10 & -15 & -9 \\ 1 & 26 & 41 & 25 \\ -1 & -15 & -23 & -14 \end{bmatrix}$
% ## Part Six
% In $\mathbb{R}^4$, $\mathbb{W} = span\;(\;\Bigg\{ \begin{bmatrix} 2 \\ -1 \\ 1 \\ 0 \end{bmatrix},\ \begin{bmatrix} 1 \\ -1 \\ 2 \\ 2 \end{bmatrix} \Bigg\}\;)$ and $\vec{v} = \begin{bmatrix} -1 \\ 3 \\ 3 \\ 2 \end{bmatrix}$
%
% * Find $\mathrm{proj}_wv$.
% * Find $w_1 \in \mathbb{W}$ and $w_2 \in \mathbb{W}^{\perp}$ such that $v = w_1 + w_2$.
% * Find orthogonal basis of $\mathbb{W}^{\perp}$.
% #### Solution
%
% ##### Findng $\mathrm{proj}_wv$
% We need an orthonormal basis to compute $\mathrm{proj}_wv$. We can normalize the orthogonal basis to get the orthonormal basis.
%
% Checking if $w \subset \mathbb{R}^4$ has orthogonal basis $w_1 \cdot w_j = \begin{bmatrix} 2 \\ -1 \\ 1 \\ 0 \end{bmatrix} \begin{bmatrix} 1 \\ -1 \\ 2 \\ 2 \end{bmatrix} = 5 \neq 0 $
%
% Therefore, the given basis is not an orthogonal basis.
%
% Using the Gram-Schmidt Process,
%
% $v_1 = w_1 = \left [ 2, -1, 1, 0 \right ]$
%
% $v_2 = w_2 - \mathrm{proj}_{v_1} w_2 = w_2 - \big( \frac{w_2 \cdot v_1}{\|v_1\|^2} \big) v_1 = \left [ \frac{-4}{6}, \frac{-1}{6}, \frac{7}{6}, \frac{12}{6} \right ] = \left [ -4, -1, 7, 12 \right ]$
%
% Now, $T = \Bigg\{ \begin{bmatrix} 2 \\ -1 \\ 1 \\ 0 \end{bmatrix},\ \begin{bmatrix} -4 \\ -1 \\ 7 \\ 12 \end{bmatrix} \Bigg\}$ is an orthogonal basis for $\mathbb{W}$ such that $\mathbb{W} = span(T)$.
%
% Normalizing vectors in $T$,
%
% $U = \Bigg\{ \bigg[ \frac{2}{\sqrt{6}}, \frac{-1}{\sqrt{6}}, \frac{1}{\sqrt{6}}, 0 \bigg ], \bigg[ \frac{-4}{\sqrt{210}}, \frac{-1}{\sqrt{210}}, \frac{7}{\sqrt{210}}, \frac{12}{\sqrt{210}} \bigg] \Bigg\}$
%
% Now $U$ is an orthonormal basis for $\mathbb{W}$ such that $\mathbb{W} = span(U)$.
% Computing $\mathrm{proj}_wv = (v \cdot u_1) u_1 + (v \cdot u_2) u_2$,
warning('off')
v = sym([-1;3;3;2]'),
u1 = sym([2/sym(sqrt(6));-1/sym(sqrt(6));1/sym(sqrt(6));0]')
u2 = sym([-4/sym(sqrt(210));-1/sym(sqrt(210));7/sym(sqrt(210));12/sym(sqrt(210))]')
proj_w_v = sym(dot(v, u1) * u1 + dot(v, u2) * u2)
% $\therefore \mathrm{proj}_wv = \bigg[ \frac{-54}{35}, \frac{4}{35}, \frac{42}{35}, \frac{92}{35} \bigg]$
% ##### Finding **$w_1$** and **$w_2$**
% We know that if $\mathbb{W} \subset \mathbb{R}^n$ and $v \in \mathbb{R}^n$, then $v$ can be expressed as $v = w_1 + w_2$ where $w_1 = \mathrm{proj}_wv \in \mathbb{W}$ and $w_2 = v - \mathrm{proj}_wv \in \mathbb{W}^{\perp}$ .
%
% Therefore, $w_1 = \mathrm{proj}_w = \bigg[ \frac{-54}{35}, \frac{4}{35}, \frac{42}{35}, \frac{92}{35} \bigg] \in \mathbb{W}$ and $w_2 = v - \mathrm{proj}_wv = \bigg[ \frac{19}{35}, \frac{101}{35}, \frac{63}{35}, \frac{-22}{35} \bigg] \in \mathbb{W}^{\perp}$
%
% Verification: $w_1 + w_2 = \bigg[ \frac{-54}{35}, \frac{4}{35}, \frac{42}{35}, \frac{92}{35} \bigg] + \bigg[ \frac{19}{35}, \frac{101}{35}, \frac{63}{35}, \frac{-22}{35} \bigg] = \big[ -1, 3, 3, 2 \big] = v$
w1 = proj_w_v'
w2 = v' - proj_w_v'
w1 + w2
% ##### Finding Orthogonal Basis for **$\mathbb{W}^{\perp}$**
% We have $T = \Bigg\{ \begin{bmatrix} 2 \\ -1 \\ 1 \\ 0 \end{bmatrix},\ \begin{bmatrix} -4 \\ -1 \\ 7 \\ 12 \end{bmatrix} \Bigg\}$ which is an orthogonal basis for $\mathbb{W}$*.
%
% Enlarging $\left [ \begin{array}{r|r} T & I \end{array} \right ]$ to $\mathbb{R}^4$,
%
% $\; \Rightarrow \left [ \begin{array}{rr|rrrr}
% 2 & -4 & 1 & 0 & 0 & 0 \\
% -1 & -1 & 0 & 1 & 0 & 0 \\
% 1 & 7 & 0 & 0 & 1 & 0 \\
% 0 & 12 & 0 & 0 & 0 & 1
% \end{array} \right ]$
T_aug_I = sym([2 -4 1 0 0 0;-1 -1 0 1 0 0;1 7 0 0 1 0; 0 12 0 0 0 1])
rref(T_aug_I)
% On row reducing, we see that the first four columns are linearly independent. Thus, we can have $w_3 = [1, 0, 0, 0]$ and $w_4 = [0, 1, 0, 0]$.
%
% Now the new basis is $T^{\ast} = \Bigg\{ \begin{bmatrix} 2 \\ -1 \\ 1 \\ 0 \end{bmatrix},\ \begin{bmatrix} -4 \\ -1 \\ 7 \\ 12 \end{bmatrix},\ \begin{bmatrix} 1 \\ 0 \\ 0 \\ 0 \end{bmatrix},\ \begin{bmatrix} 0 \\ 1 \\ 0 \\ 0 \end{bmatrix} \Bigg\}$
% Using Gram-Schmidt Process for $v_3$ and $v_4$,
%
% $v_3 = w_3 - \mathrm{proj}_{v_1}w_3 - \mathrm{proj}_{v_2}w_3 = w_3 - \big( \frac{w_3 \cdot v_1}{\|v_1\|^2} \big)v_1 - \big( \frac{w_3 \cdot v_2}{\|v_2\|^2} \big)v_2 = \left [ \frac{9}{35}, \frac{11}{35}, \frac{-7}{35}, \frac{8}{35} \right ]$
%
% $v_4 = w_4 - \mathrm{proj}_{v_1}w_4 - \mathrm{proj}_{v_2}w_4 - \mathrm{proj}_{v_3}w_4 = w_4 - \big( \frac{w_4 \cdot v_1}{\|v_1\|^2} \big)v_1 - \big( \frac{w_4 \cdot v_2}{\|v_2\|^2} \big)v_2 - \big( \frac{w_4 \cdot v_3}{\|v_3\|^2} \big)v_3 = \left [ 0 , \frac{4}{9}, \frac{4}{9}, \frac{-2}{9} \right ]$
% As $v_3$, $v_4 \in \mathbb{W}^{\perp}$,
%
% $\therefore \mathbb{W}^{\perp} = span\;(\;
% \Bigg\{
% \begin{bmatrix} \frac{9}{35} \\ \frac{11}{35} \\ \frac{-7}{35} \\ \frac{8}{35} \end{bmatrix},\
% \begin{bmatrix} 0 \\ \frac{4}{9} \\ \frac{4}{9} \\ \frac{-2}{9} \end{bmatrix}
% \Bigg\}
% \;)$ where orthogonal basis of $\mathbb{W}^{\perp}$ is $\Bigg\{
% \begin{bmatrix} \frac{9}{35} \\ \frac{11}{35} \\ \frac{-7}{35} \\ \frac{8}{35} \end{bmatrix},\
% \begin{bmatrix} 0 \\ \frac{4}{9} \\ \frac{4}{9} \\ \frac{-2}{9} \end{bmatrix}
% \Bigg\}$
% ---
% Last Updated on April 25, 2020
| YearI/SemesterII/LinearAlgebra/GELinearAlgebraAssignment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### 0. 安裝需要的函式庫
import sys
# !{sys.executable} -m pip install matplotlib
# !{sys.executable} -m pip install descartes
# !{sys.executable} -m pip install geopandas
# !{sys.executable} -m pip install imageio
# !{sys.executable} -m pip install shapely
# !{sys.executable} -m pip install pandas
# ### 1. 匯入函式庫
import matplotlib.pyplot as plt
import geopandas as gpd
import shapely
import descartes
# ### 2. 匯入地形資料
counties_shp = gpd.read_file('mapdata201907311006/COUNTY_MOI_1080726.shp',encoding='utf-8')
town_shp = gpd.read_file('mapdata201910221133/TOWN_MOI_1081007.shp',encoding='utf-8')
# ### 3. 繪製台灣地圖
fig = counties_shp.plot(column='COUNTYNAME')
ax = fig.axis((119.2,122.5,21.5,25.5))
# ### 4. 繪製單一縣市
counties_shp.loc[5,'geometry']
# ### 5. 繪製台灣大圖
# +
fig, ax = plt.subplots(1, figsize=(20, 20))
ax = counties_shp.plot(ax=ax)
ax.set_xlim((119.2,122.5))
ax.set_ylim((21.5,25.5))
fig.suptitle('Taiwan counties')
plt.show()
# -
# ### 6. 刪除縣市、檢視縣市細節資訊
for index, row in counties_shp.iterrows():
if row['COUNTYNAME'] == '連江縣' or row['COUNTYNAME'] == '金門縣' or row['COUNTYNAME'] == '澎湖縣' :
counties_shp.drop(index, inplace=True)
counties_shp
# ### 7. 更詳盡的台灣地圖
# +
f, ax = plt.subplots(1, figsize=(20, 20))
ax = town_shp.plot(ax=ax,cmap='hot')
ax.set_xlim((119.2,122.5))
ax.set_ylim((21.5,25.5))
f.suptitle('Taiwan towns',fontsize=35)
plt.show()
# -
# ### 8. 更詳盡的單一縣市地圖
# +
fig, ax = plt.subplots(1, figsize=(10, 10))
taichung_town_shp=town_shp[town_shp['COUNTYNAME']=='臺北市']
ax = taichung_town_shp.plot(ax=ax,cmap='RdBu')
fig.suptitle('Taipei map',fontsize=35)
plt.show()
# -
# ### 9. 匯入函式庫
import os
import csv
import pandas as pd
import geopandas as gpd
# ### 10. 匯入新創公司資本額相關資料
path = "company-test"
files=[]
data=[]
for r,d,f in os.walk(path):
for file in f:
files.append(os.path.join(r,file))
for f in files:
print(f)
year = f[-10:-6]
month = f[-6:-4]
with open(f, 'r') as csvfile:
r= csv.reader(csvfile, delimiter=',')
for i,row in enumerate(r):
if i == 1:
#print(row)
data.append({
'year':int(year),
'month': int(month),
'city': row[3][:3],
'capital': int(row[5])
})
#print(data)
# ### 11. 基礎資料操作
# +
#使用pandas提供的框架
company_data = pd.DataFrame()
for f in files:
if company_data.empty:
company_data = pd.read_csv(f)
else:
company_data_new = pd.read_csv(f)
frames = [company_data, company_data_new]
company_data = pd.concat(frames)
company_data = company_data.drop(company_data.columns[[0,1,2,4,6]],axis=1)
#刪除資本額為零的公司
#for index, row in company_data.iterrows():
# if row[1] == 0 :
# company_data.drop(index, inplace=True)
#僅留下縣市名稱
company_data['公司所在地']=company_data['公司所在地'].apply(lambda t: t[:3])
company_data.head()
# -
# ### 12. 將縣市地圖資料及新創投資金額整合到同一個資料框架中
# +
counties_shp = gpd.read_file('mapdata201907311006/COUNTY_MOI_1080726.shp',encoding='utf-8')
countynames = counties_shp['COUNTYNAME']
#各縣市該月份的總共資本額(單位為百萬元)
MoneyDic={'County':[],'Money':[]}
for c in countynames:
count = 0.0 # in million
for index, row in company_data.iterrows():
if row[0] == c :
count += (float)(row[1])/1000000.0
#print(c,round(count,2))
MoneyDic['County'].append(c)
MoneyDic['Money'].append(round(count,2))
'''for index, row in counties_shp.iterrows():
if row['COUNTYNAME'] == c:
counties_shp.loc[index]['Money']=round(count,2)
#s = pd.Series([round(count,2)], index=[index])
#counties_shp = counties_shp.assign(Money=s)'''
money_merge = pd.DataFrame(MoneyDic)
print(money_merge)
# -
New_counties_shp=counties_shp.merge(money_merge,left_on=('COUNTYNAME'),right_on=('County'))
New_counties_shp
# ### 13. 利用合併資料製圖
fig = New_counties_shp.plot(column='Money', cmap='OrRd',figsize=(10, 10))
ax = fig.axis((119.2,122.5,21.5,25.5))
# ### 14. 利用全部資料製作gif動圖
##匯入函式庫
import os
import numpy as np
import pandas as pd
import geopandas as gpd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
##讀取地理資訊
counties_shp = gpd.read_file('mapdata201907311006/COUNTY_MOI_1080726.shp',encoding='utf-8')
countynames = counties_shp['COUNTYNAME']
# +
##選用company資料中的所有資料
path = "company"
files=[]
for r,d,f in os.walk(path):
for file in f:
files.append(os.path.join(r,file))
company_data = pd.DataFrame()
# -
##整理資料,整理順序不影響後面動畫順序(需要一段時間)
list_of_years=[]
for f in files:
year_month = f[-10:-4]
list_of_years.append(year_month)
company_data = pd.read_csv(f)
company_data = company_data.drop(company_data.columns[[0,1,2,4]],axis=1)
company_data['公司所在地']=company_data['公司所在地'].apply(lambda t: t[:3])
MoneyDic={'County':[],year_month:[]}
for c in countynames:
count = 0.0 # in million
for index, row in company_data.iterrows():
if row[0] == c :
count += (float)(row[1])/1000000.0
MoneyDic['County'].append(c)
MoneyDic[year_month].append(round(count,2))
#print(MoneyDic)
money_merge = pd.DataFrame(MoneyDic)
counties_shp=counties_shp.merge(money_merge,left_on=('COUNTYNAME'),right_on=('County'))
print(year_month)
# +
# GIF用圖儲存資料夾名稱
output_path = 'charts'
# 迴圈計數器
i = 0
# color bar數值上下限
vmin, vmax = 0, 10000
print(list_of_years)
# -
# 開始製圖
for year in list_of_years:
fig = counties_shp.plot(column=year, cmap='Blues', figsize=(10,10), linewidth=0.8, edgecolor='0.8', vmin=vmin, vmax=vmax, legend=True, norm=plt.Normalize(vmin=vmin, vmax=vmax))
ax = fig.axis((119.2,122.5,21.5,25.5))
fig.axis('off')
fig.set_title('Total Invested Money of New Company', \
fontdict={'fontsize': '25',
'fontweight' : '3'})
fig.annotate(year,
xy=(0.1, .225), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=25)
filepath = os.path.join(output_path, year+'_company.png')
chart = fig.get_figure()
chart.savefig(filepath, dpi=300)
##用剛剛儲存的圖檔製作GIF
import imageio
path = "charts"
imagefile_list = []
for r,d,f in os.walk(path):
for file in f:
imagefile_list.append(os.path.join(r,file))
sorted_imagefile_list=sorted(imagefile_list)
images = []
for filename in sorted_imagefile_list:
#print(filename[-3:])
if filename[-3:] == "png":
images.append(imageio.imread(filename))
imageio.mimsave('company.gif', images)
| 01-Opendata_Map_Geopandas.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # What is the image moment (or how to fit and ellipse)
#
# A moment (M) is a specific quantitative measure of a given distribution. The distribution can be one or multi-dimensional ([wikipedia definition](https://en.wikipedia.org/wiki/Moment_(mathematics)).
#
# Now let's try to have an intuitive view of what it is in the case of an image.
#
# Remember that an image is only a 2D distribution of a set of points. Each point being localized by two coordinates $x$ and $y$. So fo each pixel we have the following $f(x, y) = I_{x, y}$. Where $I_{x, y}$ corresponds to the intensity at the coordinate $x$ and $y$.
#
# Before going to intuition let's do some easy math. The formal definition of the image moment (2D and continuous) is:
#
# $$M_{pq} = \int_{-\infty}^{\infty} x^p y^q f(x, y) dx dy$$
#
# And the 2D discrete equation is :
#
# $$M_{pq} = \sum_x \sum_y x^p y^q I(x,y)$$
#
# So we see here the moment (M) depends on two parameters $p$ and $q$. They are called **the order** of the moment. Different order will give a different **measure** of the distribution we are looking at.
#
# For example let's define a simple 1D distribution of length $N$ $f(x) = A$.
#
# - the zero order ($p=0$) moment of $A$ is **the number of element** : $M_0 = \sum_x x^0 = len(A)$ (for pythonist)
# - the first order ($p=1$) moment of a $A$ if the **sum** of all the element : $M_1 = \sum_x x^1 = np.sum(A)$ (for pythonist)
#
# Now if we divide the first order moment by the zero order moment we have the mean :
#
# $$\bar{A} = \frac{1}{N} \sum_x x = \frac{M_1}{M_0}$$
# ## The image moment
#
# Now let's try to apply this 1D example to an image.
# Do some import
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from tifffile import TiffFile
# +
# Load the image
tf = TiffFile("binary_cell.tif")
# Get the numpy array
a = tf.asarray()
# Replace all 255 to 1 so the image is now made of "0" and "1"
a[a == 255] = 1
print(np.unique(a))
_ = plt.imshow(a, interpolation="none", cmap="gray", origin='lower')
# -
# The goal here is to use the image moment to **fit an ellipse**. The ellipse can be defined by four parameters : the center, the orientation, the major axis and the minor axis.
#
# Note it exists many different method to fit an ellipse.
#
# ### Find the centroid
#
# First we are going to detect the centroid (the center of the ellipse) of our object by computing the zero and first order of the image.
#
# Remember the discrete equation :
#
# $$M_{pq} = \sum_x \sum_y x^p y^q I(x,y)$$
#
# Since we are working on a binary image (only $0$ and $1$) values we remove $I(x,y)$.
# The zero order moment is then :
#
# $$M_{00} = \sum_x \sum_y x^0 y^0$$
#
#
# Let's do it in python.
# The sum of all value of 1
M_00 = np.sum(a)
M_00
# Now let's compute the first order moment for $x$ :
#
# $$M_{10} = \sum_x \sum_y x^1 y^0$$
# +
# Here we get all the coordinates of pixel equal to 1
xx, yy = np.where(a == 1)
M_10 = np.sum(xx)
M_10
# -
# Now let's compute the first order moment for $y$ :
M_01 = np.sum(yy)
M_01
# So the centroid $C$ is given by :
#
#
# $$C_x = \bar{x} = \frac{M_{10}}{M_{00}}$$
#
# $$C_y = \bar{y} = \frac{M_{01}}{M_{00}}$$
C_x = M_10 / M_00
C_y = M_01 / M_00
print("C =", (C_x, C_y))
# Let's verify it visually :
plt.scatter(C_x, C_y, color='red', marker='+', s=100)
_ = plt.imshow(a, interpolation="none", cmap="gray", origin='lower')
# Well it seems to be exact !
#
# ### Find the major and minor axis
#
# Here it becomes a little bit tricky.
#
# The information about the object orientation can be derived using the **second order central moments** to construct a **covariance matrix** (see [Wikipedia](https://en.wikipedia.org/wiki/Image_moment) for more details).
#
# Here is a new concept : **central moment** ($\mu$) which describes **distribution of mean** (unlike moment (M) which describes distribution only).
#
# Note that sometime moment is also called **raw moment**.
#
# The discrete equation of the central moment is the :
#
# $$\mu_{pq} = \sum_{x} \sum_{y} (x - \bar{x})^p(y - \bar{y})^q f(x,y)$$
#
# with $\bar{x}=\frac{M_{10}}{M_{00}}$ and $\bar{y}=\frac{M_{01}}{M_{00}}$
#
# Now it becomes difficult to get the intuition of what's going next. From [Wikipedia](https://en.wikipedia.org/wiki/Image_moment) :
#
# > The covariance matrix of the image $I(x,y)$ is :
#
# > $$\operatorname{cov}[I(x,y)] = \begin{bmatrix} \mu'_{20} & \mu'_{11} \\ \mu'_{11} & \mu'_{02} \end{bmatrix}$$
#
# > The eigenvectors of the covariance matrix of the image correspond to the **major** and **minor** axes of the image intensity, so the orientation can thus be extracted from the **angle of the eigenvector** associated with the **largest eigenvalue**. It can be shown that this angle Θ is given by the following formula:
#
# > $$\Theta = \frac{1}{2} \arctan \left( \frac{2\mu'_{11}}{\mu'_{20} - \mu'_{02}} \right)$$
#
# > Where :
#
# > $$\mu'_{20} = \mu_{20} / \mu_{00} = M_{20}/M_{00} - \bar{x}^2$$
# > $$\mu'_{02} = \mu_{02} / \mu_{00} = M_{02}/M_{00} - \bar{y}^2$$
# > $$\mu'_{11} = \mu_{11} / \mu_{00} = M_{11}/M_{00} - \bar{x}\bar{y}$$
# Let's first compute the second order raw moment ($M_{20}$, $M_{02}$ and $M_{11}$) :
M_20 = np.sum(xx ** 2)
M_02 = np.sum(yy ** 2)
M_11 = np.sum(xx * yy)
# Compute $\mu'_{20}$, $\mu'_{02}$ and $\mu'_{11}$ :
mu_20 = M_20 / M_00 - C_x ** 2
mu_02 = M_20 / M_00 - C_y ** 2
mu_11 = M_11 / M_00 - C_x * C_y
# Get the **orientation** $\Theta$ :
#
# $$\Theta = \frac{1}{2} \arctan \left( \frac{2\mu'_{11}}{\mu'_{20} - \mu'_{02}} \right)$$
# +
theta = 1/2 * np.arctan((2 * mu_11) / (mu_20 - mu_02))
# Convert it in degree
angle = np.rad2deg(theta)
print("angle = {}°".format(angle))
# -
# Get the eigenvalues with this equation :
#
# $$\Delta = \sqrt{4{\mu'}_{11}^2 + ({\mu'}_{20}-{\mu'}_{02})^2}$$
# $$\lambda_i = \frac{\mu'_{20} + \mu'_{02}}{2} \pm \frac{\Delta}{2}$$
# +
delta = np.sqrt(4 * mu_11 ** 2 + (mu_20 - mu_02) ** 2)
lambda_1 = ((mu_20 + mu_02) + delta) / 2
lambda_2 = ((mu_20 + mu_02) - delta) / 2
# -
# Get the major and minor axes from the eigenvalues :
# +
semi_major_length = np.sqrt(np.abs(lambda_1)) * 2
semi_minor_length = np.sqrt(np.abs(lambda_2)) * 2
major_length = semi_major_length * 2
minor_length = semi_minor_length * 2
print("Major axis = {}".format(major_length))
print("Minor axis = {}".format(minor_length))
# -
# Alternatively we can also compute (with Numpy) the **orientation** and **axes length** from the eigenvectors of the covariance matrix.
#
# $$\operatorname{cov}[I(x,y)] = \begin{bmatrix} \mu'_{20} & \mu'_{11} \\ \mu'_{11} & \mu'_{02} \end{bmatrix}$$
# +
cov = np.asarray([[mu_20, mu_11],
[mu_11, mu_02]])
eigvalues, eigvectors = np.linalg.eig(cov)
# Get the associated eigenvectors and eigenvalues
eigval_1, eigval_2 = eigvalues
eigvec_1, eigvec_2 = eigvectors[:, 0], eigvectors[:, 1]
# -
# Get the orientation from the **first eigenvector** with $ \Theta = \operatorname{atan2}(y, x) \quad$ and the **axes length** from the **eigenvalues**.
# +
theta = np.arctan2(eigvec_1[1], eigvec_1[0])
angle = np.rad2deg(theta)
print("angle = {}°".format(angle))
semi_major_length = np.sqrt(np.abs(eigval_1)) * 2
semi_minor_length = np.sqrt(np.abs(eigval_2)) * 2
major_length = semi_major_length * 2
minor_length = semi_minor_length * 2
print("Major axis = {}".format(major_length))
print("Minor axis = {}".format(minor_length))
# -
# We find the **same value** as above.
# Now let's see how our vector looks (which is supposed to define the major orientation of our object).
# +
plt.figure()
# Plot the centroid in red
plt.scatter(C_x, C_y, color='red', marker='+', s=100)
# Plot the first eigenvector
scale = 100
x1, x2 = [C_x, eigvec_1[0] * scale]
y1, y2 = [C_y, eigvec_1[1] * scale]
plt.arrow(x1, y1, x2, y2, color='green', lw=1, head_width=20)
# Show the image
_ = plt.imshow(a, interpolation="none", cmap="gray", origin='lower')
# -
# The **orientation** seems to be correct.
# Now we draw the major and minor axes.
# +
fig, ax = plt.subplots()
# Plot the centroid in red
ax.scatter(C_x, C_y, color='red', marker='+', s=100)
# Plot the major axis
x1 = C_x + semi_major_length * np.cos(theta)
y1 = C_y + semi_major_length * np.sin(theta)
x2 = C_x - semi_major_length * np.cos(theta)
y2 = C_y - semi_major_length * np.sin(theta)
ax.plot([x1, x2], [y1, y2], color='green', lw=1)
# Plot the minor axis
x1 = C_x + semi_minor_length * np.cos(theta + np.pi/2)
y1 = C_y + semi_minor_length * np.sin(theta + np.pi/2)
x2 = C_x - semi_minor_length * np.cos(theta + np.pi/2)
y2 = C_y - semi_minor_length * np.sin(theta + np.pi/2)
ax.plot([x1, x2], [y1, y2], color='green', lw=1)
# Plot the ellipse
angles = np.arange(0, 360, 1) * np.pi / 180
x = 0.5 * major_length * np.cos(angles)
y = 0.5 * minor_length * np.sin(angles)
R = np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]])
x, y = np.dot(R, np.array([x, y]))
x += C_x
y += C_y
ax.plot(x, y, lw=1, color='red')
# Show the image
_ = ax.imshow(a, interpolation="none", cmap="gray", origin='lower', aspect='equal')
# -
# It seems to work but there is an underestimation of the axes length...
#
# The method is not exactly the same but this understimation does not appear in the [ImageJ/Fiji algoritm](http://imagej.nih.gov/ij/source/ij/process/EllipseFitter.java).
#
# Any modifications are welcome !
# ## References
#
# Some links which help me :
#
# - <NAME>, <NAME>, Fitting an ellipse to an arbitrary shape: implications for strain analysis, Journal of Structural Geology, Volume 26, Issue 1, January 2004, Pages 143-153, ISSN 0191-8141. http://dx.doi.org/10.1016/S0191-8141(03)00093-2
# - https://en.wikipedia.org/wiki/Image_moment
# - https://github.com/shackenberg/Image-Moments-in-Python/blob/master/moments.py
# - http://imagej.nih.gov/ij/source/ij/process/EllipseFitter.java
# - http://imagej.1557.x6.nabble.com/Ellipse-fitting-algorithm-used-by-ImageJ-td3686611.html
#
# Another method to detect ellipse :
#
# - <NAME>., & <NAME>. (2002). A new efficient ellipse detection method. Object Recognition Supported by User Interaction for Service Robots, 2(c), 0–3. http://doi.org/10.1109/ICPR.2002.1048464
| Analysis/Fit_Ellipse/notebook.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Final Presentation Notebook
# ### Introduction
# In my personal notebook, I analyze which neighboorhood was cleaned up the most to determine which one is the most environmentally safe. This will be done by analyzing the area covered in each neighborhood by clean-up crews. Then, I will combine that data with data from another data set that contains overall areas of each neighborhood to see which area was cleaned up the most.
# #### Step 1. Import all the datasets that must be used.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
beautify_pgh = pd.read_csv('Pittsburgh_Beautify_The_Burgh.csv')
neighborhoodData = pd.read_csv('neighborhoodData.csv')
# #### Step 2. Here I will add up the areas covered by groups in each neighborhood and sort them from greatest to least. The first neighborhood would have had the most ground covered.
import pandas as pd
df = pd.read_csv('Pittsburgh_Beautify_The_Burgh.csv')
dataSetTwo = df[['Neighborhood','SHAPE_Area']]
#dataSetTwo = df.groupby('Neighborhood').mean().sort_values(['SHAPE_Area','Neighborhood'],ascending =[False,True])
#dataSetTwo['SHAPE_Area'] = dataSetTwo['SHAPE_Area']/4046.86
sortDataSetTwo = dataSetTwo.sort_values(by="Neighborhood")
mergedf = pd.DataFrame(data=sortDataSetTwo)
mergedf2 = mergedf.groupby(['Neighborhood']).agg({'Neighborhood' : 'sum'})
print(mergedf2)
# #### Step 3. Next, I will extract the neighborhood name and area from the Beautify Pittsburgh dataset and sort them the in alphabetical order. I will divide the area by 4046.86 to change from square meters to acres
temporarySet = neighborhoodData.sort_values(by = "hood")
temporarySet = sortedarea[['hood','acres']]
dataSetOne = sortedareadf.reset_index(drop=True)
dataSetOne
# +
# using the df from the last step create a
#new data frame
##neighborhoodFrame = pd.read_csv('neighborhoodData.csv')
##df = pd.read_csv('Pittsburgh_Beautify_The_Burgh.csv')
##dataSetTwo = pd.read_csv('Pittsburgh_Beautify_The_Burgh.csv')
#dataSetTwo['SHAPE_Area'] = dataSetTwo['SHAPE_Area']/4046.86
#dataSetTwo.sort_values(by = 'Neighborhood')
#newDataSetTwo = dataSetTwo[['Neighborhood', 'SHAPE_Area']]
#finalDataSetTwo = newDataSetTwo.reset_index(drop=True)
#finalDataSetTwo
#print(dataSetTwo)
#temporary_Set =dataSetTwo.sort_values(by = "Neighborhood")
#temporary_Set = sortedarea[['Neighborhood','SHAPE_Area]]
#final = sortedareadf.reset_index(drop=True)
#final
#dataSetTwo['SHAPE_Area'] = dataSetOne['shape_length']
#convertedDataNewCol= (dataSetTwo['SHAPE_Area'])/4046.86
#convertedData is a new column insert this into NeighborhoodData
## Merge both sets and data so you can do an operation
## df= data set 1 without converstion
#newFrame = dataSetTwo.merge(convertedDataNewCol)
#newFrame
##newFrame = dataSetOne.merge(convertedData, left_on ='neighborhood', right_on = 'hood', suffixes='ratio','convertedData')
#newDataSet = newFrame[['Neighborhood', 'convertedData','acres', 'ratio']]
merge = sortDataSetTwo.groupby(['Neighborhood']).agg({'SHAPE_Area':'sum'})
merge
# -
import pandas as pd
df = pd.read_csv('Pittsburgh_Beautify_The_Burgh.csv')
dataSetTwo = df[['Neighborhood','SHAPE_Area']]
dataSetTwo = df.groupby('Neighborhood').mean().sort_values(['SHAPE_Area','Neighborhood'],ascending =[False,True])
dataSetTwo['SHAPE_Area'] = dataSetTwo['SHAPE_Area']/4046.86
sortDataSetTwo = dataSetTwo.sort_values(by="Neighborhood").sum()
sortDataSetTwo
| djt (1).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.6 (Develer Science)
# language: python
# name: develer-science
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# # Indexing and Slicing
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Setting up the data
# + slideshow={"slide_type": "fragment"}
import numpy as np
np.random.seed(42)
# + slideshow={"slide_type": "fragment"}
# a vector: the argument to the array function is a Python list
v = np.random.rand(10)
v
# + slideshow={"slide_type": "fragment"}
# a matrix: the argument to the array function is a nested Python list
M = np.random.rand(10, 2)
M
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Indexing
# + [markdown] slideshow={"slide_type": "fragment"}
# We can index elements in an array using the square bracket and indices:
# + slideshow={"slide_type": "fragment"}
# v is a vector, and has only one dimension, taking one index
v[0]
# + slideshow={"slide_type": "fragment"}
# M is a matrix, or a 2 dimensional array, taking two indices
M[1,1]
# + [markdown] slideshow={"slide_type": "subslide"}
# If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)
# + slideshow={"slide_type": "fragment"}
M
# + slideshow={"slide_type": "fragment"}
M[1]
# + [markdown] slideshow={"slide_type": "subslide"}
# The same thing can be achieved with using `:` instead of an index:
# + slideshow={"slide_type": "fragment"}
M[1,:] # row 1
# + slideshow={"slide_type": "fragment"}
M[:,1] # column 1
# + [markdown] slideshow={"slide_type": "subslide"}
# We can assign new values to elements in an array using indexing:
# + slideshow={"slide_type": "fragment"}
M[0,0] = 1
# + slideshow={"slide_type": "fragment"}
M
# + slideshow={"slide_type": "subslide"}
# also works for rows and columns
M[1,:] = 0
M[:,1] = -1
# + slideshow={"slide_type": "fragment"}
M
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Index slicing
# + [markdown] slideshow={"slide_type": "subslide"}
# Index slicing is the technical name for the syntax `M[lower:upper:step]` to extract part of an array:
# + slideshow={"slide_type": "fragment"}
a = np.array([1,2,3,4,5])
a
# + slideshow={"slide_type": "fragment"}
a[1:3]
# + [markdown] slideshow={"slide_type": "subslide"}
# Array slices are **mutable**: if they are assigned a new value the original array from which the slice was extracted is modified:
# + slideshow={"slide_type": "fragment"}
a[1:3] = [-2,-3]
a
# + [markdown] slideshow={"slide_type": "subslide"}
# * We can omit any of the three parameters in `M[lower:upper:step]`:
# + slideshow={"slide_type": "fragment"}
a[::] # lower, upper, step all take the default values
# + slideshow={"slide_type": "fragment"}
a[::2] # step is 2, lower and upper defaults to the beginning and end of the array
# + slideshow={"slide_type": "fragment"}
a[:3] # first three elements
# + slideshow={"slide_type": "fragment"}
a[3:] # elements from index 3
# + [markdown] slideshow={"slide_type": "subslide"}
# * Negative indices counts from the end of the array (positive index from the begining):
# + slideshow={"slide_type": "fragment"}
a = np.array([1,2,3,4,5])
# + slideshow={"slide_type": "fragment"}
a[-1] # the last element in the array
# + slideshow={"slide_type": "fragment"}
a[-3:] # the last three elements
# + [markdown] slideshow={"slide_type": "subslide"}
# * Index slicing works exactly the same way for multidimensional arrays:
# + slideshow={"slide_type": "fragment"}
A = np.array([[n+m*10 for n in range(5)] for m in range(5)])
A
# + slideshow={"slide_type": "fragment"}
# a block from the original array
A[1:4, 1:4]
# + slideshow={"slide_type": "fragment"}
# strides
A[::2, ::2]
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Fancy indexing
# + [markdown] slideshow={"slide_type": "subslide"}
# Fancy indexing is the name for when an array or list is used in-place of an index:
# + slideshow={"slide_type": "fragment"}
row_indices = [1, 2, 3]
A[row_indices]
# + slideshow={"slide_type": "fragment"}
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]
# + [markdown] slideshow={"slide_type": "subslide"}
# * We can also index **masks**:
#
# - If the index mask is an Numpy array of with data type `bool`, then an element is selected (True) or not (False) depending on the value of the index mask at the position each element:
# + slideshow={"slide_type": "subslide"}
b = np.array([n for n in range(5)])
b
# + slideshow={"slide_type": "fragment"}
row_mask = np.array([True, False, True, False, False])
b[row_mask]
# + [markdown] slideshow={"slide_type": "subslide"}
# * Alternatively:
# + slideshow={"slide_type": "fragment"}
# same thing
row_mask = np.array([1,0,1,0,0], dtype=bool)
b[row_mask]
# + [markdown] slideshow={"slide_type": "subslide"}
# This feature is very useful to conditionally select elements from an array, using for example comparison operators:
# + slideshow={"slide_type": "fragment"}
x = np.arange(0, 10, 0.5)
x
# + slideshow={"slide_type": "subslide"}
mask = (5 < x) * (x < 7.5)
mask
# + slideshow={"slide_type": "subslide"}
x[mask]
# + [markdown] slideshow={"slide_type": "slide"}
# ## Indexing and Array Memory Management
# + [markdown] slideshow={"slide_type": "subslide"}
# Numpy arrays support two different way of storing data into memory, namely
#
# * F-Contiguous
# - i.e. *column-wise* storage, Fortran-like
# * C-Contiguous
# - i.e. *row-wise* storage, C-like
#
# The **storage** strategy is controlled by the parameter `order` of `np.array`
#
# <img src="../images/storage_simple.png" />
# + [markdown] slideshow={"slide_type": "subslide"}
# Let's an example
# + slideshow={"slide_type": "fragment"}
import numpy as np
FC = np.array([[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]], order='F')
# + slideshow={"slide_type": "fragment"}
CC = np.array([[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]], order='C')
# + [markdown] slideshow={"slide_type": "subslide"}
# * **Note**: no changes in meaning for indexing operations
# + slideshow={"slide_type": "fragment"}
FC[0, 1]
# + slideshow={"slide_type": "fragment"}
CC[0, 1]
# + slideshow={"slide_type": "subslide"}
FC.shape
# + slideshow={"slide_type": "fragment"}
CC.shape
# + [markdown] slideshow={"slide_type": "slide"}
# <img src="../images/storage_index.png" />
# + [markdown] slideshow={"slide_type": "slide"}
# ## Functions for extracting data from arrays and creating arrays
# + [markdown] slideshow={"slide_type": "subslide"}
# ### `np.where`
# + [markdown] slideshow={"slide_type": "fragment"}
# The index mask can be converted to position index using the `np.where` function
# + slideshow={"slide_type": "fragment"}
indices = np.where(mask)
indices
# + slideshow={"slide_type": "fragment"}
x[indices] # this indexing is equivalent to the fancy indexing x[mask]
# + [markdown] slideshow={"slide_type": "subslide"}
# ### `np.diag`
# + [markdown] slideshow={"slide_type": "fragment"}
# With the `np.diag` function we can also extract the diagonal and subdiagonals of an array:
# + slideshow={"slide_type": "fragment"}
np.diag(A)
# + slideshow={"slide_type": "fragment"}
np.diag(A, -1)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### `np.take`
# + [markdown] slideshow={"slide_type": "fragment"}
# The `np.take` function is similar to fancy indexing described above:
# + slideshow={"slide_type": "fragment"}
v2 = np.arange(-3,3)
v2
# + slideshow={"slide_type": "fragment"}
row_indices = [1, 3, 5]
v2[row_indices] # fancy indexing
# + slideshow={"slide_type": "fragment"}
v2.take(row_indices)
# + [markdown] slideshow={"slide_type": "subslide"}
# * But `take` also works on lists and other objects:
# + slideshow={"slide_type": "fragment"}
np.take([-3, -2, -1, 0, 1, 2], row_indices)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### `np.choose`
# + [markdown] slideshow={"slide_type": "fragment"}
# Constructs and array by picking elements form several arrays:
# + slideshow={"slide_type": "fragment"}
which = [1, 0, 1, 0]
choices = [[-2,-2,-2,-2], [5,5,5,5]]
np.choose(which, choices)
# -
import numpy as np
# + [markdown] slideshow={"slide_type": "slide"}
# ## Computations on subsets of arrays
# + [markdown] slideshow={"slide_type": "subslide"}
# We can compute with subsets of the data in an array using indexing, fancy indexing, and the other methods of extracting data from an array (described above).
# + slideshow={"slide_type": "subslide"}
data = np.random.randn(77431, 3)
months_of_the_year = np.arange(1, 13)
data[:, 1] = np.random.choice(months_of_the_year, size=data.shape[0])
# + slideshow={"slide_type": "subslide"}
np.unique(data[:,1]) # the month column takes values from 1 to 12
# + slideshow={"slide_type": "fragment"}
mask_feb = data[:,1] == 2
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Very simple Data Analysis
# + slideshow={"slide_type": "fragment"}
# compute the mean of values in column 2 (the third one)
np.mean(data[mask_feb,2])
# + [markdown] slideshow={"slide_type": "subslide"}
# With these tools we have very powerful data processing capabilities at our disposal. For example, to extract the average monthly average temperatures for each month of the year only takes a few lines of code:
# + slideshow={"slide_type": "fragment"}
# %matplotlib inline
# + slideshow={"slide_type": "subslide"}
months = np.arange(1,13)
monthly_mean = [np.mean(data[data[:,1] == month, 2]) for month in months]
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(months, monthly_mean)
ax.set_xlabel("Month")
ax.set_ylabel("Monthly avg. temp.");
# + [markdown] slideshow={"slide_type": "slide"}
# # Iterating over array elements
# + [markdown] slideshow={"slide_type": "fragment"}
# Generally, we want to avoid iterating over the elements of arrays whenever we can (at all costs). The reason is that in a interpreted language like Python (or MATLAB), iterations are really slow compared to vectorized operations.
#
# However, sometimes iterations are unavoidable. For such cases, the Python `for` loop is the most convenient way to iterate over an array:
# + slideshow={"slide_type": "subslide"}
v = np.array([1,2,3,4])
for element in v:
print(element)
# + slideshow={"slide_type": "fragment"}
M = np.array([[1,2], [3,4]])
for row in M:
print("row", row)
for element in row:
print(element)
# + [markdown] slideshow={"slide_type": "subslide"}
# we can also `enumerate` over array...
# + slideshow={"slide_type": "fragment"}
for row_idx, row in enumerate(M):
print("row_idx", row_idx, "row", row)
for col_idx, element in enumerate(row):
print("col_idx", col_idx, "element", element)
# update the matrix M: square each element
M[row_idx, col_idx] = element ** 2
# + slideshow={"slide_type": "fragment"}
# each element in M is now squared
M
# -
# ## however, please avoid this as much as possible!!!
# + [markdown] slideshow={"slide_type": "slide"}
# # Vectorizing functions
# + [markdown] slideshow={"slide_type": "subslide"}
# As mentioned several times by now, to get good performance we should try to avoid looping over elements in our vectors and matrices, and instead use vectorized algorithms. The first step in converting a scalar algorithm to a vectorized algorithm is to make sure that the functions we write work with vector inputs.
# + slideshow={"slide_type": "subslide"}
def Theta(x):
"""
Scalar implemenation of the Heaviside step function.
"""
if x >= 0:
return 1
else:
return 0
# + slideshow={"slide_type": "subslide"}
Theta(array([-3,-2,-1,0,1,2,3]))
# + [markdown] slideshow={"slide_type": "subslide"}
# OK, that didn't work because we didn't write the `Theta` function so that it can handle with vector input...
#
# To get a vectorized version of Theta we can use the Numpy function `np.vectorize`. In many cases it can automatically vectorize a function:
# + [markdown] slideshow={"slide_type": "subslide"}
# ### `np.vectorize`
# + slideshow={"slide_type": "fragment"}
Theta_vec = np.vectorize(Theta)
# + slideshow={"slide_type": "fragment"}
Theta_vec(array([-3,-2,-1,0,1,2,3]))
# + [markdown] slideshow={"slide_type": "subslide"}
# ### `np.frompyfunc`
# + [markdown] slideshow={"slide_type": "subslide"}
# **Universal functions** (Ufuncs) work on arrays, element-by-element, or on scalars.
#
# Ufuncs accept a set of scalars as input, and produce a set of scalars as output.
# + slideshow={"slide_type": "fragment"}
Theta_vec = np.frompyfunc(Theta, 1, 1)
print("Result: ", ufunc(np.arange(4)))
# + [markdown] slideshow={"slide_type": "slide"}
# ## Excercise
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Avoiding Vectorize
#
# * Implement the function to accept vector input from the beginning
# - This requires "more effort" but might give better performance
# -
# + [markdown] slideshow={"slide_type": "slide"}
# # Using arrays in conditions
# + [markdown] slideshow={"slide_type": "subslide"}
# When using arrays in conditions in for example `if` statements and other boolean expressions, one need to use one of `any` or `all`, which requires that any or all elements in the array evalutes to `True`:
# + slideshow={"slide_type": "fragment"}
M
# + slideshow={"slide_type": "subslide"}
if (M > 1).any():
print("at least one element in M is larger than 5")
else:
print("no element in M is larger than 5")
# + slideshow={"slide_type": "subslide"}
if (M > 0).all():
print("all elements in M are larger than 5")
else:
print("not all elements in M are larger than 5")
# -
M>0
| 1_apprentice/1.2. Numpy Indexing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import ntpath, os
import azureml.core, azureml.data
print("SDK version:", azureml.core.VERSION)
#from azureml.contrib.pipeline.steps import ParallelRunStep, ParallelRunConfig
from azureml.core import Datastore, Experiment, ScriptRunConfig, Workspace
from azureml.core.compute import AmlCompute
from azureml.core.compute import ComputeTarget
from azureml.core.conda_dependencies import CondaDependencies
from azureml.core.dataset import Dataset
from azureml.core.model import Model
from azureml.core.runconfig import DEFAULT_CPU_IMAGE, RunConfiguration
from azureml.data.azure_storage_datastore import AzureFileDatastore, AzureBlobDatastore
from azureml.data.data_reference import DataReference
from azureml.pipeline.core import Pipeline, PipelineData
from azureml.pipeline.steps import PythonScriptStep
from azureml.train.estimator import Estimator
from azureml.widgets import RunDetails
from pathlib import Path
# -
DEFAULT_CPU_IMAGE
# %run Common.ipynb
ws = Workspace.from_config()
print('Name: {0}'.format(ws.name), 'Resource Group: {0}'.format(ws.resource_group), 'Location: {0}'.format(ws.location), 'Subscription Id: {0}'.format(ws.subscription_id), sep = '\n')
# +
compute_name = 'CPU'
if compute_name in ws.compute_targets:
compute_target = ws.compute_targets[compute_name]
if compute_target and type(compute_target) is AmlCompute:
print('Found compute target: ' + compute_name)
else:
provisioning_configuration = AmlCompute.provisioning_configuration(vm_size = 'STANDARD_D2_V2',
min_nodes = 1,
max_nodes = 2)
compute_target = ComputeTarget.create(ws, compute_name, provisioning_configuration)
compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)
print(compute_target.status.serialize())
# +
compute_name = 'GPU'
if compute_name in ws.compute_targets:
compute_target = ws.compute_targets[compute_name]
if compute_target and type(compute_target) is AmlCompute:
print('Found compute target: ' + compute_name)
else:
provisioning_configuration = AmlCompute.provisioning_configuration(vm_size = 'Standard_NC6',
min_nodes = 1,
max_nodes = 2)
compute_target = ComputeTarget.create(ws, compute_name, provisioning_configuration)
compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)
print(compute_target.status.serialize())
# +
DATA_DIR = './data/HealthyHabitat/'
# load repo with data if it is not exists
if not os.path.exists(DATA_DIR):
print('Run download_healthyhabitat notebook....')
# -
raw = Datastore.register_azure_blob_container(workspace=ws,
datastore_name='raw',
container_name='raw',
account_name='healthyhabitatsvb',
account_key='<KEY>',
create_if_not_exists=True)
target_path = "HealthyHabitat"
raw.upload(src_dir=DATA_DIR[0:-1],
target_path=target_path,
overwrite=True,
show_progress=True)
habitat_data = DataReference(
datastore=raw,
data_reference_name='habitat_data',
path_on_datastore=target_path)
# #### Scripts
# - train.py
# - score.py
# +
# %%writefile ./scripts/train.py
import argparse, cv2, keras, os, sys
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import albumentations as A
import matplotlib.pyplot as plt
import numpy as np
import segmentation_models as sm
from azureml.core import Run
from keras.callbacks import Callback
print("In train.py")
parser = argparse.ArgumentParser("train")
parser.add_argument("--input_data", type=str, help="input data")
args = parser.parse_args()
print("Argument 1: %s" % args.input_data)
x_train_dir = os.path.join(args.input_data, 'train')
y_train_dir = os.path.join(args.input_data, 'trainannot')
x_valid_dir = os.path.join(args.input_data, 'val')
y_valid_dir = os.path.join(args.input_data, 'valannot')
# helper function for data visualization
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(' '.join(name.split('_')).title())
plt.savefig('{0}/{1}.png'.format(args.input_data, name))
plt.savefig('./outputs/{0}.png'.format(name))
# helper function for data visualization
def denormalize(x):
"""Scale image to range 0..1 for correct plot"""
x_max = np.percentile(x, 98)
x_min = np.percentile(x, 2)
x = (x - x_min) / (x_max - x_min)
x = x.clip(0, 1)
return x
# classes for data loading and preprocessing
class Dataset:
"""HealthHabitat Dataset. Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation masks folder
class_values (list): values of classes to extract from segmentation mask
augmentation (albumentations.Compose): data transfromation pipeline
(e.g. flip, scale, etc.)
preprocessing (albumentations.Compose): data preprocessing
(e.g. noralization, shape manipulation, etc.)
"""
CLASSES = ['bare_ground','burnt_para_grass','dead_para_grass','dense_para_grass','other_grass','lily',
'para_grass','tree','water','wet_para_grass','unlabelled']
def __init__(
self,
images_dir,
masks_dir,
classes=None,
augmentation=None,
preprocessing=None,
):
self.ids = os.listdir(images_dir)
self.images_fps = [os.path.join(images_dir, image_id) for image_id in self.ids]
self.masks_fps = [os.path.join(masks_dir, image_id) for image_id in self.ids]
# convert str names to class values on masks
self.class_values = [self.CLASSES.index(cls.lower()) for cls in classes]
self.augmentation = augmentation
self.preprocessing = preprocessing
def __getitem__(self, i):
# read data
image = cv2.imread(self.images_fps[i])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mask = cv2.imread(self.masks_fps[i], 0)
# extract certain classes from mask (e.g. cars)
masks = [(mask == v) for v in self.class_values]
mask = np.stack(masks, axis=-1).astype('float')
# add background if mask is not binary
if mask.shape[-1] != 1:
background = 1 - mask.sum(axis=-1, keepdims=True)
mask = np.concatenate((mask, background), axis=-1)
# apply augmentations
if self.augmentation:
sample = self.augmentation(image=image, mask=mask)
image, mask = sample['image'], sample['mask']
# apply preprocessing
if self.preprocessing:
sample = self.preprocessing(image=image, mask=mask)
image, mask = sample['image'], sample['mask']
return image, mask
def __len__(self):
return len(self.ids)
class Dataloder(keras.utils.Sequence):
"""Load data from dataset and form batches
Args:
dataset: instance of Dataset class for image loading and preprocessing.
batch_size: Integet number of images in batch.
shuffle: Boolean, if `True` shuffle image indexes each epoch.
"""
def __init__(self, dataset, batch_size=1, shuffle=False):
self.dataset = dataset
self.batch_size = batch_size
self.shuffle = shuffle
self.indexes = np.arange(len(dataset))
self.on_epoch_end()
def __getitem__(self, i):
# collect batch data
start = i * self.batch_size
stop = (i + 1) * self.batch_size
data = []
for j in range(start, stop):
data.append(self.dataset[j])
# transpose list of lists
batch = [np.stack(samples, axis=0) for samples in zip(*data)]
return batch
def __len__(self):
"""Denotes the number of batches per epoch"""
return len(self.indexes) // self.batch_size
def on_epoch_end(self):
"""Callback function to shuffle indexes each epoch"""
if self.shuffle:
self.indexes = np.random.permutation(self.indexes)
def round_clip_0_1(x, **kwargs):
return x.round().clip(0, 1)
# define heavy augmentations
def get_training_augmentation():
train_transform = [
A.HorizontalFlip(p=0.5),
A.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0),
A.PadIfNeeded(min_height=320, min_width=320, always_apply=True, border_mode=0),
A.RandomCrop(height=320, width=320, always_apply=True),
A.IAAAdditiveGaussianNoise(p=0.2),
A.IAAPerspective(p=0.5),
A.OneOf(
[
A.CLAHE(p=1),
A.RandomBrightness(p=1),
A.RandomGamma(p=1),
],
p=0.9,
),
A.OneOf(
[
A.IAASharpen(p=1),
A.Blur(blur_limit=3, p=1),
A.MotionBlur(blur_limit=3, p=1),
],
p=0.9,
),
A.OneOf(
[
A.RandomContrast(p=1),
A.HueSaturationValue(p=1),
],
p=0.9,
),
A.Lambda(mask=round_clip_0_1)
]
return A.Compose(train_transform)
def get_validation_augmentation():
"""Add paddings to make image shape divisible by 32"""
test_transform = [
A.PadIfNeeded(384, 480)
]
return A.Compose(test_transform)
def get_preprocessing(preprocessing_fn):
"""Construct preprocessing transform
Args:
preprocessing_fn (callbale): data normalization function
(can be specific for each pretrained neural network)
Return:
transform: albumentations.Compose
"""
_transform = [
A.Lambda(image=preprocessing_fn),
]
return A.Compose(_transform)
# Lets look at data we have
dataset = Dataset(x_train_dir, y_train_dir, classes=['para_grass', 'tree'])
image, mask = dataset[5] # get some sample
visualize(
image=image,
cars_mask=mask[..., 0].squeeze(),
sky_mask=mask[..., 1].squeeze(),
background_mask=mask[..., 2].squeeze(),
)
# Lets look at augmented data we have
dataset = Dataset(x_train_dir, y_train_dir, classes=['para_grass', 'tree'], augmentation=get_training_augmentation())
image, mask = dataset[12] # get some sample
visualize(
image=image,
cars_mask=mask[..., 0].squeeze(),
sky_mask=mask[..., 1].squeeze(),
background_mask=mask[..., 2].squeeze(),
)
BACKBONE = 'efficientnetb3'
BATCH_SIZE = 8
CLASSES = ['car']
LR = 0.0001
#EPOCHS = 40
EPOCHS = 5
preprocess_input = sm.get_preprocessing(BACKBONE)
# define network parameters
n_classes = 1 if len(CLASSES) == 1 else (len(CLASSES) + 1) # case for binary and multiclass segmentation
activation = 'sigmoid' if n_classes == 1 else 'softmax'
#create model
model = sm.Unet(BACKBONE, classes=n_classes, activation=activation)
# define optomizer
optim = keras.optimizers.Adam(LR)
# Segmentation models losses can be combined together by '+' and scaled by integer or float factor
dice_loss = sm.losses.DiceLoss()
focal_loss = sm.losses.BinaryFocalLoss() if n_classes == 1 else sm.losses.CategoricalFocalLoss()
total_loss = dice_loss + (1 * focal_loss)
# actulally total_loss can be imported directly from library, above example just show you how to manipulate with losses
# total_loss = sm.losses.binary_focal_dice_loss # or sm.losses.categorical_focal_dice_loss
metrics = [sm.metrics.IOUScore(threshold=0.5), sm.metrics.FScore(threshold=0.5)]
# compile keras model with defined optimozer, loss and metrics
model.compile(optim, total_loss, metrics)
# Dataset for train images
train_dataset = Dataset(
x_train_dir,
y_train_dir,
classes=CLASSES,
augmentation=get_training_augmentation(),
preprocessing=get_preprocessing(preprocess_input),
)
# Dataset for validation images
valid_dataset = Dataset(
x_valid_dir,
y_valid_dir,
classes=CLASSES,
augmentation=get_validation_augmentation(),
preprocessing=get_preprocessing(preprocess_input),
)
train_dataloader = Dataloder(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
valid_dataloader = Dataloder(valid_dataset, batch_size=1, shuffle=False)
# check shapes for errors
assert train_dataloader[0][0].shape == (BATCH_SIZE, 320, 320, 3)
assert train_dataloader[0][1].shape == (BATCH_SIZE, 320, 320, n_classes)
run = Run.get_context()
class LogRunMetrics(Callback):
# callback at the end of every epoch
def on_epoch_end(self, epoch, log):
# log a value repeated which creates a list
run.log('Val. Loss', log['val_loss'])
run.log('Val. IoU Score', log['val_iou_score'])
run.log('Val. F1 Score', log['val_f1-score'])
run.log('Loss', log['loss'])
run.log('IoU Score', log['iou_score'])
run.log('F1 Score', log['f1-score'])
run.log('LR', log['lr'])
# define callbacks for learning rate scheduling and best checkpoints saving
callbacks = [
keras.callbacks.ModelCheckpoint('./outputs/best_model.h5', save_weights_only=True, save_best_only=True, mode='min'),
#keras.callbacks.ModelCheckpoint(os.path.join(args.input_data, 'best_model.h5'), save_weights_only=True, save_best_only=True, mode='min'),
keras.callbacks.ReduceLROnPlateau(),
LogRunMetrics()
]
# train model
history = model.fit_generator(
train_dataloader,
steps_per_epoch=len(train_dataloader),
epochs=EPOCHS,
callbacks=callbacks,
validation_data=valid_dataloader,
validation_steps=len(valid_dataloader),
)
fname = 'plot.jpg'
# Plot training & validation iou_score values
plt.figure(figsize=(30, 5))
plt.subplot(121)
plt.plot(history.history['iou_score'])
plt.plot(history.history['val_iou_score'])
plt.title('Model iou_score')
plt.ylabel('iou_score')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# Plot training & validation loss values
plt.subplot(122)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.savefig('{0}/{1}'.format(args.input_data, fname))
plt.savefig('./outputs/{0}'.format(fname))
test_dataset = Dataset(
x_test_dir,
y_test_dir,
classes=CLASSES,
augmentation=get_validation_augmentation(),
preprocessing=get_preprocessing(preprocess_input),
)
test_dataloader = Dataloder(test_dataset, batch_size=1, shuffle=False)
# load best weights
model.load_weights('./outputs/best_model.h5')
scores = model.evaluate_generator(test_dataloader)
print("Loss: {:.5}".format(scores[0]))
for metric, value in zip(metrics, scores[1:]):
print("mean {}: {:.5}".format(metric.__name__, value))
n = 5
ids = np.random.choice(np.arange(len(test_dataset)), size=n)
for i in ids:
image, gt_mask = test_dataset[i]
image = np.expand_dims(image, axis=0)
pr_mask = model.predict(image).round()
visualize(
image=denormalize(image.squeeze()),
gt_mask=gt_mask[..., 0].squeeze(),
pr_mask=pr_mask[..., 0].squeeze(),
)
model = run.register_model(model_name='qubvel-segmentation_models-u-net', model_path='./outputs/best_model.h5')
print(model.name, model.id, model.version, sep = '\t')
# +
# %%writefile ./scripts/score.py
import argparse, keras, os, sys
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import matplotlib.pyplot as plt
import numpy as np
import segmentation_models as sm
from azureml.core import Model, Run
print("In score.py")
parser = argparse.ArgumentParser("score")
parser.add_argument("--input_data", type=str, help="input data")
parser.add_argument("--output_data", type=str, help="output data")
args = parser.parse_args()
print("Argument 1: %s" % args.input_data)
print("Argument 2: %s" % args.output_data)
x_test_dir = os.path.join(args.input_data, 'test')
y_test_dir = os.path.join(args.input_data, 'testannot')
# helper function for data visualization
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(' '.join(name.split('_')).title())
plt.savefig('{0}/{1}.png'.format(args.input_data, name))
plt.savefig('./outputs/{0}.png'.format(name))
# helper function for data visualization
def denormalize(x):
"""Scale image to range 0..1 for correct plot"""
x_max = np.percentile(x, 98)
x_min = np.percentile(x, 2)
x = (x - x_min) / (x_max - x_min)
x = x.clip(0, 1)
return x
# classes for data loading and preprocessing
class Dataset:
"""CamVid Dataset. Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation masks folder
class_values (list): values of classes to extract from segmentation mask
augmentation (albumentations.Compose): data transfromation pipeline
(e.g. flip, scale, etc.)
preprocessing (albumentations.Compose): data preprocessing
(e.g. noralization, shape manipulation, etc.)
"""
CLASSES = ['sky', 'building', 'pole', 'road', 'pavement',
'tree', 'signsymbol', 'fence', 'car',
'pedestrian', 'bicyclist', 'unlabelled']
def __init__(
self,
images_dir,
masks_dir,
classes=None,
augmentation=None,
preprocessing=None,
):
self.ids = os.listdir(images_dir)
self.images_fps = [os.path.join(images_dir, image_id) for image_id in self.ids]
self.masks_fps = [os.path.join(masks_dir, image_id) for image_id in self.ids]
# convert str names to class values on masks
self.class_values = [self.CLASSES.index(cls.lower()) for cls in classes]
self.augmentation = augmentation
self.preprocessing = preprocessing
def __getitem__(self, i):
# read data
image = cv2.imread(self.images_fps[i])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mask = cv2.imread(self.masks_fps[i], 0)
# extract certain classes from mask (e.g. cars)
masks = [(mask == v) for v in self.class_values]
mask = np.stack(masks, axis=-1).astype('float')
# add background if mask is not binary
if mask.shape[-1] != 1:
background = 1 - mask.sum(axis=-1, keepdims=True)
mask = np.concatenate((mask, background), axis=-1)
# apply augmentations
if self.augmentation:
sample = self.augmentation(image=image, mask=mask)
image, mask = sample['image'], sample['mask']
# apply preprocessing
if self.preprocessing:
sample = self.preprocessing(image=image, mask=mask)
image, mask = sample['image'], sample['mask']
return image, mask
def __len__(self):
return len(self.ids)
class Dataloder(keras.utils.Sequence):
"""Load data from dataset and form batches
Args:
dataset: instance of Dataset class for image loading and preprocessing.
batch_size: Integet number of images in batch.
shuffle: Boolean, if `True` shuffle image indexes each epoch.
"""
def __init__(self, dataset, batch_size=1, shuffle=False):
self.dataset = dataset
self.batch_size = batch_size
self.shuffle = shuffle
self.indexes = np.arange(len(dataset))
self.on_epoch_end()
def __getitem__(self, i):
# collect batch data
start = i * self.batch_size
stop = (i + 1) * self.batch_size
data = []
for j in range(start, stop):
data.append(self.dataset[j])
# transpose list of lists
batch = [np.stack(samples, axis=0) for samples in zip(*data)]
return batch
def __len__(self):
"""Denotes the number of batches per epoch"""
return len(self.indexes) // self.batch_size
def on_epoch_end(self):
"""Callback function to shuffle indexes each epoch"""
if self.shuffle:
self.indexes = np.random.permutation(self.indexes)
def round_clip_0_1(x, **kwargs):
return x.round().clip(0, 1)
# define heavy augmentations
def get_training_augmentation():
train_transform = [
A.HorizontalFlip(p=0.5),
A.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0),
A.PadIfNeeded(min_height=320, min_width=320, always_apply=True, border_mode=0),
A.RandomCrop(height=320, width=320, always_apply=True),
A.IAAAdditiveGaussianNoise(p=0.2),
A.IAAPerspective(p=0.5),
A.OneOf(
[
A.CLAHE(p=1),
A.RandomBrightness(p=1),
A.RandomGamma(p=1),
],
p=0.9,
),
A.OneOf(
[
A.IAASharpen(p=1),
A.Blur(blur_limit=3, p=1),
A.MotionBlur(blur_limit=3, p=1),
],
p=0.9,
),
A.OneOf(
[
A.RandomContrast(p=1),
A.HueSaturationValue(p=1),
],
p=0.9,
),
A.Lambda(mask=round_clip_0_1)
]
return A.Compose(train_transform)
def get_validation_augmentation():
"""Add paddings to make image shape divisible by 32"""
test_transform = [
A.PadIfNeeded(384, 480)
]
return A.Compose(test_transform)
def get_preprocessing(preprocessing_fn):
"""Construct preprocessing transform
Args:
preprocessing_fn (callbale): data normalization function
(can be specific for each pretrained neural network)
Return:
transform: albumentations.Compose
"""
_transform = [
A.Lambda(image=preprocessing_fn),
]
return A.Compose(_transform)
test_dataset = Dataset(
x_test_dir,
y_test_dir,
classes=CLASSES,
augmentation=get_validation_augmentation(),
preprocessing=get_preprocessing(preprocess_input),
)
def init():
global model
model_path = Model.get_model_path('qubvel-segmentation_models-u-net')
BACKBONE = 'efficientnetb3'
CLASSES = ['car']
n_classes = 1 if len(CLASSES) == 1 else (len(CLASSES) + 1) # case for binary and multiclass segmentation
activation = 'sigmoid' if n_classes == 1 else 'softmax'
model = sm.Unet(BACKBONE, classes=n_classes, activation=activation)
model.load_weights(os.path.join(model_path, 'best_model.h5'))
def run(mini_batch):
print(f'run method start: {__file__}, run({mini_batch})')
resultList = []
print(mini_batch)
test_dataloader = Dataloder(test_dataset, batch_size=1, shuffle=False)
scores = model.evaluate_generator(test_dataloader)
print("Loss: {:.5}".format(scores[0]))
for metric, value in zip(metrics, scores[1:]):
print("mean {}: {:.5}".format(metric.__name__, value))
'''
for image in mini_batch:
# prepare each image
data = Image.open(image)
np_im = np.array(data).reshape((1, 784))
# perform inference
inference_result = output.eval(feed_dict={in_tensor: np_im}, session=g_tf_sess)
# find best probability, and add to result list
best_result = np.argmax(inference_result)
resultList.append("{}: {}".format(os.path.basename(image), best_result))
'''
return resultList
# -
# ### Pipeline
# +
conda_dependencies = CondaDependencies()
conda_dependencies.add_pip_package('albumentations')
conda_dependencies.add_pip_package('keras')
conda_dependencies.add_pip_package('matplotlib')
conda_dependencies.add_pip_package('opencv-python')
conda_dependencies.add_pip_package('segmentation-models')
conda_dependencies.add_pip_package('tensorflow')
run_configuration = RunConfiguration()
run_configuration.environment.docker.enabled = True
run_configuration.environment.docker.base_image = DEFAULT_CPU_IMAGE
run_configuration.environment.python.user_managed_dependencies = False
run_configuration.environment.python.conda_dependencies = conda_dependencies
run_configuration.target = compute_target
# +
source_directory = './scripts'
train_step = PythonScriptStep(name="train",
source_directory=source_directory,
script_name="train.py",
arguments=['--input_data', camvid_data],
inputs=[camvid_data],
compute_target=compute_target,
runconfig=run_configuration,
allow_reuse=False)
# -
pipeline = Pipeline(workspace=ws, steps=[train_step])
pipeline_run = Experiment(ws, 'train_pipeline').submit(pipeline)
pipeline_run
RunDetails(pipeline_run).show()
pipeline_run.wait_for_completion(show_output=True)
# ### Batch Inference
# +
dataset_name = 'camvid_dataset'
camvid_dataset = Dataset.File.from_files(path=camvid_data , validate=False)
registered_camvid_dataset = camvid_dataset.register(ws, dataset_name, create_new_version=True)
named_camvid_dataset = registered_camvid_dataset.as_named_input(dataset_name)
# -
output_data = PipelineData(name="results",
datastore=raw,
output_path_on_compute="CamVid/results")
parallel_run_config = ParallelRunConfig(
source_directory=scripts_folder,
entry_script=script_file,
mini_batch_size="5",
error_threshold=10,
output_action="append_row",
environment=batch_env,
compute_target=compute_target,
node_count=2)
| v1/notebooks/qubvel-segmentation_models-U-Net-ML-Pipeline-healthyhabitat.ipynb |
# # Fast tokenizers' special powers (PyTorch)
# Install the Transformers and Datasets libraries to run this notebook.
# !pip install datasets transformers[sentencepiece]
# +
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
example = "My name is Sylvain and I work at Hugging Face in Brooklyn."
encoding = tokenizer(example)
print(type(encoding))
# -
tokenizer.is_fast
encoding.is_fast
encoding.tokens()
encoding.word_ids()
start, end = encoding.word_to_chars(3)
example[start:end]
# +
from transformers import pipeline
token_classifier = pipeline("token-classification")
token_classifier("My name is Sylvain and I work at Hugging Face in Brooklyn.")
# +
from transformers import pipeline
token_classifier = pipeline("token-classification", aggregation_strategy="simple")
token_classifier("My name is Sylvain and I work at Hugging Face in Brooklyn.")
# +
from transformers import AutoTokenizer, AutoModelForTokenClassification
model_checkpoint = "dbmdz/bert-large-cased-finetuned-conll03-english"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
model = AutoModelForTokenClassification.from_pretrained(model_checkpoint)
example = "My name is Sylvain and I work at Hugging Face in Brooklyn."
inputs = tokenizer(example, return_tensors="pt")
outputs = model(**inputs)
# -
print(inputs["input_ids"].shape)
print(outputs.logits.shape)
# +
import torch
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)[0].tolist()
predictions = outputs.logits.argmax(dim=-1)[0].tolist()
print(predictions)
# -
model.config.id2label
# +
results = []
tokens = inputs.tokens()
for idx, pred in enumerate(predictions):
label = model.config.id2label[pred]
if label != "O":
results.append(
{"entity": label, "score": probabilities[idx][pred], "word": tokens[idx]}
)
print(results)
# -
inputs_with_offsets = tokenizer(example, return_offsets_mapping=True)
inputs_with_offsets["offset_mapping"]
example[12:14]
# +
results = []
inputs_with_offsets = tokenizer(example, return_offsets_mapping=True)
tokens = inputs_with_offsets.tokens()
offsets = inputs_with_offsets["offset_mapping"]
for idx, pred in enumerate(predictions):
label = model.config.id2label[pred]
if label != "O":
start, end = offsets[idx]
results.append(
{
"entity": label,
"score": probabilities[idx][pred],
"word": tokens[idx],
"start": start,
"end": end,
}
)
print(results)
# -
example[33:45]
# +
import numpy as np
results = []
inputs_with_offsets = tokenizer(example, return_offsets_mapping=True)
tokens = inputs_with_offsets.tokens()
offsets = inputs_with_offsets["offset_mapping"]
idx = 0
while idx < len(predictions):
pred = predictions[idx]
label = model.config.id2label[pred]
if label != "O":
# Remove the B- or I-
label = label[2:]
start, _ = offsets[idx]
# Grab all the tokens labeled with I-label
all_scores = []
while (
idx < len(predictions)
and model.config.id2label[predictions[idx]] == f"I-{label}"
):
all_scores.append(probabilities[idx][pred])
_, end = offsets[idx]
idx += 1
# The score is the mean of all the scores of the tokens in that grouped entity
score = np.mean(all_scores).item()
word = example[start:end]
results.append(
{
"entity_group": label,
"score": score,
"word": word,
"start": start,
"end": end,
}
)
idx += 1
print(results)
| notebooks/course/chapter6/section3_pt.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %load_ext autoreload
# %autoreload 2
from ceres_infer.data import process_data
# +
# Preprocess data for gene effect (continuous)
ext_data = {'dir_datasets': '../data/DepMap_DROP_PC9/19Q3',
'dir_ceres_datasets': '../data/ceres_external/PC9_corrected',
'data_name': 'data_pc9',
'fname_gene_effect': 'gene_effect.csv',
'fname_gene_dependency': None,
'out_name': 'dm_data_pc9',
'out_match_name': 'dm_data_match_pc9'}
preprocess_params = {'useGene_dependency': False,
'dir_out': '../out/21.0423 proc_data PC9/gene_effect/',
'dir_depmap': '../data/DepMap_DROP_PC9/',
'ext_data':ext_data}
# -
proc = process_data(preprocess_params)
proc.process()
proc.process_external(match_samples=['PC9'], shared_only=False)
# ***
# ### Standalone l200
from ceres_infer.data import process_data
# +
# Preprocess data for gene effect (continuous)
ext_data = {'dir_datasets': '../data/DepMap_DROP_PC9/19Q3',
'dir_ceres_datasets': '../data/ceres_external/PC9_corrected',
'data_name': 'data_pc9',
'fname_gene_effect': 'gene_effect_standalone.csv',
'fname_gene_dependency': None,
'out_name': 'dm_data_pc9',
'out_match_name': 'dm_data_match_pc9'}
preprocess_params = {'useGene_dependency': False,
'dir_out': '../out/21.0720 proc_data PC9Standalone/gene_effect/',
'dir_depmap': '../data/DepMap_DROP_PC9/',
'ext_data': ext_data}
# -
proc = process_data(preprocess_params)
proc.process()
proc.process_external(match_samples=['PC9'], shared_only=False)
| notebooks/Rrun01a-preprocess_PC9-YR.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Markup Languages
# XML and its relatives are based on the idea of *marking up* content with labels on its purpose:
#
# <name>James</name> is a <job>Programmer</job>
# One of the easiest ways to make a markup-language based fileformat is the use of a *templating language*.
# +
from parsereactions import parser
from IPython.display import display, Math
with open("system.tex", "r") as f_latex:
system = parser.parse(f_latex.read())
display(Math(str(system)))
# -
# %%writefile chemistry_template.mko
<?xml version="1.0" encoding="UTF-8"?>
<system>
# %for reaction in reactions:
<reaction>
<reactants>
# %for molecule in reaction.reactants.molecules:
<molecule stoichiometry="${reaction.reactants.molecules[molecule]}">
# %for element in molecule.elements:
<atom symbol="${element.symbol}" number="${molecule.elements[element]}"/>
# %endfor
</molecule>
# %endfor
</reactants>
<products>
# %for molecule in reaction.products.molecules:
<molecule stoichiometry="${reaction.products.molecules[molecule]}">
# %for element in molecule.elements:
<atom symbol="${element.symbol}" number="${molecule.elements[element]}"/>
# %endfor
</molecule>
# %endfor
</products>
</reaction>
# %endfor
</system>
# +
from mako.template import Template
mytemplate = Template(filename="chemistry_template.mko")
with open("system.xml", "w") as xmlfile:
xmlfile.write((mytemplate.render(**vars(system))))
# -
# !cat system.xml
# Markup languages are verbose (jokingly called the "angle bracket tax") but very clear.
# ## Data as text
# The above serialisation specifies all data as XML "Attributes". An alternative is to put the data in the text:
# %%writefile chemistry_template2.mko
<?xml version="1.0" encoding="UTF-8"?>
<system>
# %for reaction in reactions:
<reaction>
<reactants>
# %for molecule in reaction.reactants.molecules:
<molecule stoichiometry="${reaction.reactants.molecules[molecule]}">
# %for element in molecule.elements:
<atom symbol="${element.symbol}">${molecule.elements[element]}</atom>
# %endfor
</molecule>
# %endfor
</reactants>
<products>
# %for molecule in reaction.products.molecules:
<molecule stoichiometry="${reaction.products.molecules[molecule]}">
# %for element in molecule.elements:
<atom symbol="${element.symbol}">${molecule.elements[element]}</atom>
# %endfor
</molecule>
# %endfor
</products>
</reaction>
# %endfor
</system>
# +
from mako.template import Template
mytemplate = Template(filename="chemistry_template2.mko")
with open("system2.xml", "w") as xmlfile:
xmlfile.write((mytemplate.render(**vars(system))))
# -
# !cat system2.xml
# ## Parsing XML
# XML is normally parsed by building a tree-structure of all the `tags` in the file, called a `DOM` or Document Object Model.
# +
from lxml import etree
with open("system.xml", "r") as xmlfile:
tree = etree.parse(xmlfile)
print(etree.tostring(tree, pretty_print=True, encoding=str))
# -
# We can navigate the tree, with each **element** being an iterable yielding its children:
tree.getroot()[0][0][1].attrib["stoichiometry"]
# ## Searching XML
# `xpath` is a sophisticated tool for searching XML DOMs:
#
# There's a good explanation of how it works here: https://www.w3schools.com/xml/xml_xpath.asp but the basics are reproduced below.
# | XPath Expression | Result |
# | :- | :- |
# | `/bookstore/book[1]` | Selects the first `book` that is the child of a `bookstore` |
# | `/bookstore/book[last()]` | Selects the last `book` that is the child of a `bookstore` |
# | `/bookstore/book[last()-1]` | Selects the last but one `book` that is the child of a `bookstore` |
# | `/bookstore/book[position()<3]`| Selects the first two `book`s that are children of a `bookstore` |
# | `//title[@lang]` | Selects all `title`s that have an attribute named "lang" |
# | `//title[@lang='en']` | Selects all `title`s that have a "lang" attribute with a value of "en" |
# | `/bookstore/book[price>35.00]` | Selects all `book`s that are children of a `bookstore` and have a `price` with a value greater than 35.00 |
# | `/bookstore/book[price>35.00]/title` | Selects all the `title`s of a `book` of a `bookstore` that have a `price` with a value greater than 35.00 |
# For all molecules
# ... with a child atom whose number attribute is '1'
# ... return the symbol attribute of that child
tree.xpath("//molecule/atom[@number='1']/@symbol")
# It is useful to understand grammars like these using the "FOR-LET-WHERE-ORDER-RETURN" (pronounced Flower) model.
# The above says: "For element in molecules where number is one, return symbol", roughly equivalent to `[element.symbol for element in molecule for molecule in document if element.number==1]` in Python.
with open("system2.xml") as xmlfile:
tree2 = etree.parse(xmlfile)
# For all molecules with a child atom whose text is 1
# ... return the symbol attribute of any child (however deeply nested)
print(tree2.xpath("//molecule[atom=1]//@symbol"))
# Note how we select on text content rather than attributes by using the element tag directly. The above says "for every molecule where at least one element is present with just a single atom, return all the symbols of all the elements in that molecule."
# ## Transforming XML : XSLT
# Two technologies (XSLT and XQUERY) provide capability to produce text output from an XML tree.
# We'll look at XSLT as support is more widespread, including in the python library we're using. XQuery is probably easier to use and understand, but with less support.
#
# However, XSLT is a beautiful functional declarative language, once you read past the angle-brackets.
# Here's an XSLT to transform our reaction system into a LaTeX representation:
# +
# %%writefile xmltotex.xsl
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
<!-- Decompose reaction into "reactants \rightarrow products" -->
<xsl:template match="//reaction">
<xsl:apply-templates select="reactants"/>
<xsl:text> \rightarrow </xsl:text>
<xsl:apply-templates select="products"/>
<xsl:text>\\
</xsl:text>
</xsl:template>
<!-- For a molecule anywhere except the first position write " + " and the number of molecules-->
<xsl:template match="//molecule[position()!=1]">
<xsl:text> + </xsl:text>
<xsl:apply-templates select="@stoichiometry"/>
<xsl:apply-templates/>
</xsl:template>
<!-- For a molecule in first position write the number of molecules -->
<xsl:template match="//molecule[position()=1]">
<xsl:apply-templates select="@stoichiometry"/>
<xsl:apply-templates/>
</xsl:template>
<!-- If the stoichiometry is one then ignore it -->
<xsl:template match="@stoichiometry[.='1']"/>
<!-- Otherwise, use the default template for attributes, which is just to copy value -->
<!-- Decompose element into "symbol number" -->
<xsl:template match="//atom">
<xsl:value-of select="@symbol"/>
<xsl:apply-templates select="@number"/>
</xsl:template>
<!-- If the number of elements/molecules is one then ignore it -->
<xsl:template match="@number[.=1]"/>
<!-- ... otherwise replace it with "_ value" -->
<xsl:template match="@number[.!=1][10>.]">
<xsl:text>_</xsl:text>
<xsl:value-of select="."/>
</xsl:template>
<!-- If a number is greater than 10 then wrap it in "{}" -->
<xsl:template match="@number[.!=1][.>9]">
<xsl:text>_{</xsl:text>
<xsl:value-of select="."/>
<xsl:text>}</xsl:text>
</xsl:template>
<!-- Do not copy input whitespace to output -->
<xsl:template match="text()" />
</xsl:stylesheet>
# -
with open("xmltotex.xsl") as xslfile:
transform_xsl = xslfile.read()
transform = etree.XSLT(etree.XML(transform_xsl))
print(str(transform(tree)))
display(Math(str(transform(tree))))
# ## Validating XML : Schema
# XML Schema is a way to define how an XML file is allowed to be: which attributes and tags should exist where.
#
# You should always define one of these when using an XML file format.
# +
# %%writefile reactions.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="atom">
<xs:complexType>
<xs:attribute name="symbol" type="xs:string"/>
<xs:attribute name="number" type="xs:integer"/>
</xs:complexType>
</xs:element>
<xs:element name="molecule">
<xs:complexType>
<xs:sequence>
<xs:element ref="atom" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="stoichiometry" type="xs:integer"/>
</xs:complexType>
</xs:element>
<xs:element name="reaction">
<xs:complexType>
<xs:sequence>
<xs:element name="reactants">
<xs:complexType>
<xs:sequence>
<xs:element ref="molecule" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="products">
<xs:complexType>
<xs:sequence>
<xs:element ref="molecule" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="system">
<xs:complexType>
<xs:sequence>
<xs:element ref="reaction" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
# -
with open("reactions.xsd") as xsdfile:
schema_xsd = xsdfile.read()
schema = etree.XMLSchema(etree.XML(schema_xsd))
parser = etree.XMLParser(schema=schema)
with open("system.xml") as xmlfile:
tree = etree.parse(xmlfile, parser)
# For all atoms return their symbol attribute
tree.xpath("//atom/@symbol")
# Compare parsing something that is not valid under the schema:
# +
# %%writefile invalid_system.xml
<system>
<reaction>
<reactants>
<molecule stoichiometry="two">
<atom symbol="H" number="2"/>
</molecule>
<molecule stoichiometry="1">
<atom symbol="O" number="2"/>
</molecule>
</reactants>
<products>
<molecule stoichiometry="2">
<atom symbol="H" number="2"/>
<atom symbol="O" number="1"/>
</molecule>
</products>
</reaction>
</system>
# -
try:
with open("invalid_system.xml") as xmlfile:
tree = etree.parse(xmlfile, parser)
tree.xpath("//element//@symbol")
except etree.XMLSyntaxError as e:
print(e)
# This shows us that the validation has failed and why.
| ch09fileformats/10MarkupLanguages.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: conda_python3
# language: python
# name: conda_python3
# ---
# ## Develop, Train, Optimize and Deploy Scikit-Learn Random Forest
#
# * Doc https://sagemaker.readthedocs.io/en/stable/using_sklearn.html
# * SDK https://sagemaker.readthedocs.io/en/stable/sagemaker.sklearn.html
# * boto3 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#client
#
# In this notebook we show how to use Amazon SageMaker to develop, train, tune and deploy a Scikit-Learn based ML model (Random Forest). More info on Scikit-Learn can be found here https://scikit-learn.org/stable/index.html. We use the Boston Housing dataset, present in Scikit-Learn: https://scikit-learn.org/stable/datasets/index.html#boston-dataset
#
#
# More info on the dataset:
#
# The Boston house-price data of <NAME>. and <NAME>. 'Hedonic prices and the demand for clean air', J. Environ. Economics & Management, vol.5, 81-102, 1978. Used in Belsley, Kuh & Welsch, 'Regression diagnostics ...', Wiley, 1980. N.B. Various transformations are used in the table on pages 244-261 of the latter.
#
# The Boston house-price data has been used in many machine learning papers that address regression problems.
# References
#
# * Belsley, Kuh & Welsch, 'Regression diagnostics: Identifying Influential Data and Sources of Collinearity', Wiley, 1980. 244-261.
# * Quinlan,R. (1993). Combining Instance-Based and Model-Based Learning. In Proceedings on the Tenth International Conference of Machine Learning, 236-243, University of Massachusetts, Amherst. <NAME>.
#
#
#
#
# **This sample is provided for demonstration purposes, make sure to conduct appropriate testing if derivating this code for your own use-cases!**
# +
import datetime
import time
import tarfile
import boto3
import pandas as pd
import numpy as np
from sagemaker import get_execution_role
import sagemaker
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_boston
sm_boto3 = boto3.client('sagemaker')
sess = sagemaker.Session()
region = sess.boto_session.region_name
bucket = sess.default_bucket() # this could also be a hard-coded bucket name
print('Using bucket ' + bucket)
# -
# ## Prepare data
# We load a dataset from sklearn, split it and send it to S3
# we use the Boston housing dataset
data = load_boston()
# +
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.25, random_state=42)
trainX = pd.DataFrame(X_train, columns=data.feature_names)
trainX['target'] = y_train
testX = pd.DataFrame(X_test, columns=data.feature_names)
testX['target'] = y_test
# -
trainX.head()
trainX.to_csv('boston_train.csv')
testX.to_csv('boston_test.csv')
# +
# send data to S3. SageMaker will take training data from s3
trainpath = sess.upload_data(
path='boston_train.csv', bucket=bucket,
key_prefix='sagemaker/sklearncontainer')
testpath = sess.upload_data(
path='boston_test.csv', bucket=bucket,
key_prefix='sagemaker/sklearncontainer')
# -
# ## Writing a *Script Mode* script
# The below script contains both training and inference functionality and can run both in SageMaker Training hardware or locally (desktop, SageMaker notebook, on prem, etc). Detailed guidance here https://sagemaker.readthedocs.io/en/stable/using_sklearn.html#preparing-the-scikit-learn-training-script
# +
# %%writefile script.py
import argparse
import joblib
import os
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
# inference functions ---------------
def model_fn(model_dir):
clf = joblib.load(os.path.join(model_dir, "model.joblib"))
return clf
if __name__ =='__main__':
print('extracting arguments')
parser = argparse.ArgumentParser()
# hyperparameters sent by the client are passed as command-line arguments to the script.
# to simplify the demo we don't use all sklearn RandomForest hyperparameters
parser.add_argument('--n-estimators', type=int, default=10)
parser.add_argument('--min-samples-leaf', type=int, default=3)
# Data, model, and output directories
parser.add_argument('--model-dir', type=str, default=os.environ.get('SM_MODEL_DIR'))
parser.add_argument('--train', type=str, default=os.environ.get('SM_CHANNEL_TRAIN'))
parser.add_argument('--test', type=str, default=os.environ.get('SM_CHANNEL_TEST'))
parser.add_argument('--train-file', type=str, default='boston_train.csv')
parser.add_argument('--test-file', type=str, default='boston_test.csv')
parser.add_argument('--features', type=str) # in this script we ask user to explicitly name features
parser.add_argument('--target', type=str) # in this script we ask user to explicitly name the target
args, _ = parser.parse_known_args()
print('reading data')
train_df = pd.read_csv(os.path.join(args.train, args.train_file))
test_df = pd.read_csv(os.path.join(args.test, args.test_file))
print('building training and testing datasets')
X_train = train_df[args.features.split()]
X_test = test_df[args.features.split()]
y_train = train_df[args.target]
y_test = test_df[args.target]
# train
print('training model')
model = RandomForestRegressor(
n_estimators=args.n_estimators,
min_samples_leaf=args.min_samples_leaf,
n_jobs=-1)
model.fit(X_train, y_train)
# print abs error
print('validating model')
abs_err = np.abs(model.predict(X_test) - y_test)
# print couple perf metrics
for q in [10, 50, 90]:
print('AE-at-' + str(q) + 'th-percentile: '
+ str(np.percentile(a=abs_err, q=q)))
# persist model
path = os.path.join(args.model_dir, "model.joblib")
joblib.dump(model, path)
print('model persisted at ' + path)
print(args.min_samples_leaf)
# -
# ## Local training
# Script arguments allows us to remove from the script any SageMaker-specific configuration, and run locally
# ! python script.py --n-estimators 100 \
# --min-samples-leaf 2 \
# --model-dir ./ \
# --train ./ \
# --test ./ \
# --features 'CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO B LSTAT' \
# --target target
# ## SageMaker Training
# ### Launching a training job with the Python SDK
# +
# We use the Estimator from the SageMaker Python SDK
from sagemaker.sklearn.estimator import SKLearn
FRAMEWORK_VERSION = '0.23-1'
sklearn_estimator = SKLearn(
entry_point='script.py',
role = get_execution_role(),
train_instance_count=1,
train_instance_type='ml.c5.xlarge',
framework_version=FRAMEWORK_VERSION,
base_job_name='rf-scikit',
metric_definitions=[
{'Name': 'median-AE',
'Regex': "AE-at-50th-percentile: ([0-9.]+).*$"}],
hyperparameters = {'n-estimators': 100,
'min-samples-leaf': 3,
'features': 'CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO B LSTAT',
'target': 'target'})
# -
# launch training job, with asynchronous call
sklearn_estimator.fit({'train':trainpath, 'test': testpath}, wait=False)
# ### Alternative: launching a training with `boto3`
# `boto3` is more verbose yet gives more visibility in the low-level details of Amazon SageMaker
# +
# first compress the code and send to S3
source = 'source.tar.gz'
project = 'scikitlearn-train-from-boto3'
tar = tarfile.open(source, 'w:gz')
tar.add ('script.py')
tar.close()
s3 = boto3.client('s3')
s3.upload_file(source, bucket, project+'/'+source)
# -
# When using `boto3` to launch a training job we must explicitly point to a docker image.
# +
from sagemaker import image_uris
training_image = image_uris.retrieve(
framework="sklearn",
region=region,
version=FRAMEWORK_VERSION,
py_version="py3",
instance_type="ml.c5.xlarge"
)
print(training_image)
# +
# launch training job
response = sm_boto3.create_training_job(
TrainingJobName='sklearn-boto3-' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'),
HyperParameters={
'n_estimators': '300',
'min_samples_leaf': '3',
'sagemaker_program': 'script.py',
'features': 'CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO B LSTAT',
'target': 'target',
'sagemaker_submit_directory': 's3://' + bucket + '/' + project + '/' + source
},
AlgorithmSpecification={
'TrainingImage': training_image,
'TrainingInputMode': 'File',
'MetricDefinitions': [
{'Name': 'median-AE', 'Regex': 'AE-at-50th-percentile: ([0-9.]+).*$'},
]
},
RoleArn=get_execution_role(),
InputDataConfig=[
{
'ChannelName': 'train',
'DataSource': {
'S3DataSource': {
'S3DataType': 'S3Prefix',
'S3Uri': trainpath,
'S3DataDistributionType': 'FullyReplicated',
}
}},
{
'ChannelName': 'test',
'DataSource': {
'S3DataSource': {
'S3DataType': 'S3Prefix',
'S3Uri': testpath,
'S3DataDistributionType': 'FullyReplicated',
}
}},
],
OutputDataConfig={'S3OutputPath': 's3://'+ bucket + '/sagemaker-sklearn-artifact/'},
ResourceConfig={
'InstanceType': 'ml.c5.xlarge',
'InstanceCount': 1,
'VolumeSizeInGB': 10
},
StoppingCondition={'MaxRuntimeInSeconds': 86400},
EnableNetworkIsolation=False
)
print(response)
# -
# ### Launching a tuning job with the Python SDK
# +
# we use the Hyperparameter Tuner
from sagemaker.tuner import IntegerParameter
# Define exploration boundaries
hyperparameter_ranges = {
'n-estimators': IntegerParameter(20, 100),
'min-samples-leaf': IntegerParameter(2, 6)}
# create Optimizer
Optimizer = sagemaker.tuner.HyperparameterTuner(
estimator=sklearn_estimator,
hyperparameter_ranges=hyperparameter_ranges,
base_tuning_job_name='RF-tuner',
objective_type='Minimize',
objective_metric_name='median-AE',
metric_definitions=[
{'Name': 'median-AE',
'Regex': "AE-at-50th-percentile: ([0-9.]+).*$"}], # extract tracked metric from logs with regexp
max_jobs=10,
max_parallel_jobs=2)
# -
Optimizer.fit({'train': trainpath, 'test': testpath})
# get tuner results in a df
results = Optimizer.analytics().dataframe()
while results.empty:
time.sleep(1)
results = Optimizer.analytics().dataframe()
results.head()
# ## Deploy to a real-time endpoint
# ### Deploy with Python SDK
# An `Estimator` could be deployed directly after training, with an `Estimator.deploy()` but here we showcase the more extensive process of creating a model from s3 artifacts, that could be used to deploy a model that was trained in a different session or even out of SageMaker.
# +
sklearn_estimator.latest_training_job.wait(logs='None')
artifact = sm_boto3.describe_training_job(
TrainingJobName=sklearn_estimator.latest_training_job.name)['ModelArtifacts']['S3ModelArtifacts']
print('Model artifact persisted at ' + artifact)
# +
from sagemaker.sklearn.model import SKLearnModel
model = SKLearnModel(
model_data=artifact,
role=get_execution_role(),
entry_point='script.py',
framework_version=FRAMEWORK_VERSION)
# -
predictor = model.deploy(
instance_type='ml.c5.large',
initial_instance_count=1)
# ### Invoke with the Python SDK
# the SKLearnPredictor does the serialization from pandas for us
print(predictor.predict(testX[data.feature_names]))
# ### Alternative: invoke with `boto3`
runtime = boto3.client('sagemaker-runtime')
# #### Option 1: `csv` serialization
# +
# csv serialization
response = runtime.invoke_endpoint(
EndpointName=predictor.endpoint,
Body=testX[data.feature_names].to_csv(header=False, index=False).encode('utf-8'),
ContentType='text/csv')
print(response['Body'].read())
# -
# #### Option 2: `npy` serialization
# +
# npy serialization
from io import BytesIO
#Serialise numpy ndarray as bytes
buffer = BytesIO()
# Assuming testX is a data frame
np.save(buffer, testX[data.feature_names].values)
response = runtime.invoke_endpoint(
EndpointName=predictor.endpoint,
Body=buffer.getvalue(),
ContentType='application/x-npy')
print(response['Body'].read())
# -
# ## Don't forget to delete the endpoint !
sm_boto3.delete_endpoint(EndpointName=predictor.endpoint)
| sagemaker-python-sdk/scikit_learn_randomforest/Sklearn_on_SageMaker_end2end.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.3 64-bit (''base'': conda)'
# name: python383jvsc74a57bd0ce483ef3f3f15830cc71af6662324550274ded09d10a1a693bdaad1eb103022d
# ---
# + [markdown] tags=[] cell_id="00000-cb34c893-19b5-4eb7-bf5a-d02ead8d44fe" deepnote_cell_type="markdown"
# # Project 3: Skin Lesion Detection in Medical Treatment using Machine Learning
# ## Detecting Skin Cancer Type 'Melanoma' through Machine Learning
# ---
#
# **Group 9: <NAME>, <NAME>, <NAME>, <NAME>**
#
# Submission: *23.04.2021* / Last Modified: *22.04.2021*
#
# ---
#
# This notebook contains the step-by-step data science process performed on the *ISIC 2017* public test data and official training data on medical image recognition. The goal of this project was to extract and automatically analyse features from medical images of skin lesions in order to predict whether or not the lesion is *melanoma* using image processing and machine learning classification algorithms.
#
# The initial data (containing the medical images, masked images and information on features and disease) was given for 150 medical images (equivalent to the public test data of the *ISIC 2017* challenge) by the project manager *Veronika *.
# To develop more accurate models, we extended the initially given data by the official training data that could be obtained from the official [ISIC 2017 Website](https://challenge.isic-archive.com/data). In a later part of the notebook, we will explain how to download the images for reproducing the results of this notebook.
# + [markdown] tags=[] cell_id="00001-0c890553-5249-4dc4-b863-ecba0193daab" deepnote_cell_type="markdown"
# ## Introduction
# ---
# When diagnosing the skin cancer **melanoma**, there are some key features doctors look for. Melanoma is typically: Asymmetrical, has an uneven Border, non-uniformly Colored, larger in Diameter than a pencil eraser, and can over time causing bleeding and other effects. This common guide for spotting melanoma is known as the ABCDE model.
#
# A quick search on mobile phone app stores will show dozens of different skin diagnosis apps, where a user can take a photo of their affected area of skin and get an unofficial diagnosis of what the condition could be. These apps calculate some of the aforementioned features from images to estimate a diagnosis. Medical imaging is also widely used to monitor and diagnose several conditions by medical professionals (*[Source](https://www.postdicom.com/en/blog/medical-imaging-science-and-applications)*). Thus there is great demand for machine learning algorithms to aid in diagnosing large volumes of such image data, thereby reducing the workload of doctors.
#
# This notebook contains all the code to explore the digital diagnosis process, by analysing images of skin lesions and using image processing and machine learning to attempt to accurately diagnose whether or not a lesion is melanoma. This formed the research question:
#
# > **To what degree of certainty can we predict if a patient has melanoma from a given medical image using machine learning?**
#
# + [markdown] tags=[] cell_id="00002-9d760373-d759-41b1-9739-48d3452591b9" deepnote_cell_type="markdown"
# ## Running this Notebook
# ---
# This notebook contains all code to reproduce the findings of the project as can be seen on the [GitHub](https://github.com/jonas-mika/fyp2021p03g09) page of this project.
# If one downloads the images used within this project, it is important that the global paths are correctly set. This can either be achieved through locally changing the file structure (ie. naming folders as defined in the notebook) or by adjusting the global variables within the `Constants` section of this notebook.
#
# *Note that the rest of the file structure as can be seen on the [GitHub](https://github.com/jonas-mika/fyp2021p03g09) page of the project generates automatically*
# + [markdown] tags=[] cell_id="00003-6e74ab3c-05a2-47b0-95c8-bd85fea6fefc" deepnote_cell_type="markdown"
# ## Required Libraries
# ---
# Throughout the project, we will use a range of both built-in and external Python Libraries. This notebook will only run if all libraries and modules are correctly installed on your local machines.
# To install missing packages use `pip install <package_name>` (PIP (Python Package Index) is the central package management system, read more [here](https://pypi.org/project/pip/)). You can do this directly within the notebook by uncommenting the below cell.
#
# In case you desire further information about the used packages, click the following links to find detailed documentations:
# - [Pandas](https://pandas.pydata.org/)
# - [Numpy](https://numpy.org/)
# - [Matplotlib](https://matplotlib.org/stable/index.html)
# - [PIL](https://pillow.readthedocs.io/en/stable/)
# - [SciKit Learn](https://scikit-learn.org/stable/)
# - [SciKit Image](https://scikit-image.org/)
# - [Scipy](https://www.scipy.org/)
# - [ImbLearn](https://imbalanced-learn.org/stable/)
# + tags=[] cell_id="00004-54b6965a-fb79-43bd-b513-36fb8a2673bf" deepnote_to_be_reexecuted=false source_hash="a281805d" execution_millis=5929 output_cleared=true execution_start=1618999781334 deepnote_cell_type="code"
# %%capture
# stop cell from displaying output
# uncomment lines with uninstalled packages on local machine
# #!pip install scikit-image
# #!pip install imblearn
# #!pip install scikit-learn
# #!pip install pillow
# #!pip install itertools
# + tags=[] cell_id="00000-ce265327-d417-47b0-850b-6a4f0ab3a9cf" deepnote_to_be_reexecuted=false source_hash="3285c3db" execution_millis=3297 output_cleared=true execution_start=1618999796906 deepnote_cell_type="code"
# python standard libraries
import os # automates saving of export files (figures, summaries, ...)
import re # used for checking dateformat in data cleaning
# external libraries
import pandas as pd # provides major datastructure pd.DataFrame() to store datasets
import numpy as np # used for numerical calculations and fast array manipulations
import matplotlib.pyplot as plt # standard data visualisation
import seaborn as sns # convenient data visualisation
from PIL import Image # fork from PIL (python image library), image processing in python
# specific functions
import matplotlib.cm as cm
from skimage import morphology
#from scipy.stats.stats import mode
# preprocessing
from sklearn.preprocessing import StandardScaler # normalise features
from imblearn.under_sampling import RandomUnderSampler # balancing data
from imblearn.over_sampling import RandomOverSampler # balancing data
from imblearn.over_sampling import SMOTE # balancing data
# feature selection
from sklearn.feature_selection import mutual_info_classif, SelectKBest # univariate feature selection with mutual information for feature scoring
from sklearn.feature_selection import SequentialFeatureSelector # sequential selection of k-features given fixed classifier
# classifiers used in this project
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier # k-nearest neighbour classifier
# model selection
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold # producing equal cross-validation sets (reproducable results)
from sklearn.model_selection import cross_val_score # perform cross-validation and report single metric
from sklearn.model_selection import cross_validate # perform cross-validation and report set of metrics
from sklearn.model_selection import GridSearchCV # perform cross-validation on given set of hyperparameters to find best hyperparamters optimising single metric
from imblearn.pipeline import Pipeline, make_pipeline # balancing on each k-th training set in cross validation
# evaluating model
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
# + [markdown] tags=[] cell_id="00009-ab8c2759-432e-4819-be9d-80d303620266" deepnote_cell_type="markdown"
# ## Downloading Additional Data
# ---
# The data analysis was performed on the concatenated data of the 150 initially given images and 2000 additional images obtained from the same data source - the [ISIC](https://challenge.isic-archive.com/data) (International Skin Imaging Collaboration) 2017 Competition. The links automatically start the download from the website - so be aware of clicking them, if no big downloads are intended.
#
# **REMARK: Not downloading the images will cause the image processing and feature extraction part of the notebook to not run properly. However, these sections can be skipped, by simply loading in the `feature.csv` dataframe that is provided in the submission**
#
# > Raw Data
#
# >> [Raw Data Images](https://isic-challenge-data.s3.amazonaws.com/2017/ISIC-2017_Test_v2_Data.zip)
#
# >> [Raw Data Masks](https://isic-challenge-data.s3.amazonaws.com/2017/ISIC-2017_Test_v2_Part1_GroundTruth.zip)
#
# >> [Raw Data Ground Truth](https://isic-challenge-data.s3.amazonaws.com/2017/ISIC-2017_Test_v2_Part3_GroundTruth.csv)
#
# > External Data
#
# >> [External Data Images](https://isic-challenge-data.s3.amazonaws.com/2017/ISIC-2017_Training_Data.zip)
#
# >> [External Data Masks](https://isic-challenge-data.s3.amazonaws.com/2017/ISIC-2017_Training_Part1_GroundTruth.zip)
#
# >> [External Ground Truth](https://isic-challenge-data.s3.amazonaws.com/2017/ISIC-2017_Training_Part3_GroundTruth.csv)
# + [markdown] tags=[] cell_id="00008-8d4d4766-2724-4033-8584-15fe4722f493" deepnote_cell_type="markdown"
# ## Constants
# ---
# To enhance the readibilty, as well as to decrease the maintenance effort, it is useful for bigger projects to define contants that need to be accessed globally throughout the whole notebook in advance.
# The following cell contains all of those global constants. By convention, we write them in caps (https://www.python.org/dev/peps/pep-0008/#constants)
# + tags=[] cell_id="00012-b0a63da5-4fc5-41b4-86d4-5705799185d1" deepnote_to_be_reexecuted=false source_hash="27b7344f" execution_millis=2 output_cleared=true execution_start=1618999811932 deepnote_cell_type="code"
# global parameters for running the notebooks (each computation )
PREPROCESS_IMAGES = False
COMPUTE_FEATURES = False
# + tags=[] cell_id="00009-4e13d720-e857-4d9a-8abb-632aa8f19e3c" deepnote_to_be_reexecuted=false source_hash="a1d98c23" execution_millis=7 output_cleared=true execution_start=1618999816931 deepnote_cell_type="code"
PATH = {}
PATH['data'] = {}
PATH['data']['raw'] = "../data/raw/"
PATH['data']['processed'] = "../data/processed/"
PATH['data']['external'] = "../data/external/"
PATH['images'] = 'images/'
PATH['masks'] = 'masks/'
PATH['filtered_images'] = 'filtered_images/'
PATH['dummy_images']= 'dummy_images/'
PATH['reports'] = "../reports/"
# filename lookup dictionary storing the most relevant filenames
FILENAME = {}
FILENAME['diagnosis'] = 'diagnosis.csv' # changed from original name
FILENAME['features'] = 'features.csv' # changed from original name
# store filenames of different files in the project for easy iteration
FILENAME['raw_images'] = sorted([image[:-4] for image in os.listdir(PATH['data']['raw'] + PATH['images']) if not re.match('.*super.*', image) and re.match('^ISIC', image)])
FILENAME['raw_masks'] = sorted([mask[:-4] for mask in os.listdir(PATH['data']['raw'] + PATH['masks'])])
FILENAME['external_images'] = sorted([image[:-4] for image in os.listdir(PATH['data']['external'] + PATH['images']) if not re.match('.*super.*', image)])[1:] # need to subscript because of weird dotfile
FILENAME['external_masks'] = sorted([mask[:-4] for mask in os.listdir(PATH['data']['external'] + PATH['masks'])])
FILENAME['all_images'] = sorted(FILENAME['raw_images'] + FILENAME['external_images'])
FILENAME['all_masks'] = sorted(FILENAME['raw_masks'] + FILENAME['external_masks'])
# defining main dictionaries to store data. each dictionary will reference different pd.DataFrames
DATA = {}
# + [markdown] tags=[] cell_id="00013-3916c960-be31-476a-80d7-841da336db90" deepnote_cell_type="markdown"
# **TASK 0**
# # Image Preprocessing
# ---
# In this section we preprocess our image to make it nicer to deal with them in the later part of the project.
#
# 1. Crop Images and Masks to be bound by lesion
# 2. Make Width and Length an even number to be able to crop evenly
# 3. Maybe save filtered image with color
# + tags=[] cell_id="00014-13f4e761-daae-49a7-acf7-41412d5e2a0f" deepnote_to_be_reexecuted=false source_hash="23a735da" execution_millis=0 output_cleared=true execution_start=1618981586076 deepnote_cell_type="code"
# helper function to make width and lengths even
def make_even(img):
if img.size[0] % 2 != 0: # making number of cols even
img = np.array(img)
mid = int(img.shape[1] / 2)
img = np.delete(img, mid, axis=1)
img = Image.fromarray(img)
if img.size[1] % 2 != 0: # making number of rows even
img = np.array(img)
mid = int(img.shape[0] / 2)
img = np.delete(img, mid, axis=0)
img = Image.fromarray(img)
return img
# + tags=[] cell_id="00014-e8cc52ac-d501-404c-b8ab-f75edf0227d4" deepnote_to_be_reexecuted=false source_hash="ad6ddc9e" execution_millis=0 output_cleared=true execution_start=1618981586453 deepnote_cell_type="code"
# preprocessing (170 seconds to run)
if PREPROCESS_IMAGES == True:
try:
os.makedirs(PATH['data']['processed'] + PATH['images'])
os.makedirs(PATH['data']['processed'] + PATH['masks'])
os.makedirs(PATH['data']['processed'] + PATH['filtered_images'])
except: print('Directories already exist.')
print('Starting Preprocessing of Raw Images...')
for i in range(150):
# get image names
img_name = FILENAME['raw_images'][i] + '.jpg'
mask_name = FILENAME['raw_masks'][i] + '.png'
# open temporarily
img = Image.open(PATH['data']['raw'] + PATH['images'] + img_name)
mask = Image.open(PATH['data']['raw'] + PATH['masks'] + mask_name)
# crop to only store lesion
cropped_img = img.crop(mask.getbbox())
cropped_mask = mask.crop(mask.getbbox())
# make width and length even (two cases)
cropped_img = make_even(cropped_img)
cropped_mask = make_even(cropped_mask)
# create filtered with color
dummy = Image.new("RGB", cropped_img.size, 0)
filtered_img = Image.composite(cropped_img, dummy, cropped_mask)
# save to '../data/processed' in correct subfolder
cropped_img.save(PATH['data']['processed'] + PATH['images'] + img_name)
cropped_mask.save(PATH['data']['processed'] + PATH['masks'] + mask_name)
filtered_img.save(PATH['data']['processed'] + PATH['filtered_images'] + img_name)
print('Processed Raw-Data\n')
print('Starting Preprocessing of External Images...')
for i in range(2000):
# get image names
img_name = FILENAME['external_images'][i] + '.jpg'
mask_name = FILENAME['external_masks'][i] + '.png'
# open temporarily
img = Image.open(PATH['data']['external'] + PATH['images'] + img_name)
mask = Image.open(PATH['data']['external'] + PATH['masks'] + mask_name)
# crop to only store lesion
cropped_img = img.crop(mask.getbbox())
cropped_mask = mask.crop(mask.getbbox())
# make width and length even (two cases)
cropped_img = make_even(cropped_img)
cropped_mask = make_even(cropped_mask)
# create filtered with color
dummy = Image.new("RGB", cropped_img.size, 0)
filtered_img = Image.composite(cropped_img, dummy, cropped_mask)
# save to '../data/processed' in correct subfolder
cropped_img.save(PATH['data']['processed'] + PATH['images'] + img_name)
cropped_mask.save(PATH['data']['processed'] + PATH['masks'] + mask_name)
filtered_img.save(PATH['data']['processed'] + PATH['filtered_images'] + img_name)
print('Preprocessing Done')
# + [markdown] tags=[] cell_id="00010-94b50f7c-6711-4349-bbfc-c11ba8d47de0" deepnote_cell_type="markdown"
# *TASK 0.5*
# # Data Exploration
#
# ---
#
# + [markdown] tags=[] cell_id="00011-b337fa92-d698-471c-bc5b-f941c1aef692" deepnote_to_be_reexecuted=true source_hash="b623e53d" deepnote_cell_type="markdown"
# ## Loading in Data
#
# ---
#
# The task involves different sources of data, namely:
#
# > **Images**: 150 initially given medical images of skin lesions + 2000 externally obtained images of the same format.
#
# > **Masks**: 150 initially given binary masks, specificying the region of the skin lesion + 2000 externally obtained masks of the same format.
#
# > **Diagnosis**: Dataset storing whether or not the lesion was either *melanoma*, *seborrheic_keratosis* or *neither* through binary values.
#
# We conveniently load in the raw and external *diagnosis* dataset into individual `pd.DataFrames` using the built-in pandas method `pd.read_csv()`. We store those in our `DATA` dictionary in the corresponding keys and concatenate them, to have one central diagnosis dataframe holding all 2150 diagnoses.
#
# For saving RAM, neither the *images* nor the *masks* are read in locally into the script, but instead read in one-by-one from the file system, whenever they are needed.
# + tags=[] cell_id="00013-2900529b-7a4b-4fce-bc3c-11beff12d811" deepnote_to_be_reexecuted=false source_hash="e604c12e" execution_millis=15 output_cleared=true execution_start=1618999822838 deepnote_cell_type="code"
# load in raw and external dataset from different paths
DATA['raw_diagnosis'] = pd.read_csv(PATH['data']['raw'] + FILENAME['diagnosis']) # 150 x 3
DATA['external_diagnosis'] = pd.read_csv(PATH['data']['external'] + FILENAME['diagnosis']) # 2000 x 3
# concatenate into big dataframe
DATA['diagnosis'] = pd.concat([DATA['raw_diagnosis'], DATA['external_diagnosis']], ignore_index=True).sort_values(by=['image_id']) # 2150 x 3
# + [markdown] tags=[] cell_id="00015-bc508507-98dd-4277-95d2-820a3765f909" deepnote_cell_type="markdown"
# ## Inspection of Dataset (Target Variable)
#
# ---
#
# The *diagnosis* dataset contains our target variable - the binary label *melanoma* or *not melanoma*.
# In this section we get some first understanding of the frequency of our target label in the data, which will play an important role when developing the machine learning model.
#
# We start by reporting the number of records and fields/ variables in the dataset by using the shape property of the `pd.DataFrame`. We then continue to have an actual look into the data. Similiar to the head command in terminal, we can use the method `head()` onto our DataFrames, which outputs an inline representation of the first five data records of the dataset.
# We then visualise the frequency distribution of the three possible labels within the data.
# + [markdown] tags=[] cell_id="00016-d2dacc61-945c-4362-8d5d-474ff69ead14" deepnote_cell_type="markdown"
# **Shape**
# + tags=[] cell_id="00015-061506db-72d9-42ea-8d71-96b100252925" deepnote_to_be_reexecuted=false source_hash="cf497bf3" execution_millis=14 output_cleared=false execution_start=1618999831092 deepnote_cell_type="code"
print(f"Diagnosis: {DATA['diagnosis'].shape}")
# + [markdown] tags=[] cell_id="00019-32045793-8a8c-4aae-a08f-8a8d0c8482e6" deepnote_cell_type="markdown"
# **Diagnosis Dataset**
# + tags=[] cell_id="00020-46b4d62f-7504-43ed-9415-48567333d4fb" deepnote_to_be_reexecuted=false source_hash="8e901a74" execution_millis=40 output_cleared=false execution_start=1618999831911 deepnote_cell_type="code"
DATA['diagnosis'].head() # confirm its sorted
# + tags=[] cell_id="00025-19369e86-c8a2-44c4-982f-5ce5a8148e3f" deepnote_to_be_reexecuted=false source_hash="881eae63" execution_millis=172 output_cleared=true execution_start=1618999832564 deepnote_cell_type="code"
# %%capture
# extract cols
mel = DATA['diagnosis']['melanoma']
ker = DATA['diagnosis']['seborrheic_keratosis']
# mask all cases
mel_mask = (mel == 1) & (ker == 0)
ker_mask = (mel == 0) & (ker == 1)
neither_mask = (mel == 0) & (ker == 0)
both_mask = (mel == 1) & (ker == 1)
# append 3-class label into 'diagnosis' col
DATA['diagnosis']['diagnosis'] = 0
for i in range(DATA['diagnosis'].shape[0]):
if mel_mask[i]: DATA['diagnosis']['diagnosis'].loc[i] = 2
elif ker_mask[i]: DATA['diagnosis']['diagnosis'].loc[i] = 1
else: DATA['diagnosis']['diagnosis'].loc[i] = 0
# + tags=[] cell_id="00022-0c9e3f29-3e98-440d-99b0-d600fc63f164" deepnote_to_be_reexecuted=false source_hash="a3ce5907" execution_millis=301 output_cleared=false execution_start=1618999834930 deepnote_cell_type="code"
# distribution of diagnosis
diagnosis, counts = np.unique(DATA['diagnosis']['diagnosis'], return_counts=True)
for x in range(len(diagnosis)):
print(f"{diagnosis[x]}: {counts[x]}")
# plot
fig,ax = plt.subplots()
ax.bar(diagnosis, counts, color='gray')
# maybe add text with numeric count
ax.set_title('Distribution of Diagnosis', fontweight='bold'); ax.set_xlabel('Diagnosis', fontstyle='italic'); ax.set_ylabel('Frequency', fontstyle='italic');
ax.set_xticks(diagnosis); ax.set_xticklabels(['Neither', 'Keratosis', 'Melanoma']);
# + [markdown] tags=[] cell_id="00026-e5b563ed-0d60-4d37-ac09-3cc0a1505f27" deepnote_cell_type="markdown"
# The majority (~67%) of the recorded skin lesions were neither *melanoma* nor *non-melanoma*. Only ~14% were *keratosis* and ~19% were *melanoma*.
#
# This significant imbalance is important to keep in mind, when building our model, as high class imbalance, makes machine learning models often biased towards rigoursly detecting the dominating the label - result in high accuracy scores, but 0 sensitivity.
#
# Furthermore, the visualisation reveals that he two diseases are - as expected - mutually exclusive, meaning that a single skin lesion cannot be diagnosed with multiple diseases.
# + [markdown] tags=[] cell_id="00022-74d262e9-0785-418b-a633-7e5351b05a1e" deepnote_cell_type="markdown"
# ## Inspection of Images
# ---
# The main part of the project is to analyse medical images for a set of features. To do so, we can analyse both the original image and a binary mask. In this section, we will look at examples of images and their corresponding mask to get a feel for the type of images we are dealing with and assess the quality of the masks.
# + tags=[] cell_id="00023-98a3e227-2bf8-417a-80a6-b3badc4edf43" deepnote_to_be_reexecuted=false source_hash="759b8a1" execution_millis=2586 output_cleared=false execution_start=1618999853711 deepnote_cell_type="code"
# load test image using PIL
fig, ax = plt.subplots(nrows=3, ncols=2, figsize=(15,15))
fig.suptitle('Examples of Images and Corresponding Masks', fontsize=16, fontweight='bold')
for i in range(3):
ex_img = Image.open('../data/processed/images/' + FILENAME['all_images'][i] + '.jpg')
ex_img_mask = Image.open('../data/processed/masks/' + FILENAME['all_masks'][i] + '.png')
ax[i][0].imshow(ex_img)
ax[i][0].set_xlabel(f"{ex_img.format}, {ex_img.size}, {ex_img.mode}");
ax[i][1].imshow(ex_img_mask, cmap='gray')
ax[i][1].set_xlabel(f"{ex_img_mask.format}, {ex_img_mask.size}, {ex_img_mask.mode}");
ax[0][0].set_title('Medical Image');
ax[0][1].set_title('Corresponding Binary Mask');
# -
# The initially given high-resolution images (often 3000X2000px) were sucessfully cut down in size within our preprocessing to only display the part of the image that is relevant for our analysis and decrease running times of feature computation and training of models. Furthermore, all images and masks were modified in a way that all images and masks have an even width and length, which is necessary to correctly compute the asymmetry score in a later section.
#
# From the three sampled pictures, it generally appears that the masks give a well-enough approximation of the actual shape of the lesion. However, they do seem to differ in the way they were computed, as some smoothen out borders more than others.
# + [markdown] tags=[] cell_id="00011-2f24366e-2e6e-4fb6-bd80-8420bbf40dde" deepnote_cell_type="markdown"
# *TASK 1*
# # Extracting Features
#
# ---
#
# We need to find quantitative measures of how to best classify *melanoma*. The following handcrafted features are assessed during this project:
#
# > **Compactness**. A quantitative measure of the shape of the lesion. The smaller the value, the more compact the lesion is. A perfect circle has a compactness score of roughly 1.
#
# > **Average Luminance**. A quantitative measure of the averaged brightness of the lesion. The higher the value, the lighter the lesion, and vice versa. Values range from 0 (meaning 100% black) to 255 (meaning 100% white).
#
# > **Luminance Variability**. A quantitative measure to determine the variation of luminance of the lesion. The higher the value, the more variation can be found on the lesion.
#
# > **Average Colour**. A quantitative measure of the averaged colour of the lesion. This metric is split up inthe the average color in the three RGB channels individually. Each ranges between 0 and 255.
#
# > **Colour Variability**. A quantitative measure to determine the variation of color of the lesion. The higher the value, the more variation can be found on the lesion. output in the format of (rvariation,gvariation,bvariation),average variation
#
# > **Asymmetry**. A quantitative measure to assess the symmetry of the lesion. Measured through relative number of non-overlapping pixels in different rotations. The higher the value, the less symmmetric the lesion is. A perfect circle, should score a 0 asymmetry score.
# + [markdown] tags=[] cell_id="00032-577c1d3c-aca3-4b53-b527-01781d1e819a" deepnote_cell_type="markdown"
# ## Functions for Feature Extraction
# + tags=[] cell_id="00033-50ce0ba4-6e2a-4f83-9209-da3d252a2ab3" deepnote_to_be_reexecuted=false source_hash="ef3eec4d" execution_millis=0 output_cleared=true execution_start=1618999888016 deepnote_cell_type="code"
def measure_area_perimeter(mask):
# Measure area: the sum of all white pixels in the mask image
mask = np.where(np.array(mask)==255, 1, 0)
# compute area as number of white pixels
area = np.sum(mask)
# compute perimeter by eroding 1 pixel from mask and then compute the difference between original and eroded mask
struct_el = morphology.disk(1)
mask_eroded = morphology.binary_erosion(mask, struct_el)
image_perimeter = mask - mask_eroded
perimeter = np.sum(image_perimeter)
return area, perimeter
# + tags=[] cell_id="00029-d9616ba2-826f-40c2-8d07-5d8ab8fd7c5e" deepnote_to_be_reexecuted=false source_hash="b436d025" execution_millis=5 output_cleared=true execution_start=1618999888783 deepnote_cell_type="code"
# compactness
def get_compactness(mask):
area, perimeter = measure_area_perimeter(mask)
# return compactness formula
return ( ( perimeter ** 2) / (4 * np.pi * area ) )
# + tags=[] cell_id="00028-ef906370-e43a-41aa-90d7-aa44d8cf16fe" deepnote_to_be_reexecuted=false source_hash="ba4da5b5" execution_millis=6 output_cleared=true execution_start=1618999889269 deepnote_cell_type="code"
# average luminance
def get_average_luminance(filtered_image): # image needs to be filtered for lesion
gray = np.array(filtered_image.convert('L')) # converting to gray scale
return round(np.mean(gray[gray > 0]))
# + tags=[] cell_id="00042-54d6c44d-ae8c-4362-ad59-6e7e30c06b71" deepnote_to_be_reexecuted=false source_hash="e39f82f" execution_millis=12 output_cleared=true execution_start=1618999889756 deepnote_cell_type="code"
# luminance variability
def get_luminance_variability(filtered_image, measure='variance'):
gray = np.array(filtered_image.convert('L')) # converting to gray scale
if measure == 'variance': return round(np.var(gray[gray > 0]))
elif measure == 'standard_deviation': return round(np.std(gray[gray > 0]))
else: print('Cannot compute this `measure`. Try `variance` or `standard_deviation`')
# + tags=[] cell_id="00056-68ee87e3-71b4-493a-b296-a58f9365fcda" deepnote_to_be_reexecuted=false source_hash="a9eb3fdc" execution_millis=5 output_cleared=true execution_start=1618999893143 deepnote_cell_type="code"
# average color
def get_average_color(filtered_image): # image needs to be filtered for lesion
r, g, b = filtered_image.split() # converting to separate channels
r= np.array(r)
g= np.array(g)
b= np.array(b)
return [round(np.mean(r[r > 0])),round(np.mean(g[g > 0])),round(np.mean(b[b > 0]))]
# + tags=[] cell_id="00043-e14402fc-ca64-4234-8d4d-9c6a06ddfcb8" deepnote_to_be_reexecuted=false source_hash="d728f987" execution_millis=21 output_cleared=true execution_start=1618999894117 deepnote_cell_type="code"
# color variability
def get_color_variability(filtered_image, measure='variance'): # image needs to be filteredd for lesion
r, g, b = filtered_image.split() # converting to separate channels
r= np.array(r)
g= np.array(g)
b= np.array(b)
if measure == 'variance': rgb=(np.var(r[r > 0]),np.var(g[g > 0]),np.var(b[b > 0]))
elif measure == 'standard_deviation': rgb=(np.std(r[r > 0]),np.std(g[g > 0]),np.std(b[b > 0]))
else: return
return np.mean(rgb)
# + tags=[] cell_id="00038-30509f12-2361-4e03-804c-cdc34f4aea6f" deepnote_to_be_reexecuted=false source_hash="1dbe74ba" execution_millis=7 output_cleared=true execution_start=1618999900075 deepnote_cell_type="code"
def get_asymmetry(mask):
return round(np.mean([asymmetry(mask), asymmetry(mask.rotate(90, expand=True))]),2)
# + tags=[] cell_id="00030-7ee66c85-2792-4ad4-935f-dfc3e8257a30" deepnote_to_be_reexecuted=false source_hash="ce804e57" execution_millis=4 output_cleared=true execution_start=1618999900459 deepnote_cell_type="code"
# helper for asymmetry
def asymmetry(mask):
# calculate basic properties of image
width, length = mask.size # requires even number of pixels in both dimensions
size = width * length
if width%2!=0:
print("Uneven Number of Pixels. Can't calculate asymmetry.")
# cut in half and fold
left = mask.crop((0,0,(width/2), length))
right = mask.crop((width/2,0,width,length))
right = right.transpose(Image.FLIP_LEFT_RIGHT)
# get binary array of unequal positions (the closer the sum to 0, the better the symmetry)
diff = np.where(np.array(left) != np.array(right), 1, 0)
return np.sum(diff) / (size / 2) # percentage of asymmetric pixels
# + [markdown] tags=[] cell_id="00055-1858f146-2046-4965-b2cc-f966cab2caf6" deepnote_cell_type="markdown"
# ## Evaluating Feature Extraction
# ---
#
# Before accepting our functions to compute the featurs as universal truth, we need to test them on a set of dummy images, for which we know what metrics we are expecting. If the computed values of our functions match with the expectation, it is reasonable to believe that the functions indeed compute the desired feature.
# + tags=[] cell_id="00042-1eae9862-d608-44ec-b89e-54ecf331b7b9" deepnote_to_be_reexecuted=false source_hash="31dd0608" execution_millis=2379 output_cleared=false execution_start=1618999904924 deepnote_cell_type="code"
dummies = ['dummy' + str(i+1) for i in range(2)]
# show dummy image and mask
fig, ax = plt.subplots(nrows=len(dummies), ncols=2, figsize=(16, 6 * len(dummies)))
fig.suptitle("Feature Extration on Dummies", fontsize=16, fontweight='bold')
for i, img_name in enumerate(dummies):
# compute features
img = Image.open('../data/external/dummy_images/' + img_name + '.jpg')
img_mask = Image.open('../data/external/dummy_images/' + img_name + '_mask.png').convert('L')
area, perimeter = measure_area_perimeter(img_mask)
compactness = get_compactness(img_mask)
asymmetry_score = get_asymmetry(img_mask)
average_luminance = get_average_luminance(img)
luminance_variance = get_luminance_variability(img)
average_colors = get_average_color(img)
color_variance = get_color_variability(img)
# print out computed features
print('#'*15 + f" Dummy {i+1} " + '#'*15)
print(f"Area / Perimeter : {area}px / {perimeter}px")
print(f"Compactness : {compactness}")
print(f"Asymmetry : {asymmetry_score * 100}%")
print(f"Average Luminance : {average_luminance}")
print(f"Luminance Variance : {luminance_variance}")
print(f"Average Colors (RGB) : {average_colors}")
print(f"Color Variability : {color_variance}\n")
ax[i][0].imshow(img);
ax[i][1].imshow(img_mask, cmap='gray');
ax[i][0].set_title(f'Dummy {i+1}', fontsize=10, fontstyle='italic')
ax[i][1].set_title(f'Dummy {i+1} Mask', fontsize=10, fontstyle='italic')
ax[i][0].set_xlabel(f'{img.format}, {img.size}, {img.mode}', fontstyle='italic');
ax[i][1].set_xlabel(f'{img_mask.format}, {img_mask.size}, {img_mask.mode}', fontstyle='italic');
# -
# **Evaluation**
#
# > *Compactness*: A perfect circle should have a lower compactnes score (and is thusly more compact), than the triangle. This is indeed computed by our `get_compactness()` function.
#
# > *Asymmetry*: A perfect circle shouldn't be asymmetric accross the two main axes, and thusly a asymmetry score of 0%, whereas the triangle should report a higher value, since the second fold is asymmetric. This is indeed computed by our `get_asymmetry()` function.
#
# > *Average Luminance*: We expect the red-gradient circle to have a higher average luminance than the dark grey triangle. This is indeed computed by our `get_average_luminance()` function.
#
# > *Luminance Variance*: We expect the gradient circle to have a higher variance in the luminance than the uniformly colored triangle. This is indeed computed by our `get_luminance_variability()` function.
#
# > *Average Color*: We expect the red-gradient circle to have a high average color value in the red-channel and a lower in the remaining two, whereas the uniformly grey-colored triangle is expected to have equal values in all three channels. This is indeed computed by our `get_average_color()` function.
#
# > *Color Variability*: We expect the gradient circle to have a higher variance amongst all three color channels than the uniformly colored triangle. This is indeed computed by our `get_color_variability()` function.
# + [markdown] tags=[] cell_id="00053-e69f91a1-e003-4880-bc8e-9ccdc2a51e04" deepnote_cell_type="markdown"
# ## Compute Features
# ---
#
# We have developed our functions to extract features from the medical images of the lesions and have proven them to work on dummy images, where we were able to validate assumed scores in each feature. We can therefore now compute the features for each image and append it to our main dataframe to store the data, that is later used to train our model.
#
# At the end of the cell, a pd.Dataframe called `DATA['features']` is computed, which holds the Image ID, all eight computed features and the diagnosis for each image.
#
# *Note*: If the `COMPUTE_FEATURES` variable is set to `False` (to save roughly 8min of computation), the already computed dataframe is read in from the file structure.
# + tags=[] cell_id="00059-ff38722b-dbe7-43fd-85ea-453cf62b1180" deepnote_to_be_reexecuted=false source_hash="2d7e6f16" execution_millis=1 output_cleared=true execution_start=1619000224638 deepnote_cell_type="code"
features = ['compactness', 'average_luminance', 'luminance_variability', 'average_red', 'average_green', 'average_blue', 'color_variability', 'asymmetry']
feature_functions = {
'compactness': get_compactness,
'average_luminance': get_average_luminance,
'luminance_variability': get_luminance_variability,
'average_red': get_average_color,
'average_green': get_average_color,
'average_blue': get_average_color,
'color_variability': get_color_variability,
'asymmetry': get_asymmetry
}
# + tags=[] cell_id="00054-4dafbcbe-8adc-43ff-942e-82502bfbf355" deepnote_to_be_reexecuted=false source_hash="ff8e3abd" execution_millis=107882 output_cleared=true execution_start=1619000225591 deepnote_cell_type="code"
# compute all features (execution time: >8min)
if COMPUTE_FEATURES == True:
feature_dict = {feature: [] for feature in features}
for i in range(len(FILENAME['all_images'])):
name = FILENAME['all_images'][i]
img_name = FILENAME['all_images'][i] + '.jpg'
mask_name = FILENAME['all_masks'][i] + '.png'
# open temporarily
filtered_img = Image.open(PATH['data']['processed'] + PATH['filtered_images'] + img_name)
mask = Image.open(PATH['data']['processed'] + PATH['masks'] + mask_name)
# measure features and append to feature_dict
for feature in features:
if feature in ['compactness', 'asymmetry']:
feature_dict[feature].append(feature_functions[feature](mask))
elif feature in ['average_luminance', 'luminance_variability', 'color_variability']:
feature_dict[feature].append(feature_functions[feature](filtered_img))
elif feature == 'average_red':
feature_dict[feature].append(feature_functions[feature](filtered_img)[0])
elif feature == 'average_green':
feature_dict[feature].append(feature_functions[feature](filtered_img)[1])
elif feature == 'average_blue':
feature_dict[feature].append(feature_functions[feature](filtered_img)[2])
# append extracted features and diagnosis to features.csv
DATA['features'] = pd.DataFrame({'id': FILENAME['all_images']})
DATA['features'] = pd.concat([DATA['features'], pd.DataFrame(feature_dict), DATA['diagnosis'][['melanoma', 'seborrheic_keratosis', 'diagnosis']]], axis=1) # concatenating handcrafted features and diagnosis
# save all computed features
DATA['features'].to_csv(PATH['data']['processed'] + 'features.csv')
else: DATA['features'] = pd.read_csv(PATH['data']['processed'] + 'features.csv').iloc[: , 1:]
# + [markdown] tags=[] cell_id="00054-91ebedfb-45da-4415-a8a8-795538fbefa6" deepnote_cell_type="markdown"
# ### Inspect Main DataFrame
# ---
# Check that the computation or reading in of the dataframe was successful, by displaying it inline in Jupyter.
# + tags=[] cell_id="00060-344598b0-1f7c-4353-997d-46f4c12178aa" deepnote_to_be_reexecuted=false source_hash="4c274380" execution_millis=110 output_cleared=false execution_start=1619000764532 deepnote_cell_type="code"
DATA['features']
# + [markdown] tags=[] cell_id="00053-69c9fc88-3be3-4112-8c01-f0dbb64ad41a" deepnote_cell_type="markdown"
# *TASK 1.5*
# # Evaluate Features for Classification
# ---
#
# In this section, we are plotting the handcrafted features in order to see, whether any correaltions appear. Since we are trying to classify a binary label, namely whether a lesion is diseased with *melanoma* or not, we plot the distribution of each feature in the two classes *melanoma* and *no melanoma* to get a visual intuition of how good the specific feature might be able to distinguish between our target label.
# The more distinct the two distributions are, the better the feature will be at prediciting the tartget value.
# + [markdown] tags=[] cell_id="00062-7e6b9ce6-6d64-4bad-9689-2e22cb93bfbf" deepnote_cell_type="markdown"
# ### Visual Exploration
# + tags=[] cell_id="00056-59589987-30e3-42b4-b59a-04f452c8a344" deepnote_to_be_reexecuted=false source_hash="bb95ba7a" execution_millis=1807 output_cleared=true execution_start=1618981735158 deepnote_cell_type="code"
fig, ax = plt.subplots(nrows=len(features), figsize=(8, 6 * len(features)))
for i, feature in enumerate(features):
sns.violinplot(x='melanoma',
y=feature,
data=DATA['features'],
ax=ax[i]).set_title(f"Distribution of {feature.title().replace('_', ' ')} in Different Classes");
# + tags=[] cell_id="00067-14466d2a-d096-4e81-a4d6-25b9d15b5e50" deepnote_to_be_reexecuted=true source_hash="6af9874d" execution_millis=47781 output_cleared=true deepnote_cell_type="code"
sns.pairplot(DATA['features'], hue='melanoma', height=2, diag_kind="hist");
# + [markdown] tags=[] cell_id="00012-7fd9c2d5-6342-493a-af45-dc85efb4d664" deepnote_cell_type="markdown"
# *TASK 2*
# # Predict Diagnosis
#
# ---
#
# We have 'handcrafted' a number of features and now aim to find the model that is the most robust to predict our target variable - whether the lesion is our is not diseased with melanoma. In the process of doing so, a number of questions arise that we will step-by-step tackle in order to build the 'best' model.
#
# > **Performance Metrics**: Which metrics do we use to assess whether or not our model does good?
#
# > **Defining Features and Target Variable**: Which label are we trying to predict and what features do we have at hand to do so?
#
# > **Train-Test Split**: How can we get scores that resemble the model's performance on real out-of-sample data?
#
# > **Normalisation**: How do we make sure that each feature contributes equally to the model's prediction?
#
# > **Selecting Features**: Which (combination of) features are (/is) likely do perform best?
#
# > **Building Model**: Which model (and with which hyperparameters) does best in achieving the desired performance?
# -
# ## Performance Metrics
# ---
#
# Choosing performance metrics is arguably a design choice for the model, and different approaches are surely possible. For the purpose of this ML model, which detects a minority class, we chose to go with the widely used metric of `Recall`, which measures the *sensitivity* of the model towards detecting positives (The percentage of positives that were detected by the model).
# That is, because in medical diagnosis detecting false positives is generally more acceptable than false negatives, since the latter could potentially result into serious diseases.
# + [markdown] tags=[] cell_id="00067-01107798-cc24-4632-a815-3423c563b1f0" deepnote_cell_type="markdown"
# ## Define Initial Features and Target Variable
# ---
# First, we need to define from which set of features our model should choose the ones that are likely to perform best on a specified target variable.
# In our case, each measured feature is potentially interesting for the model, and we want to predict the binary label, whether or not the classifier is diseased with *melanoma* or not.
#
# By, convention, we call the feature matrix `X` and the target column `y`.
# + tags=[] cell_id="00068-a4ea27ed-35f8-42a1-8ce0-beed82d2528b" deepnote_to_be_reexecuted=false source_hash="1274c265" execution_millis=5 output_cleared=true execution_start=1619001396722 deepnote_cell_type="code"
X = DATA['features'][features]
y = DATA['features'][['melanoma']]
# + [markdown] tags=[] cell_id="00065-dc7dbdd2-dbd1-4a7d-a7e8-9f93e056de62" deepnote_cell_type="markdown"
# ### Train-Test Split
# ---
# Before, we doing anything further with our data, we split our data into a `development` set and a `test` set. The test set will be used to assess the final performance of the model by mimicing a true *out-of-sample* set of datapoints. For this project, we chose a standard split size of `0.3`, meaning that 30% of the original data will be used for testing, and 70% for the development of the model.
#
# We split the data at this early stage to not bias our model towards the test dataset, ie. performing the feature selection, normalisation or balancing process on all of the data, might bias it towards the test data, and thus result in a sligthly overfitted model, that might perform good on the test, but not in real-life.
#
# *Note: Whenever there is randomness involved, we set `random_state=1` to produce reproducable results.*
# + tags=[] cell_id="00066-81016beb-b954-4925-a39e-26939fbbc303" deepnote_to_be_reexecuted=false source_hash="511c379a" execution_millis=1 output_cleared=true execution_start=1619001927120 deepnote_cell_type="code"
# split into dev-test data (hold-out data to mimic true 'out-of-sample' data)
X_dev, X_test, y_dev, y_test = train_test_split(X, y, stratify=y, test_size=0.3, random_state=1)
# -
print(X_dev.shape, y_dev.shape)
print(X_test.shape, y_test.shape)
# + [markdown] tags=[] cell_id="00077-b097ada6-58a9-40c9-90ca-d8dcbad7434a" deepnote_cell_type="markdown"
# ## Normalisation
# ---
# Our measured handcrafted features all perform on different scales, ie. the *average luminance* can only obtain values between 0 and 255, whereas the *asymmetry* is the average percentage of non-matching pixels in two-folds of the image.
#
# Since we want each of our features to equally contribute to the prediction of the model, we need to normalise them. We do this through the formula of the standard score $\frac{x-\mu}{\sigma}$ ([Wikipedia](https://en.wikipedia.org/wiki/Standard_score)). We computed the values for the normalisation solely on the development set (again, to not bias the model towards the test data) and then use this scaling to scale both the development and test features matrices. Within the whole process the target column (the binary label 0 and 1), is not scaled.
#
# We can easily use `sklearn`'s `StandardScaler`, which does the job for us.
# + tags=[] cell_id="00072-d68daeff-2cd4-4673-8d0f-997340d766de" deepnote_to_be_reexecuted=false source_hash="5fba9c86" execution_millis=536 output_cleared=false execution_start=1619001428586 deepnote_cell_type="code"
# distribution of features after normalisation
plt.figure(figsize=(15,5));
sns.boxplot(data=X_dev, width=0.5);
# + tags=[] cell_id="00078-c08a7e1c-a0ee-4d29-9ea6-3ee1b70ea292" deepnote_to_be_reexecuted=false source_hash="41bfd634" execution_millis=12 output_cleared=true execution_start=1619001427490 deepnote_cell_type="code"
scaler = StandardScaler().fit(X_dev) # (x - mu) / std
X_dev = pd.DataFrame(scaler.transform(X_dev), columns=features)
X_test = pd.DataFrame(scaler.transform(X_test), columns=features)
# + tags=[] cell_id="00070-1542bccc-2f57-49fb-b39d-f1844e915367" deepnote_to_be_reexecuted=false source_hash="6444a681" execution_millis=519 output_cleared=false execution_start=1619001398505 deepnote_cell_type="code"
# distribution of features before normalisation
plt.figure(figsize=(15,5));
sns.boxplot(data=X_dev, width=0.5);
# -
# ## Balancing Data
# ---
# As we have seen in the initial exploration of the data, the labels are heavily imbalanced. Out of the 150 observed images, only 30 are diseased with *melanoma*, which results in precisely 20% of the data. If we would naively train our model disregarding the imbalance and only evaluate the model's performance by its *accuracy score*, we are likely to see a model performing equally or very similar to the so-called *null-hypotheses* (always predicting the dominating label), which would lead to a 80% accuracy in our case.
#
# To prevent this we balance our data, such that at the end of the process the data we train our model has equal amounts of *melanoma* and *not melanoma*.
# There are two ways of doing this:
#
# > **Random Undersampling**: Cutting down the frequency of the dominant label.
#
# > **Random Oversampling**: Duplicating the less dominant feature.
#
# Although, both option are obviously not ideal (since we loose information in the first, and create duplicate information in the second), and we would always prefer a orginally balanced dataset, we need to make a choice. For this project, we *upsampled* our data, since undersampling, would have limited our whole analyis to only 60 images, which is likely to not create an accurate model.
#
# We oversample using `imblearn`'s class `RandomOverSampler`.
#
# > **REMARK:** As we will later see, estimating the model's performance by cross-validating on an oversampled development set, produces highly overconfident scores. Correct upsampling, is therefore done by iteratively upsampling for each k-fold during the cross-validation, to create unbiased results. This is shown in detail in a later section.
# plot before oversampling
fig, axes = plt.subplots(ncols=3, figsize=(12, 3))
for ax, dataset in zip(axes, [y, y_dev, y_test]):
unique, counts = np.unique(dataset, return_counts=True)
ax.bar(unique, counts); ax.set_xticks([1,0])
axes[0].set_title('Target Imbalance on `y`');
axes[1].set_title('Target Imbalance on `y_dev`');
axes[2].set_title('Target Imbalance on `y_test`');
# balance data (using over-sampling)
oversampler = RandomOverSampler(random_state=1)
X_dev_sampled, y_dev_sampled = oversampler.fit_resample(X_dev, y_dev)
# plot after oversampling
fig, axes = plt.subplots(ncols=3, figsize=(12, 3))
for ax, dataset in zip(axes, [y, y_dev_sampled, y_test]):
unique, counts = np.unique(dataset, return_counts=True)
ax.bar(unique, counts); ax.set_xticks([1,0])
axes[0].set_title('Target Imbalance on `y`');
axes[1].set_title('Target Imbalance on `y_dev_sampled`');
axes[2].set_title('Target Imbalance on `y_test`');
print(f'#Images before Upsampling: {X_dev.shape[0]}')
print(f'#Images after Upsampling: {X_dev_sampled.shape[0]}')
print(f'Upsampled Images: {X_dev_sampled.shape[0]-X_dev.shape[0]}')
# + [markdown] tags=[] cell_id="00065-f41ea02b-0bc5-4b45-9c2f-7b25dcb838d9" deepnote_to_be_reexecuted=true source_hash="8c0913b" deepnote_cell_type="markdown"
# ## Feature Selection
# ---
#
# *Feature Selection* is the process of identifying the most related features from the data and removing the irrelvant or less important features which do not contribute much to our target variable.
#
# There are a number of advantages that come along with feature selection, which make it an important step of every machine learning project.
#
# 1. **Reduces Overfitting**: Less redundant data means less opportunity to make decisions based on noise.
#
# 2. **Improves Accuracy**: Less misleading data means modeling accuracy improves.
#
# 3. **Reduces Training Time**: fewer data points reduce algorithm complexity and algorithms train faster.
#
# Since brute-forcing the best features on a given model with 8 features already results in $\sum_{i=1}^{8} {8 \choose i}=255$ unique combination of features, the computational effort quickly becomes infeasible. We can therefore use statistics to try to pick the most relevant features in a computatinally less expensive way.
# + [markdown] tags=[] cell_id="00075-9ce8c66f-4892-46ad-b6f7-1983a4a8e83c" deepnote_cell_type="markdown"
# ### K-Best
# ---
#
# Statistical tests can be used to select those features that have the strongest relationship with the output variable.
# The scikit-learn library provides the `SelectKBest` class that can be used with a suite of different statistical tests to select a specific number of features.
#
# In order to evaluate our features with respect to randomly generated data, we add some uniformly random columns to our development data, in order to select the features that are likely to perform best.
#
# It is however important to notice, that K-Best Selection is a way of selecting univariate features, meaning that it only checks the likely performance for each single feature. This method might ie. give us 5 individually good performing features, which are highly correlated. In that case, the 4 additionally selected features, don't add any value to our model and thus increase running time and potentially accuracy.
# + tags=[] cell_id="00068-853c950c-08b2-44b9-9c38-171085a681ec" deepnote_to_be_reexecuted=false source_hash="45dfa306" execution_millis=1910 output_cleared=false execution_start=1619002422141 deepnote_cell_type="code"
# generate some noise
noise_cols = 4
features_noise = features + ['Noise' for _ in range(noise_cols)] # list of features + noise columns
noise = np.random.RandomState(1).uniform(0,0.1, size=(noise_cols, X_dev_sampled.shape[0])).transpose()
# feature matrix and target variable
X_select = np.hstack((X_dev_sampled, noise))
y_select = y_dev_sampled
# plot scores for features and noise
fig, ax = plt.subplots(ncols=5, figsize=(4*5, 3))
fig.suptitle('Univariate Feature Scores for Features and Noise for different K-Best', fontsize=14)
# select k-best
for k in range(1,5+1):
kbest = SelectKBest(mutual_info_classif, k=k)
kbest.fit(X_select, np.ravel(y_select)) # ravel cause of sklearn warning
scores = kbest.scores_ # univariate features scores for each feature and noise
print('-'*10 + f' k = {k} ' + '-'*10)
scores_dict = {scores[i]: i for i in range(len(scores))}
for val in sorted(scores_dict, reverse=True)[:k]:
print(features_noise[scores_dict[val]])
ax[k-1].bar(np.arange(0,len(scores)), scores)
ax[k-1].tick_params(labelrotation=90) # readable labels
ax[k-1].set_xticks(np.arange(0, len(features) + noise_cols));
ax[k-1].set_xticklabels([f.replace('_', ' ').title() for f in features] + ['Noise' for _ in range(noise_cols)]);
# + [markdown] tags=[] cell_id="00072-900e0e6a-2251-4e02-9d77-771007f4cb09" deepnote_cell_type="markdown"
# ## Building KNN-Model
# ---
#
# For the scope of this project, we first limit ourselves to a basic classifier called `KNN` (*K-Nearest-Neighbors*) algorithm, classifies out-of-sample data by evaluating the label frequency of k-surrounding (mostly measured through *euclidean distance*) neighbors in a n-dimensional space (where n is the number of features).
#
# To build the model, we choose the features selected by *K-Best Features* and and train our model using cross-validation of 5 partitions. In that way we get a more robust estimate for the performance of the metric.
#
# In this section we will build three different models:
# > **Case 1 (Baseline)**: In the baseline model, we train our model on the unbalanced dataset. We expect the model to not perform on the recall score, given the high class imbalance.
#
# > **Case 2 (Wrong Upsampling)**: Here we do the cross-validation on the entire upsampled dataset. We expect highly overconfident metrics since on each fold, we expect a number of images being a copy from an image in the training in the validation set, which results in a highly biased model that overfits the training data. This overfitting through wrong upsampling, however, is expected to be exposed when testing the model on the real test data, which achieves a similar score as the baseline.
#
# > **Case 3 (Correct Upsampling)**: Instead, we need to upsample for each training set in each of the folds in the cross-validation to create an unbiased estimation of the model’s performance. With this technique, we expect to increase the model’s performance on recall and make it robust to out-of-sample data in a way, that we perform equally good on the test data.
# -
# define splitting for cross-validation (shuffle=False for reproducable results)
kf = KFold(n_splits=5,shuffle=False)
# +
# selected features from k-best
selected_features = ['compactness', 'color_variability', 'luminance_variability']
# condense feature matrix to only contain selected features (in non-upsampled and upsampled development set and test set)
X_dev_selected = X_dev[selected_features]
X_dev_sampled_selected = X_dev_sampled[selected_features]
X_test_selected = X_test[selected_features]
# -
MODEL = {}
MODEL['baseline'] = {}
MODEL['upsample_before_cv'] = {}
MODEL['upsample_during_cv'] = {}
# initialise data structure to hold performance results in the three cases
DATA['results'] = pd.DataFrame({'Method': ['No Upsampling (Baseline)', 'Upsample Training Data before CV', 'Upsample within CV']})
# ### Base-Performance on Unbalanced Data
# ---
# +
cross_val_reports = {'Classifier': [], 'Hyperparameter': [], 'Accuracy': [], 'Precision': [], 'Recall (Sensitivity)': []}
params = {'n_neighbors': range(1,6), 'weights': ['distance', 'uniform']}
knn = KNeighborsClassifier()
grid_no_upsampling = GridSearchCV(knn, param_grid=params, cv=kf,
scoring=['accuracy', 'recall'], refit='recall')
grid_no_upsampling.fit(X_dev_selected, np.ravel(y_dev))
# cv results
MODEL['baseline']['cv_results'] = pd.DataFrame(grid_no_upsampling.cv_results_)
try: os.makedirs(PATH['reports'] + 'model_evaluation/cross_val/')
except: None
MODEL['baseline']['cv_results'].to_csv(PATH['reports'] + 'model_evaluation/cross_val/' + 'baseline.csv')
# report best score (and the hyperparameters used)
MODEL['baseline']['best_recall'] = grid_no_upsampling.best_score_
MODEL['baseline']['hyperparameters'] = grid_no_upsampling.best_estimator_
# display results
print(MODEL['baseline']['best_recall'])
print(MODEL['baseline']['hyperparameters'])
MODEL['baseline']['cv_results'] # display inline
# -
# ### Performance on Wrongly Upsampled Data
# ---
# +
cross_val_reports = {'Classifier': [], 'Hyperparameter': [], 'Accuracy': [], 'Precision': [], 'Recall (Sensitivity)': []}
params = {'n_neighbors': range(1,11), 'weights': ['distance', 'uniform']}
knn = KNeighborsClassifier()
grid_upsampling_before_cv = GridSearchCV(knn, param_grid=params, cv=kf,
scoring=['accuracy', 'recall'], refit='recall')
grid_upsampling_before_cv.fit(X_dev_sampled_selected, np.ravel(y_dev_sampled))
# cv results
MODEL['upsample_before_cv']['cv_results'] = pd.DataFrame(grid_upsampling_before_cv.cv_results_)
try: os.makedirs(PATH['reports'] + 'model_evaluation/cross_val/')
except: None
MODEL['upsample_before_cv']['cv_results'].to_csv(PATH['reports'] + 'model_evaluation/cross_val/' + 'upsample_before_cv.csv')
# report best score (and the hyperparameters used)
MODEL['upsample_before_cv']['best_recall'] = grid_upsampling_before_cv.best_score_
MODEL['upsample_before_cv']['hyperparameters'] = grid_upsampling_before_cv.best_estimator_
# display results
print(MODEL['upsample_before_cv']['best_recall'])
print(MODEL['upsample_before_cv']['hyperparameters'])
MODEL['upsample_before_cv']['cv_results'] # display inline
# -
# ### Performance on Correctly Upsampled Data
# ---
# +
cross_val_reports = {'Classifier': [], 'Hyperparameter': [], 'Accuracy': [], 'Precision': [], 'Recall (Sensitivity)': []}
params = {
'kneighborsclassifier__n_neighbors': range(1, 11), # technicalities
'kneighborsclassifier__weights': ['distance', 'uniform']
}
pipeline = make_pipeline(SMOTE(random_state=1),
KNeighborsClassifier())
grid_upsampling_during_cv = GridSearchCV(pipeline, param_grid=params, cv=kf, scoring=['accuracy', 'recall'], refit='recall')
grid_upsampling_during_cv.fit(X_dev_selected, np.ravel(y_dev));
# cv results
MODEL['upsample_during_cv']['cv_results'] = pd.DataFrame(grid_upsampling_during_cv.cv_results_)
try: os.makedirs(PATH['reports'] + 'model_evaluation/cross_val/')
except: None
MODEL['upsample_during_cv']['cv_results'].to_csv(PATH['reports'] + 'model_evaluation/cross_val/' + 'upsample_during_cv.csv')
# report best score (and the hyperparameters used)
MODEL['upsample_during_cv']['best_recall'] = grid_upsampling_during_cv.best_score_
MODEL['upsample_during_cv']['hyperparameters'] = grid_upsampling_during_cv.best_estimator_
# display results
print(MODEL['upsample_during_cv']['best_recall'])
print(MODEL['upsample_during_cv']['hyperparameters'])
MODEL['upsample_during_cv']['cv_results'] # display inline
# -
DATA['results'] = pd.concat([DATA['results'], pd.DataFrame({'Recall Score (Validation)': [MODEL[key]['best_recall'] for key in MODEL.keys()]})], axis=1)
DATA['results']
# ### Evaluating Final Performance
# ---
# + tags=[] cell_id="00091-47587e16-dcca-4a6f-952c-7ead42e7a28c" deepnote_to_be_reexecuted=false source_hash="7e049a0" execution_millis=29 output_cleared=false execution_start=1619003433493 deepnote_cell_type="code"
# fit best performing model on recall saved through grid search cv to whole dev set
grid_no_upsampling.fit(X_dev_selected, np.ravel(y_dev)) # knn(n_neighbors=1, weights='distance')
grid_upsampling_before_cv.fit(X_dev_sampled_selected, np.ravel(y_dev_sampled)) # KNeighborsClassifier(n_neighbors=8, weights='distance')
grid_upsampling_during_cv.fit(X_dev_sampled_selected, np.ravel(y_dev_sampled)) # KNeighborsClassifier(n_neighbors=7)
# predict test set
pred1 = grid_no_upsampling.predict(X_test_selected)
pred2 = grid_upsampling_before_cv.predict(X_test_selected)
pred3 = grid_upsampling_during_cv.predict(X_test_selected)
# make classification report and
try: os.makedirs(PATH['reports'] + 'model_evaluation/test_data/')
except: None
pd.DataFrame(classification_report(y_test, pred1, output_dict=True)).transpose().to_csv(PATH['reports'] + 'model_evaluation/test_data/baseline.csv')
pd.DataFrame(classification_report(y_test, pred2, output_dict=True)).transpose().to_csv(PATH['reports'] + 'model_evaluation/test_data/upsampling_before_cv.csv')
pd.DataFrame(classification_report(y_test, pred3, output_dict=True)).transpose().to_csv(PATH['reports'] + 'model_evaluation/test_data/upsampling_during_cv.csv')
# recall
sens1 = recall_score(y_test, pred1)
sens2 = recall_score(y_test, pred2)
sens3 = recall_score(y_test, pred3)
DATA['results'] = pd.concat([DATA['results'], pd.DataFrame({'Recall Score (Test)': [sens1, sens2, sens3]})], axis=1)
DATA['results'].to_csv(PATH['reports'] + 'commparison_of_recall_scores.csv')
DATA['results']
# -
# final model's performance
print(classification_report(y_test, pred3))
# + [markdown] tags=[] cell_id="00013-facea51d-4f84-4003-a25d-67505e0f0718" deepnote_cell_type="markdown"
# *TASK 3*
# # Open Question: How can we make our model more sensitive?
#
# ---
#
# In the previous section we have developed a model, that is optimised for performing as well as possible on the `recall` metric on a specified classifer with specified features. However, it becomes obvious that the model is stil only able to predict roughly 40% of the *melanoma* lesions as diseased. In real-world, we would rather want to model to be more sensitive to positives, as a false negative (we do not detect cancer) has potentially fatal consequences, whereas a false positive only motivates people do go to a doctor.
#
# In this section we are therefore investigating, how we can tweak our model in a way that it gets more sensitive (increasing the 'recall' metric). In order to do so, we need a model, which outputs predictive labeling (ie. gives a probability on the binary label). With such a model, we can adjust the threshold of prediciting positive. This increases sensitivity, knowing that we will also have more false positives.
# -
# ## Model and Feature Selection
# ---
#
# We now use the `Random Forest Classifier`, which is a widely used classifier, which allows us to adjust the performance of detecting positives through lowering the threshold for detecting them. We use the same balanced scaled development set to monitor the performance on cross-validated sets and later evaluate the final performance on the spared test-set - one time with the regular threshold of 0.5 and another time with the adjusted one.
# +
rf = RandomForestClassifier(n_estimators=100) # initialise random forest classifier
rf.fit(X_dev_sampled, y_dev_sampled) # fit on all features and select highest scoring features
rf_feature_importance = pd.DataFrame({'Feature': features, 'Importance': rf.feature_importances_})
# plot
x = sns.barplot(x='Feature', y='Importance', data=rf_feature_importance);
x.set_title("Feature Importance in Random Forest Classifier");
x.set_xticklabels(x.get_xticklabels(), rotation=90);
# -
# select best performing features from above output
rf_selected_features = ['compactness', 'color_variability', 'average_blue']
# ## Train and Evaluate Models
# ---
# +
rf = RandomForestClassifier(n_estimators=100) # initialise random forest classifier
X_train, y_train = X_dev_sampled[rf_selected_features], np.ravel(y_dev_sampled)
rf.fit(X_dev_sampled[rf_selected_features], np.ravel(y_dev_sampled))
y_pred = rf.predict(X_test[rf_selected_features])
fig, ax = plt.subplots()
labels, counts = np.unique(y_pred, return_counts=True)
ax.bar(labels, counts, color='gray'); ax.set_xticks(labels); ax.set_xticklabels(['Non-Melanoma', 'Melanoma']); ax.set_title('Predicted Labels')
print(classification_report(y_test, y_pred))
# +
threshold = 0.1 # setting the threshold for positive predictions low
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_dev_sampled[rf_selected_features], np.ravel(y_dev_sampled))
predicted_proba = rf.predict_proba(X_test[rf_selected_features])
y_pred = (predicted_proba [:,1] >= threshold).astype('int')
fig, ax = plt.subplots()
labels, counts = np.unique(y_pred, return_counts=True)
ax.bar(labels, counts, color='gray'); ax.set_xticks(labels); ax.set_xticklabels(['Non-Melanoma', 'Melanoma']); ax.set_title('Predicted Labels')
#y_pred=clf.predict(X_test)
print(classification_report(y_test, y_pred))
# + [markdown] tags=[] cell_id="00025-86c4f020-f4de-43e0-88d0-d1f5b1b0874e" deepnote_cell_type="markdown"
# ## Summary
# ---
# In conclusion, one can tweak the ratio between sensitivity and specificity, but improving one will categorically impact the other negatively. Therefore, tweaking these parameters is a design choice that needs to be specifically adjusted for the classification problem at hand. It should always be the final step of perfecting a model towards desired performance.
# + [markdown] tags=[] cell_id="00026-bed7848d-d805-47f0-8bf7-523a4cb790f6" deepnote_cell_type="markdown"
#
# + [markdown] tags=[] cell_id="00027-65d1e65c-b9c5-4a9a-83da-9c4055f03f8c" deepnote_cell_type="markdown"
#
# + [markdown] tags=[] cell_id="00028-64a0d452-fc0a-40c4-a3b2-4d35e7515feb" deepnote_cell_type="markdown"
#
# + [markdown] tags=[] cell_id="00029-c9887334-2738-44bb-90a3-2b94c9240649" deepnote_cell_type="markdown"
#
# + [markdown] tags=[] cell_id="00030-3232008b-99b3-4ce6-8bb7-627d3c530a81" deepnote_cell_type="markdown"
#
| notebooks/project3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.7.4
# language: python
# name: python-374
# ---
# # GeoPandas-Beispiele
# In den folgenden Beispielen verwenden wir den [nybb](https://data.cityofnewyork.us/dataset/nybb/7t3b-ywvw)-Datensatz.
# ## GeoPandas-Plot
import geopandas as gpd
df = gpd.read_file(gpd.datasets.get_path('nybb'))
df.head()
ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')
# ## Plotten in Folium
#
# [Folium](https://python-visualization.github.io/folium/) oder genauer das mit Folium verwendete [leaflet.js](https://leafletjs.com/) verwendet standardmäßig die Werte für Breiten- und Längengrade. Daher müssen wir unsere Werte erst konvertieren:
print(df.crs)
df = df.to_crs(epsg=4326)
print(df.crs)
df.head()
import folium
m = folium.Map(location=[40.70, -73.94], zoom_start=10, tiles='CartoDB positron')
for _, r in df.iterrows():
#without simplifying the representation of each borough, the map might not be displayed
sim_geo = gpd.GeoSeries(r['geometry']).simplify(tolerance=0.001)
geo_j = sim_geo.to_json()
geo_j = folium.GeoJson(data=geo_j,)
folium.Popup(r['BoroName']).add_to(geo_j)
geo_j.add_to(m)
m
| docs/matplotlib/geopandas/example.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %load_ext autoreload
# %autoreload 2
# +
import lightgbm as lgb
import numpy as np
import pandas as pd
import csv
from hyperopt import fmin
from hyperopt import hp
from hyperopt import tpe
from hyperopt import Trials
from hyperopt import STATUS_OK
from hyperopt.pyll.stochastic import sample
from sklearn.metrics import roc_auc_score
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelBinarizer
from timeit import default_timer as timer
import sdss_gz_data as sgd
from sdss_gz_data import SPIRIAL_GALAXY_TYPE
from sdss_gz_data import ELLIPTICAL_GALAXY_TYPE
from sdss_gz_data import UNKNOWN_GALAXY_TYPE
from joblib import Parallel, delayed
# -
features = sgd.generate_features()
features
# %ls -l data/
orig_data = sgd.load_data('data/astromonical_data.csv.gz')
prepared_data = sgd.prepare_data(orig_data)
transformed_data = sgd.transform_data(prepared_data)
X = transformed_data[features]
y = transformed_data['galaxy_type']
len(transformed_data)
y_visualisation = y.map({SPIRIAL_GALAXY_TYPE: 'Spiral', ELLIPTICAL_GALAXY_TYPE: 'Ellipitcal', UNKNOWN_GALAXY_TYPE: 'Unknown'})
print("Percent Class Distribution:")
print(y_visualisation.value_counts(normalize=True)*100)
# +
known_galaxy_type_idx = transformed_data.galaxy_type != sgd.UNKNOWN_GALAXY_TYPE
X = X[known_galaxy_type_idx]
y = y[known_galaxy_type_idx]
# -
len(X)
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
# ## Hyperparameter Search
# +
N_FOLDS = 5
hp_out_file = 'gbm_hp_trials.csv'
of_connection = open(hp_out_file, 'w')
writer = csv.writer(of_connection)
# Write the headers to the file
writer.writerow(['loss', 'params', 'iteration', 'estimators', 'train_time'])
of_connection.close()
def objective(x_train, y_train, random_state=42, stratified=True):
def _objective(params, n_folds=N_FOLDS):
# Keep track of evals
global ITERATION
ITERATION += 1
# # Retrieve the subsample
# subsample = params['boosting_type'].get('subsample', 1.0)
# # Extract the boosting type and subsample to top level keys
# params['boosting_type'] = params['boosting_type']['boosting_type']
# params['subsample'] = subsample
# Make sure parameters that need to be integers are integers
for parameter_name in ['num_leaves', 'subsample_for_bin', 'min_child_samples']:
params[parameter_name] = int(params[parameter_name])
params['boosting_type'] = 'gbdt'
train_set = lgb.Dataset(x_train, y_train)
start = timer()
cv_results = lgb.cv(params, train_set, nfold=n_folds, num_boost_round=1000,
early_stopping_rounds=100,
metrics='auc', seed=random_state, stratified=stratified)
run_time = timer() - start
best_score = max(cv_results['auc-mean'])
# need a function to minimise
loss = 1 - best_score
# Boosting rounds that returned the highest cv score
n_estimators = int(np.argmax(cv_results['auc-mean']) + 1)
if ITERATION % 10 == 0:
# Display the information
display('Iteration {}: {} Fold CV AUC ROC {:.5f}'.format(ITERATION, N_FOLDS, best_score))
of_connection = open(hp_out_file, 'a')
writer = csv.writer(of_connection)
writer.writerow([loss, params, ITERATION, n_estimators, run_time])
of_connection.close()
# Dictionary with information for evaluation
return {'loss': loss, 'params': params, 'iteration': ITERATION,
'estimators': n_estimators,
'train_time': run_time, 'status': STATUS_OK}
return _objective
# -
space = {
'class_weight': hp.choice('class_weight', [None, 'balanced']),
'num_leaves': hp.quniform('num_leaves', 30, 150, 1),
'learning_rate': hp.loguniform('learning_rate', np.log(0.01), np.log(0.2)),
'subsample_for_bin': hp.quniform('subsample_for_bin', 20000, 300000, 20000),
'min_child_samples': hp.quniform('min_child_samples', 20, 500, 5),
'reg_alpha': hp.uniform('reg_alpha', 0.0, 1.0),
'reg_lambda': hp.uniform('reg_lambda', 0.0, 1.0),
'colsample_bytree': hp.uniform('colsample_by_tree', 0.6, 1.0)
}
# +
ITERATION = 0
MAX_EVALS = 10
tpe_algorithm = tpe.suggest
bayes_trials = Trials()
# Optimize
best = fmin(fn = objective(x_train, y_train), space = space, algo = tpe.suggest,
max_evals = MAX_EVALS, trials = bayes_trials)
# -
best
hyperparams = bayes_trials.best_trial['result']['params']
hyperparams['class_weight'] = None
hyperparams
# ## K-Folds
hyperparams = {
'class_weight': 'balanced',
'num_leaves': 150,
'learning_rate': 0.1,
# 'subsample_for_bin': hp.quniform('subsample_for_bin', 20000, 300000, 20000),
# 'min_child_samples': hp.quniform('min_child_samples', 20, 500, 5),
# 'reg_alpha': hp.uniform('reg_alpha', 0.0, 1.0),
# 'reg_lambda': hp.uniform('reg_lambda', 0.0, 1.0),
# 'colsample_bytree': hp.uniform('colsample_by_tree', 0.6, 1.0)
}
# +
N_FOLDS = 5
#learning_rate = 0.1
def kfolds(x_train, x_test, y_train, y_test, n_splits=N_FOLDS, random_state=1138, verbose=True, features=None):
if (features is not None):
x_train = x_train[features]
x_test = x_test[features]
folds = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
oof_preds = np.zeros(x_train.shape[0])
predictions = np.zeros(x_test.shape[0])
models = []
for n_fold, (train_index, validate_index) in enumerate(folds.split(x_train, y_train)):
X_t, X_v = x_train.iloc[train_index], x_train.iloc[validate_index]
y_t, y_v = y_train.iloc[train_index], y_train.iloc[validate_index]
clf = lgb.LGBMClassifier(
objective='binary',
**hyperparams
)
clf.fit(X_t, y_t, eval_set=[(X_v, y_v)],
early_stopping_rounds=100,
eval_metric='auc',
verbose=False,
)
oof_preds[validate_index] = clf.predict_proba(X_v, num_iteration=clf.best_iteration_)[:, 1]
predictions += clf.predict_proba(x_test, num_iteration=clf.best_iteration_)[:, 1]/N_FOLDS
if (verbose):
print('Fold %2d AUC : %.6f' % (n_fold + 1, roc_auc_score(y_v, oof_preds[validate_index])))
models.append(clf)
del clf, X_t, X_v, y_t, y_v
result = roc_auc_score(y_train, oof_preds)
if (verbose):
print(f'Full AUC score {result:0.6f}')
return result, models
# -
def predict(models, x_test, features=None):
if (features is not None):
x_test = x_test[features]
num_of_models = len(models)
predictions = np.zeros(x_test.shape[0])
for idx, model in enumerate(models):
predictions += model.predict_proba(x_test, num_iteration=model.best_iteration_)[:, 1]/num_of_models
return predictions
_ = kfolds(x_train, x_test, y_train, y_test)
# +
import multiprocessing
num_cores = multiprocessing.cpu_count()
NO_BEST_FEATURE = ''
NO_BEST_AUC = -1
def get_feature_score(features):
auc, models = kfolds(x_train[features], x_test[features], y_train, y_test, verbose=False)
return auc
# Model colour indexes are the base features. Everything else additional
def determine_best_features(base_features, base_auc, bad_features):
# x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
def best_auc_results(results):
if (len(results) == 0):
return NO_BEST_FEATURE, NO_BEST_AUC
best_feature, best_auc = max(results.items(), key=lambda x:x[1])
return best_feature, best_auc
def process(results):
def _process(feature):
print(f'Checking feature: {feature}')
run_features = base_features.copy()
run_features.add(feature)
curr_auc = get_feature_score(run_features)
if (curr_auc < base_auc):
print(f'WARNING - {feature} reduces model accuracy!!!')
bad_features.add(feature)
else:
results[feature] = curr_auc
best_feature, best_auc = best_auc_results(results)
if (best_feature == feature):
print(f'{feature} has best AUC score {curr_auc:0.6f}')
return (curr_auc, feature)
return _process
print(f'Base AUC: {base_auc:0.6f}')
features_to_scan = set(features)
features_to_scan = features_to_scan.difference(base_features).difference(bad_features)
results = {}
print(f'Checking {len(features_to_scan)} features... this might take awhile')
process_feature = process(results)
_ = Parallel(n_jobs=num_cores, verbose=1, backend="threading")(map(delayed(process_feature), features_to_scan))
best_feature, best_auc = best_auc_results(results)
return results, best_auc, best_feature
# +
# base_features = set(['model_u_g_colour_index',
# 'model_g_r_colour_index',
# 'model_r_i_colour_index',
# 'model_i_z_colour_index',
# ])
base_features = set([
# 'psfMag_r',
# 'psfMag_g_u_colour_index',
# 'psfMag_r_g_colour_index',
# 'psfMag_i_r_colour_index',
# 'psfMag_z_i_colour_index',
# 'expRad_g',
# 'petroR50_i',
# 'petroRad_r',
# 'deVAB_r',
# 'petro_g_r_colour_index',
# 'petro_R90_R50_ratio_g',
# 'model_r_i_colour_index',
# 'expAB_g',
# 'petro_R90_R50_ratio_r',
# 'fracDeV_i',
# 'model_u_g_colour_index',
# 'expAB_z',
# 'expAB_i',
# 'petroRad_g'
])
#base_auc = get_feature_score(list(base_features))
base_auc = 0.998908
extra_base_features = ['expRad_g', 'petroR90_i', 'petro_r_g_colour_index', 'mag_g', 'deVAB_i', 'petroRad_r', 'model_i_r_colour_index', 'petro_R90_R50_ratio_g', 'expAB_g', 'psfMag_r']
#all_bad_features = set([])
for idx in range(5):
base_features.update(extra_base_features)
print(f'Starting a round {idx} to find best feature. Current extra features = {extra_base_features}')
feature_results, best_auc, best_feature = determine_best_features(base_features, base_auc, all_bad_features)
if (best_feature == NO_BEST_FEATURE):
print('No new feature found. Exiting')
break
print(f'Found {best_feature} as extra feature')
extra_base_features.append(best_feature)
base_auc = best_auc
base_features.update(extra_base_features)
print(f'Final extra features = {extra_base_features}')
# -
base_features = set([
'deVAB_i',
'deVRad_i',
'expAB_g',
'expAB_i',
'expAB_z',
'expRad_g',
'mag_g',
'model_g_u_colour_index',
'model_i_r_colour_index',
'petroR90_i',
'petroRad_r',
'petro_R90_R50_ratio_g',
'petro_R90_R50_ratio_i',
'petro_r_g_colour_index',
'psfMag_r'
])
base_features.intersection(set([
'expAB_z',
'expRad_g',
'expRad_i',
'expRad_u',
'expRad_z',
'fiberMag_g',
'fiberMag_r',
'fiberMag_u',
'fiberMag_z',
'model_g_u_colour_index',
'model_i_r_colour_index',
'model_r_g_colour_index',
'model_z_i_colour_index',
'petroR50_i',
'petro_R90_R50_ratio_g',
'dered_r']))
extra_base_features
all_bad_features
# selected_features = base_features.copy()
# selected_features.update([
# 'expAB_z',
# 'expRad_g',
# 'expRad_i',
# 'expRad_u',
# 'expRad_z',
# 'fiberMag_g',
# 'fiberMag_r',
# 'fiberMag_u',
# 'fiberMag_z',
# 'model_g_u_colour_index',
# 'model_i_r_colour_index',
# 'model_r_g_colour_index',
# 'model_z_i_colour_index',
# 'petroR50_i',
# 'petro_R90_R50_ratio_g',
# 'dered_r'
# ])
selected_features = set([
'deVAB_i',
'expAB_g',
'expAB_i',
'expAB_z',
'expRad_g',
'expRad_u',
'expRad_z',
'fiberMag_g',
'fiberMag_u',
'fiberMag_z',
'model_g_u_colour_index',
'model_i_r_colour_index',
'model_r_g_colour_index',
'model_z_i_colour_index',
'petroRad_r',
'petro_R90_R50_ratio_g',
'petro_R90_R50_ratio_i',
'petro_r_g_colour_index',
'psfMag_r'
])
selected_features
auc_score, models = kfolds(x_train, x_test, y_train, y_test, features=selected_features)
# +
# clf = lgb.LGBMClassifier(
# objective='binary',
# **hyperparams
# )
# clf.fit(x_train[base_features], y_train, verbose=True, eval_metric='auc')
# predictions = clf.predict_proba(x_test[base_features], num_iteration=clf.best_iteration_)
predictions = predict(models, x_test, features=selected_features)
print(predictions)
# -
import matplotlib.pyplot as plt
import seaborn as sns
# +
feature_importances = pd.DataFrame(sorted(zip(x_train[selected_features].columns, np.zeros(len(selected_features)))), columns=['Feature', 'Value'])
#feature_importances
#pd.DataFrame(sorted(zip(x_train[selected_features].columns, model.feature_importances_)), columns=['Feature', 'Value'])
# feature_importances = np.empty((len(models), len(selected_features), 2), dtype=object)
for idx, model in enumerate(models):
feature_importance = pd.DataFrame(sorted(zip(x_train[selected_features].columns, model.feature_importances_)), columns=['Feature','Value'])
feature_importances['Value'] += feature_importance['Value']/len(models)
plt.figure(figsize=(20, 10))
sns.barplot(x="Value", y="Feature", data=feature_importances.sort_values(by="Value", ascending=False))
plt.title('LightGBM Features (avg over folds)')
plt.tight_layout()
plt.show()
# -
feature_importances.sort_values(by="Value", ascending=False)
common_features = [
'expAB_z',
'expRad_g',
'model_g_u_colour_index',
'model_i_r_colour_index',
'petro_R90_R50_ratio_g'
]
non_common_features_importance = feature_importances[np.invert(feature_importances.Feature.isin(common_features))]
non_common_features_importance.sort_values(by="Value", ascending=False)
predictions
pred = np.empty(predictions.shape, dtype=int)
pred[predictions < 0.5] = SPIRIAL_GALAXY_TYPE
pred[predictions >= 0.5] = ELLIPTICAL_GALAXY_TYPE
pred
sgd.classification_scores(y_test, pred)
# +
results = pd.DataFrame(y_test).rename(columns={'galaxy_type':'actual_galaxy_type'})
results['pred_galaxy_type'] = pred
results['prediction'] = predictions
results['raw_error'] = np.abs(results.actual_galaxy_type - results.prediction)
results = results.sort_values(by=['raw_error'], ascending=False)
results
# -
errors = results[(results.actual_galaxy_type - results.pred_galaxy_type) != 0]
error_size = len(errors)
print(error_size)
cutoff_idx = int(error_size * 0.05)
print(cutoff_idx)
top_errors = errors[0:cutoff_idx]
bottom_errors = errors[-cutoff_idx:]
top_errors
error_data = x_test[x_test.index.isin(errors.index)]
errors[errors.pred_galaxy_type == 0].raw_error.plot.hist(bins=30)
errors[errors.pred_galaxy_type == 1].raw_error.plot.hist(bins=30)
errors = pd.DataFrame(np.abs(y_test - pred) * predictions).rename(columns={'galaxy_type': 'raw_error'})
errors['error_val'] = np.abs(2 * (errors.raw_error - 0.5))
errors['pred_galaxy_type'] = pred
errors = errors[errors.raw_error > 0.0]
errors.sort_values(by=['error_val'], ascending=False)
len(x_test)
# +
unknown = transformed_data[transformed_data.galaxy_type == sgd.UNKNOWN_GALAXY_TYPE]
unknown.loc[unknown.debiased_elliptical > 0.75, 'galaxy_type'] = sgd.ELLIPTICAL_GALAXY_TYPE
unknown.loc[unknown.debiased_spiral > 0.75, 'galaxy_type'] = sgd.SPIRIAL_GALAXY_TYPE
X_unknown = unknown[unknown.galaxy_type != sgd.UNKNOWN_GALAXY_TYPE][base_features]
y_unknown_expected = unknown[unknown.galaxy_type != sgd.UNKNOWN_GALAXY_TYPE]['galaxy_type']
y_unknown_predictions = predict(models, X_unknown, features=base_features)
# -
y_unknown_pred = np.empty(y_unknown_predictions.shape, dtype=int)
y_unknown_pred[y_unknown_predictions < 0.5] = SPIRIAL_GALAXY_TYPE
y_unknown_pred[y_unknown_predictions >= 0.5] = ELLIPTICAL_GALAXY_TYPE
sgd.classification_scores(y_unknown_expected, y_unknown_pred)
| notebooks/Galaxy Classification Feature Importances.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: python36
# language: python
# name: python36
# ---
from sklearn.svm import SVR
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV, train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# +
path = ".\\data\\"
df = pd.read_csv(path + 'LatentVec_Drug+GeneExp(breast+eliminated+unsampledGene+unsampledDrug).txt', sep='\t')
'''
path = ".\\data\\"
df = pd.read_csv(path + 'LatentVec_Drug+GeneExp(cgc+eliminated+unsampledGene+unsampledDrug).txt', sep='\t')
'''
'''
path = ".\\data\\"
df = pd.read_csv(path + 'LatentVec_Drug+RawVec_GeneExp(cgc+eliminated+unsampledDrug).txt', sep='\t')
'''
# -
# 自动选择合适的参数
svr = GridSearchCV(SVR(), param_grid={"kernel": ("linear", 'rbf'), "C": np.logspace(-3, 3, 7), "gamma": np.logspace(-3, 3, 7)})
svr.fit(x, y)
# joblib.dump(svr, 'svr.pkl') # 保存模型
xneed = np.linspace(0, 100, (100,3))[:, None]
y_pre = svr.predict(xneed)# 对结果进行可视化:
plt.scatter(x[0], y, c='k', label='data', zorder=1)
# plt.hold(True)
plt.plot(xneed[0], y_pre, c='r', label='SVR_fit')
plt.xlabel('data')
plt.ylabel('target')
plt.title('SVR versus Kernel Ridge')
plt.legend()
plt.show()
print(svr.best_params_)
| Code/CancerML/support_vector_regression/.ipynb_checkpoints/svr-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/fongabc/dcgan_code/blob/master/VAE.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="jIQWAzLvBu06" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 105} outputId="13bb8960-0031-4ca4-b40f-c6e97fb3b25c"
import tensorflow.keras
from tensorflow.keras import layers
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
import numpy as np
img_shape=(28, 28, 1)
batch_size = 16
latent_dim= 2
input_img = tensorflow.keras.Input(shape = img_shape)
x = layers.Conv2D(32,3,padding='same',activation='relu')(input_img)
x = layers.Conv2D(64,3,padding='same',activation='relu',strides=(2,2))(x)
x = layers.Conv2D(64,3,padding='same',activation='relu')(x)
x = layers.Conv2D(64,3,padding='same',activation='relu')(x)
shape_before_flattening = K.int_shape(x)
x = layers.Flatten()(x)
x = layers.Dense(32, activation='relu')(x)
z_mean = layers.Dense(latent_dim)(x)
z_log_var = layers.Dense(latent_dim)(x)
# + id="nDCJKhtkFB-u" colab_type="code" colab={}
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(K.shape(z_mean)[0],latent_dim),mean=0.,stddev=1.)
return z_mean+K.exp(z_log_var)* epsilon
z = layers.Lambda(sampling)([z_mean,z_log_var])
decoder_input = layers.Input(K.int_shape(z)[1:])
x = layers.Dense(np.prod(shape_before_flattening[1:]),activation='relu')(decoder_input)
x = layers.Reshape(shape_before_flattening[1:])(x)
x = layers.Conv2DTranspose(32, 3,padding='same',activation='relu',strides=(2,2))(x)
x = layers.Conv2D(1, 3, padding='same',activation='sigmoid')(x)
decoder = Model(decoder_input, x)
z_decoded = decoder(z)
# + id="B9cac2YVnga4" colab_type="code" colab={}
class CustomVariationalLayer(tensorflow.keras.layers.Layer):
def vae_loss(self, x, z_decoded):
x = K.flatten(x)
z_decoded = K.flatten(z_decoded)
xent_loss = tensorflow.keras.metrics.binary_crossentropy(x, z_decoded)
kl_loss = -5e-4 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
return K.mean(xent_loss + kl_loss)
def call(self, inputs):
x = inputs[0]
z_decoded = inputs[1]
loss = self.vae_loss(x, z_decoded)
self.add_loss(loss, inputs = inputs)
return x
y = CustomVariationalLayer()([input_img, z_decoded])
# + id="C6UQor2GHSBn" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 88} outputId="113bc2ba-27bc-4e98-ce00-57f0fec53f47"
from tensorflow.keras.datasets import mnist
vae=Model(input_img, y)
vae.compile(optimizer='rmsprop',loss=None)
(x_train, _), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32')/255.
| VAE.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Code to create biochem ICs for SOG model for full Salish Sea domain
# - not final; should find climatology of deep values and try to find more measurements for lateral resolution
# - all based on S3 from October 2004
# +
import netCDF4 as nc
import matplotlib.pyplot as plt
import numpy as np
import os
import re
# %matplotlib inline
#resultsDir='/data/eolson/MEOPAR/SS2DSOGruns/'
N2chl=1.600
# -
TS=nc.Dataset('/results/SalishSea/nowcast/11jun15/SalishSea_02376000_restart.nc')
zvar='nav_lev'
xvar='nav_lon'
yvar='nav_lat'
tvar='time_counter'
tlen=TS.variables['sn'].shape[0]
zlen=TS.variables['sn'].shape[1]
ylen=TS.variables['sn'].shape[2]
xlen=TS.variables['sn'].shape[3]
print(TS.dimensions)
print(TS.variables)
# read z, T, S into CTD
CTD=np.loadtxt('/data/eolson/SOG/SOG-initial/ctd/SG-S3-2004-10-19.sog',skiprows=12,usecols=(1, 4, 2, 8))
# columns are 0:z 1:chl 2:T 3:Si
print(TS.variables[zvar][:])
nuts=np.loadtxt('/data/eolson/SOG/SOG-initial/stratogem_nuts/Nuts-S3-2004-10-19.sog', skiprows=12, usecols=(0,1,2))
# columns are 0:z 1:NO 2:Si
print(CTD.shape)
# add z=0 at first row, repeating T,S values from next level
data=np.vstack((CTD[0,:],CTD))
data[0,0]=0.
zs=TS.variables[zvar][:]
# Remove records with negative data values (typically -99.0 or
# -99999) because that indicates invalid data
data_qty=nuts[:,1] #NO
mask = (data_qty >= 0.0)
data_records = len(data_qty[mask])
qty_clean = data_qty[mask]
depth_clean= nuts[:,0][mask]
# Calculate depth and quantity differences from field data for use
NO=np.interp(zs,depth_clean,qty_clean)
print(NO)
# Remove records with negative data values (typically -99.0 or
# -99999) because that indicates invalid data
data_qty=nuts[:,2] #Si
mask = (data_qty >= 0.0)
data_records = len(data_qty[mask])
qty_clean = data_qty[mask]
depth_clean= nuts[:,0][mask]
Si=np.interp(zs,depth_clean,qty_clean)
print (Si)
# Remove records with negative data values (typically -99.0 or
# -99999) because that indicates invalid data
data_qty=data[:,1] # chl
mask = (data_qty >= 0.0)
data_records = len(data_qty[mask])
qty_clean = data_qty[mask]
depth_clean= data[:,0][mask]
P=np.interp(zs,depth_clean,qty_clean)
P[zs>150]=0.0
print (P)
# create temp and sal arrays with correct dimensions
vecNO=np.reshape(NO,(zlen,1,1))
data_NO=np.tile(vecNO,(1,1,ylen,xlen))
vecSi=np.reshape(Si,(zlen,1,1))
data_Si=np.tile(vecSi,(1,1,ylen,xlen))
print (data_Si.shape)
vecP=0.33*np.reshape(P,(zlen,1,1))/N2chl
data_PHY=np.tile(vecP,(1,1,ylen,xlen))
data_PHY2=data_PHY
data_MYRI=data_PHY*1e-6
data_MICZ=data_MYRI
data_NH4=0.0*data_PHY+1.0
data_POC=data_PHY2/5.0*1e-6
data_DOC=data_POC/10.0
data_bSi=data_POC
data_POC=data_POC*7.6
data_DOC=data_DOC*7.6
print (data_NH4[0,0,:,:])
# +
new_nuts=nc.Dataset('/ocean/eolson/MEOPAR/NEMO-3.6-inputs/initial_conditions/nuts_SOG_fullDomain.nc','w')
new_nuts.createDimension('y', ylen)
new_nuts.createDimension('x', xlen)
new_nuts.createDimension('z', zlen)
new_nuts.createDimension('t', None)
print(TS)
print(new_nuts)
# +
new_tc=new_nuts.createVariable(tvar,float,('t'),zlib=True)
#new_tc.setncattr('units',TS.variables[tvar].units)
#new_tc.setncattr('long_name',TS.variables[tvar].long_name)
new_tc[:]=TS.variables[tvar]
print (TS.variables[tvar])
print( new_nuts.variables[tvar])
# +
new_z=new_nuts.createVariable(zvar,float,('z'),zlib=True)
#new_z.setncattr('units',TS.variables[zvar].units)
#new_z.setncattr('long_name',TS.variables[zvar].long_name)
#new_z.setncattr('positive',TS.variables[zvar].positive)
new_z[:]=zs
print( TS.variables[zvar])
print (new_nuts.variables[zvar])
# +
new_x=new_nuts.createVariable(xvar,float,('y','x'),zlib=True)
#new_x.setncattr('units',TS.variables[xvar].units)
#new_x.setncattr('long_name',TS.variables[xvar].long_name)
new_x=TS.variables[xvar]
print (TS.variables[xvar])
print (new_nuts.variables[xvar])
# +
new_y=new_nuts.createVariable(yvar,float,('y','x'),zlib=True)
#new_y.setncattr('units',TS.variables[yvar].units)
#new_y.setncattr('long_name',TS.variables[yvar].long_name)
new_y=TS.variables[yvar]
print( TS.variables[yvar])
print( new_nuts.variables[yvar])
# -
new_NO=new_nuts.createVariable('NO3',float,('t','z','y','x'),zlib=True)
#new_Tem.setncattr('units',TS.variables['NO3'].units)
#new_NO.setncattr('long_name','Nitrate')
#new_NO.setncattr('coordinates',TS.variables['votemper'].coordinates)
new_NO[:,:,:,:]=data_NO
print( TS.variables['sn'])
print( new_nuts.variables['NO3'])
new_Si=new_nuts.createVariable('Si',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_Si.setncattr('long_name','Silicate')
#new_Si.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_Si[:,:,:,:]=data_Si
print( new_nuts.variables['Si'])
new_NH4=new_nuts.createVariable('NH4',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_NH4.setncattr('long_name','Ammonium')
#new_NH4.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_NH4[:,:,:,:]=data_NH4
print (new_nuts.variables['NH4'])
new_PHY=new_nuts.createVariable('PHY',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_PHY.setncattr('long_name','PHY')
#new_PHY.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_PHY[:,:,:,:]=data_PHY
print (new_nuts.variables['PHY'])
new_PHY2=new_nuts.createVariable('PHY2',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_PHY2.setncattr('long_name','PHY2')
#new_PHY2.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_PHY2[:,:,:,:]=data_PHY2
print( new_nuts.variables['PHY2'])
new_MYRI=new_nuts.createVariable('MYRI',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_MYRI.setncattr('long_name','MYRI')
#new_MYRI.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_MYRI[:,:,:,:]=data_MYRI
print( new_nuts.variables['MYRI'])
new_MICZ=new_nuts.createVariable('MICZ',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_MICZ.setncattr('long_name','MICZ')
#new_MICZ.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_MICZ[:,:,:,:]=data_MICZ
print( TS.variables['sn'])
print (new_nuts.variables['MICZ'])
new_POC=new_nuts.createVariable('POC',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_POC.setncattr('long_name','POC')
#new_POC.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_POC[:,:,:,:]=data_POC
print (new_nuts.variables['POC'])
new_DOC=new_nuts.createVariable('DOC',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_DOC.setncattr('long_name','DOC')
#new_DOC.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_DOC[:,:,:,:]=data_DOC
print( new_nuts.variables['DOC'])
new_bSi=new_nuts.createVariable('bSi',float,('t','z','y','x'),zlib=True)
#new_Sal.setncattr('units',TS.variables['vosaline'].units)
#new_bSi.setncattr('long_name','bSi')
#new_bSi.setncattr('coordinates',TS.variables['vosaline'].coordinates)
new_bSi[:,:,:,:]=data_bSi
print (new_nuts.variables['bSi'])
new_nuts.title="""SalishSea SOG full domain NO, Si, NH4, PHY, PHY2, MYRI, Z, DOC, POC, bSi initialization"""
new_nuts.institution="""
Dept of Earth, Ocean & Atmospheric Sciences, University of British Columbia"""
new_nuts.comment= """
Based on SG-S3-2004-10-19.sog and nuts-S3-2004-10-19.sog"""
new_nuts.reference= """
eolson: createIC_NutsPhy_fullDomain.ipynb"""
new_nuts.close()
| Elise/modelInput/createIC_NutsPhy_fullDomain.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from date_tool import dt_search
text = '2020-03-19 Jumat, 12 Februari 2016 14:57, 13 Februari 2016, january 31, 2020, january 1, 2020, 2020/09/01, 2020\\09\\02'
dt_search.find_date(text)
| date/date_test.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + language="bash"
#
# ### Prepare ImageNet 32x32 and 64x64 ###
# DATA_DIR=/tandatasets/small_imnet
#
# mkdir ${DATA_DIR}
# cd ${DATA_DIR}
#
# for FILENAME in train_32x32.tar valid_32x32.tar train_64x64.tar valid_64x64.tar
# do
# curl -O http://image-net.org/small/$FILENAME
# tar -xvf $FILENAME
# done
# -
| prepare_imnet.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Answering Business Questions Using SQL
# ## *Chinook Database SQLite*
# In this guided project from [Dataquest.io](https://dataquest.io), I will be writing SQL queries, creating plots, and explaining the data based on the given business questions.
# +
import pandas as pd
import sqlite3
import matplotlib.pyplot as plt
from matplotlib import cm
import seaborn as sns
# %matplotlib inline
sns.set(style="white", palette="Set2")
def run_query(q):
with sqlite3.connect("chinook.db") as conn:
return pd.read_sql(q, conn)
def run_command(c):
with sqlite3.connect("chinook.db") as conn:
conn.isolation_level = None
conn.execute(c)
def show_tables():
q = ('SELECT name, type FROM sqlite_master WHERE type IN ("table","view");')
return run_query(q)
show_tables()
# -
# ### Question 1: Chinook record store has signed a deal with a record label; find out which genres sell the most tracks in the USA and create a visualization of those findings.
q1 = (
'''
WITH tracks_usa AS (
SELECT il.* FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c ON c.customer_id = i.customer_id
WHERE c.country = "USA")
SELECT
g.name genre,
COUNT(tu.invoice_line_id) absolute,
cast(COUNT(tu.invoice_line_id) AS float)/ (SELECT COUNT(*) FROM tracks_usa) percent
FROM tracks_usa tu
INNER JOIN track t ON t.track_id = tu.track_id
INNER JOIN genre g ON g.genre_id = t.genre_id
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10
''')
run_query(q1)
# +
top_usa = run_query(q1)
with sns.color_palette("BuGn_r"):
sns.barplot(x="percent", y="genre", data=top_usa, orient="h")
# -
# Based on the top ten genres, we would want to purchase the albums from:
# * Red Tone, as Alternative & Punk is the number two genre
# * Slim Jim Bites, as Blues is fifth
# * Meteor and the Girls, in eighth
# ### Question 2: Find the total dollar amount of sales assigned to each support agent within the company and plot the results.
q2 = (
'''
SELECT
e.first_name || " " || e.last_name employee_name,
e.hire_date,
SUM(i.total) total_sales
FROM employee e
INNER JOIN customer c ON c.support_rep_id = e.employee_id
INNER JOIN invoice i ON i.customer_id = c.customer_id
GROUP BY e.employee_id
'''
)
run_query(q2)
e_sales = run_query(q2)
sns.barplot(x="total_sales", y="employee_name", data=e_sales, orient="h")
plt.title("Employee Sales")
plt.xlabel("Total Sales in Dollars")
plt.ylabel("Name")
# While <NAME> has the lowest sales numbers, we can see from the results of the query that he was hired later than the other employees, which excuses him.
# ### Question 3: Calculate, per country, the:
# * total number of customers
# * total value of sales
# * average value of sales per customer
# * average order value <br/>
# _Where a country has only one customer, collect them into an "Other" group._
# Sort the results from highest total sales to lowest, with "Other" at the bottom.
# this command assigns a country of "Other" to countries with only one customer
qt = '''
CREATE VIEW other_assignment AS
SELECT
CASE
WHEN (
SELECT count(*)
FROM customer
where country = c.country
) = 1 THEN "Other"
ELSE c.country
END AS country,
c.customer_id,
il.*
FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c ON c.customer_id = i.customer_id
'''
run_command(qt)
q3a = '''
SELECT
CASE
WHEN (
SELECT count(*)
FROM customer
where country = c.country
) = 1 THEN "Other"
ELSE c.country
END AS country,
c.customer_id,
il.*
FROM invoice_line il
INNER JOIN invoice i ON i.invoice_id = il.invoice_id
INNER JOIN customer c ON c.customer_id = i.customer_id
LIMIT 5
'''
run_query(q3a)
# Above we can see the output of the view we created.
q3 = (
'''
SELECT
country,
total_customers,
total_sales,
average_sales_per_customer,
average_order
FROM
(
SELECT
country,
COUNT(DISTINCT customer_id) total_customers,
SUM(unit_price) total_sales,
ROUND(SUM(unit_price) / COUNT(DISTINCT customer_id), 2) average_sales_per_customer,
ROUND(SUM(unit_price) / COUNT(DISTINCT invoice_id), 2) average_order,
CASE
WHEN country = "Other" THEN 1
ELSE 0
END AS sort
FROM other_assignment oa
GROUP BY 1
ORDER BY sort ASC, 3 DESC
)
''')
run_query(q3)
# +
by_country = run_query(q3)
by_country.set_index("country", inplace=True, drop=True)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 10))
ax1, ax2, ax3, ax4 = axes.flatten()
fig.subplots_adjust(hspace=.5, wspace=.3)
# top left
sales_breakdown = by_country["total_sales"].copy().rename('')
sales_breakdown.plot.pie(
ax=ax1,
startangle=-90,
counterclock=False,
title='Sales Breakdown by Country,\nNumber of Customers',
colormap=plt.cm.Accent,
fontsize=8,
wedgeprops={'linewidth':0}
)
# top right
cvd_cols = ["total_customers","total_sales"]
custs_vs_dollars = by_country[cvd_cols].copy()
custs_vs_dollars.index.name = ''
for c in cvd_cols:
custs_vs_dollars[c] /= custs_vs_dollars[c].sum() / 100
custs_vs_dollars.plot.bar(
ax=ax2,
title="Pct Customers vs Sales"
)
ax2.tick_params(top="off", right="off", left="off", bottom="off")
ax2.spines["top"].set_visible(False)
ax2.spines["right"].set_visible(False)
# bottom left
avg_order = by_country["average_order"].copy()
avg_order.index.name = ''
difference_from_avg = avg_order * 100 / avg_order.mean() - 100
difference_from_avg.drop("Other", inplace=True)
difference_from_avg.plot.bar(
ax=ax3,
title="Average Order,\nPct Difference from Mean"
)
ax3.tick_params(top="off", right="off", left="off", bottom="off")
ax3.axhline(0, color='k')
ax3.spines["top"].set_visible(False)
ax3.spines["right"].set_visible(False)
ax3.spines["bottom"].set_visible(False)
# bottom right
ltv = by_country["average_sales_per_customer"].copy()
ltv.index.name = ''
ltv.drop("Other",inplace=True)
ltv.plot.bar(
ax=ax4,
title="Customer Lifetime Value, Dollars"
)
ax4.tick_params(top="off", right="off", left="off", bottom="off")
ax4.spines["top"].set_visible(False)
ax4.spines["right"].set_visible(False)
plt.show()
# -
# #### Interpretations
# It is interesting to note that the Czech Republic has the highest total spending per customer and the highest average order total. There are two possible interpretations: one, that Czech customers are valuable in general and that expanding there would be worthwhile; or two, that other countries are just behind, and effort should be spending increasing spending on a per-customer basis to the Czech levels.
# _Another thing to note: there are not that many sales overall, so the sample size is rather limited. It would not be prudent to launch large campaigns based on this data._
# That being said, I would recommend a closer look at implementing pilot campaigns in Czechia, United Kingdom, and India in the hopes of capitalizing on those larger average orders and attempting to expand total orders and total customers.
# ### Question 4: Categorize each invoice as either album purchase or not, calculating:
# * Number of invoices
# * Percentage of invoices
q4 = '''
WITH invoice_first_track AS
(
SELECT
il.invoice_id invoice_id,
MIN(il.track_id) first_track_id
FROM invoice_line il
GROUP BY 1
)
SELECT
album_purchase,
COUNT(invoice_id) number_of_invoices,
CAST(count(invoice_id) AS FLOAT) / (
SELECT COUNT(*) FROM invoice
) percent
FROM
(
SELECT
ifs.*,
CASE
WHEN
(
SELECT t.track_id FROM track t
WHERE t.album_id = (
SELECT t2.album_id FROM track t2
WHERE t2.track_id = ifs.first_track_id
)
EXCEPT
SELECT il2.track_id FROM invoice_line il2
WHERE il2.invoice_id = ifs.invoice_id
) IS NULL
AND
(
SELECT il2.track_id FROM invoice_line il2
WHERE il2.invoice_id = ifs.invoice_id
EXCEPT
SELECT t.track_id FROM track t
WHERE t.album_id = (
SELECT t2.album_id FROM track t2
WHERE t2.track_id = ifs.first_track_id
)
) IS NULL
THEN "yes"
ELSE "no"
END AS "album_purchase"
FROM invoice_first_track ifs
)
GROUP BY album_purchase;
'''
run_query(q4)
# #### Final Results
# This was a very difficult final question (regarding the EXCEPT and IS NULL CASE), but the output supports the idea that a non-trivial amount of purchases are full album purchases and should not be ignored.
# #### Further Questions:
# * Which artist is used in the most playlists?
# * How many tracks have been purchases vs not purchased?
# * Is the range of tracks in the store reflective of their sales popularity?
# * Do protected vs non-protected media types have an effect on popularity?
| Basics.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# > This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.
#
# # 4.9. Processing huge NumPy arrays with memory mapping
import numpy as np
# ## Writing a memory-mapped array
# We create a memory-mapped array with a specific shape.
nrows, ncols = 1000000, 100
f = np.memmap('memmapped.dat', dtype=np.float32,
mode='w+', shape=(nrows, ncols))
# Let's feed the array with random values, one column at a time because our system memory is limited!
for i in range(ncols):
f[:,i] = np.random.rand(nrows)
# We save the last column of the array.
x = f[:,-1]
# Now, we flush memory changes to disk by removing the object.
del f
# ## Reading a memory-mapped file
# Reading a memory-mapped array from disk involves the same memmap function but with a different file mode. The data type and the shape need to be specified again, as this information is not stored in the file.
f = np.memmap('memmapped.dat', dtype=np.float32, shape=(nrows, ncols))
np.array_equal(f[:,-1], x)
del f
# > You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
#
# > [IPython Cookbook](http://ipython-books.github.io/), by [<NAME>](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).
| notebooks/chapter04_optimization/09_memmap.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
'''
import sys
!{sys.executable} -m pip install demjson
!{sys.executable} -m pip install geocoder
import demjson
'''
##json file source : https://wapi.gogoro.com/tw/api/vm/list
import json
import re
import geocoder
g = geocoder.ip('me')
print(g.latlng[0])
print(g.latlng[1])
mylat = g.latlng[0]
mylon = g.latlng[1]
gogoro_battery = []
with open('list.json') as reader:
json_file = json.loads(reader.read())
#print(json_file)
for p in json_file['data']:
#print(p)
#print(p['LocName'])
_list = re.split('\"',p['LocName'])
#print("Location Name : "+_list[13]+" / "+ _list[5])
loc_EN=_list[5]
loc_ZH=_list[13]
#print('Latitude: ' + str(p['Latitude']))
lat = p['Latitude']
#print('Longitude: ' + str(p['Longitude']))
lon = p['Longitude']
#print('ZipCode: ' + p['ZipCode'])
zipcode = p['ZipCode']
#print('Address: ' + p['Address'])
_list = re.split('\"',p['Address'])
#print("Address : "+_list[13]+" / "+ _list[5])
addre_EN =_list[5]
addre_ZH =_list[13]
#print('District: ' + p['District'])
#print('City: ' + p['City'])
_list = re.split('\"',p['District'])
#print("District : "+ _list[13]+" / "+_list[5])
dist_EN = _list[5]
dist_ZH = _list[13]
_list = re.split('\"',p['City'])
#print("City : "+ _list[13]+" / "+_list[5])
city_EN = _list[5]
city_ZH = _list[13]
#print('AvailableTime: ' + p['AvailableTime'])
avail_t = p['AvailableTime']
#print('--------------------')
gogoro_battery.append({
'loc_EN':loc_EN,
'loc_ZH': loc_ZH,
'lat': lat,
'lon': lon,
'zipcode' : zipcode,
'addre_EN' : addre_EN,
'addre_ZH': addre_ZH,
'dist_EN': dist_EN,
'dist_ZH': dist_ZH,
'city_EN': city_EN,
'city_ZH' : city_ZH,
'avail_t' : avail_t,
})
print (gogoro_battery)
# -
nearest_val = 9999
nearest_store = []
for store in gogoro_battery:
dis = (mylat-store['lat'])**2+(mylon-store['lon'])**2
if dis < nearest_val:
nearest_val = dis
nearest_store = store
print("The recommanded nearest gogoro battery stop is as below: ")
print(nearest_store)
| 01_python_crawler/03_gogoro/Gogoro test.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # GRIP : The Sparks Foundation
# ## Data Science & Business Analytics
#
# ### Task 6 : Prediction using Decision Tree Algorithm
# **Level : Intermidate**
#
# **Author Name : <NAME>**
#
# **Batch : October 2021**
#
# **Programming Language : python**
#
# **IDE : Jupyter Notebook**
#
# Dataset download link : https://bit.ly/3kXTdox
# ### Importing Libraries
# +
import pandas as pd # for loading dataset
import numpy as np # for numerical computation
from matplotlib import pyplot as plt # visualize tool
import seaborn as sns # visualize tool
from statsmodels.stats.outliers_influence import variance_inflation_factor # to calculate VIF
from sklearn.model_selection import train_test_split # to split data into train and test sets
from sklearn.model_selection import GridSearchCV # to perform hyper-parameter optimization
from sklearn.tree import DecisionTreeClassifier # Decision Tree model for classfication
from sklearn.metrics import confusion_matrix, plot_confusion_matrix # to draw confusion matrix
from sklearn.metrics import classification_report # breif report about DTC model
from sklearn.tree import plot_tree # to draw Decision Tree
from sklearn.model_selection import cross_val_score # to perform cross validation
import joblib # to save DTC model
# -
import warnings # ignoring warnings
warnings.filterwarnings("ignore")
# ### Loading Dataset
df = pd.read_csv('Iris.csv', index_col='Id')
df.head()
df.dtypes
df.info()
df.shape
# ### Numerical and Categorical features/ Variables
numerical_cols = [col for col in df.columns if df[col].dtype!='O']
categorical_cols = [col for col in df.columns if df[col].dtype=='O']
print(f"Numberical columns are = {numerical_cols}")
print(f"Categorical columns are = {categorical_cols}")
continuous_cols = [col for col in numerical_cols if df[col].nunique() >= 25]
discrete_cols = [col for col in numerical_cols if df[col].nunique() < 25]
print(f"Continuous values features are = {continuous_cols}")
print(f"Discrete values feature is = {discrete_cols}")
# ### Checking for missing values
df.isnull().sum()
# We can confirm that there are no nan values. Meaning No missing value, that is good for us because we don’t need to impute those missing values or dropping them.
# ### checking for multi-collinearity
sns.heatmap(df.corr(), annot=True, fmt='.2f',)
# There are some features that are highly corelated with each other, like sepalLength and PetalLength (pearson correlation coefficient = **0.87**). Same with PetalLength and PetalWidth (pearson correlation coefficient = **0.96**). And with PetalWidth and SeptalLength (pearson correlation coefficient = **0.82**)
def vif_scores(df): #calculating VIF scores for dataSet
VIF_Scores = pd.DataFrame()
VIF_Scores["Independent Features"] = df.columns
VIF_Scores["VIF Scores"] = [variance_inflation_factor(df.values,i) for i in range(df.shape[1])]
return VIF_Scores
vif_scores(df.iloc[:, :-1])
# With high VIF values (>10) multi-collinearity exist in data.
#
# Because we are going to use Decision Tree so we are not doing anything to remove multi-collinearity
# ### Visualizing Data
sns.pairplot(data=df, hue='Species')
# #### checking for imbalance data
sns.countplot(x ='Species', data=df)
# We have equal no of counts of each class (33.33% each). Not imbalance data.
# #### outliers
# +
fig, ax = plt.subplots(2, 2, figsize=(12, 6))
fig.tight_layout(h_pad=4, w_pad=7)
plt.suptitle('All Box-Plots')
for i in range(2):
for j in range(2):
index = 2*i +j
sns.boxplot(y='Species', x=df.iloc[:, index], data=df, ax=ax[i, j])
plt.show()
# -
# There exist few outliers in data. Majority in 'PetalLengthcm'. Decision Tree don't get affected by outliers, unlike (KNN).Thats why not removing outliers.
# +
fig, ax = plt.subplots(2, 2, figsize=(12, 6))
fig.tight_layout(h_pad=4, w_pad=7)
plt.suptitle('All violin-Plots')
for i in range(2):
for j in range(2):
index = 2*i +j
sns.violinplot(y='Species', x=df.iloc[:, index], data=df,ax=ax[i, j])
# -
# #### Distribution of the Numerical Variables
# +
fig, ax = plt.subplots(2, 2, figsize=(12, 6))
fig.tight_layout(h_pad=5, w_pad=5)
for i in range(2):
for j in range(2):
index = 2*i +j
sns.histplot(df.iloc[:, index], ax=ax[i, j], kde=True, stat="density")
# -
# SepalLengthCm and SepalWidthCm both follows normal distribution, but PetalLengthCm and PetalWidthCm do not follow normal distribution.
# ### Peparing Data for Model
unique_types_i = df['Species'].unique()
unique_types = [x.replace('Iris-', '') for x in unique_types_i]
unique_types
mapper = {unique_types_i[x]:x for x in range(len(unique_types))}
mapper
# ### classifing multi-class target
df['Species'] = df['Species'].map(mapper)
df['Species'].unique()
# ### Dividing Data into X(independent variables) and y(dependent variable)
X = df.iloc[:, :-1]
y = df.iloc[:, -1]
# ## Spliting Data into train and test split
# ___
# default train set = 70% of data and test set = 30% data
#
# we are not Normalizing Data becuase DT don't need any kind of scaling because it doesn't use any distance algorithm, to select any branch it generally use gini score.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# we are scaling features with training set to avoid data-leakage
# # Model Building
#
clf_dt = DecisionTreeClassifier(random_state=42)
clf_dt.fit(X_train, y_train)
plot_confusion_matrix(clf_dt,
X_test,
y_test,
values_format='d',
display_labels=unique_types)
plt.show()
# +
y_pred = clf_dt.predict(X_test)
print(classification_report(y_test, y_pred))
# -
# Out of the box DT perform very well with avg_accuracy 97%. Let's still do hyper parameter opmization to see if we can improve model more.
#
# precision, recall, f1-score there value should be close to 1. 0 is worst and 1 is best.
# # Applying HyperParameter Optimization using GridSearchCv
# +
max_depth = range(1, 10)
min_samples_split = range(1, 10)
min_samples_leaf = range(1, 5)
params = {
'max_depth': max_depth,
'min_samples_split':min_samples_split,
'min_samples_leaf':min_samples_leaf,
}
optimal_params = GridSearchCV(DecisionTreeClassifier(),
params,
cv=10,
scoring='accuracy',
verbose=0,
n_jobs=-1,
)
optimal_params.fit(X_train, y_train)
# +
print('GridSearch CV best score : {:.4f}\n\n'.format(optimal_params.best_score_))
print('Parameters that give the best results :','\n\n', (optimal_params.best_params_))
# -
# # Apply best params
clf_dt = DecisionTreeClassifier(random_state=42, **optimal_params.best_params_)
clf_dt.fit(X_train, y_train)
clf_dt.score(X_test, y_test)
plot_confusion_matrix(clf_dt,
X_test,
y_test,
values_format='d',
display_labels=unique_types)
# +
y_pred = clf_dt.predict(X_test)
print(classification_report(y_test, y_pred))
# -
# # Vizualize Decision Tree
# +
plt.figure(figsize=(10, 10), dpi=200)
plot_tree(clf_dt,
feature_names = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm'],
class_names= ['setosa', 'versicolor', 'virginica'],
filled = True,
rounded = True)
plt.show()
# -
# ### Saving Model
dt_model_filename = 'model/iris_dt_model.sav'
joblib.dump(clf_dt, dt_model_filename)
# ## Conclusion
# So we have successfully created a model to predict the class of iris based on sepal length, sepal width, petal length and petal width. And we created the model with approx 97% accuracy.
| Prediction using Decision Tree Algorithm/Prediction using Decision tree algorithm.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Simplex
#
# #### <NAME>
# #### <NAME>
import numpy as np
import sys
import math
# +
# En archivo exercise01.txt x1, x2 y x3 es el nombre de las variables, se usaron esas para seguir con el estándar de nombramiento en Programación Lineal.
# Es necesario escribir si es min/max para que el programa identifique si es de maximización o minimización, st para indicar que esas son las restricciones y end para indicar al programa que el problema termina ahí
def parse_coefficients(coefficient_list, monomial):
"""
Este es un parseador de coeficientes. Consiste en comprobar si una cadena tiene una expresión regular en donde pueda extraer caracteres específicos, en este caso se busca extraer los coeficientes.
Args:
:rtype: None
:param coefficient_list: Lista en la que se almacenarán los coeficientes
:param monomial: Una cadena (por ejemplo, -3x1) que será analizada hasta su coeficiente (por ejemplo, -3)
Verifica qué patrón coincide. Válidos son: (s)(n)lv
Los paréntesis indican la existencia opcional
s es + o - (la ausencia significa +)
n es un número (coeficiente, la ausencia significa 1)
l es una letra latina minúscula (letra variable)
v es un número, probablemente incremental (número variable)
Import re:
Una expresión regular (o RE) especifica un conjunto de cadenas que se corresponde con ella; las funciones de este módulo le permiten comprobar si una cadena particular se corresponde con una expresión regular dada (o si una expresión regular dada se corresponde con una cadena particular, que se reduce a lo mismo)
Source: https://docs.python.org/3/library/re.html
"""
import re
if re.match('[ ]*[\+ ]?[\d]+[\.]?[\d]*', monomial):
float_cast = float(re.match('[ ]*[\+ ]?[\d]+[\.]?[\d]*', monomial).group(0))
coefficient_list.append(float_cast)
elif re.match('[ ]*[\-][\d]+[\.]?[\d]*', monomial):
float_cast = float(re.match('[ ]*[\-][\d]+[\.]?[\d]*', monomial).group(0))
coefficient_list.append(float_cast)
elif re.match('[ ]*[\+]*[a-z][\d]+', monomial):
coefficient_list.append(1)
elif re.match('[ ]*[\-][a-z][\d]+', monomial):
coefficient_list.append(-1)
# -
lines = []
def parse_lp1(input_filename):
"""
Esta función es la encargada de leer el archivo, hará uso del parser para mandar línea a línea el contenido del .txt y según los coeficientes que obtenga devolverá las matrices y arrays correspondientes.
Tiene tareas como verificar que el archivo haya sido encontrado, leer si es un problema de maximización o minimización, llenar las matrices/ arrays.
:rtype : tuple
:param input_filename: Nombre de archivo de la entrada del problema lineal
:return: Retorna A-matrix, b-vector, c-vector, MinMax
"""
import re
error = 0 # Inicializar la variable de error. Si el error!=0 entonces hubo un problema de entrada de archivo
try:
infile = open('Simplex2.txt')
except FileNotFoundError:
error = 1
print('\nInput file error: Archivo no encontrado.') # Archivo no encontrado
#lines = []
if error != 1:
for line in infile:
lines.append(line)
infile.close()
for line in lines:
print(line, end='')
minmax_line = '' # Verficar si el problema es de maximización o de minimización
for line in lines:
if re.match('^[ ]*max|min', line):
minmax_line = line
minmax = 0
objective_function = ''
if re.match('^[ ]*max', minmax_line): #Si en el archivo se encuentra la palabra 'max' entonces el problema es de maximización
minmax = -1
objective_function = minmax_line
objective_function = objective_function.strip('max')
elif re.match('^[ ]*min', minmax_line): # Si en el archivo se encuentra la palabra 'min' entonces el problema es de minimización
minmax = 1
objective_function = minmax_line
objective_function = objective_function.strip('min')
if minmax_line == '' and minmax == 0: # Si en el archivo no se encuentra ni 'max' ni 'min' entonces no hay función objetivo
error = 2
print('\nInput file error: Función objetivo no encontrada.')
c_vector = [] # Rellenar el vector c con coeficientes de función objetiva
regex = re.compile('^[\+\- ]?[\d]*[\.]?[\d]*[a-z][\d+]')
while regex.match(objective_function):
monomial = regex.match(objective_function).group(0)
parse_coefficients(c_vector, monomial)
objective_function = objective_function.replace(monomial, '', 1)
a_matrix = [] # Rellenar la matriz A (coeficientes) y el vector b utilizando las restricciones del problema
b_vector = []
eqin = []
st_line = ''
st_index = 0
for index, line in enumerate(lines):
if 'st' in line:
st_index = index
st_line = line
if re.match('^[ ]*st', st_line):
st_line = st_line.replace('st', ' ', 1)
if st_line == '':
error = 3
print('\nInput file error: Línea de restricciones no encontrada. No existe la keyword \'st\'.')
while st_index < len(lines) - 1:
sub_a_vector = []
a_matrix.append(sub_a_vector)
while True:
st_line = st_line.strip(' ')
if re.match('^[\+\- ]?[\d]*[\.]?[\d]*[a-z][\d+]', st_line):
monomial = re.match('^[\+\- ]?[\d]*[\.]?[\d]*[a-z][\d+]', st_line).group(0)
parse_coefficients(sub_a_vector, monomial)
st_line = st_line.replace(monomial, '', 1)
elif re.match('^[<>=]+', st_line):
monomial = re.match('^[<>=]+', st_line).group(0)
if monomial == '<=':
eqin.append(-1)
elif monomial == '>=':
eqin.append(1)
elif monomial == '==':
eqin.append(0)
else:
error = 4
print('\nInput file error: Caracter inesperado; esperados <=, >=, = al menos', monomial)
st_line = st_line.replace(monomial, '', 1)
elif re.match('^[\d]+', st_line):
monomial = re.match('^[\d]+', st_line).group(0)
int_cast = int(re.match('^[\d]+', st_line).group(0))
b_vector.append(int_cast)
st_line = st_line.replace(monomial, '', 1)
else:
if not sub_a_vector: # Evalúa true cuando las líneas están vacías entre las restricciones
a_matrix.pop()
break
st_index += 1 # Incrementar el número de línea y obtener el siguiente
st_line = lines[st_index]
if st_line == 'end\n' and error == 0: # Búsqueda de la declaración final y ausencia de errores
print('\nArchivo cargado exitosamente.')
break
return a_matrix, b_vector, c_vector, eqin, minmax # Devolver todas las listas y variables creadas
# +
def convert_to_dual(input_filename, output_filename):
"""
Verifica si son restricciones de >=, <= o =. También tiene como tarea hacer un archivo de salida en el que muestre los resultados de las matrices que se llenaron.
:param input_filename: Nombre de archivo de la entrada del problema lineal
:param output_filename: Filename of the linear problem output
:return: Returns A-matrix, b-vector, c-vector, Variable-constraints, MinMax
"""
(a_matrix, b_vector, c_vector, eqin, minmax) = parse_lp1(input_filename) # Llamar la función parse_lp1
variable_constraints = [] # Convertir las restricciones a equivalentes duales '*' significa libre
if minmax == -1:
for el in eqin:
if el == 0:
variable_constraints.append('==')
elif el == 1:
variable_constraints.append('>=')
elif el == -1:
variable_constraints.append('<=')
a_matrix = list(zip(a_matrix)) # Traspuesta de A-matrix
minmax = -minmax # min(max) el problema dual es max(min)
outfile = open(output_filename, 'w') # Escribir el problema a un archivo de salida
outfile.write('(Objective Function) b-vector: [' + ', '.join(map(str, b_vector)) + ']\n')
outfile.write('\nA-matrix: [')
thing = ''
for index, sub_a_vector in enumerate(a_matrix):
thing += '[ ' + ', '.join(map(str, sub_a_vector)) + ']'
if index != (len(a_matrix) - 1):
thing += ', '
outfile.write(thing + ']\n')
outfile.write('\n(Contraints) c-vector: [' + ', '.join(map(str, c_vector)) + ']\n')
outfile.write('\n(Variable Contraints) variable_constraints-vector: [' + ', '.join(map(str, c_vector)) + ']\n')
outfile.write('\nEqin: [' + ', '.join(map(str, eqin)) + ']\n')
outfile.write('\nMinMax: [' + str(minmax) + ']\n')
outfile.close()
return a_matrix, b_vector, c_vector, variable_constraints, eqin, minmax
(a_matrix, b_vector, c_vector, variable_contraints, eqin, minmax) = convert_to_dual('input-lp1', 'output-lp2')
# +
"""
únicamente imprimimos los distintos arrays necesarios para realizar el programa.
"""
print(a_matrix)
print(b_vector)
print(c_vector)
print(variable_contraints)
# -
"""
Solicita el número de restricciones para que el programa sepa las iteraciones que tiene que hacer para
la matriz de restricciones
"""
no_restricciones = int(input("Ingrese el no. de restricciones: "))
# +
"""
Solicita el número de variables para que sepa la cantidad de columnas que tiene que tener el programa para crear una matriz
de restricciones.
Variables sirven para saber el número de columnas de la matriz
Restricciones sirven para saber el número de filas de la matriz
"""
no_variables = int(input("Ingrese el no. de variables: "))
# +
'''
Revisar si los coeficientes son binarios o no.
Lo que es hace es multiplicar la cantidad de variables por la cantidad de restricciones, esto indicará la cantidad
de coeficientes que estarán en la matriz.
Se añadió un contador llamado "sumador_binarios", que se autosuma una unidad cuando encuentra una variable binaria.
Cuando el número de coeficientes coincida con la suma del contador, es porque ya puede resolver la maximización.
'''
sumador_enteros = 0
numero_para_cant_enteros = no_variables * no_restricciones
enteros = 0
a_matrix2 = []
for i in a_matrix:
a_matrix2.append((i[0]))
print(a_matrix2)
for row in a_matrix2:
for elem in row:
num_int = round(elem)
#check_int = isinstance(elem, int)
if elem-num_int != 0:
print(elem)
print("No todos los coeficientes son enteros, vuelva ingresar")
else:
sumador_enteros+=1
print(elem)
print("Coeficiente sí es entero")
enteros = 1
print("numero_para_cant_enteros ", numero_para_cant_enteros)
print("sumador_enteros", sumador_enteros)
if sumador_enteros == numero_para_cant_enteros:
print("Ya todos son enteros, se resolverá la maximización")
else:
print("Debe actualizar para que sean sólo enteros")
sys.exit(1)
# +
'''
Revisar si los coeficientes de la matriz C son binarios o no.
Lo que es hace es tomar el cuenta el número de variables..
Se añadió un contador llamado "sumador_binarios_c", que se autosuma una unidad cuando encuentra una variable binaria.
Cuando el número de variables coincida con la suma del contador, es porque ya puede resolver la maximización.
'''
print(c_vector)
sumador_enteros_c = 0
numero_para_cant_enteros_c = no_variables
for row in c_vector:
num_int = round(elem)
#check_int = isinstance(elem, int)
if elem-num_int != 0:
print(elem)
print("No todos los coeficientes son enteros, vuelva ingresar")
else:
sumador_enteros_c+=1
print(elem)
print("Coeficiente sí es entero")
enteros = 1
print("numero_para_cant_enteros ", numero_para_cant_enteros_c)
print("sumador_enteros", sumador_enteros_c)
if sumador_enteros_c == numero_para_cant_enteros_c:
print("Ya todos son enteros, se resolverá la maximización")
else:
print("Debe actualizar para que sean sólo enteros")
sys.exit(1)
# +
#Hacer matriz
#aqui estan los coeficientes de las restricciones
"""
Aqui se hace la matriz con las slack variables y con las variables artificiales que sean necesarias
"""
positions = []
a_matrix2 = []
for i in a_matrix:
a_matrix2.append((i[0]))
#print(a_matrix2[0])
print(a_matrix2)
#convertimos a_matrix2 en una matriz de numpy para hacer operaciones con ella
mat = np.asmatrix(a_matrix2)
size = len(variable_contraints)
for i in range (len(variable_contraints)):
if variable_contraints[i] == "<=":
#hacemos la columna de ceros, de tamaño igual
# a las columnas que están en la matrix (length del arreglo de símbolos)
new_matrix = np.asmatrix(np.zeros(size))
#colocamos 1 en el espacio correspondiente de la fila en donde está
# la constrait
new_matrix[0,i]=1
#asignamos la forma para que sea un vector columna
new_matrix.shape = (size,1)
# obtenemos las dimensiones de la matrix actual
x, y = mat.shape
# hacemos el append de la columna de ceros y el uno en la posición correspondiente
# al final de la matriz, a la derecha
mat = np.hstack((mat[:,:y], new_matrix, mat[:,y:]))
print(a_matrix2[i])
print("menor")
if variable_contraints[i] == "==":
new_matrix = np.asmatrix(np.zeros(size))
new_matrix[0,i]=1
new_matrix.shape = (size,1)
x, y = mat.shape
mat = np.hstack((mat[:,:y], new_matrix, mat[:,y:]))
print(a_matrix2[i])
print("igual")
positions.append(y)
if variable_contraints[i] == ">=":
new_matrix = np.asmatrix(np.zeros(size))
new_matrix[0,i]=1
new_matrix1 = np.asmatrix(np.zeros(size))
new_matrix1[0,i]=-1
new_matrix.shape = (size,1)
new_matrix1.shape = (size,1)
x, y = mat.shape
mat = np.hstack((mat[:,:y], new_matrix, mat[:,y:]))
mat = np.hstack((mat[:,:y+1], new_matrix1, mat[:,y+1:]))
print(a_matrix2[i])
print("mayor")
positions.append(y)
#print(variable_contraints[i])
#print(variable_contraints[0])
print(mat)
#Numero de columnas en la matriz
num_cols = mat.shape[1]
print(num_cols)
print(positions)
# +
"""
Aquí es la orquetastación principal, porque aquí es donde se miden el número de filas y columnas que tendrá la tableau.
Así mismo se inicializa el algoritmo simplex de manera explícita. También se le indica si es un problema tipo Min o Max.Luego
empieza a buscar los puntos pivote, apoyándose de la eliminación gaussiana.
Más adelante han sido definidas dos funciones: una de maximización, donde se le envía la palabra 'MAX' y esta función
reconoce que tiene que resolver una maximización. La otra función es de minimización, que envía la palabra 'MIN'
lo que significa que se requiere de una minimización.
Estas palabras permiten que el algoritmo prepare la tableau según lo requiere la maximización y la minimización, porque
ambos tienen una resolución distinta.
"""
def simplex(of,basis,tableau,opt):
# Obtiene el número de filas y columnas que tiene la tableau
n_rows = tableau.shape[0]
n_cols = tableau.shape[1]
if opt =='MIN':
# Inicia el algoritmo simplex
# Calcula zj-cj. Si cj - zj >= 0 para todas las columnas, entonces la solución actual es la solución óptima.
check = of - np.sum(np.reshape(of[list(basis)],(n_rows,1)) * tableau[:,0:n_cols-1],axis=0)
else:
# Inicia el algoritmo simplex
# Calcula cj-zj. Si zj - cj >= 0 para todas las columnas, entonces la solución actual es la solución óptima.
check = np.sum(np.reshape(of[list(basis)],(n_rows,1)) *tableau[:,0:n_cols-1],axis=0) - of
count = 0
while ~np.all(check >=0):
print(check)
# Determina la columna pivote: La columna pivotante es la columna correspondiente al mínimo zj-cj.
pivot_col = np.argmin(check)
# Determinar los elementos positivos en la columna pivote. Si no hay elementos positivos en la columna pivote,
# entonces la solución óptima no tiene límites.
positive_rows = np.where(tableau[:,pivot_col] > 0)[0]
if positive_rows.size == 0:
print('*******SOLUCIÓN SIN LÍMITES******')
break
# Determinar la hilera de pivote: prueba de min-ration
divide=(tableau[positive_rows,n_cols-1]
/tableau[positive_rows,pivot_col])
pivot_row = positive_rows[np.where(divide
== divide.min())[0][-1]]
# Actualizar las bases
basis[pivot_row] = pivot_col
# Realizar la eliminación gaussiana para hacer girar el elemento uno y los elementos por encima y por debajo del cero:
tableau[pivot_row,:]=(tableau[pivot_row,:]
/tableau[pivot_row,pivot_col])
for row in range(n_rows):
if row != pivot_row:
tableau[row,:] = (tableau[row,:]
- tableau[row,pivot_col]*tableau[pivot_row,:])
if opt =='MIN':
check = of - np.sum(np.reshape(of[list(basis)],(n_rows,1)) * tableau[:,0:n_cols-1],axis=0)
else:
check = np.sum(np.reshape(of[list(basis)],(n_rows,1)) *tableau[:,0:n_cols-1],axis=0) - of
count += 1
print('Paso %d' % count)
print(tableau)
return basis,tableau
def get_solution(of,basis,tableau):
# Obtiene el número de columnas de la tableau
n_cols = tableau.shape[1]
# Obtener la solución óptima
solution = np.zeros(of.size)
solution[list(basis)] = tableau[:,n_cols-1]
# Determinar el valor óptimo
value = np.sum(of[list(basis)] * tableau[:,n_cols-1])
return solution,value
# +
"""
Esta función es muy importante, ya que permite ingresar variables artificiales si son necesarias. Los símbolos que requieren
que se añadan variables artificiales son los signos de >=. El símbolo == requiere una variable artificial en vez de una de
holgura, el signo >= requiere de una variable artificial 1 y de una variable de holgura -1.
"""
n_b_vector = []
for i in b_vector:
list1 = [i]
n_b_vector.append(list1)
#Esta es la matriz que si sirve
matrix_mat = np.concatenate((mat, n_b_vector),axis =1)
print(matrix_mat)
# +
print(variable_contraints)
def check_availability(element, collection: iter):
return element in collection
verificar_menoresque = check_availability('<=', variable_contraints)
print(verificar_menoresque)
verificar_mayoresque = check_availability('>=', variable_contraints)
print(verificar_mayoresque)
verificar_igualesque = check_availability('==', variable_contraints)
print(verificar_igualesque)
# +
"""
Esta función es utilizado por la maximización, por eso aquí se añaden los coeficientes de la función objetivo, y se añaden
la misma cantidad de ceros que las variables de holgura, por ejemplo si se añadieron 3 variables de holgura, esta identifica
que tiene que añadir 3 ceros. Pero si se añaden variables de holgura y artifiales, la suma de estas será la cantidad de ceros
que se añadan.
"""
matrix_cero = []
size_ceros = num_cols - no_variables
print(size_ceros)
for i in range(size_ceros):
matrix_cero.append(0)
print(matrix_cero)
objective_matrix = np.concatenate((c_vector, matrix_cero), axis=0)
print(objective_matrix )
# +
"""
Esta función la hemos colocado, ya que nuestro algoritmo requiere que se le indican las variables de holgura, las cuales
son la base de la resolución del caso. Este array con bases es importante para el buen funcionamiento de los pivotes,
ya que si no se le dice explícitamente cuáles son las bases, sería difícil para nuestro algoritmo determinar cuál columna
sale y cuál fila entra.
"""
array_con_bases = []
numero_base = no_variables
for item in range(no_restricciones):
array_con_bases.append(item + numero_base)
print(array_con_bases)
# +
"""
Esta es la función de maximización. Nos hemos fijado que la maximización requieres que los coeficientes de la función objetivo
no sean negativos, por eso se le manda explícitamente a la función simplex la palabra 'MAX' que identifica la maximización.
Eso permite que se diferencie la minimización con la maximización, y haga el procedimiento adecuado según lo requiera
cada caso.
"""
#def max_function():
# Definir la tableau:
tableau = np.array(matrix_mat)
print(tableau)
# Define la función objetivo y las bases iniciales
print(objective_matrix)
of = np.array(objective_matrix)
# bases iniciales
#basis = np.array([4,5,6])
basis = np.array(array_con_bases)
# Correr el algorithm simplex
basis,tableau = simplex(of,basis,tableau,'MAX')
# Obtener la solución óptima
optimal_solution,optimal_value = get_solution(of,basis,tableau)
# Imprimir al tableau final.
print('La base final es:')
print(basis)
print('solución')
for i in range(len(optimal_solution)):
print('X%d'%(i+1),'=',optimal_solution[i])
print('Z=',optimal_value)
#max_function()
# -
print(optimal_value)
contador_enteros_x = 0
for i in range(no_variables):
check_int = isinstance(optimal_solution[i], int)
print(check_int)
if check_int == True:
contador_enteros_x+=1
if contador_enteros_x == no_variables:
print("todos enteros")
else:
print("No todos son enteros")
# +
greater = 0
for i in optimal_solution:
if [i]>greater:
greater = optimal_solution[i]
print(greater)
#n_b_vector = []
#for i in b_vector:
# list1 = [i]
# n_b_vector.append(list1)
# +
arra_posibles_int = []
convert_int = math.modf(optimal_value)
print(convert_int)
try:
val = int(optimal_value)
print("Z is an integer number. Number = ", val)
except ValueError:
try:
val = float(optimal_value)
print("Z is a float number. Number = ", val)
except ValueError:
print("No... Z is not a number. It's a string")
# -
# """
# Debido a que solo se harán maximizaciones, dejamos solo el código para realizar estas
#
# Al mismo tiempo, imprime la la solución optimizada.
# """
#
# print("==== MAXIMIZACION ====")
# max_function()
| Proyecto 05/Proyecto_5 - sin aprox.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Visualization of pre-generated images.
# This is a notebook to load and display pre-generated images used in parameter exploration.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.image as mpimg
# Widgets library
from ipywidgets import interact
# %matplotlib inline
# We need to load all the files here
# Load the file
folder = '../results/'
name = 'parameter_swep_SLM-0.00-0.00-10.00.png'
file_name = folder + name
image = mpimg.imread(file_name)
# Now let's plot it
figsize = (16, 12)
figure = plt.figure(figsize=figsize)
ax = figure.add_subplot(1, 1, 1)
ax.set_axis_off()
ax.imshow(image)
# ### Now we need to build a function that takes distance, base and value as a parameter and returns the the SLE, STDM, Visualize Cluster Matrix.
def load_SLM(base, distance, value):
# Load the image
folder = '../results/'
name = 'parameter_swep_SLM'
parameter_marker = '-{0:4.2f}-{1:4.2f}-{2:4.2f}'.format(base, distance, value)
file_name = folder + name + parameter_marker + '.png'
image = mpimg.imread(file_name)
# Plot
figsize = (16, 12)
figure = plt.figure(figsize=figsize)
ax = figure.add_subplot(1, 1, 1)
ax.set_axis_off()
ax.imshow(image)
def load_STDM(base, distance, value):
folder = '../results/'
name = 'parameter_swep_STDM'
parameter_marker = '-{0:5.2f}-{1:5.2f}-{2:5.2f}'.format(base, distance, value)
file_name = folder + name + parameter_marker + '.png'
image = mpimg.imread(file_name)
# Plot
figsize = (16, 12)
figure = plt.figure(figsize=figsize)
ax = figure.add_subplot(1, 1, 1)
ax.set_axis_off()
ax.imshow(image)
def load_cluster(distance, base, value):
folder = '../results/'
name = 'parameter_swep_cluster'
parameter_marker = '-{0:5.2f}-{1:5.2f}-{2:5.2f}'.format(base, distance, value)
file_name = folder + name + parameter_marker + '.png'
image = mpimg.imread(file_name)
# Plot
figsize = (16, 12)
figure = plt.figure(figsize=figsize)
ax = figure.add_subplot(1, 1, 1)
ax.set_axis_off()
ax.imshow(image)
def load_cluster_SLM(base, distance, value):
folder = '../results/'
name = 'parameter_swep_cluster_SLM'
parameter_marker = '-{0:5.2f}-{1:5.2f}-{2:5.2f}'.format(base, distance, value)
file_name = folder + name + parameter_marker + '.png'
image = mpimg.imread(file_name)
# Plot
figsize = (16, 12)
figure = plt.figure(figsize=figsize)
ax = figure.add_subplot(1, 1, 1)
ax.set_axis_off()
ax.imshow(image)
# ## Now we build the widget for each exploration
interact(load_SLM, base=(0, 200, 40), distance=(0, 601, 40), value=(10, 200, 38))
interact(load_STDM, base=(0, 200, 40), distance=(0, 601, 40), value=(10, 200, 38))
interact(load_cluster, base=(0, 200, 40), distance=(0, 601, 40), value=(10, 200, 38))
interact(load_cluster_SLM, base=(0, 200, 40), distance=(0, 601, 40), value=(10, 200, 38))
| presentations/2015-10-27(Visualization of pre-generated images).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="el9TLbo3dgYs"
# 
#
# [](https://colab.research.google.com/github/JohnSnowLabs/nlu/blob/master/examples/colab/component_examples/chunking/NLU_n-gram.ipynb)
#
# # Getting n-Grams with NLU
# N-Grams are subsequences of text with N tokens.
# Some of their applications are used for auto completion of sentences, auto spell check and grammar check.
# In general they are als overy useful for gaining insight about a text dataset.
#
# Examples of n-grams :
# 1. Hello world (is a 2 gram)
# 2. I like peanutbutter (is a 3 gram)
# 3. I like peanutbutter and jelly ( is a 5 gram)
#
#
#
#
#
#
# # 1. Install Java and NLU
# + id="M2-GiYL6xurJ"
import os
# ! apt-get update -qq > /dev/null
# Install java
# ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"]
# ! pip install nlu pyspark==2.4.7 > /dev/null
# + [markdown] id="Gph8XOL1Pzpl"
# # 2. Load pipeline and predict on sample data
#
# By default NLU is configured to get 2 grams
# + id="pmpZSNvGlyZQ" colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"status": "ok", "timestamp": 1604911099432, "user_tz": -60, "elapsed": 101017, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjqAD-ircKP-s5Eh6JSdkDggDczfqQbJGU_IRb4Hw=s64", "userId": "14469489166467359317"}} outputId="2f495561-21cd-40ac-aec0-91ae5ae8e21e"
import nlu
example_text = ["A person like Jim or Joe",
"An organisation like Microsoft or PETA",
"A location like Germany",
"Anything else like Playstation",
"Person consisting of multiple tokens like <NAME> or <NAME>",
"Organisations consisting of multiple tokens like <NAME>",
"Locations consiting of multiple tokens like Los Angeles",
"Anything else made up of multiple tokens like Super Nintendo",]
pipe = nlu.load('ngram')
pipe.predict(example_text)
# + [markdown] id="fvWCtpHCwOYz"
# ## Configure the Ngram with custom parameters
# Use the pipe.print_info() to see all configurable parameters and infos about them for every NLU component in the pipeline pipeline.
# Even tough only 'ngram' is loaded, many NLU component dependencies are automatically loaded into the pipeline and also configurable.
#
#
# By default the n-gram algorithm is configured with n=2
# + id="j2ZZZvr1uGpx" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1604911102001, "user_tz": -60, "elapsed": 103579, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjqAD-ircKP-s5Eh6JSdkDggDczfqQbJGU_IRb4Hw=s64", "userId": "14469489166467359317"}} outputId="6ca6f6f3-0767-47b7-9527-78b8e09dbb65"
pipe.print_info()
# Lets configure the NGRAM to get get us 5grams
pipe['ngram'].setN(5)
# Now we can predict with the configured pipeline
pipe.predict("Jim and Joe went to the market next to the town hall")
# + id="JJaMftSyhtYj"
| examples/colab/component_examples/chunkers/NLU_n-gram.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .sos
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: SoS
# language: sos
# name: sos
# ---
# + [markdown] kernel="SoS"
# # Forced Alignment Notes for Southpark TTS Data
#
# The purpose of this notebook is to record some of the exploration around the topic of forced aligment for these data.
#
# For a full description of the steps leading up to generating wav files and srt files, see the main notebook.
# + [markdown] kernel="SoS"
# ## CCAligner
#
# One tool specifically designed to work with subtitle data is [CCAligner](https://github.com/saurabhshri/CCAligner/blob/master/README.adoc).
#
# ### CCAligner: Single file example
#
# See main notebook for running large batches
# + kernel="Bash"
cd "/vm/CCAligner/install"
echo "In $PWD"
#-audioWindow 500 -searchWindow 6 -useBatchMode yes
./ccaligner -wav /y/south-park-1-to-20/1-1.wav -srt /y/south-park-1-to-20/1-1.srt -oFormat json >> ccalign.log 2>&1
# + [markdown] kernel="Bash"
# ### CCAligner: Evaluations
#
#
# #### Comparison to SRT
#
# We load up SRT and CCAligner outputs for the same disc and evaluate the times:
#
# - Subtitle times (when it appears and disappears); compare across SRT and CCAligner
# - Number of words recognized (only in CCAligner)
# - Word alignment times (only in CCAligner)
#
# Comparison between SRT and CCAligner times is approximate b/c ccaligner changes strings.
# Some strings will not be matched at all (missing at random?); some repeated strings will be matched in the wrong location (false difference).
# + kernel="ifsharp"
#r "/z/aolney/repos/Newtonsoft.Json.9.0.1/lib/net40/Newtonsoft.Json.dll"
type Word =
{
word : string
recognised : int //logical 1/0
start : int
``end`` : int
duration : int
}
type Subtitle =
{
subtitle : string
edited_text : string
start : int
``end`` : int
words: Word[]
}
override x.ToString() = x.edited_text + "-" + x.start.ToString() + ":" + x.``end``.ToString()
type CCAligned =
{
subtitles : Subtitle[]
}
///The CCAligned json is invalid; we must fix unescaped quotes and put commas b/w objects
let FixCCAlignedJSON filePath =
let json =
filePath
|> System.IO.File.ReadAllLines
|> Seq.map( fun line -> line.Replace("} {","}, {"))
|> Seq.map( fun line -> line.Replace("}\t{","}, {")) //new version of json.net requires
|> Seq.map( fun line -> line.Replace("\\","")) //bad escape sequences - bad OCR?
|> Seq.map( fun line ->
let fieldIndex = line.IndexOf(":")
if fieldIndex > 0 then
let propertyString = line.Substring(fieldIndex+1)
if propertyString.Contains("\"") then
line.Substring(0,fieldIndex + 1) + "\"" + propertyString.Trim([|' ';'"';','|]).Replace("\"","\\\"") + "\","
else
line
else
line
)
//System.IO.File.WriteAllLines( filePath + ".corrected",json )
//let correctedJson = System.IO.File.ReadAllText( filePath + ".corrected" )
let ccAligned = Newtonsoft.Json.JsonConvert.DeserializeObject<CCAligned>(json |> String.concat "\n" ) //correctedJson)
//
ccAligned
let SrtStringToTime( timeString ) =
System.TimeSpan.ParseExact(timeString, @"hh\:mm\:ss\,fff", null).TotalMilliseconds
let blankLinesRegex = new System.Text.RegularExpressions.Regex("\n\n+")
let RegexSplit (regex : System.Text.RegularExpressions.Regex) (input:string) = regex.Split( input )
let SubtitlesFromSRT filePath =
( filePath |> System.IO.File.ReadAllText).Trim()
|> RegexSplit blankLinesRegex
//Split([|"\n\n"|],System.StringSplitOptions.None)
|> Array.map(fun block ->
let blockLines = block.Split('\n')
if blockLines.[1].Contains( " --> ") |> not then
System.Console.WriteLine()
let startEnd = blockLines.[1].Replace( " --> ", " ").Trim().Split(' ')
let start = startEnd.[0] |> SrtStringToTime |> int
let stop = startEnd.[1] |> SrtStringToTime |> int
let subtitle = blockLines |> Array.skip 2 |> String.concat " "
{ subtitle = subtitle ; edited_text = ""; start = start; ``end`` = stop ; words = [||]}
)
let CompareSrtAndCCAlign srtDirectory alignedDirectory =
let fileTuples =
Seq.zip
( System.IO.Directory.GetFiles(srtDirectory, "*.srt") |> Seq.sort )
( System.IO.Directory.GetFiles(alignedDirectory, "*.json") |> Seq.sort )
//this is approximate b/c ccAligner changes the text slightly for some subtitles
let srtCCAlignSubtitleCorrespondence =
fileTuples
|> Seq.collect( fun (srtFile,alignedFile) ->
let srtMap = srtFile |> SubtitlesFromSRT |> Seq.groupBy( fun subtitle -> subtitle.subtitle ) |> Map.ofSeq
let ccAligned = alignedFile |> FixCCAlignedJSON
ccAligned.subtitles
|> Seq.choose( fun aSubtitle ->
match srtMap.TryFind( aSubtitle.subtitle ) with
| Some( subSequence ) ->
let closestSubtitleToSRT =
subSequence
|> Seq.sortBy( fun s -> System.Math.Abs( aSubtitle.start - s.start ) )
|> Seq.head
let isMatch,matchString =
if closestSubtitleToSRT.start = aSubtitle.start && closestSubtitleToSRT.``end`` = aSubtitle.``end`` then
true,"SAME"
else
false,"DIFF"
Some(
(isMatch, srtFile + "\t" + aSubtitle.edited_text + "\t" + aSubtitle.start.ToString() + "\t" + aSubtitle.``end``.ToString() + "\t" +
closestSubtitleToSRT.subtitle + "\t" + closestSubtitleToSRT.start.ToString() + "\t" + closestSubtitleToSRT.``end``.ToString() + "\t" + matchString)
)
| None -> None
)
)
System.IO.File.WriteAllLines( "srt-aligned-correspondence-" + System.DateTime.Now.ToString("s").Replace(" ","-").Replace(":","_") + ".tsv", srtCCAlignSubtitleCorrespondence |> Seq.map snd )
//Compare with default CCAlign
//CompareSrtAndCCAlign "/y/south-park-1-to-20/" "/y/south-park-1-to-20/ccalign-json-default"
//CompareSrtAndCCAlign "/y/south-park-1-to-20/" "/y/south-park-1-to-20/ccalign-json-audioWindow500"
//Count percentage of recognized words
let PercentRecognized alignedDirectory =
let words =
System.IO.Directory.GetFiles(alignedDirectory, "*.json")
|> Seq.collect( fun alignedFile ->
(alignedFile |> FixCCAlignedJSON).subtitles
|> Seq.collect( fun s -> s.words ) )
let totalWords = words |> Seq.length |> float
let recognizedWords = words |> Seq.sumBy( fun w -> w.recognised ) |> float
//
(recognizedWords/totalWords).ToString()
//Percent recognized; notebook output (crashes mono)
[
"default" ; PercentRecognized "/y/south-park-1-to-20/ccalign-json-default";
"audioWindow500" ; PercentRecognized "/y/south-park-1-to-20/ccalign-json-audioWindow500";
]
# + [markdown] kernel="Bash"
# ### CCAligner: Results
#
# 1. CCAligner's start/end at the subtitle level is not changed by audio parameters. So unless word timings are going to be used for alignment, CCAligner adds no value over SRT.
# 2. Listening to wav in Audacity at the start/end points of the word alignments indicate they are usually OK **when the word is recognized**; even still there is some clipping around words.
# 3. If the word is not recognized, the alignments are not good at all.
# 4. Percent correct words recognized
# - Using default settings on CCAligner (default + useBatchMode) gives 31% recognized words
# - Using audioWindow = 500 with useBatchMode gives 33% recognized words
# - The relative improvement between these settings is not clear
#
# **Overall, CCAligner seems marginally viable for South Park. It probably isn't better than using the SRT**
# + [markdown] kernel="Bash"
# # aeneas
#
# [aeneas](https://www.readbeyond.it/aeneas/) was investigated to see if it improved performance relative to CCAligner.
#
# Using aeneas required reformatting the srt file into a suitable text file.
# The code below creates a whole disc of text.
# This file was also used in later evaluations of whole disc text.
# + kernel="ifsharp"
//create plain text file from srt https://www.readbeyond.it/aeneas/docs/textfile.html#aeneas.textfile.TextFileFormat.PLAIN
let whiteSpaceRegex = System.Text.RegularExpressions.Regex("\s+")
let nonApostrophePunctRegex = System.Text.RegularExpressions.Regex("[^\w\s']")
let RemovePunctuation inputString =
whiteSpaceRegex.Replace( nonApostrophePunctRegex.Replace( inputString, " "), " " ).Trim()
let tagRegex = System.Text.RegularExpressions.Regex("<.*?>") //only acceptable b/c our subtitle markup is so simplistic it does not require CFG parser
let RemoveTags inputString =
whiteSpaceRegex.Replace( tagRegex.Replace( inputString, " "), " " ).Trim()
let lines =
("/y/south-park-1-to-20/1-1.srt" |> System.IO.File.ReadAllText).Trim().Split("\n\n")
|> Seq.map(fun block ->
let text =
block.Split("\n")
|> Seq.skip 2
|> String.concat " "
|> RemoveTags
text
)
System.IO.File.WriteAllLines("1-1.foraeneas", lines)
# + [markdown] kernel="ifsharp"
# ### aeneas: Whole Disc Example
# + kernel="Bash"
python -m aeneas.tools.execute_task \
/y/south-park-1-to-20/1-1.wav \
1-1.foraeneas \
"task_language=eng|os_task_file_format=json|is_text_type=plain" \
1-1.aeneas.json
# + [markdown] kernel="Bash"
# ### aeneas: Whole Disc Results
#
# Aeneas lost alignment by a minute or two into the whole disc.
# The first minute (real speech, not character voices) had good alignment.
#
# ### aeneas: Clip Evaluation, Strict SRT
#
# The first couple of utterances looked plausible though, so the evaluation was repeated using the following methodology:
#
# - Using SRT to get clip for alignment, where clip consists of multiple subtitles
# - Extract WAV file using the SRT clip boundaries
# - Use corresponding text of clip
#
# The first text block evaluated was
# ```
# AND NOW A FIRESIDE CHAT
# WITH THE CREATORS OF COMEDY CENTRAL'S SOUTH PARK
# MATT STONE AND TREY PARKER
# ```
# The second block was
# ```
# THEN I WAS LYING ON A TABLE
# AND THESE SCARY ALIENS WANTED TO OPERATE ON ME.
# AND THEY HAD BIG HEADS AND BIG BLACK EYES.
# DUDE, VISITORS!
# TOTALLY!
# WHAT?
# THAT WASN'T A DREAM, CARTMAN.
# THOSE WERE VISITORS!
# NO, IT WAS JUST A DREAM.
# MY MOM SAID SO.
# ```
#
# The third block was the same as the second but with one word per line
# + kernel="Bash"
python -m aeneas.tools.execute_task \
1-1-clip1.wav \
1-1-clip1.txt \
"task_language=eng|os_task_file_format=json|is_text_type=plain" \
1-1-clip1.json
python -m aeneas.tools.execute_task \
1-1-clip2.wav \
1-1-clip2.txt \
"task_language=eng|os_task_file_format=json|is_text_type=plain" \
1-1-clip2.json
python -m aeneas.tools.execute_task \
1-1-clip2.wav \
1-1-clip2words.txt \
"task_language=eng|os_task_file_format=json|is_text_type=plain" \
1-1-clip2words.json
# + [markdown] kernel="Bash"
# ### aeneas: Clip Results, Strict SRT
#
# - Clip 1: Reasonable for narrator speech. Was not that different from SRT boundaries, but was a little tighter on the ends
# - Clip 2: When given longer clip 'THEN - EYES', does a better job of finding the end boundary than the SRT; However, next turn is already off by one word.
# - Clip 2words: Had different errors than Clip 2, but was similarly off
#
# Based on these results, a reasonable question is whether we can "pad" the SRT boundaries and find some words within them.
# We call this "loose" SRT.
#
# ### aeneas: Clip Results, Loose SRT
#
# Using just the following text, with SRT times +/- 1s
#
# ```
# DUDE, VISITORS!
# TOTALLY!
# WHAT?
# ```
#
# And again, with SRT +/1 500ms
# + kernel="Bash"
python -m aeneas.tools.execute_task \
1-1-clip3.wav \
1-1-clip3.txt \
"task_language=eng|os_task_file_format=json|is_text_type=plain" \
1-1-clip3.json
python -m aeneas.tools.execute_task \
1-1-clip4.wav \
1-1-clip3.txt \
"task_language=eng|os_task_file_format=json|is_text_type=plain" \
1-1-clip4.json
# + [markdown] kernel="Bash"
# ### aeneas: Clip Results, Loose SRT
#
# - Clip 3: Was basically totally garbage
# - Clip 4: Same
#
# Looks like aeneas needs pretty clean audio to do the alignment.
#
# **Since SRT does not give perfect boundaries, and since we can't align a whole file with aeneas, it doesn't seem that aeneas can be used.**
#
# ## eesen-transcriber
#
# The [vagrant installation method](https://github.com/srvk/eesen-transcriber/blob/master/INSTALL.md) was used to simplify the installation.
# However, even with vagrant, the installation was fairly complex and required tweaking of various scripts.
# As a result, it's not clear if eesen was installed correctly, though spot checking suggests that the ASR was working correctly.
#
# Example usage for alignment is `vagrant ssh -c "align.sh /vagrant/1-1.wav"` with the corresponding STM file in the same directory as the wav (i.e. the vagrant directory). The STM was created [using the SRT file](https://git.capio.ai/pub/srt-to-stm-converter).
#
# ### eesen-transcriber: Whole disc results
#
# Even the begining was significantly shifted in time:
#
# ```
# 1-1-A---0005.610-0006.610 1 5.61 0.06 now
# 1-1-A---0005.610-0006.610 1 5.67 0.00 a
# 1-1-A---0005.610-0006.610 1 5.67 0.00 fireside
# 1-1-A---0005.610-0006.610 1 5.67 0.93 chat
# 1-1-A---0006.610-0008.610 1 6.61 0.03 the
# 1-1-A---0006.610-0008.610 1 6.64 0.06 creators
# ```
#
# When the kids start speaking, the alignments get very spotty:
#
# ```
# 1-1-A---0178.280-0179.780 1 178.31 0.00 my
# 1-1-A---0178.280-0179.780 1 178.31 0.21 little
# 1-1-A---0178.280-0179.780 1 178.52 1.26 brother's
# 1-1-A---0180.780-0183.280 1 180.78 0.06 <unk>
# 1-1-A---0180.780-0183.280 1 180.84 0.00 <unk>
# 1-1-A---0184.280-0186.780 1 184.28 0.09 he
# 1-1-A---0184.280-0186.780 1 184.37 0.33 <unk>
# 1-1-A---0184.280-0186.780 1 184.70 0.57 he
# 1-1-A---0184.280-0186.780 1 185.27 0.72 <unk>
# 1-1-A---0186.790-0188.790 1 186.79 0.84 <unk>
# 1-1-A---0188.790-0189.790 1 188.79 0.03 don't
# 1-1-A---0188.790-0189.790 1 188.82 0.15 call
# 1-1-A---0188.790-0189.790 1 188.97 0.09 my
# 1-1-A---0188.790-0189.790 1 189.06 0.60 brother
# ```
#
# Overall, eesen-transcriber does not seem viable for this project.
# + [markdown] kernel="Bash"
# # Gentle
#
# The [docker installation method](https://github.com/lowerquality/gentle) was used to reduce the effort of installation, but the run instructions had to be adapted to: `docker run -p 8765:8765 lowerquality/gentle`
#
# Example usage is `curl -F "audio=@audio.mp3" -F "transcript=@words.txt" "http://0.0.0.0:8765/transcriptions?async=false"`
#
# ### Gentle: parameters
#
# Additional parameters are `?async=false&disfluency=true&conservative=true`
#
# The meanings of these parameters appear to be
#
# > Use the given token sequence to make a bigram language model
# > in OpenFST plain text format.
# > When the "conservative" flag is set, an [oov] is interleaved
# > between successive words.
# > When the "disfluency" flag is set, a small set of disfluencies is
# > interleaved between successive words
# > `Word sequence` is a list of lists, each valid as a start
#
# ### Gentle: Whole disc example
# + kernel="Bash"
date
curl -F "audio=@/y/south-park-1-to-20/1-1.wav" -F "transcript=@1-1.foraeneas" "http://0.0.0.0:8765/transcriptions?async=false&disfluency=true&conservative=true" -o 1-1.gentle.json
date
# + [markdown] kernel="SoS"
# ### Gentle: Whole Disc Results
#
# Gentle was fairly excellent. Spot checking showed alignment was still good at minutes 23, 59, 1:14, 1:30, and 1:33.
#
# # Overall Results
#
# **Based on these results, it seems plausible to use Gentle for alignment at the whole disc level.**
#
# It does not appear necessary to manually check alignments if Gentle is used.
# However, tools like [finetuneas](https://github.com/ozdefir/finetuneas) that facilitate this process exist.
# + kernel="Bash"
| forced-alignment-comparison.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # So easy, *voilà*!
#
# In this example notebook, we demonstrate how voila can render custom Jupyter widgets such as [bqplot](https://github.com/bloomberg/bqplot).
# !pip install bqplot
import warnings
warnings.filterwarnings('ignore')
# +
import numpy as np
from bqplot import pyplot as plt
plt.figure(1, title='Line Chart')
np.random.seed(0)
n = 200
x = np.linspace(0.0, 10.0, n)
y = np.cumsum(np.random.randn(n))
plt.plot(x, y)
plt.show()
# -
| voila/notebooks/bqplot.ipynb |
;; ---
;; jupyter:
;; jupytext:
;; text_representation:
;; extension: .clj
;; format_name: light
;; format_version: '1.5'
;; jupytext_version: 1.14.4
;; kernelspec:
;; display_name: Clojure (clojupyter-v0.2.2-SNAPSHOT@2bad)
;; language: clojure
;; name: clojupyter
;; ---
;; # Clojupyter - Clojure in Jupyter Lab, Notebook, and Console
;; This notebook demonstrates some of the features of Clojupyter. Things that are shown here should work in both Jupyter Lab *and* Jupyter Notebook (and some of it in Jupyter Console as well, but since Clojure has the REPL we usually don't very much about Console).
;;
;; Jupyter Lab and Jupyter Notebook are different in some respects, this notebook only shows features that work in both. There are separate demo notebooks showing clojupyter's support for features that are specific to either Lab or Notebook.
;; ## Basics: Evaluating Clojure expressions
;;
;; Clojupyter basically lets you evaluate Clojure expressions from a Jupyter notebook, at its most fundament it is not unlike a regular Clojure REPL:
(time (reduce + (range 1000)))
;; Note above that we both see the side-effects of printing *and* the result of evaluating the expression. Let's see which version of Clojure and clojupyter we're using:
(println (str "Date:\t\t\t" (java.util.Date.)))
(println (apply format "Clojure version:\tv%d.%d" ((juxt :major :minor) *clojure-version*)))
(println (str "Clojupyter version:\t" (:formatted-version clojupyter/*version*)))
;
;; The **semicolon** at the end of the cell tells clojupyter not to print the result of evaluating the cell which is useful when we're only interested in side-effects such as loading libraries. In this instance the semicolon appears on its own line which is not necessary, as long as the semicolon is the last non-whitespace character it will have the effect of suppressing printing of the cell evaluation result.
;; ## Rich content at your fingertips
;; We can use [Hiccup](https://github.com/weavejester/hiccup) to render HTML. To do this conveniently, we first add convenient access to the `clojupyter.display` namespace usng the alias `display`:
(require '[clojupyter.display :as display])
;; which gives us convenient access to generating formatted output using HTML:
;; displaying html
(display/hiccup-html
[:ul
[:li "a " [:i "emphatic"] " idea"]
[:li "a " [:b "bold"] " idea"]
[:li "an " [:span {:style "text-decoration: underline;"} "important"] " idea"]])
;; which works for Scalable Vector Graphics (SVG) as well:
(display/hiccup-html
[:svg {:height 100 :width 100 :xmlns "http://www.w3.org/2000/svg"}
[:circle {:cx 50 :cy 40 :r 40 :fill "red"}]])
;; We also have direct access to displaying bitmaps, here a clokupyter logo:
(->> clojupyter/*logo* type (str "Logo is of type: ") println)
clojupyter/*logo*
;; Overall, we have very direct access to controlling what is displayed buy Jupyter:
(display/render-mime "text/plain" "This is plain text.")
(display/render-mime "text/html" "<h1>This is a heading</h1>")
;; And we have all the facilities of Clojure at our disposal for generating the content in the notebook!
;; ## Using external Clojure libraries
;; You can fetch external Clojure dependencies using `add-dependencies` in the namespace `clojupyter.misc.helper`:
(require '[clojupyter.misc.helper :as helper])
(helper/add-dependencies '[incanter "1.5.7"])
(use '(incanter core stats charts io)) ; include Incanter's facilities into working namespace
:ok
;; ## Example: Plotting using Incanter
;;
;; As shown above, clojupyter display bitmaps directly when [BufferedImage](https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html) are returned. This makes it easy to use Java charting libraries, such as [Incanter](https://github.com/incanter/incanter), where charts are easily converted into a bitmaps. Since Incanter simply wraps the Java charting library [JFreeChart](https://github.com/incanter/incanter), we can call
;; `(.createBufferedImage chart width height)` on any Incanter chart to get an image we can render as cell output:
(-> (sample-normal 10000)
histogram
(.createBufferedImage 600 400))
;; Here's an example of a scatter plot:
(-> (scatter-plot (sample-normal 1000)
(sample-normal 1000)
:x-label "x" :y-label "y")
(.createBufferedImage 600 400))
;; + active=""
;; See the other demo notebooks to see features specific to either Jupyter Lab or Jupyter Notebook.
;; -
;; And with a very liberal license, you can do pretty much whatever you want with clojupyter:
clojupyter/*license*
;; **We hope you'll enjoy clojupyter!**
| examples/demo-clojupyter.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import time
from lib.ev3 import EV3
# センサーとモーターの通信ポートを定義
touch_port = EV3.PORT_2
lmotor_port = EV3.PORT_B
rmotor_port = EV3.PORT_C
# センサーとモーターの設定
ev3 = EV3()
ev3.motor_config(lmotor_port, EV3.LARGE_MOTOR)
ev3.motor_config(rmotor_port, EV3.LARGE_MOTOR)
ev3.sensor_config(touch_port, EV3.TOUCH_SENSOR)
# タッチセンサーを押したらスタート
print("Push touch sensor to run your EV3.")
while not ev3.touch_sensor_is_pressed(touch_port):
pass
print("Go!")
# 1
ev3.motor_steer(lmotor_port, rmotor_port, 30, 0)
time.sleep(2)
# 2
ev3.motor_steer(lmotor_port, rmotor_port, -30, 0)
time.sleep(2)
# 3
ev3.motor_steer(lmotor_port, rmotor_port, 30, -30)
time.sleep(2)
# 4
ev3.motor_steer(lmotor_port, rmotor_port, -30, -30)
time.sleep(2)
# 5
ev3.motor_steer(lmotor_port, rmotor_port, 30, 30)
time.sleep(2)
# 6
ev3.motor_steer(lmotor_port, rmotor_port, -30, 30)
time.sleep(2)
print("Stop.")
ev3.motor_steer(lmotor_port, rmotor_port, 0, 0)
ev3.close()
# -
| workspace/basic_go_back_and_forth.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Reconocimiento Facial
from sklearn.datasets import fetch_lfw_people
import matplotlib.pyplot as plt
faces = fetch_lfw_people(min_faces_per_person=60)
print(faces.target_names)
print(faces.images.shape)
fig, ax = plt.subplots(5,5, figsize=(16,9))
for i, ax_i in enumerate(ax.flat):
ax_i.imshow(faces.images[i], cmap="bone")
ax_i.set(xticks=[], yticks=[],xlabel=faces.target_names[faces.target[i]])
62*47
from sklearn.svm import SVC
from sklearn.decomposition import RandomizedPCA
from sklearn.pipeline import make_pipeline
pca = RandomizedPCA(n_components=150, whiten=True, random_state=42)
svc = SVC(kernel="rbf", class_weight="balanced")
model = make_pipeline(pca, svc)
from sklearn.cross_validation import train_test_split
Xtrain, Xtest, Ytrain, Ytest = train_test_split(faces.data, faces.target, random_state = 42)
from sklearn.grid_search import GridSearchCV
# +
param_grid = {
"svc__C":[0.1,1,5,10,50],
"svc__gamma":[0.0001, 0.0005, 0.001, 0.005, 0.01]
}
grid = GridSearchCV(model, param_grid)
# %time grid.fit(Xtrain, Ytrain)
# -
print(grid.best_params_)
classifier = grid.best_estimator_
yfit = classifier.predict(Xtest)
# +
fig, ax = plt.subplots(8,6,figsize=(16,9))
for i, ax_i in enumerate(ax.flat):
ax_i.imshow(Xtest[i].reshape(62,47), cmap="bone")
ax_i.set(xticks=[], yticks=[])
ax_i.set_ylabel(faces.target_names[yfit[i]].split()[-1],
color = "black" if yfit[i]==Ytest[i] else "red")
fig.suptitle("Predicciones de las imágnes (incorrectas en rojo)", size = 15)
# -
from sklearn.metrics import classification_report
print(classification_report(Ytest, yfit, target_names = faces.target_names))
from sklearn.metrics import confusion_matrix
mat = confusion_matrix(Ytest, yfit)
import seaborn as sns; sns.set()
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=True,
xticklabels=faces.target_names, yticklabels=faces.target_names )
| notebooks/T8 - 4 - SVM - Face Recognition.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import scipy as sp
import scipy.stats
import matplotlib.pyplot as plt
import math as mt
import scipy.special
import seaborn as sns
plt.style.use('fivethirtyeight')
from statsmodels.graphics.tsaplots import plot_acf
import pandas as pd
# # <font face="gotham" color="orange"> Markov Chain Monte Carlo </font>
# The **Markov Chain Monte Carlo** (**MCMC**) is a class of algorithm to simulate a distribution that has no closed-form expression. To illustrate the mechanism of MCMC, we resort to the example of Gamma-Poisson conjugate.
#
# Though it has a closed-form expression of posterior, we can still simulate the posterior for demonstrative purpose.
#
# To use MCMC, commonly the Bayes' Theorem is modified without affecting the final result.
# $$
# P(\lambda \mid y) \propto P(y \mid \lambda) P(\lambda)
# $$
# where $\propto$ means proportional to, the integration in the denominator can be safely omitted since it is a constant.
#
# Here we recap the example of hurricanes in the last chapter. The prior elicitation uses
# + [markdown] tags=[]
#
# $$
# E(\lambda) = \frac{\alpha}{\beta}\\
# \text{Var}(\lambda) = \frac{\alpha}{\beta^2}
# $$
# +
x = np.linspace(0, 10, 100)
params = [10, 2]
gamma_pdf = sp.stats.gamma.pdf(x, a=params[0], scale=1/params[1])
fig, ax = plt.subplots(figsize=(7, 7))
ax.plot(x, gamma_pdf, lw = 3, label = r'$\alpha = %.1f, \beta = %.1f$' % (params[0], params[1]))
ax.set_title('Prior')
mean = params[0]/params[1]
mode = (params[0]-1)/params[1]
ax.axvline(mean, color = 'tomato', ls='--', label='mean: {}'.format(mean))
ax.axvline(mode, color = 'red', ls='--', label='mode: {}'.format(mode))
ax.legend()
plt.show()
# -
# 1. Because posterior will also be Gamma distribution, we start from proposing a value drawn from posterior
# $$
# \lambda = 8
# $$
# This is an arbitrary value, which is called the **initial value**.
# 2. Calculate the likelihood of observing $k=3$ hurricanes given $\lambda=8$.
# $$
# \mathcal{L}(3 ; 8)=\frac{\lambda^{k} e^{-\lambda}}{k !}=\frac{8^{3} e^{-8}}{3 !}=0.1075
# $$
def pois_lh(k, lamda):
lh = lamda**k*np.exp(-lamda)/mt.factorial(k)
return lh
lamda_init = 8
k = 3
pois_lh(k = k, lamda = lamda_init)
# 3. Calculate prior
# $$
# g(\lambda ; \alpha, \beta)=\frac{\beta^{\alpha} \lambda^{\alpha-1} e^{-\beta \lambda}}{\Gamma(\alpha)}
# $$
def gamma_prior(alpha, beta, lamda):
prior = (beta**alpha*lamda**(alpha-1)*np.exp(-beta*lamda))/sp.special.gamma(alpha)
return prior
lamda_current = lamda_init
alpha=10
beta=2
gamma_prior(alpha=alpha, beta=beta, lamda=lamda_current)
# 4. Calculate the posterior with the first guess $\lambda=8$ and we denote it as $\lambda_{current}$
k=3
posterior_current = pois_lh(k=k, lamda=lamda_current) * gamma_prior(alpha=10, beta=2, lamda=lamda_current)
posterior_current
# 5. Draw a second value $\lambda_{proposed}$ from a **proposal distribution** with $\mu=\lambda_{current}$ and $\sigma = .5$. The $\sigma$ here is called **tuning parameter**, which will be clearer in following demonstrations.
tuning_param = .5
lamda_prop = sp.stats.norm(loc=lamda_current, scale=tuning_param).rvs()
lamda_prop
# 6. Calculate posterior based on the $\lambda_{proposed}$.
posterior_prop = gamma_prior(alpha, beta, lamda=lamda_prop)*pois_lh(k, lamda=lamda_prop)
posterior_prop
# 7. Now we have two posteriors. To proceed, we need to make some rules to throw one away. Here we introduce the **Metropolis Algorithm**. The probability threshold for accepting $\lambda_{proposed}$ is
# $$
# P_{\text {accept }}=\min \left(\frac{P\left(\lambda_{\text {proposed }} \mid \text { data }\right)}{P\left(\lambda_{\text {current }} \mid \text { data }\right)}, 1\right)
# $$
print(posterior_current)
print(posterior_prop)
prob_threshold = np.min([posterior_prop/posterior_current, 1])
prob_threshold
# It means the probability of accepting $\lambda_{proposed}$ is $1$. What if the smaller value is $\frac{\text{posterior proposed}}{\text{posterior current}}$, let's say $\text{prob_threshold}=.768$. The algorithm requires a draw from a uniform distribution, if the draw is smaller than $.768$, go for $\lambda_{proposed}$ if larger then stay with $\lambda_{current}$.
# 8. The demonstrative algorithm will be
if sp.stats.uniform.rvs() > .768:
print('stay with current lambda')
else:
print('accept next lambda')
# 9. If we accept $\lambda_{proposed}$, redenote it as $\lambda_{current}$, then repeat from step $2$ for thousands of times.
# ## <font face="gotham" color="orange"> Combine All Steps </font>
# We will join all the steps in a loop for thousands of times (the number of repetition depends on your time constraint and your computer's capacity).
def gamma_poisson_mcmc(lamda_init = 2, k = 3, alpha = 10, beta= 2, tuning_param = 1, chain_size = 10000):
np.random.seed(123)
lamda_current = lamda_init
lamda_mcmc = []
pass_rate = []
post_ratio_list = []
for i in range(chain_size):
lh_current = pois_lh(k = k, lamda = lamda_current)
prior_current = gamma_prior(alpha=alpha, beta=beta, lamda=lamda_current)
posterior_current = lh_current*prior_current
lamda_proposal = sp.stats.norm(loc=lamda_current, scale=tuning_param).rvs()
prior_next = gamma_prior(alpha=alpha, beta=beta, lamda=lamda_proposal)
lh_next = pois_lh(k, lamda=lamda_proposal)
posterior_proposal = lh_next*prior_next
post_ratio = posterior_proposal/posterior_current
prob_next = np.min([post_ratio, 1])
unif_draw = sp.stats.uniform.rvs()
post_ratio_list.append(post_ratio)
if unif_draw < prob_next:
lamda_current = lamda_proposal
lamda_mcmc.append(lamda_current)
pass_rate.append('Y')
else:
lamda_mcmc.append(lamda_current)
pass_rate.append('N')
return lamda_mcmc, pass_rate
# The proposal distribution must be symmetrical otherwise the Markov chain won't reach an equilibrium distribution. Also the tuning parameter should be set at a value which maintains $30\%\sim50\%$ acceptance.
lamda_mcmc, pass_rate = gamma_poisson_mcmc(chain_size = 10000)
# +
yes = ['Pass','Not Pass']
counts = [pass_rate.count('Y'), pass_rate.count('N')]
x = np.linspace(0, 10, 100)
params_prior = [10, 2]
gamma_pdf_prior = sp.stats.gamma.pdf(x, a=params_prior[0], scale=1/params_prior[1])
# -
# We assume $1$ year, the data records in total $3$ hurricanes. Obtain the analytical posterior, therefore we can compare the simulation and the analytical distribution.
# \begin{align}
# \alpha_{\text {posterior }}&=\alpha_{0}+\sum_{i=1}^{n} x_{i} = 10+3=13\\
# \beta_{\text {posterior }}&=\beta_{0}+n = 2+1=3
# \end{align}
# Prepare the analytical Gamma distribution
params_post = [13, 3]
gamma_pdf_post = sp.stats.gamma.pdf(x, a=params_post[0], scale=1/params_post[1])
# Because initial sampling might not converge to the equilibrium, so the first $1/10$ values of the Markov chain can be safely dropped. This $1/10$ period is termed as **burn-in** period. Also in order to minimize the _autocorrelation_ issue, we can perform **pruning** process to drop every other (or even five) observation(s).
#
# That is why we use ```lamda_mcmc[1000::2]``` in codes below.
fig, ax = plt.subplots(figsize = (12, 12), nrows = 3, ncols = 1)
ax[0].hist(lamda_mcmc[1000::2], bins=100, density=True)
ax[0].set_title(r'Posterior Frequency Distribution of $\lambda$')
ax[0].plot(x, gamma_pdf_prior, label='Prior')
ax[0].plot(x, gamma_pdf_post, label='Posterior')
ax[0].legend()
ax[1].plot(np.arange(len(lamda_mcmc)), lamda_mcmc, lw=1)
ax[1].set_title('Trace')
ax[2].barh(yes, counts, color=['green', 'blue'], alpha=.7)
plt.show()
# # <font face="gotham" color="orange"> Diagnostics of MCMC </font>
# The demonstration above has been fine-tuned deliberately to circumvent potential errors, which are common in MCMC algorithm designing. We will demonstrate how it happens, what probable remedies we might possess.
# ## <font face="gotham" color="orange"> Invalid Proposal </font>
# Following the Gamma-Poisson example, if we have a proposal distribution with $\mu=1$, the random draw from this proposal distribution might be a negative number, however the posterior is a Gamma distribution which only resides in positive domain.
#
# The remedy of this type of invalid proposal is straightforward, multiply $-1$ onto all negative draws.
# +
x_gamma = np.linspace(-3, 12, 100)
x_norm = np.linspace(-3, 6, 100)
params_gamma = [10, 2]
gamma_pdf = sp.stats.gamma.pdf(x, a=params_gamma[0], scale=1/params_gamma[1])
mu = 1
sigma = 1
normal_pdf = sp.stats.norm.pdf(x, loc=mu, scale=sigma)
fig, ax = plt.subplots(figsize=(14, 7))
ax.plot(x, gamma_pdf, lw = 3, label = r'Prior $\alpha = %.1f, \beta = %.1f$' % (params[0], params[1]), color='#FF6B1A')
ax.plot(x, normal_pdf, lw = 3, label = r'Proposal $\mu=%.1f , \sigma= %.1f$' % (mu, sigma), color='#662400')
ax.text(4, .27, 'Gamma Prior', color ='#FF6B1A')
ax.text(1.7, .37, 'Normal Proposal', color ='#662400')
ax.text(.2, -.04, r'$\lambda_{current}=1$', color ='tomato')
x_fill = np.linspace(-3, 0, 30)
y_fill = sp.stats.norm.pdf(x_fill, loc=mu, scale=sigma)
ax.fill_between(x_fill, y_fill, color ='#B33F00')
ax.axvline(mu, color = 'red', ls='--', label=r'$\mu=${}'.format(mu), alpha=.4)
ax.legend()
plt.show()
# -
# Two lines of codes will solve this issue
# ```
# if lamda_proposal < 0:
# lamda_proposal *= -1
# ```
def gamma_poisson_mcmc_1(lamda_init = 2, k = 3, alpha = 10, beta= 2, tuning_param = 1, chain_size = 10000):
np.random.seed(123)
lamda_current = lamda_init
lamda_mcmc = []
pass_rate = []
post_ratio_list = []
for i in range(chain_size):
lh_current = pois_lh(k = k, lamda = lamda_current)
prior_current = gamma_prior(alpha=alpha, beta=beta, lamda=lamda_current)
posterior_current = lh_current*prior_current
lamda_proposal = sp.stats.norm(loc=lamda_current, scale=tuning_param).rvs()
if lamda_proposal < 0:
lamda_proposal *= -1
prior_next = gamma_prior(alpha=alpha, beta=beta, lamda=lamda_proposal)
lh_next = pois_lh(k, lamda=lamda_proposal)
posterior_proposal = lh_next*prior_next
post_ratio = posterior_proposal/posterior_current
prob_next = np.min([post_ratio, 1])
unif_draw = sp.stats.uniform.rvs()
post_ratio_list.append(post_ratio)
if unif_draw < prob_next:
lamda_current = lamda_proposal
lamda_mcmc.append(lamda_current)
pass_rate.append('Y')
else:
lamda_mcmc.append(lamda_current)
pass_rate.append('N')
return lamda_mcmc, pass_rate
# This time we can set chain size much larger.
lamda_mcmc, pass_rate = gamma_poisson_mcmc_1(chain_size = 100000, tuning_param = 1)
# As you can see the frequency distribution is also much smoother.
# +
y_rate = pass_rate.count('Y')/len(pass_rate)
n_rate = pass_rate.count('N')/len(pass_rate)
yes = ['Pass','Not Pass']
counts = [pass_rate.count('Y'), pass_rate.count('N')]
fig, ax = plt.subplots(figsize = (12, 12), nrows = 3, ncols = 1)
ax[0].hist(lamda_mcmc[int(len(lamda_mcmc)/10)::2], bins=100, density=True)
ax[0].set_title(r'Posterior Frequency Distribution of $\lambda$')
ax[0].plot(x, gamma_pdf_prior, label='Prior')
ax[0].plot(x, gamma_pdf_post, label='Posterior')
ax[0].legend()
ax[1].plot(np.arange(len(lamda_mcmc)), lamda_mcmc, lw=1)
ax[1].set_title('Trace')
ax[2].barh(yes, counts, color=['green', 'blue'], alpha=.7)
ax[2].text(counts[1]*.4, 'Not Pass', r'${}\%$'.format(np.round(n_rate*100,2)), color ='tomato', size = 28)
ax[2].text(counts[0]*.4, 'Pass', r'${}\%$'.format(np.round(y_rate*100,2)), color ='tomato', size = 28)
plt.show()
# -
# ## <font face="gotham" color="orange"> Numerical Overflow </font>
# If prior and likelihood are extremely close to $0$, the product would be even closer to $0$. This would cause storage error in computer due to the binary system.
#
# The remedy is to use the log version of Bayes' Theorem, i.e.
# $$
# \ln{P(\lambda \mid y)} \propto \ln{P(y \mid \lambda)}+ \ln{P(\lambda)}
# $$
# Also the acceptance rule can be converted into log version
# $$
# \ln{ \left(\frac{P\left(\lambda_{proposed } \mid y \right)}{P\left(\lambda_{current} \mid y \right)}\right)}
# =\ln{P\left(\lambda_{proposed } \mid y \right)} - \ln{P\left(\lambda_{current } \mid y \right)}
# $$
def gamma_poisson_mcmc_2(lamda_init = 2, k = 3, alpha = 10, beta= 2, tuning_param = 1, chain_size = 10000):
np.random.seed(123)
lamda_current = lamda_init
lamda_mcmc = []
pass_rate = []
post_ratio_list = []
for i in range(chain_size):
log_lh_current = np.log(pois_lh(k = k, lamda = lamda_current))
log_prior_current = np.log(gamma_prior(alpha=alpha, beta=beta, lamda=lamda_current))
log_posterior_current = log_lh_current + log_prior_current
lamda_proposal = sp.stats.norm(loc=lamda_current, scale=tuning_param).rvs()
if lamda_proposal < 0:
lamda_proposal *= -1
log_prior_next = np.log(gamma_prior(alpha=alpha, beta=beta, lamda=lamda_proposal))
log_lh_next = np.log(pois_lh(k, lamda=lamda_proposal))
log_posterior_proposal = log_lh_next + log_prior_next
log_post_ratio = log_posterior_proposal - log_posterior_current
post_ratio = np.exp(log_post_ratio)
prob_next = np.min([post_ratio, 1])
unif_draw = sp.stats.uniform.rvs()
post_ratio_list.append(post_ratio)
if unif_draw < prob_next:
lamda_current = lamda_proposal
lamda_mcmc.append(lamda_current)
pass_rate.append('Y')
else:
lamda_mcmc.append(lamda_current)
pass_rate.append('N')
return lamda_mcmc, pass_rate
# With the use of log posterior and acceptance rule, the numerical overflow is unlikely to happen anymore, which means we can set a much longer Markov chain and also a larger tuning parameter.
lamda_mcmc, pass_rate = gamma_poisson_mcmc_2(chain_size = 100000, tuning_param = 3)
# +
y_rate = pass_rate.count('Y')/len(pass_rate)
n_rate = pass_rate.count('N')/len(pass_rate)
yes = ['Pass','Not Pass']
counts = [pass_rate.count('Y'), pass_rate.count('N')]
fig, ax = plt.subplots(figsize = (12, 12), nrows = 3, ncols = 1)
ax[0].hist(lamda_mcmc[int(len(lamda_mcmc)/10)::2], bins=100, density=True)
ax[0].set_title(r'Posterior Frequency Distribution of $\lambda$')
ax[0].plot(x, gamma_pdf_prior, label='Prior')
ax[0].plot(x, gamma_pdf_post, label='Posterior')
ax[0].legend()
ax[1].plot(np.arange(len(lamda_mcmc)), lamda_mcmc, lw=1)
ax[1].set_title('Trace')
ax[2].barh(yes, counts, color=['green', 'blue'], alpha=.7)
ax[2].text(counts[1]*.4, 'Not Pass', r'${}\%$'.format(np.round(n_rate*100,2)), color ='tomato', size = 28)
ax[2].text(counts[0]*.4, 'Pass', r'${}\%$'.format(np.round(y_rate*100,2)), color ='tomato', size = 28)
plt.show()
# -
# Larger tuning parameter yields a lower pass ($30\%\sim50\%$) rate that is exactly what we are seeking for.
# ## <font face="gotham" color="orange"> Pruning </font>
# +
lamda_mcmc = np.array(lamda_mcmc)
n = 4
fig, ax = plt.subplots(ncols = 1, nrows = n ,figsize=(12, 10))
for i in range(1, n+1):
g = plot_acf(lamda_mcmc[::i], ax=ax[i-1], title='', label=r'$lag={}$'.format(i), lags=30)
fig.suptitle('Markov chain Autocorrelation')
plt.show()
# -
# # <font face="gotham" color="orange"> Gibbs Sampling Algorithm </font>
# The **Gibbs sampler** is a special case of the Metropolis sampler in which the proposal distributions exactly match the posterior conditional distributions and naturally proposals are accepted 100% of the time.
#
# However a specialty of Gibbs Sampler is that can allow one to estimate multiple parameters.
#
# In this section, we will use Normal-Normal conjugate priors to demonstrate the algorithm of Gibbs sampler.
# <div style="background-color:Bisque; color:DarkBlue; padding:30px;">
# Suppose you want to know the average height of female in your city, in the current setting, we assume $\mu$ and $\tau$ are our parameters of interest for estimation. Note that in conjugate prior section we assumed $\tau$ to be known, however in Gibbs sampling, both can be estimated.<br>
# <br>
#
# A prior of _normal distribution_ will be assumed for $\mu$ with hyperparameters
# $$
# \text{inverse of }\sigma_0:\tau_0 = .15\\
# \text{mean}:\mu_0 = 170
# $$
#
#
# A prior of _gamma distribution_ will be assumed for $\tau$ since it can't be negative.
# $$
# \text{shape}: \alpha_0 = 2\\
# \text{rate}:\beta_0 = 1
# $$
# </div>
# The priors graphically are
# +
mu_0, tau_0 = 170, .35
x_mu = np.linspace(150, 190, 100)
y_mu = sp.stats.norm(loc=mu_0, scale=1/tau_0).pdf(x_mu)
alpha_0, beta_0 = 2, 1
x_tau = np.linspace(0, 8, 100)
y_tau = sp.stats.gamma(a=alpha_0, scale=1/beta_0).pdf(x_tau)
fig, ax = plt.subplots(figsize=(15,5), nrows=1, ncols=2)
ax[0].plot(x_mu, y_mu)
ax[0].set_title(r'Prior of $\mu$')
ax[1].plot(x_tau, y_tau)
ax[1].set_title(r'Prior of $\tau$')
plt.show()
# -
# Choose an initial value of proposal of $\tau$, denoted as $\tau_{\text{proposal},0}$, the $0$ subscript represents the time period, since this is the initial value.
#
# Say
# $$
# \tau_{\text{proposal},0} = 7
# $$
# Next step is to obtain
# $$
# \mu_{\text{proposal},0}|\tau_{\text{proposal},0}
# $$
# where $\mu_{\text{proposal},0}$ is the first value of proposal $\mu$ conditional on $\tau_{\text{proposal},0}$.
# Now go collect some data, for instance you measured $10$ random women's heights, here's the data.
heights = np.array([156, 167, 178, 182, 169, 174, 175, 164, 181, 170])
np.sum(heights)
# Recall we have a sets of analytical solution derived in chapter 2
# \begin{align}
# \mu_{\text {posterior }} &=\frac{\tau_{0} \mu_{0}+\tau \sum x_{i}}{\tau_{0}+n \tau}\\
# \tau_{\text {posterior }} &=\tau_{0}+n \tau
# \end{align}
# Substitute $\tau_{\text{proposal},0}$ into both formula.
#
# $$
# \mu_{\text {posterior},1} =\frac{\tau_{0} \mu_{0}+\tau_{\text{proposal},0} \sum_{i=0}^{100} x_{i}}{\tau_{0}+n \tau_{\text{proposal},0}}=\frac{.15\times170+7\times 1716}{.15+10\times7}\\
# \tau_{\text {posterior}, 1} =\tau_{0}+n \tau_{\text{proposal},0} = .15 + 10\times 7
# $$
# +
mu_post = [0]
tau_post = [0] # 0 is placeholder, there isn't 0th eletment, according to algo
tau_proposal = [7]
mu_proposal = [0] # 0 is placeholder
mu_post.append((.15*170+tau_proposal[0]*1716)/(.15+10*tau_proposal[0]))
tau_post.append(.15+10*tau_proposal[0])
# -
# Draw a proposal from updated distribution for $\mu$, that is $\mu_{\text{posterior}, 1}$ and $\tau_{\text{posterior}, 1}$
mu_proposal_draw = sp.stats.norm(loc=mu_post[1], scale=1/tau_post[1]).rvs()
mu_proposal.append(mu_proposal_draw)
# Turn to $\tau$ for proposal
| Chapter 4 - Markov Chain Monte Carlo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import os
import glob
from pathlib import Path
cwd = os.getcwd()
project_dir = Path(cwd).resolve().parents[1]
raw_data_dir = os.path.join(project_dir, 'data/raw/')
interim_data_dir = os.path.join(project_dir, 'data/interim/')
# +
header_file = os.path.join(raw_data_dir, 'fields.csv')
all_files = glob.glob(raw_data_dir + "/Event201*.txt")
fields = pd.read_csv(header_file)
header = fields['Header'].to_numpy()
li = []
# -
all_files[0][-8:-4]
# +
for filename in all_files:
df = pd.read_csv(filename, header=None, names=header)
li.append(df)
df = pd.concat(li, axis=0, ignore_index=True)
hits = df.groupby(['GAME_ID', 'BAT_ID']).agg({'H_FL': 'max', 'BAT_LINEUP_ID': 'first'})
hits['Win'] = hits['H_FL'] > 0
clean_events = os.path.join(interim_data_dir, 'events.pkl')
df.to_pickle(clean_events)
clean_hits = os.path.join(interim_data_dir, 'hits.pkl')
# -
hits.to_pickle(clean_hits)
| notebooks/Archive/CleanEventsData.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <a href="https://colab.research.google.com/github/PyTorchLightning/lightning-flash/blob/master/flash_notebooks/tabular_classification.ipynb" target="_parent">
# <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
# </a>
# In this notebook, we'll go over the basics of lightning Flash by training a TabularClassifier on [Titanic Dataset](https://www.kaggle.com/c/titanic).
#
# ---
# - Give us a ⭐ [on Github](https://www.github.com/PytorchLightning/pytorch-lightning/)
# - Check out [Flash documentation](https://lightning-flash.readthedocs.io/en/latest/)
# - Check out [Lightning documentation](https://pytorch-lightning.readthedocs.io/en/latest/)
# - Join us [on Slack](https://www.pytorchlightning.ai/community)
# # Training
# # %%capture
# ! pip install 'git+https://github.com/PyTorchLightning/lightning-flash.git#egg=lightning-flash[tabular]'
# +
from torchmetrics.classification import Accuracy, Precision, Recall
import flash
from flash.core.data.utils import download_data
from flash.tabular import TabularClassifier, TabularClassificationData
# -
# ### 1. Download the data
# The data are downloaded from a URL, and save in a 'data' directory.
download_data("https://pl-flash-data.s3.amazonaws.com/titanic.zip", 'data/')
# ### 2. Load the data
# Flash Tasks have built-in DataModules that you can use to organize your data. Pass in a train, validation and test folders and Flash will take care of the rest.
#
# Creates a TabularData relies on [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html).
datamodule = TabularClassificationData.from_csv(
["Sex", "Age", "SibSp", "Parch", "Ticket", "Cabin", "Embarked"],
["Fare"],
target_fields="Survived",
train_file="./data/titanic/titanic.csv",
test_file="./data/titanic/test.csv",
val_split=0.25,
batch_size=8,
)
# ### 3. Build the model
#
# Note: Categorical columns will be mapped to the embedding space. Embedding space is set of tensors to be trained associated to each categorical column.
model = TabularClassifier.from_data(datamodule)
# ### 4. Create the trainer. Run 10 times on data
trainer = flash.Trainer(max_epochs=10)
# ### 5. Train the model
trainer.fit(model, datamodule=datamodule)
# ### 6. Test model
trainer.test(model, datamodule=datamodule)
# ### 7. Save it!
trainer.save_checkpoint("tabular_classification_model.pt")
# # Predicting
# ### 8. Load the model from a checkpoint
#
# `TabularClassifier.load_from_checkpoint` supports both url or local_path to a checkpoint. If provided with an url, the checkpoint will first be downloaded and laoded to re-create the model.
model = TabularClassifier.load_from_checkpoint(
"https://flash-weights.s3.amazonaws.com/0.7.0/tabular_classification_model.pt")
# ### 9. Generate predictions from a sheet file! Who would survive?
#
# `TabularClassifier.predict` support both DataFrame and path to `.csv` file.
datamodule = TabularClassificationData.from_csv(
predict_file="data/titanic/titanic.csv",
parameters=datamodule.parameters,
batch_size=8,
)
predictions = trainer.predict(model, datamodule=datamodule)
print(predictions)
# <code style="color:#792ee5;">
# <h1> <strong> Congratulations - Time to Join the Community! </strong> </h1>
# </code>
#
# Congratulations on completing this notebook tutorial! If you enjoyed it and would like to join the Lightning movement, you can do so in the following ways!
#
# ### Help us build Flash by adding support for new data-types and new tasks.
# Flash aims at becoming the first task hub, so anyone can get started to great amazing application using deep learning.
# If you are interested, please open a PR with your contributions !!!
#
#
# ### Star [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) on GitHub
# The easiest way to help our community is just by starring the GitHub repos! This helps raise awareness of the cool tools we're building.
#
# * Please, star [Lightning](https://github.com/PyTorchLightning/pytorch-lightning)
#
# ### Join our [Slack](https://www.pytorchlightning.ai/community)!
# The best way to keep up to date on the latest advancements is to join our community! Make sure to introduce yourself and share your interests in `#general` channel
#
# ### Interested by SOTA AI models ! Check out [Bolt](https://github.com/PyTorchLightning/lightning-bolts)
# Bolts has a collection of state-of-the-art models, all implemented in [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) and can be easily integrated within your own projects.
#
# * Please, star [Bolt](https://github.com/PyTorchLightning/lightning-bolts)
#
# ### Contributions !
# The best way to contribute to our community is to become a code contributor! At any time you can go to [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) or [Bolt](https://github.com/PyTorchLightning/lightning-bolts) GitHub Issues page and filter for "good first issue".
#
# * [Lightning good first issue](https://github.com/PyTorchLightning/pytorch-lightning/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
# * [Bolt good first issue](https://github.com/PyTorchLightning/lightning-bolts/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
# * You can also contribute your own notebooks with useful examples !
#
# ### Great thanks from the entire Pytorch Lightning Team for your interest !
#
# <img src="https://raw.githubusercontent.com/PyTorchLightning/lightning-flash/18c591747e40a0ad862d4f82943d209b8cc25358/docs/source/_static/images/logo.svg" width="800" height="200" />
| flash_notebooks/tabular_classification.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: venv-datascience
# language: python
# name: venv-datascience
# ---
# # 🚜 Predicting the Sale Price of Bulldozers using Machine Learning
#
# In this notebook, we're trying to predict the sale price of bulldozers based on the past prices.
#
# We're going to take the following approach:
# 1. [Problem Definition](#definition)
# 2. [Data](#data)
# 3. [Evaluation](#evaluation)
# 4. [Features](#features)
# 5. [Modelling](#modelling)
# 6. [Experimentation](#experimentation)
# ## <a name="definition">1. Problem Definition</a>
#
# In a statement,
# > How well can we predict the future sale price of a bulldozer, given its characteristics and previous examples of how much similar bulldozers have been sold for?
# ## <a name="data">2. Data</a>
#
# [Blue Book for Bulldozers - Kaggle Version](https://www.kaggle.com/c/bluebook-for-bulldozers/overview)
#
# There are 3 datasets:
# 1. **Train.csv** - Historical bulldozer sales examples up to 2011 (close to 400,000 examples with 50+ different attributes, including `SalePrice` which is the **target variable**).
# 2. **Valid.csv** - Historical bulldozer sales examples from January 1 2012 to April 30 2012 (close to 12,000 examples with the same attributes as **Train.csv**).
# 3. **Test.csv** - Historical bulldozer sales examples from May 1 2012 to November 2012 (close to 12,000 examples but missing the `SalePrice` attribute, as this is what we'll be trying to predict).
#
# ## <a name="evaluation">3.Evaluation</a>
#
#
# For this problem, [Kaggle has set the evaluation metric to being root mean squared log error (RMSLE)](https://www.kaggle.com/c/bluebook-for-bulldozers/overview/evaluation).
#
# As with many regression evaluations, the goal will be to get this value as low as possible.
#
# To see how well our model is doing, we'll calculate the RMSLE and then compare our results to others on the [Kaggle leaderboard](https://www.kaggle.com/c/bluebook-for-bulldozers/leaderboard).
# ## <a name="features">4.Features</a>
# Based on the provided Data Dictionary.xls:
#
# **SalesID** - unique identifier of a particular sale of a machine at auction
#
# **MachineID** - identifier for a particular machine; machines may have multiple sales
#
# **ModelID** - identifier for a unique machine model (i.e. fiModelDesc)
#
# **datasource** - source of the sale record; some sources are more diligent about reporting attributes of the machine than others. Note that a particular datasource may report on multiple auctioneerIDs.
#
# **auctioneerID** - identifier of a particular auctioneer, i.e. company that sold the machine at auction. Not the same as datasource.
#
# **YearMade** - year of manufacturer of the Machine
#
# **MachineHoursCurrentMeter** - current usage of the machine in hours at time of sale (saledate); null or 0 means no hours have been reported for that sale
#
# **UsageBand** - value (low, medium, high) calculated comparing this particular Machine-Sale hours to average usage for the fiBaseModel; e.g. 'Low' means this machine has less hours given it's lifespan relative to average of fiBaseModel.
#
# **Saledate** - time of sale
#
# **Saleprice** - cost of sale in USD
#
# **fiModelDesc** - Description of a unique machine model (see ModelID); concatenation of fiBaseModel & fiSecondaryDesc & fiModelSeries & fiModelDescriptor
#
# **fiBaseModel** - disaggregation of fiModelDesc
#
# **fiSecondaryDesc** - disaggregation of fiModelDesc
#
# **fiModelSeries** - disaggregation of fiModelDesc
#
# **fiModelDescriptor** - disaggregation of fiModelDesc
#
# **ProductSize** - Don't know what this is
#
# **ProductClassDesc** - description of 2nd level hierarchical grouping (below ProductGroup) of fiModelDesc
#
# **State** - US State in which sale occurred
#
# **ProductGroup** - identifier for top-level hierarchical grouping of fiModelDesc
#
# **ProductGroupDesc** - description of top-level hierarchical grouping of fiModelDesc
#
# **Drive_System** - machine configuration; typcially describes whether 2 or 4 wheel drive
#
# **Enclosure** - machine configuration - does machine have an enclosed cab or not
#
# **Forks** - machine configuration - attachment used for lifting
#
# **Pad_Type** - machine configuration - type of treads a crawler machine uses
#
# **Ride_Control** - machine configuration - optional feature on loaders to make the ride smoother
#
# **Stick** - machine configuration - type of control
#
# **Transmission** - machine configuration - describes type of transmission; typically automatic or manual
#
# **Turbocharged** - machine configuration - engine naturally aspirated or turbocharged
#
# **Blade_Extension** - machine configuration - extension of standard blade
#
# **Blade_Width** - machine configuration - width of blade
#
# **Enclosure_Type** - machine configuration - does machine have an enclosed cab or not
#
# **Engine_Horsepower** - machine configuration - engine horsepower rating
#
# **Hydraulics** - machine configuration - type of hydraulics
#
# **Pushblock **- machine configuration - option
#
# **Ripper** - machine configuration - implement attached to machine to till soil
#
# **Scarifier** - machine configuration - implement attached to machine to condition soil
#
# **Tip_control** - machine configuration - type of blade control
#
# **Tire_Size** - machine configuration - size of primary tires
#
# **Coupler** - machine configuration - type of implement interface
#
# **Coupler_System** - machine configuration - type of implement interface
#
# **Grouser_Tracks** - machine configuration - describes ground contact interface
#
# **Hydraulics_Flow** - machine configuration - normal or high flow hydraulic system
#
# **Track_Type** - machine configuration - type of treads a crawler machine uses
#
# **Undercarriage_Pad_Width** - machine configuration - width of crawler treads
#
# **Stick_Length** - machine configuration - length of machine digging implement
#
# **Thumb** - machine configuration - attachment used for grabbing
#
# **Pattern_Changer** - machine configuration - can adjust the operator control configuration to suit the user
#
# **Grouser_Type** - machine configuration - type of treads a crawler machine uses
#
# **Backhoe_Mounting** - machine configuration - optional interface used to add a backhoe attachment
#
# **Blade_Type** - machine configuration - describes type of blade
#
# **Travel_Controls** - machine configuration - describes operator control configuration
#
# **Differential_Type** - machine configuration - differential type, typically locking or standard
#
# **Steering_Controls** - machine configuration - describes operator control configuration
# ---------
# ## Load data
# +
# Regular EDA and plotting libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Models from scikit-learn
from sklearn.ensemble import RandomForestRegressor
# Model Evaluations
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
# -
df = pd.read_csv('data/TrainAndValid.csv', low_memory=False)
# ## Exploratory Data Analysis (EDA)
#
# 1. What question(s) are we trying to solve?
# 2. What kind of data do we have and how do we treat different types?
# 3. What are the missing data and how are we going to handle them?
# 4. What are the outliers, why we care about them and how are we going to handle them?
# 5. How can we add, change or remove features to get more out of the data?
df.info()
# check missing data
df.isnull().sum()
# We can see there are a lot of missing data that we need to handle later.
df.columns
# +
# As the initial task, we want to see SalePrice and Date visually
# Dataset is too large, so we want to look at only 1000 points
sns.scatterplot(data=df[:1000], x='saledate', y='SalePrice' );
# -
sns.histplot(data=df, x='SalePrice', bins=10);
# ### Parsing dates
#
# When we work with time series data, we want to enrich time & date component as much as possible.
#
# So we will convert our related date/time column accordingly.
df['saledate'].dtype
# reimport data while parsing datetime object correctly
df = pd.read_csv('data/TrainAndValid.csv', low_memory=False, parse_dates=['saledate'])
df['saledate'].dtype
df['saledate'].head()
# now we can see that saledate is correctly parsed.
sns.scatterplot(data=df[:1000], x='saledate', y='SalePrice');
df.head(2).T
df['saledate'].head(20)
# ### Sort data by Saledate
#
# When working with timeseries data, it is good idea to sort it by date
# +
# sort dataframe by date order
df = df.sort_values(by=['saledate'], ascending=True)
df['saledate'].head(20)
# -
# ### Make copy of original dataframe
#
# We also want to keep copy original dataframe, so that there won't be any impact when we do data manipulation.
df_temp = df.copy()
df_temp.head(2)
# ### Add pandas DateTimeIndex as additional columns for `saledate`
# * [Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DatetimeIndex.html)
# * this will allow us to use additional features in an easy and quick way via `Attributes`
df_temp[:5].saledate.dt.year
# we will add Year, Month, Day as additional columns
df_temp['saleYear'] = df_temp['saledate'].dt.year
df_temp['saleMonth'] = df_temp['saledate'].dt.month
df_temp['saleDay'] = df_temp['saledate'].dt.day
df_temp['saleDayOfWeek'] = df_temp['saledate'].dt.dayofweek
df_temp['saleDayOfYear'] = df_temp['saledate'].dt.dayofyear
df_temp.head(2)
# Now we have enriched the saledate column with additional features, we will remove the orignial saledate column.
df_temp = df_temp.drop('saledate', axis=1)
df_temp.head(2)
# #### check random check of other columns
df_temp['state'].value_counts()
len(df_temp)
# ------
df_temp.columns
# --------
# ## Convert String to Categories
#
# We have multiple String type columns in dataset. Each String value (such as Low, Medium, High) doesn't mean much for machine. We might want to turn those related string values into a group of categories.
#
# We can achieve by converting the columns with the string datatype into a category datatype.
#
# To do this we can use the [pandas types API](https://pandas.pydata.org/pandas-docs/stable/reference/general_utility_functions.html#data-types-related-functionality) which allows us to interact and manipulate the types of data.
df_temp.head(2).T
# ### Find and Gather columns of string type in dataframe
# +
string_columns = []
for col_name, value in df_temp.items():
if pd.api.types.is_string_dtype(value):
string_columns.append(col_name)
len(string_columns), string_columns
# -
# ### Now we convert String column into Categorical types
for col_name, content in df_temp.items():
if pd.api.types.is_string_dtype(content):
df_temp[col_name] = content.astype('category').cat.as_ordered() #convert into Ordered category data type
# Now we can see that those columns are convered into `category` data type.
df_temp.info()
# check state column
# as it is now category, we need to access using cat
df_temp['state'].cat.categories
# **Thanks to pandas Categroy, we now have a way to access all our data in a form of numbers.**
#
# As in below example, we can access `state` columns value as numbers.
# get the categorical codes
df_temp['state'].cat.codes
# Now we need to handle missing data.
# ### check the Ratio of missing data
#
df_temp.isnull().sum()/len(df_temp)
# ### Save the preprocessed data
# +
# export the current temp dataframe
df_temp.to_csv('data/preprocessed/train_tmp.csv', index=False)
# -
# -------
# ## Fill Missing Values - Numerical variables
# check which columns are numeric data type
for col, content in df_temp.items():
if pd.api.types.is_numeric_dtype(content):
print(col)
# check which numeric columns have missing values
for col, content in df_temp.items():
if pd.api.types.is_numeric_dtype(content):
missing_counts = df_temp[col].isnull().sum()
if missing_counts > 0:
print('{} has total {} missing data.'.format(col, missing_counts))
# ### Add is_missing flag and fill with median value
#
# * we will put `is_missing` : true or false flag for those columns, before we fill in. The reason is we want to make sure we keep track of changes and we don't know yet there may be an underlying reason why those values are missing in the first place.
#
#
# * fill with `median` value. We use median value instead of mean value because mean is sensitive to outliers. If the dateset is skewed one, mean value will be impacted by those outliers value. To avoid this, we will use median instead.
for col, content in df_temp.items():
# check numeric data type
if pd.api.types.is_numeric_dtype(content):
# check has some missing count
if pd.isnull(content).sum():
# step 1) add col_name_is_missing flag (true/false)
df_temp[col+'_is_missing'] = pd.isnull(content)
# step 2) fill with median value, if it has missing content value
df_temp[col] = content.fillna(content.median())
# +
# confirm to check whether there are missing values for numeric columns
for col, content in df_temp.items():
if pd.api.types.is_numeric_dtype(content):
missing_counts = df_temp[col].isnull().sum()
if missing_counts > 0:
print('{} has total {} missing data.'.format(col, missing_counts))
# -
# Great. There is no missing value for Numeric columns anymore.
#
# And we can also see there are 2 new columns for auctioneerID_is_missing and MachineHoursCurrentMeter_is_missing with True/False value.
df_temp.head(2)
df_temp['auctioneerID_is_missing'].value_counts()
df_temp['MachineHoursCurrentMeter_is_missing'].value_counts()
df_temp[df_temp['auctioneerID_is_missing'] == True].head(5)
df_temp[df_temp['MachineHoursCurrentMeter_is_missing'] == True].head(5)
# -----
# ## Filling Missing values and Categorical variables into numbers
# check for which aren't numeric
for col, content in df_temp.items():
if not pd.api.types.is_numeric_dtype(content):
print(col)
# #### Get the categorical values of specific column
#
# We can see that for `state` column, there are 53 categories.
# let's get sample state as categorical values
# get the Categorical columns => then get this column
pd.Categorical(df_temp['state'])
# this returns codes value of each category
pd.Categorical(df_temp['state']).codes
# ### Turn categorical variables into numbers and fill missing ones
#
# #### Add is_missing flag and fill with number + 1
#
# * we will put `is_missing` : true or false flag for those columns, before we fill in. The reason is we want to make sure we keep track of changes and we don't know yet there may be an underlying reason why those values are missing in the first place.
#
#
# * get the `codes` value of category
#
#
# * increase `codes+1` and fill with that value. The reason we do this is because when pandas turn category into number code, it define integer such as 1, then increment it by 1 so that each category code value will be unique. So we will also following this principle and increment by 1 for the newly filled in `missing category` value.
for col, content in df_temp.items():
if not pd.api.types.is_numeric_dtype(content):
# Step 1) add is_missing flag (true/false)
df_temp[col+'_is_missing'] = pd.isnull(content) # return True/False
# Step 2) turn category into number and add 1, then fill in those missing slots
df_temp[col] = pd.Categorical(content).codes + 1
df_temp.info()
df_temp.head(2).T
# confirm is there any columns with missing values
df_temp.isnull().sum()
# Now all of our data have no more missing data and all categorical values are turned into numeric values, we will continue to modelling.
# ---------
# ## <a name="modelling">5. Modelling</a>
df_temp.head(2)
df_temp['saleYear'].value_counts()
# ### Split data into training and validation data sets
# +
# Split data into training and validation data sets
df_val = df_temp[df_temp['saleYear'] == 2012]
df_train = df_temp[df_temp['saleYear'] != 2012]
len(df_train), len(df_val)
# -
# ### Split features and labels
# +
# split features and labels
# Training Set
X_train, y_train = df_train.drop('SalePrice', axis=1), df_train['SalePrice']
# Validation Set
X_valid, y_valid = df_val.drop('SalePrice', axis=1), df_val['SalePrice']
# -
X_train.shape, X_valid.shape, y_train.shape, y_valid.shape
# ### Building an Evaluation Function
# +
# create evaluation function (RMSLE that competion uses)
from sklearn.metrics import mean_squared_log_error, mean_absolute_error, r2_score
def root_mean_squared_log_error(y_test, y_preds):
"""
Calculate Root Mean Squared Log error between predictions and true labels.
"""
return np.sqrt(mean_squared_log_error(y_test, y_preds))
# create function to evaluate model on few different levels
def show_scores(model):
"""
shows the scores of MAE and Root Mean Squared Log Error.
"""
train_preds = model.predict(X_train)
val_preds = model.predict(X_valid)
scores = {
"Training MAE": mean_absolute_error(y_train, train_preds),
'Validation MAE': mean_absolute_error(y_valid, val_preds),
'Training RMSLE': root_mean_squared_log_error(y_train, train_preds),
'Validation RMSLE': root_mean_squared_log_error(y_valid, val_preds),
'Training R^2': r2_score(y_train, train_preds),
'Validation R^2': r2_score(y_valid, val_preds)
}
return scores
# -
# ## Testing model on subset (to tune hyperparameters)
# As our dataset is quite huge, we might want to train on the subset of data first.
# cutting down on the max number of samples that each estimator can use, here : 10,000 data points
model = RandomForestRegressor(n_jobs=-1,
random_state=42,
max_samples=10000)
# %%time
model.fit(X_train, y_train)
show_scores(model)
# -------
# ## <a name="experimentation">6. Experimentation</a>
# ## Hyperparameter tuning with RandomizedSearchCV
from sklearn.model_selection import RandomizedSearchCV
# +
# help(RandomForestRegressor)
# +
# define different hyperparameters with Max_samples: using 10000 (subset of original dataset)
rf_grid = {
'n_estimators': np.arange(10, 100, 10),
'max_depth': [None, 3, 5, 10],
'min_samples_split': np.arange(2, 20, 2),
'min_samples_leaf': np.arange(1, 20, 2),
'max_features': [0.5, 1, 'auto', 'sqrt'],
'max_samples': [10000]
}
# institiate model
rs_model = RandomizedSearchCV(RandomForestRegressor(n_jobs=-1, random_state=42),
rf_grid,
cv=5,
n_iter=5,
verbose=True)
# fit RandomizedSearchCV
rs_model.fit(X_train, y_train)
# -
# get the best params
rs_model.best_params_
# Evaluate RandomizedSearchCV model
show_scores(rs_model)
# --------
# ## Train a model with best hyperparameters
#
# NOTE: These were founds after 100 iterations (n_iter=100) of RandomizedSearchCV
#
# We will also train the model on the FULL training dataset. (max_samples=None)
#
# Tell computer to put all resources (n_jobs=-1 means that the computation will be dispatched on all the CPUs of the computer)
# +
# %%time
# Most ideal hyperparameters
ideal_model = RandomForestRegressor(n_estimators=40,
min_samples_leaf=1,
min_samples_split=14,
max_features=0.5,
n_jobs=-1,
max_samples=None,
random_state=42)
# fit ideal model
ideal_model.fit(X_train, y_train)
# -
# scores for ideal model (trained on full training set)
show_scores(ideal_model)
# ------------
# ## Make Predictions on Test Dataset
# +
# import test data
df_test = pd.read_csv('data/Test.csv', low_memory=False, parse_dates=['saledate'])
df_test.head(2)
# -
df_test.info()
df_test.isnull().sum()
# ### Data Preprocessing for Test Data
# - getting the test data set as in the same format as training dataset.
def preprocess_data(df):
"""
Performs transformation on df and returned preprocessed df.
"""
# we will add Year, Month, Day as additional columns
df['saleYear'] = df['saledate'].dt.year
df['saleMonth'] = df['saledate'].dt.month
df['saleDay'] = df['saledate'].dt.day
df['saleDayOfWeek'] = df['saledate'].dt.dayofweek
df['saleDayOfYear'] = df['saledate'].dt.dayofyear
# drop original saledate column
df = df.drop('saledate', axis=1)
# fill missing data for numerical variables with median
for col, content in df.items():
if pd.api.types.is_numeric_dtype(content):
if pd.isnull(content).sum():
# step 1) add col_name_is_missing flag (true/false)
df[col+'_is_missing'] = pd.isnull(content)
# step 2) fill with median value, if it has missing content value
df[col] = content.fillna(content.median())
# convert string data column into categories and fill missing data for categorical variables
if not pd.api.types.is_numeric_dtype(content):
df[col+'_is_missing'] = pd.isnull(content)
# we add +1 to the category code because pandas encode missing categories as -1
df[col] = pd.Categorical(content).codes + 1
return df
# +
# preprocessed data
df_test = preprocess_data(df_test)
df_test.head()
# -
df_test.isnull().sum()
X_train.head()
# There are differences between Test (101 columns) and Train set (102 columns).
# ### differences between test and train set columns
set(X_train.columns) - set(df_test.columns)
# It seem that `auctioneerID_is_missing` column is not existed in df_test.
#
# The reason is there is no missing values for `auctioneerID` in df_test .When preprocessing function run, there is no need to add a new column named `auctioneerID_is_missing` with True/False value.
#
# So we need to manually adjust.
# ### Manully adjust new column `auctioneerID_is_missing` for df_test
# +
df_test['auctioneerID_is_missing'] = False
df_test.head()
# -
# now the shape of df_test has the same features as training dataset. So we can proceed to predictions.
# ### Make predictions on test data
test_preds = ideal_model.predict(df_test)
test_preds[:10]
# ### Format the test prediction into competition defined format
#
# Have a header: "SalesID,SalePrice"
#
# Contain two columns.
# * SalesID: SalesID for the validation set in sorted order
# * SalePrice: Your predicted price of the sale
df_preds = pd.DataFrame()
df_preds['SalesID'] = df_test['SalesID']
df_preds['SalePrice'] = test_preds
df_preds.head()
# ### Export predictions data to csv
df_preds.to_csv('data/predictions/test_predictions.csv')
# ---------------
# ## Features Importances
#
# Features Importance seeks to figure out which different attributes of data were most important when it comes to predicting **target variable (Sale Price)**
ideal_model.feature_importances_
len(ideal_model.feature_importances_)
# #### helper function to visualize feature importances
def plot_feature_importances(columns, importances, n=20):
df = (pd.DataFrame({'features': columns,
'feature_importances': importances})
.sort_values('feature_importances', ascending=False)
.reset_index(drop=True)
)
# plot
plt.figure(figsize=(10,8))
base_color = sns.color_palette()[1]
sns.barplot(data=df[:n], x='feature_importances', y='features', color=base_color)
plt.xlabel('Feature Importances')
plt.ylabel('Features')
plot_feature_importances(df_test.columns, ideal_model.feature_importances_)
| Complete Machine Learning and Data Science - Zero to Mastery - AN/12.Bulldozer Sales Price Prediction Project/Milestone Project - Bluebook Bulldozer Price Prediction.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# CWPK \#32: Iterating Over a Full Extraction
# =======================================
#
# It is Time to Explore Python Dictionaries and Packaging
# --------------------------
#
# <div style="float: left; width: 305px; margin-right: 10px;">
#
# <img src="http://kbpedia.org/cwpk-files/cooking-with-kbpedia-305.png" title="Cooking with KBpedia" width="305" />
#
# </div>
#
# In our last coding installments in this [*Cooking with Python and KBpedia*](https://www.mkbergman.com/cooking-with-python-and-kbpedia/) series, prior to our single-installment detour to learn about files, we developed extraction routines for both structure (<code>rdfs:subClassOf</code>) and annotations (of various properties) using the fantastic package [owlready2](https://owlready2.readthedocs.io/en/latest/intro.html). In practice, these generic routines will loop over populations of certain object types in [KBpedia](https://kbpedia.org/), such as typologies or property types. We want a way to feed these variations to the generic routines in an efficient and understandable way.
#
# [Python](https://en.wikipedia.org/wiki/Python_(programming_language)) lists are one way to do so, and we have begun to gain a bit of experience in our prior work with lists and sets. But there is another structure in Python called a 'dictionary' that sets up [key-value pairs](https://en.wikipedia.org/wiki/Attribute%E2%80%93value_pair) of 2-[tuples](https://en.wikipedia.org/wiki/Tuple) that promises more flexibility and power. The 2-tuple sets up a relationship between an attribute name (a variable name) with a value, quite similar to the [associative arrays](https://en.wikipedia.org/wiki/Associative_array) in [JSON](https://en.wikipedia.org/wiki/JSON). The values in a dictionary can be any object in Python, including functions or other dictionaries, the latter which allows 'record'-like data structures. However, there may not be duplicate names for keys within a given dictionary (but names may be used again in other dictionaries without global reference).
#
# Dictionaries (<code>'dicts'</code>) are like Python lists except list elements are accessed by their position in the list using a numeric index, while we access <code>dict</code> elements via keys. This makes tracing the code easier. We have also indicated that dictionary structures may be forthcoming in other uses of KBpedia, such as [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) or [master data](https://en.wikipedia.org/wiki/Master_data). So, I decided to start gaining experience with <code>'dicts'</code> in this installment.
#
# (Other apparent advantages of dictionaries not directly related to our immediate needs include:
#
# - Dictionaries can be expanded without altering what is already there
# - From Python 3.7 onward, the order entered into a dict is preserved in loops
# - Dictionaries can handle extremely large data sets
# - <code>Dicts</code> are fast because they are implemented as a [hash table](https://en.wikipedia.org/wiki/Hash_table), and
# - They can be directly related to a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) should we go that route.)
#
# We can inspect this method with our standard statement:
dir(dict)
# ### The Basic Iteration Approach
#
# In installments [**CWPK #28**](https://www.mkbergman.com/2363/cwpk-28-extracting-structure-for-typologies/), [**CWPK #29**](https://www.mkbergman.com/2364/cwpk-29-extracting-object-and-data-properties/), and [**CWPK #30**](https://www.mkbergman.com/2365/cwpk-30-extracting-annotations/), we created generic prototype routines for extracting structure from typologies and properties and then annotations from classes (including typologies as a subset) and properties as well. We thus have generic extraction routines for:
#
# | Structure | Annotations |
# |:--------- |:----------- |
# | classes | classes |
# | typologies | typologies (possible) |
# | properties | properties |
#
# Our basic iteration approach, then, is to define dictionaries for the root objects in these categories and loop over them invoking these generic routines. In the process we want to write out results for each iteration, provide some progress messages, and then complete the looping elements for each root object. Labels and internal lookups to the namespace objects come from the dictionary. In generic terms, then, here is how we want these methods to be structured:
#
# - Initialize method
# - Message: starting method
# - Get <code>dict</code> iterator:
# - Message: iterating current element
# - Get owlready2 set iterator for element:
# - Populate row
# - Print to file
# - Return to prompt without error message.
# ### Starting and Load
# To demonstrate this progression, we begin with our standard opening routine:
#
# <div style="background-color:#eee; border:1px dotted #aaa; vertical-align:middle; margin:15px 60px; padding:8px;"><strong>Which environment?</strong> The specific load routine you should choose below depends on whether you are using the online MyBinder service (the 'raw' version) or local files. The example below is based on using local files (though replace with your own local directory specification). If loading from MyBinder, replace with the lines that are commented (<code>#</code>) out.</div>
# +
kbpedia = 'C:/1-PythonProjects/kbpedia/sandbox/kbpedia_reference_concepts.owl'
# kbpedia = 'https://raw.githubusercontent.com/Cognonto/CWPK/master/sandbox/builds/ontologies/kbpedia_reference_concepts.owl'
skos_file = 'http://www.w3.org/2004/02/skos/core'
kko_file = 'C:/1-PythonProjects/kbpedia/sandbox/kko.owl'
# kko_file = 'https://raw.githubusercontent.com/Cognonto/CWPK/master/sandbox/builds/ontologies/kko.owl'
from owlready2 import *
world = World()
kb = world.get_ontology(kbpedia).load()
rc = kb.get_namespace('http://kbpedia.org/kko/rc/')
skos = world.get_ontology(skos_file).load()
kb.imported_ontologies.append(skos)
core = world.get_namespace('http://www.w3.org/2004/02/skos/core#')
kko = world.get_ontology(kko_file).load()
kb.imported_ontologies.append(kko)
kko = kb.get_namespace('http://kbpedia.org/ontologies/kko#')
# -
# Like always, we execute each cell as we progress down this notebook page by pressing <code>shift+enter</code> for the highlighted cell or by choosing Run from the notebook menu.
#
# ### Creating the Dictionaries
# We will now create dictionaries for typologies and properties. We will construct them using our standard internal name as the 'key' for each element, with the value being the internal reference including the namespace prefix (easier than always concatenating using strings). I'll first begin with the smaller properties dictionary and explain the sytax afterwards:
prop_dict = {
'objectProperties' : 'kko.predicateProperties',
'dataProperties' : 'kko.predicateDataProperties',
'annotationProperties': 'kko.representations',
}
# A dictionary is declared either with the curly brackets (<code>{ }</code>) with the colon separator for key:value, or by using the <code>d = dict([(<key>, <value>)])</code> form. The 'key' field is normally quoted, except where the variable is globally defined. The 'value' field in this instance is the internal owlready2 notation of <namespace> + <class>. There is no need to align the colons except to enhance readability.
#
# Our longer listing is the typology one:
typol_dict = {
'ActionTypes' : 'kko.ActionTypes',
'AdjunctualAttributes' : 'kko.AdjunctualAttributes',
'Agents' : 'kko.Agents',
'Animals' : 'kko.Animals',
'AreaRegion' : 'kko.AreaRegion',
'Artifacts' : 'kko.Artifacts',
'Associatives' : 'kko.Associatives',
'AtomsElements' : 'kko.AtomsElements',
'AttributeTypes' : 'kko.AttributeTypes',
'AudioInfo' : 'kko.AudioInfo',
'AVInfo' : 'kko.AVInfo',
'BiologicalProcesses' : 'kko.BiologicalProcesses',
'Chemistry' : 'kko.Chemistry',
'Concepts' : 'kko.Concepts',
'ConceptualSystems' : 'kko.ConceptualSystems',
'Constituents' : 'kko.Constituents',
'ContextualAttributes' : 'kko.ContextualAttributes',
'CopulativeRelations' : 'kko.CopulativeRelations',
'Denotatives' : 'kko.Denotatives',
'DirectRelations' : 'kko.DirectRelations',
'Diseases' : 'kko.Diseases',
'Drugs' : 'kko.Drugs',
'EconomicSystems' : 'kko.EconomicSystems',
'EmergentKnowledge' : 'kko.EmergentKnowledge',
'Eukaryotes' : 'kko.Eukaryotes',
'EventTypes' : 'kko.EventTypes',
'Facilities' : 'kko.Facilities',
'FoodDrink' : 'kko.FoodDrink',
'Forms' : 'kko.Forms',
'Generals' : 'kko.Generals',
'Geopolitical' : 'kko.Geopolitical',
'Indexes' : 'kko.Indexes',
'Information' : 'kko.Information',
'InquiryMethods' : 'kko.InquiryMethods',
'IntrinsicAttributes' : 'kko.IntrinsicAttributes',
'KnowledgeDomains' : 'kko.KnowledgeDomains',
'LearningProcesses' : 'kko.LearningProcesses',
'LivingThings' : 'kko.LivingThings',
'LocationPlace' : 'kko.LocationPlace',
'Manifestations' : 'kko.Manifestations',
'MediativeRelations' : 'kko.MediativeRelations',
'Methodeutic' : 'kko.Methodeutic',
'NaturalMatter' : 'kko.NaturalMatter',
'NaturalPhenomena' : 'kko.NaturalPhenomena',
'NaturalSubstances' : 'kko.NaturalSubstances',
'OrganicChemistry' : 'kko.OrganicChemistry',
'OrganicMatter' : 'kko.OrganicMatter',
'Organizations' : 'kko.Organizations',
'Persons' : 'kko.Persons',
'Places' : 'kko.Places',
'Plants' : 'kko.Plants',
'Predications' : 'kko.Predications',
'PrimarySectorProduct' : 'kko.PrimarySectorProduct',
'Products' : 'kko.Products',
'Prokaryotes' : 'kko.Prokaryotes',
'ProtistsFungus' : 'kko.ProtistsFungus',
'RelationTypes' : 'kko.RelationTypes',
'RepresentationTypes' : 'kko.RepresentationTypes',
'SecondarySectorProduct': 'kko.SecondarySectorProduct',
'Shapes' : 'kko.Shapes',
'SituationTypes' : 'kko.SituationTypes',
'SocialSystems' : 'kko.SocialSystems',
'Society' : 'kko.Society',
'SpaceTypes' : 'kko.SpaceTypes',
'StructuredInfo' : 'kko.StructuredInfo',
'Symbolic' : 'kko.Symbolic',
'Systems' : 'kko.Systems',
'TertiarySectorService' : 'kko.TertiarySectorService',
'Times' : 'kko.Times',
'TimeTypes' : 'kko.TimeTypes',
'TopicsCategories' : 'kko.TopicsCategories',
'VisualInfo' : 'kko.VisualInfo',
'WrittenInfo' : 'kko.WrittenInfo'
}
# To get a listing of entries in a dictionary, simply reference its name and run:
prop_dict
# There are a variety of methods for nesting or merging dictionaries. We do not have need at present for that, but one example shows how we can create a new dictionary, relate it to an existing one, and then update (or merge) another dictionary with it, using the two dictionaries from above as examples:
total_dict = dict(typol_dict)
total_dict.update(prop_dict)
print(total_dict)
# This now gives us a merged dictionary. However, whether keys match or vary in number means specific cases need to be evaluated individually. The <code>.update</code> may not always be an appropriate approach.
#
# In these <code>dicts</code>, we now have the population of items (sets) from which we want to obtain all of their members and get the individual extractions. We also have them organized into dictionaries that we can iterate over to complete a full extraction from KBpedia.
#
# ### Marrying Iterators and Routines
# We can now return to our generic extraction prototypes and enhance them a bit to loop over these iterators. Let's take the structure extraction of <code>rdfs:subPropertyOf</code> from **CWPK #29** to extract out structural aspects of our properties. I will keep the form from the earlier installment and comment all lines of code added to accommodate the iterations loops and message feedback. First we will add the iterator:
# +
for value in prop_dict.values(): # iterates over dictionary 'values' with each occurence a 'value'
root = eval(value) # need to convert value 'string' to internal variable
p_set=root.descendants()
# o_frag = set() # left over from prior development; commented out
# s_frag = set() # left over from prior development; commented out
p_item = 'rdfs:subPropertyOf'
for s_item in p_set:
o_set = s_item.is_a
for o_item in o_set:
print(s_item,',',p_item,',',o_item,'.','\n', sep='', end='')
# o_frag.add(o_item) # left over from prior development; commented out
# s_frag.add(s_item) # left over from prior development; commented out
# -
# You could do a <code>len()</code> to test output lines or make other tests to ensure you are iterating over the property groupings.
#
# The <code>eval()</code> function submits the string represented by <code>value</code> to the resident Python code base and in this case returns the owlready2 property object, which then allows proper processing of the <code>.descendants()</code> code. My understanding is that in open settings <code>eval()</code> can pose some security holes. I think it is OK in our case since we are doing local or internal processing, and not exposing this as a public method.
#
# We'll continue with this code block, but now print to file and remove the commented lines:
out_file = 'C:/1-PythonProjects/kbpedia/sandbox/prop_struct_out.csv' # variable to physical file
with open(out_file, mode='w', encoding='utf8') as out_put: # std file declaration (CWPK #31)
for value in prop_dict.values():
root = eval(value)
p_set=root.descendants()
p_item = 'rdfs:subPropertyOf'
for s_item in p_set:
o_set = s_item.is_a
for o_item in o_set:
print(s_item,',',p_item,',',o_item,'.','\n', sep='', end='', file=out_put) # add output file here
# And, then, we'll add some messages to the screen to see output as it whizzes by:
print('Beginning property structure extraction . . .') # print message
out_file = 'C:/1-PythonProjects/kbpedia/sandbox/prop_struct_out.csv'
with open(out_file, mode='w', encoding='utf8') as out_put:
for value in prop_dict.values():
print(' . . . processing', value) # loop print message
root = eval(value)
p_set=root.descendants()
p_item = 'rdfs:subPropertyOf'
for s_item in p_set:
o_set = s_item.is_a
for o_item in o_set:
print(s_item,',',p_item,',',o_item,'.','\n', sep='', end='', file=out_put)
# OK, so this looks to be a complete routine as we desire. However, we are starting to accumulate a fair number of lines in our routines, and we need additional routines very similar to what is above for extracting classes, typologies and annotations.
#
# It is time to bring a bit more formality to our code writing and management, which I address in the next installment.
# ### Additional Documentation
#
# Here is additional documentation related to today's **CWPK** installment:
#
# - [dict](https://python-reference.readthedocs.io/en/latest/docs/dict/) reference
# - RealPython's entry on [dictionaries](https://realpython.com/python-dicts/)
# - [Using Python dictionary as a database](https://developer.rhino3d.com/guides/rhinopython/python-dictionary-database/)
# - RealPython's [how to interate dictionaries](https://realpython.com/iterate-through-dictionary-python/).
#
#
# <div style="background-color:#efefff; border:1px dotted #ceceff; vertical-align:middle; margin:15px 60px; padding:8px;">
# <span style="font-weight: bold;">NOTE:</span> This article is part of the <a href="https://www.mkbergman.com/cooking-with-python-and-kbpedia/" style="font-style: italic;">Cooking with Python and KBpedia</a> series. See the <a href="https://www.mkbergman.com/cooking-with-python-and-kbpedia/"><strong>CWPK</strong> listing</a> for other articles in the series. <a href="http://kbpedia.org/">KBpedia</a> has its own Web site.
# </div>
#
# <div style="background-color:#ebf8e2; border:1px dotted #71c837; vertical-align:middle; margin:15px 60px; padding:8px;">
#
# <span style="font-weight: bold;">NOTE:</span> This <strong>CWPK
# installment</strong> is available both as an online interactive
# file <a href="https://mybinder.org/v2/gh/Cognonto/CWPK/master" ><img src="https://mybinder.org/badge_logo.svg" style="display:inline-block; vertical-align: middle;" /></a> or as a <a href="https://github.com/Cognonto/CWPK" title="CWPK notebook" alt="CWPK notebook">direct download</a> to use locally. Make sure and pick the correct installment number. For the online interactive option, pick the <code>*.ipynb</code> file. It may take a bit of time for the interactive option to load.</div>
#
# <div style="background-color:#feeedc; border:1px dotted #f7941d; vertical-align:middle; margin:15px 60px; padding:8px;">
# <div style="float: left; margin-right: 5px;"><img src="http://kbpedia.org/cwpk-files/warning.png" title="Caution!" width="32" /></div>I am at best an amateur with Python. There are likely more efficient methods for coding these steps than what I provide. I encourage you to experiment -- which is part of the fun of Python -- and to <a href="mailto:<EMAIL>">notify me</a> should you make improvements.
#
# </div>
| cwpk-32-iterating-full-extractions.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.7.10 64-bit (''base'': conda)'
# name: python3710jvsc74a57bd0b3ba2566441a7c06988d0923437866b63cedc61552a5af99d1f4fb67d367b25f
# ---
# + id="lV5PxzuGE1Mi"
import numpy as np
import pandas as pd
import seaborn as sns
import pickle
import xgboost
import matplotlib.pyplot as plt
# %matplotlib inline
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split, cross_val_score, RandomizedSearchCV
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.feature_selection import SelectKBest, chi2, mutual_info_classif
# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="dY48GrzgE4CQ" outputId="43c857af-2aeb-482f-e1b6-bb4344c5795a"
df = pd.read_csv('data/heart.csv')
df.head()
# + colab={"base_uri": "https://localhost:8080/"} id="YexKsiASGM_E" outputId="bf51a08e-d797-428e-a46f-77463e330468"
df.shape
# + colab={"base_uri": "https://localhost:8080/"} id="rXi7L7xNE39m" outputId="c2da2ecb-6c96-4c05-95fb-c85dc6267ec0"
df['thal'].value_counts()
# -
rowstodrop = df[df['thal']==0]
df.drop(index=[48,281],axis=0,inplace=True)
df['thal'].value_counts()
# + colab={"base_uri": "https://localhost:8080/"} id="lHe4gPxTE367" outputId="f13cc369-6f54-4498-a8d5-af2e2abca727"
df.info()
# + colab={"base_uri": "https://localhost:8080/"} id="iqcPqNEeE34Z" outputId="354a3ee1-449d-4539-ca68-d8abdf2ad0e8"
df.isnull().sum()
# + colab={"base_uri": "https://localhost:8080/"} id="kDD7fShkFtO7" outputId="0805dee4-143f-4005-8fb8-8c166a34fd8e"
train_df = df.iloc[:, :-1]
y = df['target'].ravel()
train_df.shape, y.shape
# + [markdown] id="XgTFHjlzLV7q"
# USING CORRELATION MATRIX
# + colab={"base_uri": "https://localhost:8080/", "height": 867} id="h9KG6kEkFtLT" outputId="02caae9c-10b5-41f2-bd92-b1acc0f74441"
# correlation matrix
corr_mat = train_df.corr()
plt.figure(figsize=(15, 15))
g = sns.heatmap(corr_mat, annot=True, cmap=sns.diverging_palette(20, 220, n=200))
# + colab={"base_uri": "https://localhost:8080/"} id="lc-o27T0FtIt" outputId="0ae444d9-c46e-472c-e5a8-4155a2cd6992"
# find and remove correlated features
threshold = 0.8
def correlation(dataset, threshold):
col_corr = set() # Set of all the names of correlated columns
corr_matrix = dataset.corr()
for i in range(len(corr_matrix.columns)):
for j in range(i):
if abs(corr_matrix.iloc[i, j]) > threshold: # we are interested in absolute coeff value
colname = corr_matrix.columns[i] # getting the name of column
col_corr.add(colname)
return col_corr
correlation(train_df.iloc[:,:-1],threshold)
# + colab={"base_uri": "https://localhost:8080/", "height": 457} id="8H6ox0mqFtGN" outputId="1401ebc1-8361-4420-e44e-adf654952d9d"
# Select K best using Chi^2 test
ordered_rank_features = SelectKBest(score_func=chi2, k=13)
ordered_feature = ordered_rank_features.fit(train_df, y)
dfscores = pd.DataFrame(ordered_feature.scores_, columns=["Score"])
dfcolumns = pd.DataFrame(train_df.columns)
features_rank = pd.concat([dfcolumns, dfscores], axis=1)
features_rank.columns = ['Features','Score']
features_rank.nlargest(13, 'Score')
# + [markdown] id="aWoYtOMyMNHE"
# USING FEATURE IMPORTANCE - This technique gives you a score for each feature of your data,the higher the score mor relevant it is
# + [markdown] id="w2WFLfGUMv1_"
# USING INFORMATION GAIN
# + colab={"base_uri": "https://localhost:8080/"} id="3nSydaCOLfdl" outputId="d0cb6daf-78e1-475b-b76a-8e0ae9c9a8ed"
mutual_info = mutual_info_classif(train_df, y)
mutual_data = pd.Series(mutual_info, index=train_df.columns)
mutual_data.sort_values(ascending=False)
# + [markdown] id="0DGkq33nNS6A"
# **FINAL SELECTION**
# + id="Q8fQAMBrLfbm"
final_selected_features = ['ca', 'cp', 'exang', 'thal', 'oldpeak', 'thalach','age']
# + id="8S7ohHjnNiBe"
X = train_df[final_selected_features]
# + colab={"base_uri": "https://localhost:8080/"} id="mNfMYFAFNilh" outputId="bc917bb1-d5de-47b4-a183-0ce21ec4bcb9"
X.shape
# + id="jin4R1rqNihN"
X_train, X_test, y_train, y_test = train_test_split(X.values, y, test_size=0.15, random_state=42)
# + [markdown] id="HDZZixIuQBMe"
# RANDOMFOREST
# + colab={"base_uri": "https://localhost:8080/"} id="LveLqOnONie8" outputId="54faede8-35fd-4720-a4e9-de74a3688aaf"
# using random forest classifier
rfc = RandomForestClassifier() # ravel : from (n,m) => (n,)
rfc.fit(X_train, y_train)
# + colab={"base_uri": "https://localhost:8080/"} id="GrfP6BdJOJau" outputId="e208661b-c17b-44b3-b275-24fb8e30babd"
# random forest classifier accuracy:
y_preds = rfc.predict(X_test)
print("Accuracy : {:.2f}%".format(accuracy_score(y_test, y_preds)*100))
# + [markdown] id="kMcS2DSFQD01"
# XGBOOST
# + colab={"base_uri": "https://localhost:8080/"} id="8pyxdKufOsBZ" outputId="23d15709-672c-4d0c-894a-b58b7de1f222"
# using xgboost
# hyperparameter optimization
params = {
"learning_rate" : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30],
"max_depth" : [3, 4, 5, 6, 8, 10, 12, 15],
"min_child_weight" : [1, 3, 5, 7],
"gamma" : [0.0, 0.1, 0.2 , 0.3, 0.4],
"colsample_bytree" : [0.3, 0.4, 0.5, 0.7]
}
clf = xgboost.XGBClassifier()
random_search = RandomizedSearchCV(
clf,
param_distributions=params,
n_iter=5,
scoring='roc_auc',
n_jobs=-1,
cv=5,
verbose=0
)
random_search.fit(X_train, y_train)
# + colab={"base_uri": "https://localhost:8080/"} id="uUfp9_gPOsrT" outputId="f23362a3-27fd-471d-bf40-3e0f59f7bec6"
random_search.best_estimator_
# +
classifier = xgboost.XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,
colsample_bynode=1, colsample_bytree=0.3, gamma=0.1, gpu_id=-1,
importance_type='gain', interaction_constraints='',
learning_rate=0.05, max_delta_step=0, max_depth=10,
min_child_weight=7, monotone_constraints='()',
n_estimators=100, n_jobs=8, num_parallel_tree=1,
objective='binary:logistic', random_state=0, reg_alpha=0,
reg_lambda=1, scale_pos_weight=1, subsample=1,
tree_method='exact', use_label_encoder=True,
validate_parameters=1, verbosity=None)
classifier.fit(X_train, y_train)
# + colab={"base_uri": "https://localhost:8080/"} id="_PV0MynvPZlr" outputId="5551c76d-0503-4ffc-e150-dfaec23886a4"
# xgboost classifier accuracy:
y_preds = classifier.predict(X_test)
print("Accuracy : {:.2f}%".format(accuracy_score(y_test, y_preds)*100))
# + colab={"base_uri": "https://localhost:8080/"} id="IoNLLnwgOskr" outputId="319ae598-0d5f-407a-b027-9872f0c80e1b"
score = cross_val_score(classifier, X_train, y_train, cv=10)
print(score.mean())
# + id="RIiF-cz1PcGZ"
# saving trained model
filename = 'heart_disease.pickle.dat'
pickle.dump(classifier, open(filename, 'wb'))
# -
df.iloc[0][final_selected_features]
classifier.predict(np.array(X_test[0]).reshape(1,-1))
| Healthcure/heart disease/heart_disease.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/dataqueenpend/-Assignments_fsDS_OneNeuron/blob/main/Programming_Assignment_3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="3x_QaPScHqS-"
# Write a Python Program to Check if a Number is Positive, Negative or Zero?
#
# + id="8egdwHkPBJv9"
def check_the_number():
"""Program asks user for a number and checks if it's positive, negative or zero"""
num = float(input('Type a number: '))
if num > 0:
print('{} is a positive number'.format(num))
elif num < 0:
print('{} is a negative number'.format(num))
else:
print('{} is equal to zero')
# + colab={"base_uri": "https://localhost:8080/"} id="zi1RrHk5IqX2" outputId="5d7971de-c5e3-4819-9ebd-201b8d39f59c"
check_the_number()
# + [markdown] id="WwcP9OlxHsfu"
# Write a Python Program to Check if a Number is Odd or Even?
#
#
# + id="ZsZbg7CVIw29"
def odd_or_even():
"""Program asks user for a number and checks if it's odd or even"""
num = float(input('Type a number: '))
if num % 2 == 0:
print('{} is an even number'.format(num))
else:
print('{} is an odd number'.format(num))
# + colab={"base_uri": "https://localhost:8080/"} id="EGeM7hwGJQaD" outputId="ffa130ea-a5d3-4ecb-8ae5-b14c9f091487"
odd_or_even()
# + [markdown] id="KlPLqPfwHt25"
# Write a Python Program to Check Leap Year?
#
# + id="4F_u9jrytotD"
def leap_year_detector():
"""Checks if year is a leap year.
Outputs True - if year is a leap year.
Outputs False if year is not a leap year."""
year = int(input('Type a year: '))
if (year % 4 ==0 )and (year % 100 != 0):
return True
elif (year % 400 == 0) and (year % 100 != 0):
return True
elif year % 4 == 0 and year % 100 == 0 and year % 400 ==0:
return True
else:
return False
# + colab={"base_uri": "https://localhost:8080/"} id="_ScQ3hGPt3CT" outputId="01e7a394-f01f-40e4-ac37-6f37e5c89a60"
leap_year_detector()
# + [markdown] id="mSzHAsuAHvLI"
# Write a Python Program to Check Prime Number?
#
# + id="claCDRpYK2aI"
def is_prime():
"""Primality test using 6k+-1 optimization."""
n = int(input('Type a number: '))
if n <= 3:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# + id="VEuEp1hKMKfH" colab={"base_uri": "https://localhost:8080/"} outputId="d2aa5d79-faab-4e86-ab1f-15dfd1a1449d"
is_prime()
# + [markdown] id="0724duXNHwQ2"
# Write a Python Program to Print all Prime Numbers in an Interval of 1-10000?
# + id="wB4jq4FlyKXD"
def print_primes():
primes = []
for i in range(1, 100):
if i == 0 or i ==1:
continue
else:
for j in range(2, int(i/2)+1):
if i % j == 0:
break
else:
primes.append(i)
return primes
# + colab={"base_uri": "https://localhost:8080/"} id="Wh3TXZc43Y3t" outputId="c0934630-8dd1-48cc-cb6d-8ee9f38e1abc"
print_primes()
| Python Assignments/Programming_Assignment_3.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#default_exp callback
# -
#export
from fastai.basics import *
from fastai.callback.all import *
from faststyle import *
# # Custom callbacks
# > Custom callbacks
#export
# TODO: This allow loss functions to be separated
class FeatsCallback(Callback):
def __init__(self, get_fts, stl_fts=None, cnt_fts=None):
store_attr('get_fts,stl_fts,cnt_fts')
# Change dict with a class. Can be accessed with .
self.fts = dict(pred={}, targ={}, source={})
self.fts['source']['stl'],self.fts['source']['cnt'] = L(stl_fts),L(cnt_fts)
def after_pred(self):
if len(self.yb) == 0: return
fts = self.fts
fts['pred']['stl'],fts['pred']['cnt'] = self.get_fts(self.pred)
fts['targ']['stl'],fts['targ']['cnt'] = self.get_fts(self.yb[0])
self.learn.yb = (*self.yb, fts)
@classmethod
def from_fns(cls, fns, get_fts):
source_tims = L(TensorImage.create(fn) for fn in L(fns))
stl_fts,cnt_fts = zip(*L(get_fts(o[None]) for o in source_tims))
stl_fts,cnt_fts = L(zip(*stl_fts)),L(zip(*cnt_fts))
return cls(get_fts=get_fts, stl_fts=stl_fts, cnt_fts=cnt_fts)
#export
class WeightsCallback(Callback):
def after_pred(self):
if len(self.yb) == 0: return
self.yb[1]['ws'] = self.xb[0].ws
# ## Export -
#hide
from nbdev.export import *
notebook2script()
| nbs/06_callback.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# Before running the code it is important to download the chrome webdriver: https://chromedriver.chromium.org/downloads
# Open the location in which Python is installed, for that open Anaconda prompt. In my case "C:\ProgramData\Anaconda3"
# +
#Packages to be installed (run only once)
#This package is used to automate tasks in chrome
# !pip install selenium
#This package is used to automated keyboard and mouse functions
# !pip install pyautogui
#This package is used to copy and paste special characters
# !pip install pyperclip
#This package is used to plot the data
# !pip install plotly
# -
# The next part will import the valeu of the euro in relation to reais from Google
# +
#Import Selenium package (https://selenium-python.readthedocs.io/)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#Import pyautogui to control the keyboard and the mouse
import pyautogui
#Import pyperclip to copy and paste special characters
import pyperclip
#Import time to control timing
import time
#Make the code waits x seconds between each comand line
pyautogui.PAUSE = 0.5
#Open a new window in Chrome
new_tab = webdriver.Chrome()
#Open an specific website
new_tab.get("https://www.google.com.br/")
#Access an specific location of the site and type a message
#To find the location of the website you want, right click on it, click on "investigate", type "ctrl + shift + c", click on the part you want (it will be highlighted in blue on the right side), right click on the highlighted blue region -> copy -> copy xpath
new_tab.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input').send_keys('1 <NAME>')
#Access the same location and press enter
new_tab.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input').send_keys(Keys.ENTER)
#Getting the wanted result
#To find the attribute you want just inspect the page like before but instead of copying the xpath read the highlighted blue region and check the data you want
euro_in_reais_str = new_tab.find_element_by_xpath('//*[@id="knowledge-currency__updatable-data-column"]/div[1]/div[2]/span[1]').get_attribute('data-value')
euro_in_reais= float(euro_in_reais_str)
# -
# This part of the code import an excel table and clean the data
# +
#Import the math lybrary
import pandas as pd
#Read the data inside the table (press tab after '.' to check all the methods)
new_table = pd.read_excel("Sales.xlsx")
#To see the table content
display(new_table)
#Prints the summarized information of the table
print(new_table.info())
#Deletes an entire column (axis=1) with the title ("Unnamed: 0")
new_table = new_table.drop("Unnamed: 0", axis=1)
#The values in "TotalGasto" were read as string values,
#to correct that they were changed using ".to_numeric",
#the parameter "errors="coerce"" forces the numbers that cant be
#transformed in numbers to get Nan
new_table[r"Total expends (R$)"] = pd.to_numeric(new_table[r"Total expends (R$)"], errors="coerce")
#To automatic delete columns that are empty the command ".dropna" is used
#how is a parameters that chooses to delete columns (axis=1)
#that are completely empty (how="all")
new_table = new_table.dropna(how="all", axis=1)
#To automatic delete columns that are empty the command ".dropna" is used
#how is a parameters that chooses to delete lines (axis=0)
#that have at least one parameter which is empty (how="any")
new_table = new_table.dropna(how="any", axis=0)
#The command ".value_counts()" counts each value inside the chosen column ("Churn")
display(new_table["Childs"].value_counts())
#The command ".value_counts()" counts each value inside the chosen column ("Churn")
#"(normalize=True)" print the values in percentage
#".map("{:.1%}".format)" formats the code as percentage with one decimal place
display(new_table["Childs"].value_counts(normalize=True).map("{:.1%}".format))
#Update the values of the total expenses
new_table["Total expends (e)"] = new_table["Total expends (R$)"] / euro_in_reais
#To see the table content after treatment and updated values for the total expenses in euros
display(new_table)
#Save new_table as csv
new_table.to_csv("Updated_Sales.csv")
#Sum the total expenses in euros and reais
total_reais_expenses = new_table["Total expends (R$)"].sum()
print(f'The total amount expended in reais was {total_reais_expenses:.2f}')
total_euros_expenses = new_table["Total expends (e)"].sum()
print(f'The total amount expended in reais was {total_euros_expenses:.2f}')
# -
# This part of the code generates some graph to be exported to the email
# +
#Import package to generate the plots
import plotly.express as px
#Iterates through all the columns ".columns" in the table "new_table"
for column in new_table.columns:
# Creates graph using "new_table", values fo x axis "x=column", separating by colors of "Churn"
# Examples of types of graphs are "histogram", and "barchart", press tab after "." to check the options
graph = px.histogram(new_table, x=column, color="Gender")
# Displays the graph
graph.show()
# -
# The last part will summarize the tasks and send via email
# +
#Import Selenium package (https://selenium-python.readthedocs.io/)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#Import pyautogui to control the keyboard and the mouse
#To find the actual mouse position type the command 'pyautogui.position()'
import pyautogui
#Import pyperclip to copy and paste special characters
import pyperclip
#Import time to control timing
import time
#Make the code waits x seconds between each comand line
pyautogui.PAUSE = 0.5
#Open email to send information (in this case hotmail)
new_tab.get("https://outlook.live.com/mail/0/")
#Waits you to sign in in the email
print('After the log in press enter to continue')
x = input()
#Selecting the write email button
#to copy and past the pyperclip package will be used to avoid errors with special characters
xpath = '//*[@id="id__6"]'
pyperclip.copy(xpath)
new_tab.find_element_by_xpath(pyperclip.paste()).click()
#The next commands uses pyautogui to control the keyboard to send the email
#After the login you need to make sure that alt + tab goes to the email window
pyautogui.hotkey('alt','tab')
#use time to wait untill the proccess ends
time.sleep(3)
#typing the name of the recipient and choosing it (the waiting time is the proccess to save the recipient)
pyautogui.write('<EMAIL>')
pyautogui.press('tab')
time.sleep(2)
#Change to the subject scope and wrting the subject
pyautogui.press('tab')
pyautogui.write('Value of euro in reais.')
time.sleep(2)
#Changing to text scope and typing the value of the euro
pyautogui.press('tab')
email_text = f"""
Dear ******Recipient********
Each euro is worth {euro_in_reais:,.2f} reais today.
The total expenses for the day in reais were R$ {total_reais_expenses:,.2f} which corresponds to {total_euros_expenses:,.2f} euros.
Kind Regards,
********Sender*********
"""
pyperclip.copy(email_text)
pyautogui.write(pyperclip.paste())
time.sleep(3)
#Finding the right place to send the email
#pyautogui.hotkey('ctrl','enter') also works to send the e-mail
pyautogui.press('tab')
pyautogui.press('tab')
pyautogui.press('tab')
pyautogui.press('enter')
#close the window
#new_tab.quit()
# -
| SendingEmailWithEuroValue/SendEuroValue.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Import libraries
import xarray as xr
from glob import glob
import numpy as np
pattern_netcdf = 'F:/data/sat_data/aviso/data/*/*.nc'
pattern_zarr = 'F:/data/sat_data/aviso/zarr/'
# # Reading netCDF files
# %%time
#list files
files = [x for x in glob(pattern_netcdf)]
#open dataset
ds=xr.open_mfdataset(files,combine='nested',concat_dim='time')
ds.close()
#remove any duplicates
_, index = np.unique(ds['time'], return_index=True)
ds=ds.isel(time=index)
#rechunck data #data in int16 = 2 bytes
ds_netcdf = ds.chunk({'time':1000,'latitude':180,'longitude':180})
# # Reading Zarr files
# %%time
ds_zarr= xr.open_zarr(pattern_zarr)
# # Compare NetCDF and Zarr computations
# %%time
ts = ds_netcdf.sla.sel(latitude=slice(-10,0),longitude=slice(170,180)).mean({'latitude','longitude'}).plot()
# %%time
ts = ds_zarr.sla.sel(latitude=slice(-10,0),longitude=slice(170,180)).mean({'latitude','longitude'}).plot()
| Test_AVISO_zarr_simple_version.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Plotting particle distributions with holoviews
import numpy as np
from netCDF4 import Dataset
import holoviews as hv
from postladim import ParticleFile
hv.extension('bokeh')
# ### Background map
#
# Make a background bathymetric map.
# A simple land representation is given by colouring the land cells in the
# ROMS file. Take the logarithm of the bathymetry to enhance topographic details
# in the shallow North Sea.
# +
# Read bathymetry and land mask
with Dataset('../data/ocean_avg_0014.nc') as ncid:
H = ncid.variables['h'][:, :]
M = ncid.variables['mask_rho'][:, :]
jmax, imax = M.shape
# Select sea and land features
H = np.where(M > 0, H, np.nan) # valid at sea
M = np.where(M < 1, M, np.nan) # valid on land
# Make land image
ds_land = hv.Dataset((np.arange(imax), np.arange(jmax), M), ['x', 'y'], 'Land mask')
im_land = ds_land.to(hv.Image, kdims=['x', 'y'], group='land')
# Make bathymetry image
ds_bathy = hv.Dataset((np.arange(imax), np.arange(jmax), -np.log10(H)),
['x', 'y'], 'Bathymetry')
im_bathy = ds_bathy.to(hv.Image, kdims=['x', 'y'])
background = im_bathy * im_land
# -
# ### Particle plot function
#
# Open the particle file and make a function to make a
# Scatter element of the particle distribution at a given time step.
# +
pf = ParticleFile('line.nc')
def pplot(timestep):
"""Scatter plot of particle distibution at a given time step"""
X, Y = pf.position(timestep)
return background * hv.Scatter((X, Y))
# -
# ### Still images
#
# Set a greyish colour on land and use shades of blue at sea. Show initial
# and final particle distributions.
# +
# %%opts Image (cmap='blues_r' alpha=0.7)
# %%opts Image.land (cmap=['#AABBAA'])
# %%opts Scatter (color='red')
pplot(0) + pplot(pf.num_times-1) # Final particle distribution
# -
# ### Dynamic map
#
# Make a DynamicMap of all the particle distributions.
# +
# %%output size=150
# %%opts Scatter (color='red')
dmap = hv.DynamicMap(pplot, kdims=['timestep'])
dmap.redim.range(timestep=(0, pf.num_times-1))
# -
| examples/line/holoviews.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# +
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig, ax = plt.subplots()
s, =plt.plot([-0.5], [-0.5], 'ro')
e, =plt.plot([2.0], [2.0], 'bo')
o, =plt.plot([0.5], [0.5], 'yo', markersize=50)
ax.set_aspect('equal', 'box')
ax.set_xlim(-1, 3)
ax.set_ylim(-1, 3)
handles, labels = ax.get_legend_handles_labels()
ax.legend([s, e], ['start', 'end'])
# plt.show()
plt.savefig("Yixuan_chap10_fig13_1.png")
# -
n = 4000
x = np.linspace(-1, 3, n)
y = np.linspace(-1, 3, n)
xv, yv = np.meshgrid(x, y)
inside = np.logical_and(np.logical_and(xv < 1, xv > 0), np.logical_and(yv < 1, yv > 0))
k_att = 1.
P_att = 0.5*k_att*((xv-2)**2+(yv-2)**2)
dist = np.zeros_like(xv)
# dist[np.logical_and((xv>1, yv>1))] = xv
dist = np.sqrt((xv-0.5)**2+(yv-0.5)**2)-0.5
k_rep = 0.5
rho_0 = 1.0
P_rep = np.zeros_like(dist)
delta = 0.1
P_rep[np.logical_and(dist>=delta, dist<=rho_0)] = 0.5*k_rep*(1/dist[np.logical_and(dist>=delta, dist<=rho_0)]-1/rho_0)**2
print(P_rep.max())
P_rep[dist<delta] = float('NaN')
P_rep[dist>rho_0] = 0
pot_fig, pot_ax = plt.subplots(subplot_kw={"projection": "3d"})
surf=pot_ax.plot_surface(xv, yv, P_rep+P_att)
pot_ax.view_init(elev=20., azim=45)
plt.savefig("Yixuan_chap10_fig13_2.png")
# + tags=[]
fig, ax = plt.subplots()
s, =plt.plot([-0.5], [-0.5], 'ro')
e, =plt.plot([2.0], [2.0], 'bo')
o, =plt.plot([0.5], [0.5], 'yo', markersize=50)
ax.legend([s, e], ['start', 'end'])
lvl = np.array([1,2,3,4,5,6,7])
CS=ax.contour(xv, yv, P_rep+P_att, levels=lvl)
ax.clabel(CS, inline=True, fontsize=10)
ax.set_aspect('equal', 'box')
ax.set_xlim(-1, 3)
ax.set_ylim(-1, 3)
plt.savefig("Yixuan_chap10_fig13_2.png")
plt.show()
# -
| figures/planning/Yixuan_chap10.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (Data Science)
# language: python
# name: python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/datascience-1.0
# ---
# # Fine-Tuning a BERT Model and Create a Text Classifier
#
# In the previous section, we've already performed the Feature Engineering to create BERT embeddings from the `reviews_body` text using the pre-trained BERT model, and split the dataset into train, validation and test files. To optimize for Tensorflow training, we saved the files in TFRecord format.
#
# Now, let’s fine-tune the BERT model to our Customer Reviews Dataset and add a new classification layer to predict the `star_rating` for a given `review_body`.
#
# 
#
# As mentioned earlier, BERT’s attention mechanism is called a Transformer. This is, not coincidentally, the name of the popular BERT Python library, “Transformers,” maintained by a company called HuggingFace.
#
# We will use a variant of BERT called [**DistilBert**](https://arxiv.org/pdf/1910.01108.pdf) which requires less memory and compute, but maintains very good accuracy on our dataset.
import time
import random
import pandas as pd
from glob import glob
import argparse
import json
import subprocess
import sys
import os
import tensorflow as tf
from transformers import DistilBertTokenizer
from transformers import TFDistilBertForSequenceClassification
from transformers import DistilBertConfig
# %store -r max_seq_length
try:
max_seq_length
except NameError:
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("[ERROR] Please run the notebooks in the PREPARE section before you continue.")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(max_seq_length)
def select_data_and_label_from_record(record):
x = {
"input_ids": record["input_ids"],
"input_mask": record["input_mask"],
# 'segment_ids': record['segment_ids']
}
y = record["label_ids"]
return (x, y)
def file_based_input_dataset_builder(channel, input_filenames, pipe_mode, is_training, drop_remainder):
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if pipe_mode:
print("***** Using pipe_mode with channel {}".format(channel))
from sagemaker_tensorflow import PipeModeDataset
dataset = PipeModeDataset(channel=channel, record_format="TFRecord")
else:
print("***** Using input_filenames {}".format(input_filenames))
dataset = tf.data.TFRecordDataset(input_filenames)
dataset = dataset.repeat(100)
dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)
name_to_features = {
"input_ids": tf.io.FixedLenFeature([max_seq_length], tf.int64),
"input_mask": tf.io.FixedLenFeature([max_seq_length], tf.int64),
# "segment_ids": tf.io.FixedLenFeature([max_seq_length], tf.int64),
"label_ids": tf.io.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
return tf.io.parse_single_example(record, name_to_features)
dataset = dataset.apply(
tf.data.experimental.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=8,
drop_remainder=drop_remainder,
num_parallel_calls=tf.data.experimental.AUTOTUNE,
)
)
dataset.cache()
if is_training:
dataset = dataset.shuffle(seed=42, buffer_size=10, reshuffle_each_iteration=True)
return dataset
# +
train_data = "./data-tfrecord/bert-train"
train_data_filenames = glob("{}/*.tfrecord".format(train_data))
print("train_data_filenames {}".format(train_data_filenames))
train_dataset = file_based_input_dataset_builder(
channel="train", input_filenames=train_data_filenames, pipe_mode=False, is_training=True, drop_remainder=False
).map(select_data_and_label_from_record)
# +
validation_data = "./data-tfrecord/bert-validation"
validation_data_filenames = glob("{}/*.tfrecord".format(validation_data))
print("validation_data_filenames {}".format(validation_data_filenames))
validation_dataset = file_based_input_dataset_builder(
channel="validation",
input_filenames=validation_data_filenames,
pipe_mode=False,
is_training=False,
drop_remainder=False,
).map(select_data_and_label_from_record)
# +
test_data = "./data-tfrecord/bert-test"
test_data_filenames = glob("{}/*.tfrecord".format(test_data))
print(test_data_filenames)
test_dataset = file_based_input_dataset_builder(
channel="test", input_filenames=test_data_filenames, pipe_mode=False, is_training=False, drop_remainder=False
).map(select_data_and_label_from_record)
# -
# # Specify Manual Hyper-Parameters
epochs = 1
steps_per_epoch = 10
validation_steps = 10
test_steps = 10
freeze_bert_layer = True
learning_rate = 3e-5
epsilon = 1e-08
# # Load Pretrained BERT Model
# https://huggingface.co/transformers/pretrained_models.html
# +
CLASSES = [1, 2, 3, 4, 5]
config = DistilBertConfig.from_pretrained(
"distilbert-base-uncased",
num_labels=len(CLASSES),
id2label={0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
label2id={1: 0, 2: 1, 3: 2, 4: 3, 5: 4},
)
print(config)
# +
transformer_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", config=config)
input_ids = tf.keras.layers.Input(shape=(max_seq_length,), name="input_ids", dtype="int32")
input_mask = tf.keras.layers.Input(shape=(max_seq_length,), name="input_mask", dtype="int32")
embedding_layer = transformer_model.distilbert(input_ids, attention_mask=input_mask)[0]
X = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(50, return_sequences=True, dropout=0.1, recurrent_dropout=0.1))(
embedding_layer
)
X = tf.keras.layers.GlobalMaxPool1D()(X)
X = tf.keras.layers.Dense(50, activation="relu")(X)
X = tf.keras.layers.Dropout(0.2)(X)
X = tf.keras.layers.Dense(len(CLASSES), activation="softmax")(X)
model = tf.keras.Model(inputs=[input_ids, input_mask], outputs=X)
for layer in model.layers[:3]:
layer.trainable = not freeze_bert_layer
# -
# # Setup the Custom Classifier Model Here
# +
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy("accuracy")
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=epsilon)
model.compile(optimizer=optimizer, loss=loss, metrics=[metric])
model.summary()
# +
callbacks = []
log_dir = "./tmp/tensorboard/"
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)
callbacks.append(tensorboard_callback)
# -
history = model.fit(
train_dataset,
shuffle=True,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
validation_data=validation_dataset,
validation_steps=validation_steps,
callbacks=callbacks,
)
print("Trained model {}".format(model))
# # Evaluate on Holdout Test Dataset
test_history = model.evaluate(test_dataset, steps=test_steps, callbacks=callbacks)
print(test_history)
# # Save the Model
tensorflow_model_dir = "./tmp/tensorflow/"
# !mkdir -p $tensorflow_model_dir
model.save(tensorflow_model_dir, include_optimizer=False, overwrite=True)
# !ls -al $tensorflow_model_dir
# !saved_model_cli show --all --dir $tensorflow_model_dir
# +
# # !saved_model_cli run --dir $tensorflow_model_dir --tag_set serve --signature_def serving_default \
# # --input_exprs 'input_ids=np.zeros((1,64));input_mask=np.zeros((1,64))'
# -
# # Predict with Model
# +
import pandas as pd
import numpy as np
from transformers import DistilBertTokenizer
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
sample_review_body = "This product is terrible."
encode_plus_tokens = tokenizer.encode_plus(
sample_review_body, padding=True, max_length=max_seq_length, truncation=True, return_tensors="tf"
)
# The id from the pre-trained BERT vocabulary that represents the token. (Padding of 0 will be used if the # of tokens is less than `max_seq_length`)
input_ids = encode_plus_tokens["input_ids"]
# Specifies which tokens BERT should pay attention to (0 or 1). Padded `input_ids` will have 0 in each of these vector elements.
input_mask = encode_plus_tokens["attention_mask"]
outputs = model.predict(x=(input_ids, input_mask))
prediction = [{"label": config.id2label[item.argmax()], "score": item.max().item()} for item in outputs]
print("")
print('Predicted star_rating "{}" for review_body "{}"'.format(prediction[0]["label"], sample_review_body))
# -
# # Release Resources
# + language="html"
#
# <p><b>Shutting down your kernel for this notebook to release resources.</b></p>
# <button class="sm-command-button" data-commandlinker-command="kernelmenu:shutdown" style="display:none;">Shutdown Kernel</button>
#
# <script>
# try {
# els = document.getElementsByClassName("sm-command-button");
# els[0].click();
# }
# catch(err) {
# // NoOp
# }
# </script>
# + language="javascript"
#
# try {
# Jupyter.notebook.save_checkpoint();
# Jupyter.notebook.session.delete();
# }
# catch(err) {
# // NoOp
# }
| 07_train/01_Train_Reviews_BERT_Transformers_TensorFlow_AdHoc.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/JiroBrent/CPEN-21A-ECE-2-2/blob/main/Loop_Statement.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="sOmSAckh70uJ"
# ##For Loop
# + colab={"base_uri": "https://localhost:8080/"} id="oQBoT74r8Pxt" outputId="f5ba46c9-a5c9-47e2-8d03-e118b6209aa5"
week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for x in week:
print(x)
# + [markdown] id="zqB3DCv-8ZGo"
# ##The Break Statement
# + colab={"base_uri": "https://localhost:8080/"} id="hrzPbfbZ8h2P" outputId="9186d23a-feff-49ff-c5fe-57ad80566368"
week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for x in week:
print(x)
if x=="Thursday":
break
# + colab={"base_uri": "https://localhost:8080/"} id="kpwxx_XK8rVA" outputId="94156fed-5b4f-4216-c0e8-91aeb603f454"
week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for x in week:
if x=="Thursday":
break
print(x)
# + [markdown] id="O0UizBGn8wpp"
# ##Loop Statement
# + colab={"base_uri": "https://localhost:8080/"} id="g_kC8nSh8yj1" outputId="7ac1af01-45d3-4d74-bc88-208cc5c48e12"
for x in "Friday":
print(x)
# + [markdown] id="RkHsc9v-82_9"
# ##The Range () Function
# + colab={"base_uri": "https://localhost:8080/"} id="PpfN5hMd88Qk" outputId="68c896ad-e172-4a76-cc58-5dd4b1c3d961"
for x in range(6):
print(x)
# + colab={"base_uri": "https://localhost:8080/"} id="MPScI0mg9AJ8" outputId="c71a02b8-2a92-48c4-b1be-03922200d178"
for x in range(2,7):
print(x)
# + [markdown] id="QjSDJSsa9DtU"
# ##Nested Loops
# + colab={"base_uri": "https://localhost:8080/"} id="XIzJBWOT9H5U" outputId="5e85ab17-7a68-4f3f-8254-aacd5156167e"
adjective=["red","big","tasty"]
fruits=["apple","banana","cherry"]
for x in adjective:
for y in fruits:
print(x,y)
# + [markdown] id="FuEf9rZm9Ton"
# ##While Loop
# + colab={"base_uri": "https://localhost:8080/"} id="Ig0g_G-c9Yla" outputId="e23d085c-7574-416d-ca52-5e5eace24dbd"
i=1
while i<6:
print(i)
i+=1 #Assignment operator for addition
# + [markdown] id="M2AaVwYo92lE"
# ##The Break Statement
# + colab={"base_uri": "https://localhost:8080/"} id="91nxfrvI942y" outputId="130afbf8-e7e4-4daa-e758-f0e67d6831e7"
i=1
while i<6:
print(i)
if i==3:
break
i+=1 #Assigment operator for addition
# + [markdown] id="u34Uc_YP98Eb"
# ##The Continue Statement
# + colab={"base_uri": "https://localhost:8080/"} id="j_VoMurO9_T_" outputId="3b39e468-b6ff-468b-e821-deb8f0baa2d7"
i=0
while i<6:
i+=1
if i==3:
continue
print(i)
# + [markdown] id="CSqs4F61-CpV"
# ##The Else Statement
# + colab={"base_uri": "https://localhost:8080/"} id="TBJUWkZ0-HYx" outputId="31991c9b-47fc-4195-9fb1-25c0a6f254c4"
i=1
while i<6:
print(i)
i+=1
else:
print("i is no longer less than 6")
# + [markdown] id="t7jmXW6C-LZF"
# ##Application 1
# + colab={"base_uri": "https://localhost:8080/"} id="8lYWHf-l-N22" outputId="d29b250f-8f75-4816-9978-d3cac315a40a"
#Create a Python Program that displays Hello 0 to Hello 10 vertically
hello = ["Hello 0","Hello 1","Hello 2","Hello 3","Hello 4","Hello 5","Hello 6","Hello 7","Hello 8","Hello 9","Hello 10"]
for x in hello:
print(x)
# + [markdown] id="n2TeRInx-Rkz"
# ##Application 2
# + colab={"base_uri": "https://localhost:8080/"} id="2a0mDPJr-V5Z" outputId="29ceafff-cb5b-4521-c533-28043500788a"
#Create a Python program that displays integers less than 10 but not less tha 3
for x in range(3,10):
print(x)
| Loop_Statement.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # An Analysis of Tmdb Movie Database - Profitability Trends
#
# ## Table of Contents
# <ul>
# <li><a href="#intro">Introduction</a></li>
# <li><a href="#wrangling">Data Wrangling</a></li>
# <li><a href="#eda">Exploratory Data Analysis</a></li>
# <li><a href="#conclusions">Conclusions</a></li>
# </ul>
# <a id='intro'></a>
# ## Introduction
#
# In this project I analyze the Imdb data set. I wanted to explore the profitability of movies and see if there is any correlations between the profitability of a movie and its budget or genre and how the profitability is mapped over the years.
#
# The following are the packages that I will use:
#
# +
# Theimport statements for all of the packages that we
# plan to use.
import numpy as np # numpy version 1.16.2
import pandas as pd # pandas version 0.24.2
import matplotlib.pyplot as plt # matplotlib version 3.0.3
import seaborn as sns # seaborn version 0.9.0
# %matplotlib inline
# -
# <a id='wrangling'></a>
# ## Data Wrangling
#
# As it is stated in the discribtion presented on kaggle.com to introduce the datasets, this dataset has been cleaned. However, I wanted to explore any anomalies. So I explored the data as shown below.
#
# I explored the data in general, its shape, summarized statisitcs, and general info.
#
# I discovered that there are several movies with a budget that is equal to 0 dollars. I removed those from the data set as my analysis depends on seeing trends between the budget and revenue of movies.
#
# I also used the adjusted budget and revenues as the numbers there are universal and useful to compare movies over the years (taking inflation into consideration).
#
# ### General Properties
# +
# Loading the data and printing out a few lines. We also Performed operations to inspect data
# types and look for instances of missing or possibly errant data. The data is stored in the file:
# "tmdb-movies.csv"
df = pd.read_csv('tmdb-movies.csv')
df.head()
# -
df.shape
df.describe()
df.info()
# ### Data Cleaning I: Removing Columns of no Interest
#
# I removed several columns of my dataset as I was not interested in them for my main analysis
df.drop(['id','imdb_id'],axis = 1, inplace=True)
df.drop(['original_title','cast','director','tagline','keywords','overview'],axis = 1, inplace=True)
# ### Data Cleaning II: Removing Movies with a Budget = 0 Dollars
# I then removed all the entries with a reported budget of 0 dollars as I am interested to compare the budget to revenue.
# I then extracted the summarized statisitcs of my dataset to make sure that all movies has a budget
df = df[df.budget != 0]
df.describe()
# <a id='eda'></a>
# ## Exploratory Data Analysis
#
# ### Is the budget correlated with the profitability of a movie
# In this section I analyze whther the budget affect the profitability of a movie
#
# I divided the movies into 4 categories:
#
# 1. Highly profitable where the revenue is more than 8 times the budget.
# 2. Reasonably profitable where the revenue is between 2 times and 8 times the budget of a movie.
# 3. Barely priftable where the revenue is more than the budget but less than twice the budget.
# 4. a movie that did not turn any profit
#
# I then calculated the mean of the budget of the movies in these 4 categories.
# I also plotted the histograms of the 4 categories over the budget to see if there is a correlation between profitability and the budget.
hihgly_proft = df.revenue_adj >= 5*df.budget_adj
reasonably_profit = (df.revenue_adj >= 2*df.budget_adj) & (df.revenue_adj < 5*df.budget_adj)
barely_profit = (df.revenue_adj > df.budget_adj) & (df.revenue_adj < 2*df.budget_adj)
lost = df.revenue_adj < df.budget_adj
"{:,}".format(int(df.budget_adj[hihgly_proft].mean()))
"{:,}".format(int(df.budget_adj[reasonably_profit].mean()))
"{:,}".format(int(df.budget_adj[barely_profit].mean()))
"{:,}".format(int(df.budget_adj[lost].mean()))
df.budget_adj[hihgly_proft].plot.hist(xlim=(10**4,2*10**8),figsize=(20,10),alpha = 0.5,bins = 50, label='Highly Profitable')
df.budget_adj[reasonably_profit].plot.hist(xlim=(10**4,2*10**8),figsize=(20,10),alpha = 0.5, bins = 50, label='Reasonably Profitable')
df.budget_adj[barely_profit].plot.hist(xlim=(10**4,2*10**8),figsize=(20,10), alpha = 0.5,bins = 50, label='Barely Profitable')
df.budget_adj[lost].plot.hist(xlim=(10**4,2*10**8),figsize=(20,10), alpha = 0.5,bins = 50, label='Lost')
plt.legend();
# Then I analyzed the revenue not as a multiple of the budget but as a wehole number with the following categories:
# 1) Huge profit where a movie profit is higher than 100 Million Dollars.
# 2) Big profit where a movie profit is more than 10 Million Dollars but less than 100 Million.
# 3) Small profit where a movie profit is more than 1 Million Dollars but less than 10 Million.
# 4) A losing movie turning no profit
#
# For this analysis I focused on movies with a commercial budget of 1 Million Dollars or above.
huge_proft = (df.revenue_adj - df.budget_adj) >= 10**8
big_profit = ((df.revenue_adj - df.budget_adj) >= 10**7) & ((df.revenue_adj - df.budget_adj) < 10**8)
small_profit = ((df.revenue_adj - df.budget_adj) >= 10**6) & ((df.revenue_adj - df.budget_adj) < 10**7)
lost_2 = (df.revenue_adj - df.budget_adj) <= 0
df.budget_adj[huge_proft].plot.hist(xlim=(10**6,2*10**8),figsize=(20,10),alpha = 0.5,bins = 100, label='Profit > 100 Million')
df.budget_adj[big_profit].plot.hist(xlim=(10**6,2*10**8),figsize=(20,10),alpha = 0.5,bins = 100, label='100 Million > Profit > 10 Million')
df.budget_adj[small_profit].plot.hist(ylim=(0,250),xlim=(10**6,2*10**8),figsize=(20,10), alpha = 0.5,bins = 100, label='Profit betwwen 1 & 10 Million')
df.budget_adj[lost_2].plot.hist(ylim=(0,250),xlim=(10**6,2*10**8),figsize=(20,10), alpha = 0.5,bins = 100, label='Lost money')
plt.legend();
# ### Is the profitability correlated with the genre
#
# I analyzed the count of movies per the main genre of the movie (the 1st genre in the list of genres in the genre column). I plotted the count of movies that secured profits higher than 100 Million Dollars and the count of movies that lost money. In this analysis, I focused on movies with a budget over a million dollar (highly commercial movies).
df_commercial = df[df.budget_adj >= 10**6]
df_commercial.genres = df_commercial.genres.str.split('|').str[0].str.strip()
df_commercial.head()
df_commercial_huge_profit = df_commercial[(df_commercial.revenue_adj - df_commercial.budget_adj) >= 10**8]
df_commercial_huge_profit.groupby('genres').budget_adj.count().plot(figsize=(20,10),kind = 'bar',label='The Number of Movies',grid='True')
plt.legend();
df_commercial_lost= df_commercial[(df_commercial.revenue_adj - df_commercial.budget_adj) < 0]
df_commercial_lost.groupby('genres').budget_adj.count().plot(figsize=(20,10),kind = 'bar',label='The Number of Movies',grid='True')
plt.legend();
# In this last analysis, I wanted to see the count of movies in the 4 categories on the sam bar plot to see if profitability is correlated to genre
huge_proft2 = (df_commercial.revenue_adj - df_commercial.budget_adj) >= 10**8
big_profit2 = ((df_commercial.revenue_adj - df_commercial.budget_adj) >= 10**7) & ((df_commercial.revenue_adj - df_commercial.budget_adj) < 10**8)
small_profit2 = ((df_commercial.revenue_adj - df_commercial.budget_adj) >= 10**6) & ((df_commercial.revenue_adj - df_commercial.budget_adj) < 10**7)
lost_3 = (df_commercial.revenue_adj - df_commercial.budget_adj) <= 0
df_commercial.genres[lost_3].value_counts().plot(figsize=(20,10),kind = 'bar',label='Lost',grid='True',color=('red'))
df_commercial.genres[big_profit2].value_counts().plot(figsize=(20,10),kind = 'bar',label='100 Million > Profit > 10 Million',grid='True',color=('green'))
df_commercial.genres[huge_proft2].value_counts().plot(figsize=(20,10),kind = 'bar',label='Profit > 100 Million',grid='True',color=('blue'))
plt.legend();
# <a id='conclusions'></a>
# ## Conclusions
#
# ### Profit Vs. Budget
#
# In the analysis seen above, we can see that there is no clear correlation between the budget of a movie and how profitable it will be. However, we can also see that as the budget exceeds 100 Million dollars, the probability of securing a profit of more than 100 Million dollars becomes more than 50%.
#
# ### Profit Vs. Genre
#
# We can also see fromt the anlaysis of profitability vs. genre that for the most common genres the chance of profitability is not that high compared to some uncommon genres such Thriller where the chance of profitability far exceeds 50%.
#
# ### Reveneue & Budget Over The Years
#
# In the plot below, we can see a very interesting observation: the amount of money spent on movies (adjusted for inflation) has not seen many ups and downs and has been relatively flat for the past 30 or so years whereas the revenues fluctuated more steeply over the same period.
# +
df_commercial = df[df.budget_adj >= 10**6]
df_commercial.groupby('release_year').revenue_adj.mean().plot(xlim=(1960,2015),figsize=(20,10),kind = 'line',label='The Average Revenue',grid='True')
df_commercial.groupby('release_year').budget_adj.mean().plot(xlim=(1960,2015),figsize=(20,10),kind = 'line',label='The Average Budget',grid='True')
plt.legend();
| Introduction_to_Data_Analysis/investigate_tmdb_movie_data_set_Github_version.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python
# language: python
# name: python
# ---
# # IEX Cloud Example Notebooks
#
# In these notebooks, we'll explore some simple functionality using [IEX Cloud](https://iexcloud.io/) data. We'll utilize the official python library, [pyEX](https://github.com/iexcloud/pyEX), as well as some common libraries from the scientific python stack like pandas, matplotlib, etc.
#
# If you're running this tutorial on [Binder](https://mybinder.org/), all the dependencies we use should come preinstalled. If you're running on your own environment, you should start by installing the required dependencies. With [pip](https://pip.pypa.io/en/stable/), this can be done by running the following commands:
#
#
# First, clone this repository:
#
# ```
# git clone git@github.com:iexcloud/examples.git
# # cd examples/
# ```
#
# Then, install the requirements file for these notebooks:
#
# ```
# pip install binder/requirements.txt
# ```
#
# If you're interested in running some of the more structured application examples, you should install the whole `iexexamples` library:
#
# ```
# pip install .
# ```
#
# ## IEX Data and pyEX
# In these examples, we will leverage `pyEX`. You can run against either the real API, or the sandbox API. To ensure the examples run with no code changes, put your token in the `IEX_TOKEN` environment variable. You can do this from python by running the following before any other cells:
#
# ```python
# import os
# os.environ["IEX_TOKEN"] = "pk_..." # Your token here
# ```
#
# ## First example - OHLCV Chart with pandas, matplotlib, and plotly
# We'll start very simple, with a plot of 1 month of data for a US-listed equity's daily open, high, low, close, and volume data.
#
# We'll pull the data directly from the API into pandas, then use matplotlib and plotly to create static and dynamic charts, respectively.
#
# Let's use the symbol `WMT` for Walmart.
# +
# imports
import pyEX as p
import pandas as pd
import matplotlib.pyplot as plt
import mplfinance as mpf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# +
# Instantiate client (will implicitly rely on IEX_TOKEN environment variable, or provide as argument)
c = p.Client()
# Pull 1m (default) as a dataframe
df = c.chartDF("WMT")
# -
# Let's take a quick look at the contents
df.head()
# Let's just plot the OHLC values as lines to start
df[["open", "high", "low", "close"]].plot(figsize=(10, 4))
# Let's use mplfinance to create an OHLCV candlestick+bar plot
mpf.plot(df, type="candle", style='yahoo', volume=True, figsize=(10, 4))
# +
# Now lets use plotly to do the same
# First create 2 subplots:
# Top for candlestick
# Bottom for volume
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
row_heights=[4, 1],
vertical_spacing=0.02)
# Add candlestick to top with OHLC
fig.add_trace(
go.Candlestick(x=df.index,
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close']
),
row=1,
col=1)
# Add bar to bottom for volume, color by value
fig.add_trace(
go.Bar(
x=df.index,
y=df['volume'],
marker=dict(
color=(df["close"] > df["open"]).map({True: "green", False: "red"}) # Map to green when close > open, else red
)
),
row=2,
col=1)
# Drop gapes due to weekends / holidays
df_tmp = df.reindex(pd.date_range(df.index[-1], df.index[0], freq='D'))
fig.update_xaxes(rangebreaks=[dict(values=df_tmp.close[df_tmp.close.isnull()].index)])
# Remove rangeslider from top subplot
fig.update_xaxes(rangeslider= {'visible':False}, row=1, col=1)
# Set height so not as squished
fig.update_layout(height=600)
# Show
fig.show()
# +
# NOTE: if you're looking at this on GitHub, the above plotly chart will not render since it requires the plotly javascript library
| notebooks/1_OHLCV.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + active=""
# 说明:
# 给定由2n个元素组成的数组num,格式为[x1,x2,...,xn,y1,y2,...,yn]。
# 返回格式为[x1,y1,x2,y2,...,xn,yn]的数组。
#
# Example 1:
# Input: nums = [2,5,1,3,4,7], n = 3
# Output: [2,3,5,4,1,7]
# Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
#
# Example 2:
# Input: nums = [1,2,3,4,4,3,2,1], n = 4
# Output: [1,4,2,3,3,2,4,1]
#
# Example 3:
# Input: nums = [1,1,2,2], n = 2
# Output: [1,2,1,2]
#
# Constraints:
# 1、1 <= n <= 500
# 2、nums.length == 2n
# 3、1 <= nums[i] <= 10^3
# -
class Solution:
def shuffle(self, nums, n):
x_arr = nums[:n]
y_arr = nums[n:]
res = []
for i in range(n):
res.append(x_arr[i])
res.append(y_arr[i])
return res
class Solution:
def shuffle(self, nums, n):
res = []
x = 0
y = n
for i in range(n):
res.append(nums[x])
res.append(nums[y])
x+= 1
y+= 1
return res
solution = Solution()
solution.shuffle(nums = [1,1,2,2], n=2)
| Array/1016/1470. Shuffle the Array.ipynb |