code
stringlengths
2.5k
150k
kind
stringclasses
1 value
``` import math import pandas as pd import geopandas as gpd import numpy as np import matplotlib.pyplot as plt import h3 # h3 bins from uber from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures import sys sys.path.append('../Scripts') import capstone_functions as cf ``` # Exploring Model Complexity vs Scores ### In this workbook we slowly add complexity to the partitioning model across a number of dimensions. We use the predicted values for first half (h1) 2019 as the train values and the actual h1 2019 calues as the test set. Finally we submit to zindi to get a score against the actual h2 2019 accident data. ## Baseline_model Uses simple grid based on quatiles to place ambulances around the city Zindi score = 68.9760227569434 ``` cf.full_pipeline(predict_period='2019_h1', frequency_cutoff=0, outlier_filter=0.00, test_period_date_start='2019-01-01', test_period_date_end='2020-07-01', tw_cluster_strategy='baseline', placement_method='baseline', verbose=2) ``` ## Adding complexity 1 Use Partioning algorithm k_means to find optimal location for ambulances that minimizes the euclidean distance between ambulances and points ``` cf.full_pipeline(predict_period='2019_h1', frequency_cutoff=0, outlier_filter=0.00, test_period_date_start='2019-01-01', test_period_date_end='2020-07-01', tw_cluster_strategy='baseline', placement_method='k_means', verbose=2) ``` ## Adding Complexity 2 Choose different algorithm that is not so influenced by outliers. Picks a median point as the cluster center. zindi score = 49.9372135333768 ``` cf.full_pipeline(predict_period='2019_h1', frequency_cutoff=0, outlier_filter=0.00, test_period_date_start='2019-01-01', test_period_date_end='2020-07-01', tw_cluster_strategy='baseline', placement_method='k_medoids', verbose=2) ``` ## Adding Complexity 3 Filter outliers to reduce overfitting for rare events out side of the center of the city zindi score = 44.4289573474198 ``` cf.full_pipeline(predict_period='2019_h1', frequency_cutoff=0, outlier_filter=0.003, test_period_date_start='2019-01-01', test_period_date_end='2020-07-01', tw_cluster_strategy='baseline', placement_method='k_means', verbose=2) ``` ## Adding Complexity 4 Using gradient descent to optimize placement by reducing loss funtion that is euclidean distance between centroids and points. zindi score = 56.49581082745 ``` cf.full_pipeline(predict_period='2019_h1', frequency_cutoff=0, outlier_filter=0.003, test_period_date_start='2019-01-01', test_period_date_end='2020-07-01', tw_cluster_strategy='baseline', placement_method='gradient_descent', verbose=2, lr=8e-3, n_epochs=50, batch_size=2) ``` ## Adding Complexity 5 Creating different placement sets for different time and day combinations zindi score = 43.9846518426706 ``` cf.full_pipeline(predict_period='2019_h1', frequency_cutoff=0, outlier_filter=0.004, test_period_date_start='2019-01-01', test_period_date_end='2020-07-01', tw_cluster_strategy='holiday_simple', placement_method='k_means', verbose=2) ```
github_jupyter
# Multipitch tracking using Echo State Networks ## Introduction In this notebook, we demonstrate how the ESN can deal with multipitch tracking, a challenging multilabel classification problem in music analysis. As this is a computationally expensive task, we have pre-trained models to serve as an entry point. At first, we import all packages required for this task. You can find the import statements below. ``` import time import numpy as np import os import csv from sklearn.base import clone from sklearn.metrics import make_scorer from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from joblib import dump, load import librosa from madmom.processors import SequentialProcessor, ParallelProcessor from madmom.audio import SignalProcessor, FramedSignalProcessor from madmom.audio.stft import ShortTimeFourierTransformProcessor from madmom.audio.filters import LogarithmicFilterbank from madmom.audio.spectrogram import FilteredSpectrogramProcessor, LogarithmicSpectrogramProcessor, SpectrogramDifferenceProcessor from pyrcn.util import FeatureExtractor from pyrcn.echo_state_network import SeqToSeqESNClassifier from pyrcn.datasets import fetch_maps_piano_dataset from pyrcn.metrics import accuracy_score from pyrcn.model_selection import SequentialSearchCV from matplotlib import pyplot as plt from matplotlib import ticker plt.rcParams["font.family"] = "Times New Roman" plt.rcParams["font.size"] = 10 %matplotlib inline import pandas as pd import seaborn as sns from mir_eval import multipitch ``` ## Feature extraction The acoustic features extracted from the input signal are obtained by filtering short-term spectra (window length 4096 samples and hop size 10 ms) with a bank of triangular filters in the frequency domain with log-spaced frequencies. The frequency range was 30 Hz to 17 000 Hz and we used 12 filters per octave. We used logarithmic magnitudes and added 1 inside the logarithm to ensure a minimum value of 0 for a frame without energy. The first derivative between adjacent frames was added in order to enrich the features by temporal information. Binary labels indicating absent (value 0) or present (value 1) pitches for each frame are assigned to each frame. Note that this task is a multilabel classification. Each MIDI pitch is a separate class, and multiple or no classes can be active at a discrete frame index. For a more detailed description, please have a look in our repository ([https://github.com/TUD-STKS/Automatic-Music-Transcription](https://github.com/TUD-STKS/Automatic-Music-Transcription)) with several detailed examples for music analysis tasks. ``` def create_feature_extraction_pipeline(sr=44100, frame_sizes=[1024, 2048, 4096], fps_hz=100.): audio_loading = Pipeline([("load_audio", FeatureExtractor(librosa.load, sr=sr, mono=True)), ("normalize", FeatureExtractor(librosa.util.normalize, norm=np.inf))]) sig = SignalProcessor(num_channels=1, sample_rate=sr) multi = ParallelProcessor([]) for frame_size in frame_sizes: frames = FramedSignalProcessor(frame_size=frame_size, fps=fps_hz) stft = ShortTimeFourierTransformProcessor() # caching FFT window filt = FilteredSpectrogramProcessor(filterbank=LogarithmicFilterbank, num_bands=12, fmin=30, fmax=17000, norm_filters=True, unique_filters=True) spec = LogarithmicSpectrogramProcessor(log=np.log10, mul=5, add=1) diff = SpectrogramDifferenceProcessor(diff_ratio=0.5, positive_diffs=True, stack_diffs=np.hstack) # process each frame size with spec and diff sequentially multi.append(SequentialProcessor([frames, stft, filt, spec, diff])) feature_extractor = FeatureExtractor(SequentialProcessor([sig, multi, np.hstack])) feature_extraction_pipeline = Pipeline([("audio_loading", audio_loading), ("feature_extractor", feature_extractor)]) return feature_extraction_pipeline ``` ## Load and preprocess the dataset This might require a large amount of time and memory. ``` # Load and preprocess the dataset feature_extraction_pipeline = create_feature_extraction_pipeline(sr=44100, frame_sizes=[2048], fps_hz=100) # New object -> PyTorch dataloader / Matlab datastore X_train, X_test, y_train, y_test = fetch_maps_piano_dataset(data_origin="/projects/p_transcriber/MAPS", data_home=None, preprocessor=feature_extraction_pipeline, force_preprocessing=False, label_type="pitch") def tsplot(ax, data,**kw): x = np.arange(data.shape[1]) est = np.mean(data, axis=0) sd = np.std(data, axis=0) cis = (est - sd, est + sd) ax.fill_between(x,cis[0],cis[1],alpha=0.2, **kw) ax.plot(x,est,**kw) ax.margins(x=0) fig, ax = plt.subplots() fig.set_size_inches(4, 1.25) tsplot(ax, np.concatenate(np.hstack((X_train, X_test)))) ax.set_xlabel('Feature Index') ax.set_ylabel('Magnitude') plt.grid() plt.savefig('features_statistics.pdf', bbox_inches='tight', pad_inches=0) ``` ## Set up a ESN To develop an ESN model for multipitch tracking, we need to tune several hyper-parameters, e.g., input_scaling, spectral_radius, bias_scaling and leaky integration. We follow the way proposed in the paper for multipitch tracking and for acoustic modeling of piano music to optimize hyper-parameters sequentially. We define the search spaces for each step together with the type of search (a grid search in this context). At last, we initialize a SeqToSeqESNClassifier with the desired output strategy and with the initially fixed parameters. ``` initially_fixed_params = {'hidden_layer_size': 500, 'input_activation': 'identity', 'k_in': 10, 'bias_scaling': 0.0, 'reservoir_activation': 'tanh', 'leakage': 1.0, 'bi_directional': False, 'k_rec': 10, 'wash_out': 0, 'continuation': False, 'alpha': 1e-5, 'random_state': 42} step1_esn_params = {'leakage': np.linspace(0.1, 1.0, 10)} kwargs_1 = {'random_state': 42, 'verbose': 2, 'n_jobs': 70, 'pre_dispatch': 70, 'n_iter': 14, 'scoring': make_scorer(accuracy_score)} step2_esn_params = {'input_scaling': np.linspace(0.1, 1.0, 10), 'spectral_radius': np.linspace(0.0, 1.5, 16)} step3_esn_params = {'bias_scaling': np.linspace(0.0, 2.0, 21)} kwargs_2_3 = {'verbose': 2, 'pre_dispatch': 70, 'n_jobs': 70, 'scoring': make_scorer(accuracy_score)} # The searches are defined similarly to the steps of a sklearn.pipeline.Pipeline: searches = [('step1', GridSearchCV, step1_esn_params, kwargs_1), ('step2', GridSearchCV, step2_esn_params, kwargs_2_3), ('step3', GridSearchCV, step3_esn_params, kwargs_2_3)] base_esn = SeqToSeqESNClassifier(**initially_fixed_params) ``` ## Optimization We provide a SequentialSearchCV that basically iterates through the list of searches that we have defined before. It can be combined with any model selection tool from scikit-learn. ``` try: sequential_search = load("sequential_search_ll.joblib") except FileNotFoundError: print(FileNotFoundError) sequential_search = SequentialSearchCV(base_esn, searches=searches).fit(X_train, y_train) dump(sequential_search, "sequential_search_ll.joblib") ``` ## Visualize hyper-parameter optimization ``` df = pd.DataFrame(sequential_search.all_cv_results_["step1"]) fig = plt.figure() fig.set_size_inches(2, 1.25) ax = sns.lineplot(data=df, x="param_leakage", y="mean_test_score") plt.xlabel("Leakage") plt.ylabel("Score") # plt.xlim((0, 1)) tick_locator = ticker.MaxNLocator(5) ax.xaxis.set_major_locator(tick_locator) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.4f')) plt.grid() plt.savefig('optimize_leakage.pdf', bbox_inches='tight', pad_inches=0) df = pd.DataFrame(sequential_search.all_cv_results_["step2"]) pvt = pd.pivot_table(df, values='mean_test_score', index='param_input_scaling', columns='param_spectral_radius') pvt.columns = pvt.columns.astype(float) pvt2 = pd.DataFrame(pvt.loc[pd.IndexSlice[0:1], pd.IndexSlice[0.0:1.0]]) fig = plt.figure() ax = sns.heatmap(pvt2, xticklabels=pvt2.columns.values.round(2), yticklabels=pvt2.index.values.round(2), cbar_kws={'label': 'Score'}) ax.invert_yaxis() plt.xlabel("Spectral Radius") plt.ylabel("Input Scaling") fig.set_size_inches(4, 2.5) tick_locator = ticker.MaxNLocator(10) ax.yaxis.set_major_locator(tick_locator) ax.xaxis.set_major_locator(tick_locator) plt.savefig('optimize_is_sr.pdf', bbox_inches='tight', pad_inches=0) df = pd.DataFrame(sequential_search.all_cv_results_["step3"]) fig = plt.figure() fig.set_size_inches(2, 1.25) ax = sns.lineplot(data=df, x="param_bias_scaling", y="mean_test_score") plt.xlabel("Bias Scaling") plt.ylabel("Score") plt.xlim((0, 2)) tick_locator = ticker.MaxNLocator(5) ax.xaxis.set_major_locator(tick_locator) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.5f')) plt.grid() plt.savefig('optimize_bias_scaling.pdf', bbox_inches='tight', pad_inches=0) ``` ## Test the ESN Finally, we test the ESN on unseen data. ``` def _midi_to_frequency(p): return 440. * (2 ** ((p-69)/12)) def get_mir_eval_rows(y, fps=100.): time_t = np.arange(len(y)) / fps freq_hz = [_midi_to_frequency(np.asarray(np.nonzero(row))).ravel() for row in y] return time_t, freq_hz esn = sequential_search.best_estimator_ y_test_pred = esn.predict_proba(X=X_test) scores = np.zeros(shape=(10, 14)) for k, thr in enumerate(np.linspace(0.1, 0.9, 9)): res = [] for y_true, y_pred in zip(y_test, y_test_pred): times_res, freqs_hz_res = get_mir_eval_rows(y_pred[:, 1:]>thr, fps=100.) times_ref, freqs_hz_ref = get_mir_eval_rows(y_true[:, 1:]>thr, fps=100.) res.append(multipitch.metrics(ref_time=times_ref, ref_freqs=freqs_hz_ref, est_time=times_res, est_freqs=freqs_hz_res)) scores[k, :] = np.mean(res, axis=0) plt.plot(np.linspace(0.1, 1, 10), scores[:, :3]) plt.plot(np.linspace(0.1, 1, 10), 2*scores[:, 0]*scores[:, 1] / (scores[:, 0] + scores[:, 1])) plt.xlabel("Threshold") plt.ylabel("Scores") plt.xlim((0.1, 0.9)) plt.legend(("Precision", "Recall", "Accuracy", "F1-Score")) np.mean(list(sequential_search.all_refit_time_.values())) t1 = time.time() esn = clone(sequential_search.best_estimator_).fit(X_train, y_train, n_jobs=8) print("Fitted in {0} seconds".format(time.time() - t1)) t1 = time.time() esn = clone(sequential_search.best_estimator_).fit(X_train, y_train) print("Fitted in {0} seconds".format(time.time() - t1)) ```
github_jupyter
``` %pylab inline import pandas as pd import plotnine as p p.theme_set(p.theme_classic()) plt.rcParams['axes.spines.top'] = False plt.rcParams['axes.spines.right'] = False counts = pd.read_parquet('mca_brain_counts.parquet') sample_info = pd.read_parquet('mca_brain_cell_info.parquet') ``` ### Differential expression Now let us investigate how this count depth effect plays in to a differential expression analysis. With all published large scale experiments cataloging cell types, it is getting increasingly easy to simply fetch some data and do quick comparisons. We will use data from the recent [single cell Mouse Cell Atlas][paper link]. To get something easy to compare, we use the samples called "Brain" and focus on the cells annotated as "Microglia" and "Astrocyte". Out of the ~400,000 cells in the study, these two cell types have 338 and 199 representative cells. On average they have about 700 total UMI counts each, so while the entire study is a pretty large scale, the individual cell types and cells are on a relatively small scale. The final table has 537 cells and 21,979 genes. [paper link]: http://www.cell.com/cell/abstract/S0092-8674(18)30116-8 ``` sample_info['super_cell_type'].value_counts() sub_samples = sample_info.query('super_cell_type in ["Microglia", "Astrocyte"]').copy() sub_counts = counts.reindex(index=sub_samples.index) sub_counts.shape sub_samples['is_astrocyte'] = sub_samples['super_cell_type'] == 'Astrocyte' import NaiveDE sub_samples['total_count'] = sub_counts.sum(1) figsize(11, 3) sub_samples.total_count.hist(grid=False, fc='w', ec='k') sub_samples.total_count.median(), sub_samples.total_count.mean() print(sub_samples.head()) ``` In a differential expression test you simply include a covariate in the design matrix that informs the linear model about the different conditions you want to compare. Here we are comparing microglia and astrocytes. ``` %%time lr_results = NaiveDE.lr_tests(sub_samples, np.log1p(sub_counts.T), alt_model='C(is_astrocyte) + np.log(total_count) + 1', null_model='np.log(total_count) + 1') lr_results.pval = lr_results.pval.clip_lower(lr_results.query('pval != 0')['pval'].min()) lr_results.qval = lr_results.qval.clip_lower(lr_results.query('qval != 0')['qval'].min()) print(lr_results.sort_values('pval').head()) example_genes = ['Apoe', 'Sparcl1', 'Tmsb4x', 'C1qa'] examples = lr_results.loc[example_genes] img = \ p.qplot('C(is_astrocyte)[T.True]', '-np.log10(pval)', lr_results) \ + p.annotate('text', x=examples['C(is_astrocyte)[T.True]'] + 0.33, y=-np.log10(examples['pval']), label=examples.index) \ + p.labs(title='Brain cell data') img.save('4.png', verbose=False) img img = \ p.qplot('C(is_astrocyte)[T.True]', 'np.log(total_count)', lr_results) \ + p.annotate('text', x=examples['C(is_astrocyte)[T.True]'] + 0.33, y=examples['np.log(total_count)'], label=examples.index) \ + p.labs(title='Brain cell data') img.save('5.png', verbose=False) img print(lr_results.sort_values('C(is_astrocyte)[T.True]').head()) print(lr_results.sort_values('C(is_astrocyte)[T.True]').tail()) ``` Also in this case we can see that the count depth weights are deflated for lowly abundant genes. ``` img = \ p.qplot(sub_counts.sum(0).clip_lower(1), lr_results['np.log(total_count)'], log='x') \ + p.labs(x='Gene count across dataset', y='np.log(total_count)', title='Brain cell data') img.save('6.png', verbose=False) img xx = np.linspace(np.log(sub_samples.total_count.min()), np.log(sub_samples.total_count.max())) def linres(gene): yy = \ lr_results.loc[gene, 'np.log(total_count)'] * xx \ + lr_results.loc[gene, 'Intercept'] yy1 = np.exp(yy) yy2 = np.exp(yy + lr_results.loc[gene, 'C(is_astrocyte)[T.True]']) return yy1, yy2 ``` Similar to above, we can look at the relation between count depth and observed counts for a few genes, but we can also make sure to plot the stratifiction into the two cell types and how the regression models are predicting the counts. ``` figsize(11, 3) ax = plt.gca() for i, gene in enumerate(['Apoe', 'Sparcl1', 'Tmsb4x', 'C1qa']): sub_samples['gene'] = counts[gene] plt.subplot(1, 4, i + 1, sharey=ax) if i == 0: plt.ylabel('Counts + 1') plt.loglog() plt.scatter(sub_samples.loc[~sub_samples.is_astrocyte]['total_count'], sub_samples.loc[~sub_samples.is_astrocyte]['gene'] + 1, c='grey', marker='o', label='Microglia') plt.scatter(sub_samples.loc[sub_samples.is_astrocyte]['total_count'], sub_samples.loc[sub_samples.is_astrocyte]['gene'] + 1, c='k', marker='x', label='Astrocyte') yy1, yy2 = linres(gene) plt.plot(np.exp(xx), yy1, c='w', lw=5) plt.plot(np.exp(xx), yy1, c='r', lw=3, ls=':') plt.plot(np.exp(xx), yy2, c='w', lw=5) plt.plot(np.exp(xx), yy2, c='r', lw=3) plt.title(gene) plt.xlabel('Total counts') plt.legend(scatterpoints=3); plt.tight_layout() plt.savefig('7.png', bbox_inches='tight') ``` Again we can see the overall abundance is related to the slope of the lines. Another thing which seem to pop out in these plots is an interaction between cell type and slope. For example looking at C1qa the slope for the microglia seem underestimated. This makes sense, if this is an effect of count noise at low abundances. My takeaway from this is that OLS regression might be OK if counts are large, but at lower levels model parameters are not estimated correctly due to the count nature of the data. Notebooks of the analysis in this post are available [here](https://github.com/vals/Blog/tree/master/180226-count-offsets).
github_jupyter
<table> <tr> <td style="background-color:#ffffff;"> <a href="http://qworld.lu.lv" target="_blank"><img src="../images/qworld.jpg" width="50%" align="left"> </a></td> <td width="70%" style="background-color:#ffffff;vertical-align:bottom;text-align:right;"> prepared by Maksim Dimitrijev(<a href="http://qworld.lu.lv/index.php/qlatvia/">QLatvia</a>) and Özlem Salehi (<a href="http://qworld.lu.lv/index.php/qturkey/">QTurkey</a>) </td> </tr></table> <table width="100%"><tr><td style="color:#bbbbbb;background-color:#ffffff;font-size:11px;font-style:italic;text-align:right;">This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. </td></tr></table> $ \newcommand{\bra}[1]{\langle #1|} $ $ \newcommand{\ket}[1]{|#1\rangle} $ $ \newcommand{\braket}[2]{\langle #1|#2\rangle} $ $ \newcommand{\dot}[2]{ #1 \cdot #2} $ $ \newcommand{\biginner}[2]{\left\langle #1,#2\right\rangle} $ $ \newcommand{\mymatrix}[2]{\left( \begin{array}{#1} #2\end{array} \right)} $ $ \newcommand{\myvector}[1]{\mymatrix{c}{#1}} $ $ \newcommand{\myrvector}[1]{\mymatrix{r}{#1}} $ $ \newcommand{\mypar}[1]{\left( #1 \right)} $ $ \newcommand{\mybigpar}[1]{ \Big( #1 \Big)} $ $ \newcommand{\sqrttwo}{\frac{1}{\sqrt{2}}} $ $ \newcommand{\dsqrttwo}{\dfrac{1}{\sqrt{2}}} $ $ \newcommand{\onehalf}{\frac{1}{2}} $ $ \newcommand{\donehalf}{\dfrac{1}{2}} $ $ \newcommand{\hadamard}{ \mymatrix{rr}{ \sqrttwo & \sqrttwo \\ \sqrttwo & -\sqrttwo }} $ $ \newcommand{\vzero}{\myvector{1\\0}} $ $ \newcommand{\vone}{\myvector{0\\1}} $ $ \newcommand{\stateplus}{\myvector{ \sqrttwo \\ \sqrttwo } } $ $ \newcommand{\stateminus}{ \myrvector{ \sqrttwo \\ -\sqrttwo } } $ $ \newcommand{\myarray}[2]{ \begin{array}{#1}#2\end{array}} $ $ \newcommand{\X}{ \mymatrix{cc}{0 & 1 \\ 1 & 0} } $ $ \newcommand{\I}{ \mymatrix{rr}{1 & 0 \\ 0 & 1} } $ $ \newcommand{\Z}{ \mymatrix{rr}{1 & 0 \\ 0 & -1} } $ $ \newcommand{\Htwo}{ \mymatrix{rrrr}{ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} & \frac{1}{2} } } $ $ \newcommand{\CNOT}{ \mymatrix{cccc}{1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0} } $ $ \newcommand{\norm}[1]{ \left\lVert #1 \right\rVert } $ $ \newcommand{\pstate}[1]{ \lceil \mspace{-1mu} #1 \mspace{-1.5mu} \rfloor } $ <h2> <font color="blue"> Solutions for </font>Grover's Search: Implementation</h2> <a id="task2"></a> <h3>Task 2</h3> Let $N=4$. Implement the query phase and check the unitary matrix for the query operator. Note that we are interested in the top-left $4 \times 4$ part of the matrix since the remaining parts are due to the ancilla qubit. You are given a function $f$ and its corresponding quantum operator $U_f$. First run the following cell to load operator $U_f$. Then you can make queries to $f$ by applying the operator $U_f$ via the following command: <pre>Uf(circuit,qreg). ``` %run ../include/quantum.py ``` Now use phase kickback to flip the sign of the marked element: <ul> <li>Set output qubit (qreg[2]) to $\ket{-}$ by applying X and H.</li> <li>Apply operator $U_f$ <li>Set output qubit (qreg[2]) back.</li> </ul> (Can you guess the marked element by looking at the unitary matrix?) <h3>Solution</h3> ``` from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg = QuantumRegister(3) #No need to define classical register as we are not measuring mycircuit = QuantumCircuit(qreg) #set ancilla mycircuit.x(qreg[2]) mycircuit.h(qreg[2]) Uf(mycircuit,qreg) #set ancilla back mycircuit.h(qreg[2]) mycircuit.x(qreg[2]) job = execute(mycircuit,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(mycircuit,decimals=3) #We are interested in the top-left 4x4 part for i in range(4): s="" for j in range(4): val = str(u[i][j].real) while(len(val)<5): val = " "+val s = s + val print(s) mycircuit.draw(output='mpl') ``` <a id="task3"></a> <h3>Task 3</h3> Let $N=4$. Implement the inversion operator and check whether you obtain the following matrix: $\mymatrix{cccc}{-0.5 & 0.5 & 0.5 & 0.5 \\ 0.5 & -0.5 & 0.5 & 0.5 \\ 0.5 & 0.5 & -0.5 & 0.5 \\ 0.5 & 0.5 & 0.5 & -0.5}$. <h3>Solution</h3> ``` def inversion(circuit,quantum_reg): #step 1 circuit.h(quantum_reg[1]) circuit.h(quantum_reg[0]) #step 2 circuit.x(quantum_reg[1]) circuit.x(quantum_reg[0]) #step 3 circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[2]) #step 4 circuit.x(quantum_reg[1]) circuit.x(quantum_reg[0]) #step 5 circuit.x(quantum_reg[2]) #step 6 circuit.h(quantum_reg[1]) circuit.h(quantum_reg[0]) ``` Below you can check the matrix of your inversion operator and how the circuit looks like. We are interested in top-left $4 \times 4$ part of the matrix, the remaining parts are because we used ancilla qubit. ``` from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg1 = QuantumRegister(3) mycircuit1 = QuantumCircuit(qreg1) #set ancilla qubit mycircuit1.x(qreg1[2]) mycircuit1.h(qreg1[2]) inversion(mycircuit1,qreg1) #set ancilla qubit back mycircuit1.h(qreg1[2]) mycircuit1.x(qreg1[2]) job = execute(mycircuit1,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(mycircuit1,decimals=3) for i in range(4): s="" for j in range(4): val = str(u[i][j].real) while(len(val)<5): val = " "+val s = s + val print(s) mycircuit1.draw(output='mpl') ``` <a id="task4"></a> <h3>Task 4: Testing Grover's search</h3> Now we are ready to test our operations and run Grover's search. Suppose that there are 4 elements in the list and try to find the marked element. You are given the operator $U_f$. First run the following cell to load it. You can access it via <pre>Uf(circuit,qreg).</pre> qreg[2] is the ancilla qubit and it is shared by the query and the inversion operators. Which state do you observe the most? ``` %run ..\include\quantum.py ``` <h3>Solution</h3> ``` from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg = QuantumRegister(3) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) #Grover #initial step - equal superposition for i in range(2): mycircuit.h(qreg[i]) #set ancilla mycircuit.x(qreg[2]) mycircuit.h(qreg[2]) mycircuit.barrier() #change the number of iterations iterations=1 #Grover's iterations. for i in range(iterations): #query Uf(mycircuit,qreg) mycircuit.barrier() #inversion inversion(mycircuit,qreg) mycircuit.barrier() #set ancilla back mycircuit.h(qreg[2]) mycircuit.x(qreg[2]) mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) # print the outcome for outcome in counts: print(outcome,"is observed",counts[outcome],"times") mycircuit.draw(output='mpl') ``` <a id="task5"></a> <h3>Task 5 (Optional, challenging)</h3> Implement the inversion operation for $n=3$ ($N=8$). This time you will need 5 qubits - 3 for the operation, 1 for ancilla, and one more qubit to implement not gate controlled by three qubits. In the implementation the ancilla qubit will be qubit 3, while qubits for control are 0, 1 and 2; qubit 4 is used for the multiple control operation. As a result you should obtain the following values in the top-left $8 \times 8$ entries: $\mymatrix{cccccccc}{-0.75 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 \\ 0.25 & -0.75 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 \\ 0.25 & 0.25 & -0.75 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 \\ 0.25 & 0.25 & 0.25 & -0.75 & 0.25 & 0.25 & 0.25 & 0.25 \\ 0.25 & 0.25 & 0.25 & 0.25 & -0.75 & 0.25 & 0.25 & 0.25 \\ 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & -0.75 & 0.25 & 0.25 \\ 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & -0.75 & 0.25 \\ 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & 0.25 & -0.75}$. <h3>Solution</h3> ``` def big_inversion(circuit,quantum_reg): for i in range(3): circuit.h(quantum_reg[i]) circuit.x(quantum_reg[i]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) circuit.ccx(quantum_reg[2],quantum_reg[4],quantum_reg[3]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) for i in range(3): circuit.x(quantum_reg[i]) circuit.h(quantum_reg[i]) circuit.x(quantum_reg[3]) ``` Below you can check the matrix of your inversion operator. We are interested in the top-left $8 \times 8$ part of the matrix, the remaining parts are because of additional qubits. ``` from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer big_qreg2 = QuantumRegister(5) big_mycircuit2 = QuantumCircuit(big_qreg2) #set ancilla big_mycircuit2.x(big_qreg2[3]) big_mycircuit2.h(big_qreg2[3]) big_inversion(big_mycircuit2,big_qreg2) #set ancilla back big_mycircuit2.h(big_qreg2[3]) big_mycircuit2.x(big_qreg2[3]) job = execute(big_mycircuit2,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(big_mycircuit2,decimals=3) for i in range(8): s="" for j in range(8): val = str(u[i][j].real) while(len(val)<6): val = " "+val s = s + val print(s) ``` <a id="task6"></a> <h3>Task 6: Testing Grover's search for 8 elements (Optional, challenging)</h3> Now we will test Grover's search on 8 elements. You are given the operator $U_{f_8}$. First run the following cell to load it. You can access it via: <pre>Uf_8(circuit,qreg)</pre> Which state do you observe the most? ``` %run ..\include\quantum.py ``` <h3>Solution</h3> ``` def big_inversion(circuit,quantum_reg): for i in range(3): circuit.h(quantum_reg[i]) circuit.x(quantum_reg[i]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) circuit.ccx(quantum_reg[2],quantum_reg[4],quantum_reg[3]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) for i in range(3): circuit.x(quantum_reg[i]) circuit.h(quantum_reg[i]) circuit.x(quantum_reg[3]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg8 = QuantumRegister(5) creg8 = ClassicalRegister(3) mycircuit8 = QuantumCircuit(qreg8,creg8) #set ancilla mycircuit8.x(qreg8[3]) mycircuit8.h(qreg8[3]) #Grover for i in range(3): mycircuit8.h(qreg8[i]) mycircuit8.barrier() #Try 1,2,6,12 8iterations of Grover for i in range(2): Uf_8(mycircuit8,qreg8) mycircuit8.barrier() big_inversion(mycircuit8,qreg8) mycircuit8.barrier() #set ancilla back mycircuit8.h(qreg8[3]) mycircuit8.x(qreg8[3]) for i in range(3): mycircuit8.measure(qreg8[i],creg8[i]) job = execute(mycircuit8,Aer.get_backend('qasm_simulator'),shots=10000) counts8 = job.result().get_counts(mycircuit8) # print the reverse of the outcome for outcome in counts8: print(outcome,"is observed",counts8[outcome],"times") mycircuit8.draw(output='mpl') ``` <a id="task8"></a> <h3>Task 8</h3> Implement an oracle function which marks the element 00. Run Grover's search with the oracle you have implemented. ``` def oracle_00(circuit,qreg): ``` <h3>Solution</h3> ``` def oracle_00(circuit,qreg): circuit.x(qreg[0]) circuit.x(qreg[1]) circuit.ccx(qreg[0],qreg[1],qreg[2]) circuit.x(qreg[0]) circuit.x(qreg[1]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg = QuantumRegister(3) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) #Grover #initial step - equal superposition for i in range(2): mycircuit.h(qreg[i]) #set ancilla mycircuit.x(qreg[2]) mycircuit.h(qreg[2]) mycircuit.barrier() #change the number of iterations iterations=1 #Grover's iterations. for i in range(iterations): #query oracle_00(mycircuit,qreg) mycircuit.barrier() #inversion inversion(mycircuit,qreg) mycircuit.barrier() #set ancilla back mycircuit.h(qreg[2]) mycircuit.x(qreg[2]) mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") mycircuit.draw(output='mpl') ```
github_jupyter
# SOM Tutorial **NOTE:** This tutorial uses supplemental data that can be obtained from [cirada.ca](cirada.ca). It can be unpacked any run from any directory, and contains another copy of this same notebook. In this tutorial we will demonstrate the process of training and analyzing a SOM. As an example we will follow the process used to quantify the probability that a component in the VLASS Component Catalogue is a false positive originating from a sidelobe. The process is divided into these steps: 1. Create the sample 1. Preprocess the images 1. Train the SOM 1. Inspect the SOM 1. Map a sample onto the SOM 1. Annotate the SOM 1. Update the catalogue ``` import numpy as np import pandas as pd from matplotlib import pyplot as plt import pyink as pu ``` # 1. Creating the sample For this exercise we have provided a 10,000 row subset of the catalogue used for the actual analysis. This is done to reduce download sizes and save processing time. The full catalogue (the VLASS Component Catalogue) is available at [cirada.ca](cirada.ca), and the subset is `catalogue.csv`. The initial training sample was selected to include only components with a `Quality_flag` of either 0 or 1 and a `Peak_to_ring` < 3. For the main analysis we trained the SOM on a sample of 100,000 radio components sample = pd.read_csv(cirada_catalogue) sample = sample[sample.Quality_flag.isin([0,1])] sample = sample["Peak_to_ring"] < 3 sample = sample.sample(100000) # choose 100k components at random sample = sample.reset_index(drop=True) # Reset the DataFrame indexing. ``` sample = pd.read_csv("catalogue.csv") sample ``` # 2. Preprocess the images Before preprocessing the images (which creates an Image Binary), first make sure that there is an image cutout for each component in the catalogue. These are already provided in the `cutouts` directory. The steps involved in preprocessing the images will depend on the science at hand. The only common requirement is that all images are normalized onto the same scale (generally 0 to 1) so that the SOM training is well-behaved. ``` import os from tqdm import tqdm from astropy.io import fits from astropy.wcs import WCS def load_fits(filename, ext=0): hdulist = fits.open(filename) d = hdulist[ext] return d def load_radio_fits(filename, ext=0): """Load the data from a single extension of a fits file.""" hdu = load_fits(filename, ext=ext) wcs = WCS(hdu.header).celestial hdu.data = np.squeeze(hdu.data) hdu.header = wcs.to_header() return hdu def scale_data(data, log=False, minsnr=None): """Scale the data so that the SOM behaves appropriately.""" img = np.zeros_like(data) noise = pu.rms_estimate(data[data != 0], mode="mad", clip_rounds=2) # data - np.median(remove_zeros) if minsnr is not None: mask = data >= minsnr * noise else: mask = np.ones_like(data, dtype=bool) data = data[mask] if log: data = np.log10(data) img[mask] = pu.minmax(data) return img.astype(np.float32) def radio_preprocess(idx, sample, path="images", img_size=(150, 150), **kwargs): """Preprocess a VLASS image. """ try: radio_comp = sample.iloc[idx] radio_file = radio_comp["filename"] radio_file = os.path.join(path, radio_file) radio_hdu = load_radio_fits(radio_file) radio_data = radio_hdu.data return idx, scale_data(radio_data, **kwargs) except Exception as e: print(f"Failed on index {idx}: {e}") return None def run_prepro_seq(sample, outfile, shape=(150, 150), **kwargs): """Non-parallelized preprocessing for all VLASS images. """ with pu.ImageWriter(outfile, 0, shape, clobber=True) as pk_img: for idx in tqdm(sample.index): out = radio_preprocess(idx, sample, img_size=shape, **kwargs) if out is not None: pk_img.add(out[1], attributes=out[0]) ``` In order to preprocess the image cutouts for the sidelobe analysis, we adopt a simple algorithm. 1. Estimate the rms in an image cutout 1. Mask out all values below a signal-to-noise ratio of 2 1. Apply a log scaling to the remaining data 1. Scale the data on a 0 to 1 scale Each image is processed sequentially after the creation of an `pu.ImageWriter` object. In addition, the index of the catalogue entry is recorded using the `attributes` keyword in order to track any images that have failed the preprocessing step. This occurs for one image in this sample, which we use to demonstrate how to handle missing entries. The output image binary contains 9999 entries, which is a different size from the original catalogue. The `IMG_catalogue.bin.records.pkl` file is (automatically) used to keep track of the differences. ``` imbin_file = "IMG_catalogue.bin" run_prepro_seq(sample, imbin_file, shape=(150, 150), path="cutouts", log=True, minsnr=2) ``` # 3. Train the SOM The SOM training was performed using the `train_som.sh` script on the main sample of 100,000 components. The resulting SOM is provided here as training on the smaller sample will provide poorer results. A single training stage is run as follows Pink --train $IMG $OUT3 --init $OUT2 --numthreads 10 \ --som-width $WIDTH --som-height $HEIGHT --num-iter 10 \ --dist-func unitygaussian 0.7 0.05 \ --inter-store keep -p 10 -n 360 \ --euclidean-distance-shape circular The parameters involved are as follows: * \$IMG: The Image Binary * \$OUT2: The output SOM file from the previous training stage. * \$OUT3: The output SOM file for the current training stage. * \$HEIGHT: An integer corresponding to the height of the SOM. * \$WIDTH: An integer corresponding to the width of the SOM. * --dist-func unitygaussian: The distribution function is a gaussian whose amplitude is normalized to 1. The two following numbers are the dispersion (sigma) of the gaussian function and then the damping factor, which reduces the magnitude to the update to neurons that are distant from the best-matching neuron. * --euclidean-distance-shape circular: A circular aperture is imposed when computing the Euclidean distance in order to prevent large differences caused by bright components near the image edge being rotated out of the frame. * -n 360: The number of rotations. With n=360 each will be 1 degree. * -num-iter 10: The dataset will be iterated through 10 times during training. # 4. Inspect the SOM Once a SOM has been trained, the first step is to visually assess the neurons to qualitatively determine whether the training has been successful. This visual inspection is best for spotting large errors in the training process. One should look for the morphologies being identified by the SOM, ensuring they are indicative of the structures of interest in the training sample. Here we show the methods in `pyink` that are helpful when plotting the SOM or one of its neurons. In addition, `som.explore` can be used with the interactive matplotlib interface from the command line in order to step through the neurons one by one, with all channels plotted together. ``` som = pu.SOM("SOM_B3_h10_w10_vlass.bin") print(som.som_rank) print(som.som_shape) print(som.neuron_rank) print(som.neuron_shape) print(som.neuron_size) # This SOM contains only one channel, but when multiple are present # the user should select one at a time. som.plot(channel=0) neuron = (4,6) som.plot_neuron(neuron) # Equivalent to # plt.imshow(som[neuron][0]) # The `0` corresponds to the channel of interest. # som.explore() can also be used to navigate the SOM, # but this works best in the matplotlib interactive window. ``` # 5. Map a sample onto the SOM A quantitative exploration of the SOM requires that a sample be mapped onto it. During the inspection stage this should be the training sample, while the final results are obtained by mapping the entire catalogue onto the SOM. A sample can be mapped onto the SOM as follows. This is provided as the final step in `train_som.sh`. Pink --map IMG_catalogue.bin MAP_catalogue.bin SOM_B3_h10_w10_vlass.bin \ --numthreads 8 --som-width 10 --som-height 10 \ --store-rot-flip TRANSFORM_catalogue.bin \ --euclidean-distance-shape circular -n 360 | tee mapping_step.log * MAP_catalogue.bin: The output MAP binary file. * TRANSFORM_catalogue.bin: The output TRANSFORM binary file. ``` import subprocess def map_imbin(imbin_file, som_file, map_file, trans_file, som_width, som_height, numthreads=8, cpu=False, nrot=360, log=True): """Map an image binary onto a SOM using Pink.""" commands = [ "Pink", "--map", imbin_file, map_file, som_file, "--numthreads", f"{numthreads}", "--som-width", f"{som_width}", "--som-height", f"{som_height}", "--store-rot-flip", trans_file, "--euclidean-distance-shape", "circular", "-n", str(nrot), ] if cpu: commands += ["--cuda-off"] if log: map_logfile = map_file.replace(".bin", ".log") with open(map_logfile, "w") as log: subprocess.run(commands, stdout=log) else: subprocess.run(commands) map_imbin("IMG_catalogue.bin", "SOM_B3_h10_w10_vlass.bin", "MAP_catalogue.bin", "TRANSFORM_catalogue.bin", 10, 10, numthreads=8, cpu=False, log=True) ``` In order to explore the mapped dataset, one should load: * The catalogue * The image binary * A SOMSet containing the SOM, Map, and Transform binaries As mentioned previously, the catalogue and image binary are not the same size as one image failed during preprocessing. Provided the `IMG_catalogue.bin.records.pkl` file is in the same dirctory as the main image binary, the `records` property of the image binary will be created. This allows us to trim the initial catalogue used the indices of the images that were preprocessed successfully. ``` # Need to exclude the failed preprocessing entries from the sample. imgs = pu.ImageReader("IMG_catalogue.bin") print(imgs.data.shape) sample = sample.iloc[imgs.records].reset_index() sample somset = pu.SOMSet(som, "MAP_catalogue.bin", "TRANSFORM_catalogue.bin") # Note that these can be initialized either from the file name (string) or # from the corresponding pu.SOM/pu.Mapping/pu.Transform objects. ``` We now show several helpful tools for visualizing either the preprocessed images or mapping statistics. Plotting a preprocessed image can be done using `pu.plot_image`. This will plot a random index unless the `idx` argument is specified. For multi-channel image binaries each channel will be shown along the horizontal axis. ``` # Plot a random preprocessed image. # Can select a specific index using the `idx` keyword. pu.plot_image(imgs, idx=None) ``` One can also plot the best-matching neuron alongside any individual image by setting `show_bmu=True` and including a `pu.SOMSet` in the `somset` keyword. It is also recommended to set `apply_transform=True` so that the neuron will be transformed and trimmed to match the frame of the input image. ``` pu.plot_image(imgs, somset=somset, apply_transform=True, show_bmu=True) # The coherence is a useful quantity to track during the training process print(somset.mapping.coherence()) ``` In order to measure the number of matches to each neuron, use the `bmu_counts` function within the `pu.Mapping` object. This is an array with the same shape as the SOM (so normally 2 dimensions). ``` plt.imshow(somset.mapping.bmu_counts()) plt.colorbar() ``` If each entry in the catalogue is associated with a label, these can also be mapped onto the SOM. This is done using the `pu.Mapping.map_labels` function. We demonstrate this by randomly assigning labels to each entry. ``` # Here we demonstrate how to map a series of labels onto the SOM labels = ["A", "B", "C"] random_labels = np.random.choice(labels, somset.mapping.data.shape[0]) label_counts = somset.mapping.map_labels(random_labels) fig, axes = plt.subplots(1, 3, figsize=(16,4)) for key, ax in zip(label_counts, axes): im = ax.imshow(label_counts[key]) ax.set_title(f"Label: {key}") plt.colorbar(im, ax=ax) ``` # 6. Annotate the SOM The annotation step is where ones attaches some kind of annotation -- whether it be a text label, image-based annotation, etc. -- to each neuron. A text-based annotation can be kept track of in a text file or spreadsheet while examining each neuron using `pu.SOM.explore` or another plotting tool. A script for creating image-based annotations is provided in `pyink/Example_Scripts`. For the project covered in this tutorial our goal was to assign a probability that a component corresponding to a given neuron is a sidelobe. There are a variety of ways to accomplish this. We have done this by plotting, for each neuron, a random sample of 100 images that have been matched to the neuron. A group of radio astronomers then counted the number of false positives for each grid. ``` from itertools import product def grid_plot_prepro(sample: pd.DataFrame, imgs: pu.ImageReader): """Create a 10x10 grid of preprocessed images. See example below. Arguments: sample (pd.DataFrame): The table of 100 images to be plotted. imgs (pu.ImageReader): The ImageReader binary """ inds = sample.index data = imgs.data[inds, 0] if len(inds) < 100: blank = np.zeros((100 - len(inds), 150, 150)) data = np.vstack([data, blank]) data = data.reshape((10, 10, 150, 150)) data = np.moveaxis(data, 2, 1).reshape((1500, 1500)) plt.figure(figsize=(20, 20), constrained_layout=True) plt.imshow(data) plt.xticks([]) plt.yticks([]) for i, j in product(range(10), range(10)): if j * 10 + i >= len(inds): continue plt.scatter(150 * i + 75, 150 * j + 75, marker="o", facecolors="none", edgecolors="r", s=200) for i in range(1, 10): plt.axvline(150 * i, c="w", ls="-", lw=0.5) plt.axhline(150 * i, c="w", ls="-", lw=0.5) neuron = (5, 2) idxs = somset.mapping.images_with_bmu(neuron) subset = sample.iloc[idxs].sample(min(100, len(idxs))) grid_plot_prepro(subset, imgs) ``` In the above neuron the consensus number of spurious components was 55/100. This refers specifically to the component indicated by the red circle. This process was performed for each neuron and the results entered into a csv file. The annotations can then be added as new columns to the original catalogue. In this case each radio component inherits the probability that its neuron corresponds to a sidelobe, so in each of the images presented in the grid the components will have a sidelobe probability of 0.55. More complex approaches would include * Create labels for a sample of images, classifying each as either real or sidelobe. Map these labels onto the SOM and then measure the fraction of sidelobes that are matched to each neuron. * Using the previous sample of classifications, train another machine learning model (likely a neural network) that takes as input the Euclidean distance to _all_ neurons for a single image and is trained to predict whether an image is real or a sidelobe. # 7. Update the catalogue The sidelobe probabilities that we estimated for this SOM are provided in `neuron_info.csv`. This is a csv of a neuron's row, column, and sidelobe probability. We will now show how this information can be appended onto the original catalogue. ``` # First add the best-matching neuron and Euclidean distance info to the catalogue bmu = somset.mapping.bmu() sample["Best_neuron_y"] = bmu[:, 0] sample["Best_neuron_x"] = bmu[:, 1] sample["Neuron_dist"] = somset.mapping.bmu_ed() # Read in the table with sidelobe probabilities neuron_table = pd.read_csv("neuron_info.csv") # Set all values to -1 (null) Psidelobe = -np.ones((neuron_table.bmu_y.max() + 1, neuron_table.bmu_x.max() + 1)) # Update values for each neuron using the corresponding number from the table Psidelobe[neuron_table.bmu_y, neuron_table.bmu_x] = neuron_table.P_sidelobe # Only components with low Peak_to_ring and S_Code != "E" should inherit P_sidelobe sample["P_sidelobe"] = -np.ones(len(sample)) lowPtR = (sample.Peak_to_ring < 3) & (sample.S_Code != "E") sample.loc[lowPtR, "P_sidelobe"] = 0.01 * Psidelobe[bmu[:, 0], bmu[:, 1]][lowPtR] ``` Since one component failed preprocessing, the catalogue does not currently match its original size. To recover the original catalogue we load it once more before merging in the new columns. ``` # First trim the table to just the new columns and a unique component identifier # This saves on computing time and makes the join cleaner. neuron_cols = ["Best_neuron_y", "Best_neuron_x", "Neuron_dist", "P_sidelobe"] update_cols = sample[["Component_name"] + neuron_cols] # Use a left join to merge the colums original_cat = pd.read_csv("catalogue.csv") final_cat = pd.merge(original_cat, update_cols, how="left") final_cat ```
github_jupyter
### Задача 1 Даны значения величины заработной платы заемщиков банка (zp) и значения их поведенческого кредитного скоринга (ks): zp = [35, 45, 190, 200, 40, 70, 54, 150, 120, 110], ks = [401, 574, 874, 919, 459, 739, 653, 902, 746, 832]. Используя математические операции, посчитать коэффициенты линейной регрессии, приняв за X заработную плату (то есть, zp - признак), а за y - значения скорингового балла (то есть, ks - целевая переменная). Произвести расчет как с использованием intercept, так и без. ``` zp = [35, 45, 190, 200, 40, 70, 54, 150, 120, 110] ks = [401, 574, 874, 919, 459, 739, 653, 902, 746, 832] import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = np.array(zp) y = np.array(ks) b = (np.mean(x*y) - np.mean(x)*np.mean(y))/(np.mean(x**2)-np.mean(x)**2) b a = np.mean(y)-b*np.mean(x) a y_hat = a + b*x # кажется b должен рассчитываться по-другому и быть в районе 6. но что-то пошло не так... :( y_bx = b*x plt.scatter(x, y) plt.xlim(0, 220) plt.plot(x, y_hat) plt.plot(x, y_bx) plt.plot(x, x*6) plt.show() mse = ((y - y_hat)**2).sum()/y.size mse ``` ### Задача 2 Посчитать коэффициент линейной регрессии при заработной плате (zp), используя градиентный спуск (без intercept). ``` def mse(b1, y, x, n=10): return np.sum(b1*x - y)**2/n def mse_p(b1, y, x, n=10): return (2/n)*(np.sum((b1*x - y)*x)) alpha = 1e-6 b1 = 1.1 n = x.size count = 1300 for i in range(count): b1 -=alpha*mse_p(b1, y, x) if i%100 == 0: print(f'Iter: {i} b1={b1} mse={mse(b1,y,x)}') ``` ### Задача 3 В каких случаях для вычисления доверительных интервалов и проверки статистических гипотез используется таблица значений функции Лапласа, а в каких - таблица критических точек распределения Стьюдента? **Распределение стьюдента используется когда небольшое количество данных (меньше 100), когда достаточно большое количество данных распределение Стьюдента приближается к стандартному** ### Задача 4 *4. Произвести вычисления как в пункте 2, но с вычислением intercept. Учесть, что изменение коэффициентов должно производиться на каждом шаге одновременно (то есть изменение одного коэффициента не должно влиять на изменение другого во время одной итерации). ``` def mse_p0(b0, b1, y, x, n=10): return (2/n)*(np.sum((b0 + b1*x - y))) def mse_p1(b0, b1, y, x, n=10): return (2/n)*(np.sum((b0 + b1*x - y)*x)) alpha = 1e-6 b1 = 1.1 b0 = 0.9 n = x.size count = 1300 for i in range(count): b0 -=alpha*mse_p0(b0, b1, y, x) b1 -=alpha*mse_p1(b0, b1, y, x) if i%100 == 0: print(f'Iter: {i} b1={b0} b1={b1} mse={mse(b1,y,x)}') plt.scatter(x, y) plt.xlim(0, 220) plt.plot(x, b0 + b1*x) plt.show() ```
github_jupyter
## Machine Learning Pipeline: Wrapping up for Deployment In the previous notebooks, we worked through the typical Machine Learning pipeline steps to build a regression model that allows us to predict house prices. Briefly, we transformed variables in the dataset to make them suitable for use in a Regression model, then we selected the most predictive variables and finally we trained our model. Now, we want to deploy our model. We want to create an API, which we can call with new data, with new characteristics about houses, to get an estimate of the SalePrice. In order to do so, we need to write code in a very specific way. We will show you how to write production code in the next sections. Here, we will summarise the key pieces of code, that we need to take forward for this particular project, to put our model in production. Let's go ahead and get started. ### Setting the seed It is important to note, that we are engineering variables and pre-processing data with the idea of deploying the model. Therefore, from now on, for each step that includes some element of randomness, it is extremely important that we **set the seed**. This way, we can obtain reproducibility between our research and our development code. This is perhaps one of the most important lessons that you need to take away from this course: **Always set the seeds**. Let's go ahead and load the dataset. ``` # to handle datasets import pandas as pd import numpy as np # to divide train and test set from sklearn.model_selection import train_test_split # feature scaling from sklearn.preprocessing import MinMaxScaler # to build the models from sklearn.linear_model import Lasso # to evaluate the models from sklearn.metrics import mean_squared_error, r2_score from math import sqrt # to persist the model and the scaler import joblib # to visualise al the columns in the dataframe pd.pandas.set_option('display.max_columns', None) import warnings warnings.simplefilter(action='ignore') ``` ## Load data We need the training data to train our model in the production environment. ``` # load dataset data = pd.read_csv('houseprice.csv') print(data.shape) data.head() ``` ## Separate dataset into train and test ``` X_train, X_test, y_train, y_test = train_test_split( data, data['SalePrice'], test_size=0.1, # we are setting the seed here random_state=0) X_train.shape, X_test.shape X_train.head() ``` ## Selected features ``` # load selected features features = pd.read_csv('selected_features.csv') # Added the extra feature, LotFrontage features = features['0'].to_list() + ['LotFrontage'] print('Number of features: ', len(features)) ``` ## Engineer missing values ### Categorical variables For categorical variables, we will replace missing values with the string "missing". ``` # make a list of the categorical variables that contain missing values vars_with_na = [ var for var in features if X_train[var].isnull().sum() > 0 and X_train[var].dtypes == 'O' ] # display categorical variables that we will engineer: vars_with_na ``` Note that we have much less categorical variables with missing values than in our original dataset. But we still use categorical variables with NA for the final model, so we need to include this piece of feature engineering logic in the deployment pipeline. ``` # I bring forward the code used in the feature engineering notebook: # (step 2) X_train[vars_with_na] = X_train[vars_with_na].fillna('Missing') X_test[vars_with_na] = X_test[vars_with_na].fillna('Missing') # check that we have no missing information in the engineered variables X_train[vars_with_na].isnull().sum() ``` ### Numerical variables To engineer missing values in numerical variables, we will: - add a binary missing value indicator variable - and then replace the missing values in the original variable with the mode ``` # make a list of the numerical variables that contain missing values: vars_with_na = [ var for var in features if X_train[var].isnull().sum() > 0 and X_train[var].dtypes != 'O' ] # display numerical variables with NA vars_with_na # I bring forward the code used in the feature engineering notebook # with minor adjustments (step 2): var = 'LotFrontage' # calculate the mode mode_val = X_train[var].mode()[0] print('mode of LotFrontage: {}'.format(mode_val)) # replace missing values by the mode # (in train and test) X_train[var] = X_train[var].fillna(mode_val) X_test[var] = X_test[var].fillna(mode_val) ``` ## Temporal variables One of our temporal variables was selected to be used in the final model: 'YearRemodAdd' So we need to deploy the bit of code that creates it. ``` # create the temporal var "elapsed years" # I bring this bit of code forward from the notebook on feature # engineering (step 2) def elapsed_years(df, var): # capture difference between year variable # and year in which the house was sold df[var] = df['YrSold'] - df[var] return df X_train = elapsed_years(X_train, 'YearRemodAdd') X_test = elapsed_years(X_test, 'YearRemodAdd') ``` ### Numerical variable transformation ``` # we apply the logarithmic function to the variables that # were selected (and the target): for var in ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice']: X_train[var] = np.log(X_train[var]) X_test[var] = np.log(X_test[var]) ``` ## Categorical variables ### Group rare labels ``` # let's capture the categorical variables first cat_vars = [var for var in features if X_train[var].dtype == 'O'] cat_vars # bringing thise from the notebook on feature engineering (step 2): def find_frequent_labels(df, var, rare_perc): # function finds the labels that are shared by more than # a certain % of the houses in the dataset df = df.copy() tmp = df.groupby(var)['SalePrice'].count() / len(df) return tmp[tmp > rare_perc].index for var in cat_vars: # find the frequent categories frequent_ls = find_frequent_labels(X_train, var, 0.01) print(var) print(frequent_ls) print() # replace rare categories by the string "Rare" X_train[var] = np.where(X_train[var].isin( frequent_ls), X_train[var], 'Rare') X_test[var] = np.where(X_test[var].isin( frequent_ls), X_test[var], 'Rare') ``` ### Encoding of categorical variables ``` # this function will assign discrete values to the strings of the variables, # so that the smaller value corresponds to the category that shows the smaller # mean house sale price def replace_categories(train, test, var, target): # order the categories in a variable from that with the lowest # house sale price, to that with the highest ordered_labels = train.groupby([var])[target].mean().sort_values().index # create a dictionary of ordered categories to integer values ordinal_label = {k: i for i, k in enumerate(ordered_labels, 0)} # use the dictionary to replace the categorical strings by integers train[var] = train[var].map(ordinal_label) test[var] = test[var].map(ordinal_label) print(var) print(ordinal_label) print() for var in cat_vars: replace_categories(X_train, X_test, var, 'SalePrice') # check absence of na [var for var in features if X_train[var].isnull().sum() > 0] # check absence of na [var for var in features if X_test[var].isnull().sum() > 0] ``` ### Feature Scaling For use in linear models, features need to be either scaled or normalised. In the next section, I will scale features between the min and max values: ``` # capture the target y_train = X_train['SalePrice'] y_test = X_test['SalePrice'] # set up scaler scaler = MinMaxScaler() # train scaler scaler.fit(X_train[features]) # explore maximum values of variables scaler.data_max_ # explore minimum values of variables scaler.data_min_ # transform the train and test set, and add on the Id and SalePrice variables X_train = scaler.transform(X_train[features]) X_test = scaler.transform(X_test[features]) ``` ## Train the Linear Regression: Lasso ``` # set up the model # remember to set the random_state / seed lin_model = Lasso(alpha=0.005, random_state=0) # train the model lin_model.fit(X_train, y_train) # we persist the model for future use joblib.dump(lin_model, 'lasso_regression.pkl') # evaluate the model: # ==================== # remember that we log transformed the output (SalePrice) # in our feature engineering notebook (step 2). # In order to get the true performance of the Lasso # we need to transform both the target and the predictions # back to the original house prices values. # We will evaluate performance using the mean squared error and # the root of the mean squared error and r2 # make predictions for train set pred = lin_model.predict(X_train) # determine mse and rmse print('train mse: {}'.format(int( mean_squared_error(np.exp(y_train), np.exp(pred))))) print('train rmse: {}'.format(int( sqrt(mean_squared_error(np.exp(y_train), np.exp(pred)))))) print('train r2: {}'.format( r2_score(np.exp(y_train), np.exp(pred)))) print() # make predictions for test set pred = lin_model.predict(X_test) # determine mse and rmse print('test mse: {}'.format(int( mean_squared_error(np.exp(y_test), np.exp(pred))))) print('test rmse: {}'.format(int( sqrt(mean_squared_error(np.exp(y_test), np.exp(pred)))))) print('test r2: {}'.format( r2_score(np.exp(y_test), np.exp(pred)))) print() print('Average house price: ', int(np.exp(y_train).median())) ``` That is all for this notebook. And that is all for this section too. **In the next section, we will show you how to productionise this code for model deployment**.
github_jupyter
Foreign Function Interface ==== ``` %matplotlib inline import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np ``` Wrapping functions written in C ---- ### Steps - Write the C header and implementation files - Write the Cython `.pxd` file to declare C function signatures - Write the Cython `.pyx` file to wrap the C functions for Python - Write `setup.py` to automate buiding of the Python extension module - Run `python setup.py build_ext --inplace` to build the module - Import module in Python like any other Python module ### C header file ``` %%file c_math.h #pragma once double plus(double a, double b); double mult(double a, double b); double square(double a); double acc(double *xs, int size); ``` ### C implementation file ``` %%file c_math.c #include <math.h> #include "c_math.h" double plus(double a, double b) { return a + b; }; double mult(double a, double b) { return a * b; }; double square(double a) { return pow(a, 2); }; double acc(double *xs, int size) { double s = 0; for (int i=0; i<size; i++) { s += xs[i]; } return s; }; ``` ### Cython "header" file The `.pxd` file is similar to a header file for Cython. In other words, we can `cimport <filename>.pxd` in the regular Cython `.pyx` files to get access to functions declared in the `.pxd` files. ``` %%file cy_math.pxd cdef extern from "c_math.h": double plus(double a, double b) double mult(double a, double b) double square(double a) double acc(double *xs, int size) ``` ### Cython "implementation" file Here is whhere we actually wrap the C code for use in Python. Note especially how we handle passing in of arrays to a C function expecting a pointer to double using `typed memoryviews`. ``` %%file cy_math.pyx cimport cy_math def py_plus(double a, double b): return cy_math.plus(a, b) def py_mult(double a, double b): return cy_math.mult(a, b) def py_square(double a): return cy_math.square(a) def py_sum(double[::1] xs): cdef int size = len(xs) return cy_math.acc(&xs[0], size) ``` ### Build script `setup.py` This is a build script for Python, similar to a Makefile ``` %%file setup.py from distutils.core import setup, Extension from Cython.Build import cythonize import numpy as np ext = Extension("cy_math", sources=["cy_math.pyx", "c_math.c"], libraries=["m"], extra_compile_args=["-w", "-std=c99"]) setup(name = "Math Funcs", ext_modules = cythonize(ext)) ``` ### Building an extension module ``` ! python setup.py clean ! python setup.py -q build_ext --inplace ! ls cy_math* ``` ### Using the extension module in Python ``` import cy_math import numpy as np print(cy_math.py_plus(3, 4)) print(cy_math.py_mult(3, 4)) print(cy_math.py_square(3)) xs = np.arange(10, dtype='float') print(cy_math.py_sum(xs)) ``` ### Confirm that we are getting C speedups by comparing with pure Python accumulator ``` def acc(xs): s = 0 for x in xs: s += x return s import cy_math xs = np.arange(1000000, dtype='float') %timeit -r3 -n3 acc(xs) %timeit -r3 -n3 cy_math.py_sum(xs) ``` C++ ---- This is similar to C. We will use Cython to wrap a simple funciton. ``` %%file add.hpp #pragma once int add(int a, int b); %%file add.cpp int add(int a, int b) { return a+b; } %%file plus.pyx cdef extern from 'add.cpp': int add(int a, int b) def plus(a, b): return add(a, b) ``` #### Note that essentially the only difference from C is `language="C++"` and the flag `-std=c++11` ``` %%file setup.py from distutils.core import setup, Extension from Cython.Build import cythonize ext = Extension("plus", sources=["plus.pyx", "add.cpp"], extra_compile_args=["-w", "-std=c++11"]) setup( ext_modules = cythonize( ext, language="c++", )) %%bash python setup.py -q build_ext --inplace import plus plus.plus(3, 4) ``` Wrap an R function from libRmath using `ctypes` ---- R comes with a standalone C library of special functions and distributions, as described in the official documentation. These functions can be wrapped for use in Python. ### Building the Rmath standalone library ```bash git clone https://github.com/JuliaLang/Rmath-julia.git cd Rmath-julia/src make cd ../.. ``` #### Functions to wrap ``` ! grep "\s.norm(" Rmath-julia/include/Rmath.h from ctypes import CDLL, c_int, c_double %%bash ls Rmath-julia/src/*so lib = CDLL('Rmath-julia/src/libRmath-julia.so') def rnorm(mu=0, sigma=1): lib.rnorm.argtypes = [c_double, c_double] lib.rnorm.restype = c_double return lib.rnorm(mu, sigma) def dnorm(x, mean=0, sd=1, log=0): lib.dnorm4.argtypes = [c_double, c_double, c_double, c_int] lib.dnorm4.restype = c_double return lib.dnorm4(x, mean, sd, log) def pnorm(q, mu=0, sd=1, lower_tail=1, log_p=0): lib.pnorm5.argtypes = [c_double, c_double, c_double, c_int, c_int] lib.pnorm5.restype = c_double return lib.pnorm5(q, mu, sd, lower_tail, log_p) def qnorm(p, mu=0, sd=1, lower_tail=1, log_p=0): lib.qnorm5.argtypes = [c_double, c_double, c_double, c_int, c_int] lib.qnorm5.restype = c_double return lib.qnorm5(p, mu, sd, lower_tail, log_p) pnorm(0, mu=2) qnorm(0.022750131948179212, mu=2) plt.hist([rnorm() for i in range(100)]) pass xs = np.linspace(-3,3,100) plt.plot(xs, list(map(dnorm, xs))) pass ``` ### Using Cython to wrap standalone library ``` %%file rmath.pxd cdef extern from "Rmath-julia/include/Rmath.h": double dnorm(double, double, double, int) double pnorm(double, double, double, int, int) double qnorm(double, double, double, int, int) double rnorm(double, double) %%file rmath.pyx cimport rmath def rnorm_(mu=0, sigma=1): return rmath.rnorm(mu, sigma) def dnorm_(x, mean=0, sd=1, log=0): return rmath.dnorm(x, mean, sd, log) def pnorm_(q, mu=0, sd=1, lower_tail=1, log_p=0): return rmath.pnorm(q, mu, sd, lower_tail, log_p) def qnorm_(p, mu=0, sd=1, lower_tail=1, log_p=0): return rmath.qnorm(p, mu, sd, lower_tail, log_p) %%file setup.py from distutils.core import setup, Extension from Cython.Build import cythonize ext = Extension("rmath", sources=["rmath.pyx"], include_dirs=["Rmath-julia/include"], library_dirs=["Rmath-julia/src"], libraries=["Rmath-julia"], runtime_library_dirs=["Rmath-julia/src"], extra_compile_args=["-w", "-std=c99", "-DMATHLIB_STANDALONE"], extra_link_args=[], ) setup( ext_modules = cythonize( ext )) ! python setup.py build_ext --inplace import rmath plt.hist([rmath.rnorm_() for i in range(100)]) pass xs = np.linspace(-3,3,100) plt.plot(xs, list(map(rmath.dnorm_, xs))) pass ``` ### `Cython` wrappers are faster than `ctypes` ``` %timeit pnorm(0, mu=2) %timeit rmath.pnorm_(0, mu=2) ``` Fortran ---- ``` ! pip install fortran-magic %load_ext fortranmagic %%fortran subroutine fort_sum(N, s) integer*8, intent(in) :: N integer*8, intent(out) :: s integer*8 i s = 0 do i = 1, N s = s + i*i end do end fort_sum(10) ``` #### Another example from the [documentation](http://nbviewer.ipython.org/github/mgaitan/fortran_magic/blob/master/documentation.ipynb) ``` %%fortran --link lapack subroutine solve(A, b, x, n) ! solve the matrix equation A*x=b using LAPACK implicit none real*8, dimension(n,n), intent(in) :: A real*8, dimension(n), intent(in) :: b real*8, dimension(n), intent(out) :: x integer :: pivot(n), ok integer, intent(in) :: n x = b ! find the solution using the LAPACK routine SGESV call DGESV(n, 1, A, n, pivot, x, n, ok) end subroutine A = np.array([[1, 2.5], [-3, 4]]) b = np.array([1, 2.5]) solve(A, b) ``` Interfacing with R ---- ``` %load_ext rpy2.ipython %%R library(ggplot2) suppressPackageStartupMessages( ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() + geom_smooth(method=loess) ) ``` #### Converting between Python and R ``` %R -o mtcars ``` #### `mtcars` is now a Python dataframe ``` mtcars.head(n=3) ``` #### We can also pass data from Python to R ``` x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) %%R -i x,y plot(x, y, main="Sine curve in R base graphics") ```
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Import-the-pandas,-os,-and-sys-libraries" data-toc-modified-id="Import-the-pandas,-os,-and-sys-libraries-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Import the pandas, os, and sys libraries</a></span></li><li><span><a href="#Import-the-basicdescriptives-module" data-toc-modified-id="Import-the-basicdescriptives-module-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Import the basicdescriptives module</a></span></li><li><span><a href="#Show-summary-statistics-for-continuous-variables" data-toc-modified-id="Show-summary-statistics-for-continuous-variables-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Show summary statistics for continuous variables</a></span></li><li><span><a href="#Create-a-function-to-count-missing-values-by-columns-and-rows" data-toc-modified-id="Create-a-function-to-count-missing-values-by-columns-and-rows-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Create a function to count missing values by columns and rows</a></span></li><li><span><a href="#Call-the-getmissings-function" data-toc-modified-id="Call-the-getmissings-function-5"><span class="toc-item-num">5&nbsp;&nbsp;</span>Call the getmissings function</a></span></li><li><span><a href="#Call-the-makefreqs-function" data-toc-modified-id="Call-the-makefreqs-function-6"><span class="toc-item-num">6&nbsp;&nbsp;</span>Call the makefreqs function</a></span></li><li><span><a href="#Pass-the-marital-status,-gender,-and-college-enrollment-columns-to-the-getcnts-function" data-toc-modified-id="Pass-the-marital-status,-gender,-and-college-enrollment-columns-to-the-getcnts-function-7"><span class="toc-item-num">7&nbsp;&nbsp;</span>Pass the marital status, gender, and college enrollment columns to the getcnts function</a></span></li><li><span><a href="#Use-the-rowsel-parameter-of-getcnts-to-limit-the-output-to-specific-rows" data-toc-modified-id="Use-the-rowsel-parameter-of-getcnts-to-limit-the-output-to-specific-rows-8"><span class="toc-item-num">8&nbsp;&nbsp;</span>Use the rowsel parameter of getcnts to limit the output to specific rows</a></span></li></ul></div> # Import the pandas, os, and sys libraries ``` import pandas as pd import os import sys import watermark %load_ext watermark %watermark -n -i -iv nls97 = pd.read_csv('data/nls97f.csv') nls97.set_index('personid', inplace=True) ``` # Import the basicdescriptives module ``` sys.path.append(os.getcwd() + '\helperfunctions') # print(sys.path) import basicdescriptives as bd ``` # Show summary statistics for continuous variables ``` bd.gettots(nls97[['satverbal', 'satmath']]).T bd.gettots(nls97.filter(like='weeksworked')) ``` # Create a function to count missing values by columns and rows ``` missingsbycols, missingsbyrows = bd.getmissings( nls97[['weeksworked16', 'weeksworked17']], True) missingsbycols # the missingbyrows value shows that 73.9% of rows have 0 missing values for # weeksworked16 and weeksworked17 missingsbyrows nls97.shape ``` # Call the getmissings function ``` missingsbycols, missingsbyrows = bd.getmissings( nls97[['weeksworked16', 'weeksworked17']]) missingsbyrows # Create a function to calculate frequencies for all categorical variables ``` # Call the makefreqs function ``` # change data type of each object column to category nls97.loc[:, nls97.dtypes == 'object'] = nls97.select_dtypes( ['object']).apply(lambda x: x.astype('category')) nls97.info() bd.makefreqs(nls97, 'views/nlsfreqs.txt') ``` # Pass the marital status, gender, and college enrollment columns to the getcnts function ``` # group counts and percentages for subgroups within groups bd.get_counts(nls97, ['maritalstatus', 'gender', 'colenroct00']) ``` # Use the rowsel parameter of getcnts to limit the output to specific rows ``` bd.get_counts(nls97, ['maritalstatus', 'gender', 'colenroct00'], 'colenroct00.str[0:1] == "1"') ```
github_jupyter
``` import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.utils import shuffle from sklearn.metrics import accuracy_score from synthesize_data_multiclass import synthesize_data import ER_multiclass as ER from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt %matplotlib inline np.random.seed(1) def inference(X_train,y_train,X_test,y_test,method='expectation_reflection'): if method == 'expectation_reflection': h0,w = ER.fit(X_train,y_train,niter_max=100,regu=0.001) y_pred = ER.predict(X_test,h0,w) else: if method == 'logistic_regression': model = LogisticRegression(multi_class='multinomial',solver='saga') if method == 'naive_bayes': model = GaussianNB() if method == 'random_forest': model = RandomForestClassifier(criterion = "gini", random_state = 1, max_depth=3, min_samples_leaf=5,n_estimators=100) if method == 'decision_tree': model = DecisionTreeClassifier() model.fit(X_train, y_train) y_pred = model.predict(X_test) accuracy = accuracy_score(y_test,y_pred) return accuracy list_methods=['logistic_regression','naive_bayes','random_forest','decision_tree','expectation_reflection'] #list_methods=['logistic_regression','expectation_reflection'] def compare_inference(X,y,train_size): npred = 500 accuracy = np.zeros((len(list_methods),npred)) precision = np.zeros((len(list_methods),npred)) recall = np.zeros((len(list_methods),npred)) accuracy_train = np.zeros((len(list_methods),npred)) for ipred in range(npred): #X, y = shuffle(X, y) X_train0,X_test,y_train0,y_test = train_test_split(X,y,test_size=0.2,random_state = ipred) idx_train = np.random.choice(len(y_train0),size=int(train_size*len(y)),replace=False) X_train,y_train = X_train0[idx_train],y_train0[idx_train] for i,method in enumerate(list_methods): accuracy[i,ipred] = inference(X_train,y_train,X_test,y_test,method) return accuracy.mean(axis=1) from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) print(X.shape,y.shape) print(np.unique(y,return_counts=True)) X from sklearn.preprocessing import MinMaxScaler X = MinMaxScaler().fit_transform(X) X, y = shuffle(X, y) list_train_size = [0.8,0.6,0.4,0.2] acc = np.zeros((len(list_train_size),len(list_methods))) for i,train_size in enumerate(list_train_size): acc[i,:] = compare_inference(X,y,train_size) print(train_size,acc[i,:]) plt.figure(figsize=(4,3)) plt.plot(list_train_size,acc[:,0],'k--',marker='o',mfc='none',label='Logistic Regression') plt.plot(list_train_size,acc[:,1],'b--',marker='s',mfc='none',label='Naive Bayes') plt.plot(list_train_size,acc[:,2],'r--',marker='^',mfc='none',label='Random Forest') #plt.plot(list_train_size,acc[:,3],'b--',label='Decision Tree') plt.plot(list_train_size,acc[:,-1],'k-',marker='o',label='Expectation Reflection') plt.xlabel('train size') plt.ylabel('accuracy') plt.legend() ```
github_jupyter
``` # from google.colab import drive # drive.mount('/content/drive') # path = "/content/drive/MyDrive/Research/cods_comad_plots/sdc_task/mnist/" import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from matplotlib import pyplot as plt import copy # Ignore warnings import warnings warnings.filterwarnings("ignore") torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5), (0.5))]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) classes = ('zero','one','two','three','four','five','six','seven','eight','nine') foreground_classes = {'zero','one'} fg_used = '01' fg1, fg2 = 0,1 all_classes = {'zero','one','two','three','four','five','six','seven','eight','nine'} background_classes = all_classes - foreground_classes background_classes trainloader = torch.utils.data.DataLoader(trainset, batch_size=10, shuffle = False) testloader = torch.utils.data.DataLoader(testset, batch_size=10, shuffle = False) dataiter = iter(trainloader) background_data=[] background_label=[] foreground_data=[] foreground_label=[] batch_size=10 for i in range(6000): images, labels = dataiter.next() for j in range(batch_size): if(classes[labels[j]] in background_classes): img = images[j].tolist() background_data.append(img) background_label.append(labels[j]) else: img = images[j].tolist() foreground_data.append(img) foreground_label.append(labels[j]) foreground_data = torch.tensor(foreground_data) foreground_label = torch.tensor(foreground_label) background_data = torch.tensor(background_data) background_label = torch.tensor(background_label) def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img#.numpy() plt.imshow(np.reshape(npimg, (28,28))) plt.show() foreground_data.shape, foreground_label.shape, background_data.shape, background_label.shape val, idx = torch.max(background_data, dim=0, keepdims= True,) # torch.abs(val) mean_bg = torch.mean(background_data, dim=0, keepdims= True) std_bg, _ = torch.max(background_data, dim=0, keepdims= True) mean_bg.shape, std_bg.shape foreground_data = (foreground_data - mean_bg) / std_bg background_data = (background_data - mean_bg) / torch.abs(std_bg) foreground_data.shape, foreground_label.shape, background_data.shape, background_label.shape torch.sum(torch.isnan(foreground_data)), torch.sum(torch.isnan(background_data)) imshow(foreground_data[0]) imshow(background_data[0]) ``` ## generating CIN train and test data ``` m = 5 desired_num = 1000 np.random.seed(0) bg_idx = np.random.randint(0,47335,m-1) fg_idx = np.random.randint(0,12665) bg_idx, fg_idx for i in background_data[bg_idx]: imshow(i) imshow(torch.sum(background_data[bg_idx], axis = 0)) imshow(foreground_data[fg_idx]) tr_data = ( torch.sum(background_data[bg_idx], axis = 0) + foreground_data[fg_idx] )/m tr_data.shape imshow(tr_data) foreground_label[fg_idx] train_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images train_label=[] # label of mosaic image = foreground class present in that mosaic for i in range(desired_num): np.random.seed(i) bg_idx = np.random.randint(0,47335,m-1) fg_idx = np.random.randint(0,12665) tr_data = ( torch.sum(background_data[bg_idx], axis = 0) + foreground_data[fg_idx] ) / m label = (foreground_label[fg_idx].item()) train_images.append(tr_data) train_label.append(label) train_images = torch.stack(train_images) train_images.shape, len(train_label) imshow(train_images[0]) test_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images test_label=[] # label of mosaic image = foreground class present in that mosaic for i in range(10000): np.random.seed(i) fg_idx = np.random.randint(0,12665) tr_data = ( foreground_data[fg_idx] ) / m label = (foreground_label[fg_idx].item()) test_images.append(tr_data) test_label.append(label) test_images = torch.stack(test_images) test_images.shape, len(test_label) imshow(test_images[0]) torch.sum(torch.isnan(train_images)), torch.sum(torch.isnan(test_images)) np.unique(train_label), np.unique(test_label) ``` ## creating dataloader ``` class CIN_Dataset(Dataset): """CIN_Dataset dataset.""" def __init__(self, list_of_images, labels): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.image = list_of_images self.label = labels def __len__(self): return len(self.label) def __getitem__(self, idx): return self.image[idx] , self.label[idx] batch = 250 train_data = CIN_Dataset(train_images, train_label) train_loader = DataLoader( train_data, batch_size= batch , shuffle=True) test_data = CIN_Dataset( test_images , test_label) test_loader = DataLoader( test_data, batch_size= batch , shuffle=False) train_loader.dataset.image.shape, test_loader.dataset.image.shape ``` ## model ``` class Classification(nn.Module): def __init__(self): super(Classification, self).__init__() self.fc1 = nn.Linear(28*28, 2) torch.nn.init.xavier_normal_(self.fc1.weight) torch.nn.init.zeros_(self.fc1.bias) def forward(self, x): x = x.view(-1, 28*28) x = self.fc1(x) return x ``` ## training ``` torch.manual_seed(12) classify = Classification().double() classify = classify.to("cuda") import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer_classify = optim.Adam(classify.parameters(), lr=0.001 ) #, momentum=0.9) correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in train_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( desired_num , 100 * correct / total)) print("total correct", correct) print("total train set images", total) correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in test_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( 10000 , 100 * correct / total)) print("total correct", correct) print("total train set images", total) nos_epochs = 200 tr_loss = [] for epoch in range(nos_epochs): # loop over the dataset multiple times epoch_loss = [] cnt=0 iteration = desired_num // batch running_loss = 0 #training data set for i, data in enumerate(train_loader): inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") inputs = inputs.double() # zero the parameter gradients optimizer_classify.zero_grad() outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) # print(outputs) # print(outputs.shape,labels.shape , torch.argmax(outputs, dim=1)) loss = criterion(outputs, labels) loss.backward() optimizer_classify.step() running_loss += loss.item() mini = 1 if cnt % mini == mini-1: # print every 40 mini-batches # print('[%d, %5d] loss: %.3f' %(epoch + 1, cnt + 1, running_loss / mini)) epoch_loss.append(running_loss/mini) running_loss = 0.0 cnt=cnt+1 tr_loss.append(np.mean(epoch_loss)) if(np.mean(epoch_loss) <= 0.001): break; else: print('[Epoch : %d] loss: %.3f' %(epoch + 1, np.mean(epoch_loss) )) print('Finished Training') plt.plot(tr_loss) correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in train_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( desired_num , 100 * correct / total)) print("total correct", correct) print("total train set images", total) correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in test_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( 10000 , 100 * correct / total)) print("total correct", correct) print("total train set images", total) ```
github_jupyter
# Let's post a message to Slack In this session, we're going to use Python to post a message to Slack. I set up [a team for us](https://ire-cfj-2017.slack.com/) so we can mess around with the [Slack API](https://api.slack.com/). We're going to use a simple [_incoming webhook_](https://api.slack.com/incoming-webhooks) to accomplish this. ### Hello API API stands for "Application Programming Interface." An API is a way to interact programmatically with a software application. If you want to post a message to Slack, you could open a browser and navigate to your URL and sign in with your username and password (or open the app), click on the channel you want, and start typing. OR ... you could post your Slack message with a Python script. ### Hello environmental variables The code for this boot camp [is on the public internet](https://github.com/ireapps/cfj-2017). We don't want anyone on the internet to be able to post messages to our Slack channels, so we're going to use an [environmental variable](https://en.wikipedia.org/wiki/Environment_variable) to store our webhook. The environmental variable we're going to use -- `IRE_CFJ_2017_SLACK_HOOK` -- should already be stored on your computer. Python has a standard library module for working with the operating system called [`os`](https://docs.python.org/3/library/os.html). The `os` module has a data attribute called `environ`, a dictionary of environmental variables stored on your computer. (Here is a new thing: Instead of using brackets to access items in a dictionary, you can use the `get()` method. The advantage to doing it this way: If the item you're trying to get doesn't exist in your dictionary, it'll return `None` instead of throwing an exception, which is sometimes a desired behavior.) ``` from os import environ slack_hook = environ.get('IRE_CFJ_2017_SLACK_HOOK', None) ``` ### Hello JSON So far we've been working with tabular data -- CSVs with columns and rows. Most modern web APIs prefer to shake hands with a data structure called [JSON](http://www.json.org/) (**J**ava**S**cript **O**bject **N**otation), which is more like a matryoshka doll. ![](https://media.giphy.com/media/Ud5r7tzmG4De0/giphy.gif "russian nesting dolls") Python has a standard library module for working with JSON data called [`json`](https://docs.python.org/3/library/json.html). Let's import it. ``` import json ``` ### Using `requests` to post data We're also going to use the `requests` library again, except this time, instead of using the `get()` method to get something off the web, we're going to use the `post()` method to send data _to_ the web. ``` import requests ``` ### Formatting the data correctly The JSON data we're going to send to the Slack webhook will start its life as a Python dictionary. Then we'll use the `json` module's `dumps()` method to turn it into a string of JSON. ``` # build a dictionary of payload data payload = { 'channel': '#general', 'username': 'IRE Python Bot', 'icon_emoji': ':ire:', 'text': 'helllllllo!' } # turn it into a string of JSON payload_as_json = json.dumps(payload) ``` ### Send it off to Slack ``` # check to see if you have the webhook URL if slack_hook: # send it to slack! requests.post(slack_hook, data=payload_as_json) else: # if you don't have the webhook env var, print a message to the terminal print("You don't have the IRE_CFJ_2017_SLACK_HOOK" " environmental variable") ``` ### _Exercise_ Read through the [Slack documentation](https://api.slack.com/incoming-webhooks) and post a message to a Slack channel ... - with a different emoji - with an image URL instead of an emoji - with a link in it - with an attachment - with other kinds of fancy formatting ### _Extra credit: Slack alert_ Scenario: You cover the Fort Calhoun Nuclear Power Station outside of Omaha, Nebraska. Every day, you'd like to check [an NRC website](https://www.nrc.gov/reading-rm/doc-collections/event-status/event/) to see if your plant had any "Event Notifications" in the agency's most recent report. You decide to write a Slack script to do this for you. (Ignore, for now, the problem of setting up the script to run daily.) Breaking down your problem, you need to: - Fetch [the page with the latest reports](https://www.nrc.gov/reading-rm/doc-collections/event-status/event/en.html) using `requests` - Look through the text and see if your reactor's name appears in the page text (you could just use an `if` statement with `in`) - If it's there, use `requests` to send a message to Slack Notice that we don't need to parse the page with BeautifulSoup -- we're basically just checking for the presence of a string inside a bigger string. ### _Extra, extra credit_ Let's extend the script you just wrote with a function that would allow you to check for the presence of _any string_ on an NRc page for _any date_ of reports -- most days have their own page, though I think weekends are grouped together. Let's break it down. Inside our function, we need to: - Figure out the URL pattern for each day's report page. [Here's the page for Sept. 29, 2017](https://www.nrc.gov/reading-rm/doc-collections/event-status/event/2017/20170929en.html) - Decide how you want to accept the two arguments in your function -- one for the date and one for the string to search for (me, I'd use a date object for the default date argument to keep things explicit, but you could also pass a string) - Fill in the URL using `format()` and the date being passed to the function - Fetch the page using `requests` - Not every day has a page, so you'll need to check to see if the request was successful (hint: use the requests [`status_code` attribute](http://docs.python-requests.org/en/master/user/quickstart/#response-status-codes) -- 200 means success) - If the request was successful, check for the presence of the string in the page text - If the text we're looking for is there, send a message to Slack
github_jupyter
# Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. **Notation**: - Superscript $[l]$ denotes an object of the $l^{th}$ layer. - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters. - Superscript $(i)$ denotes an object from the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example input. - Lowerscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer. - $n_H$, $n_W$ and $n_C$ denote respectively the height, width and number of channels of a given layer. If you want to reference a specific layer $l$, you can also write $n_H^{[l]}$, $n_W^{[l]}$, $n_C^{[l]}$. - $n_{H_{prev}}$, $n_{W_{prev}}$ and $n_{C_{prev}}$ denote respectively the height, width and number of channels of the previous layer. If referencing a specific layer $l$, this could also be denoted $n_H^{[l-1]}$, $n_W^{[l-1]}$, $n_C^{[l-1]}$. We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started! ## 1 - Packages Let's first import all the packages that you will need during this assignment. - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python. - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python. - np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. ``` import numpy as np import h5py import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) ``` ## 2 - Outline of the Assignment You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions that will walk you through the steps needed: - Convolution functions, including: - Zero Padding - Convolve window - Convolution forward - Convolution backward (optional) - Pooling functions, including: - Pooling forward - Create mask - Distribute value - Pooling backward (optional) This notebook will ask you to implement these functions from scratch in `numpy`. In the next notebook, you will use the TensorFlow equivalents of these functions to build the following model: <img src="images/model.png" style="width:800px;height:300px;"> **Note** that for every forward function, there is its corresponding backward equivalent. Hence, at every step of your forward module you will store some parameters in a cache. These parameters are used to compute gradients during backpropagation. ## 3 - Convolutional Neural Networks Although programming frameworks make convolutions easy to use, they remain one of the hardest concepts to understand in Deep Learning. A convolution layer transforms an input volume into an output volume of different size, as shown below. <img src="images/conv_nn.png" style="width:350px;height:200px;"> In this part, you will build every step of the convolution layer. You will first implement two helper functions: one for zero padding and the other for computing the convolution function itself. ### 3.1 - Zero-Padding Zero-padding adds zeros around the border of an image: <img src="images/PAD.png" style="width:600px;height:400px;"> <caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **Zero-Padding**<br> Image (3 channels, RGB) with a padding of 2. </center></caption> The main benefits of padding are the following: - It allows you to use a CONV layer without necessarily shrinking the height and width of the volumes. This is important for building deeper networks, since otherwise the height/width would shrink as you go to deeper layers. An important special case is the "same" convolution, in which the height/width is exactly preserved after one layer. - It helps us keep more of the information at the border of an image. Without padding, very few values at the next layer would be affected by pixels as the edges of an image. **Exercise**: Implement the following function, which pads all the images of a batch of examples X with zeros. [Use np.pad](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html). Note if you want to pad the array "a" of shape $(5,5,5,5,5)$ with `pad = 1` for the 2nd dimension, `pad = 3` for the 4th dimension and `pad = 0` for the rest, you would do: ```python a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..)) ``` ``` # GRADED FUNCTION: zero_pad def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- integer, amount of padding around each image on vertical and horizontal dimensions Returns: X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C) """ ### START CODE HERE ### (≈ 1 line) X_pad = np.pad(X, pad_width=((0, 0), (pad, pad), (pad, pad), (0, 0)), mode='constant') ### END CODE HERE ### return X_pad np.random.seed(1) x = np.random.randn(4, 3, 3, 2) # print(x) x_pad = zero_pad(x, 2) print ("x.shape =", x.shape) print ("x_pad.shape =", x_pad.shape) print ("x[1,1] =", x[1,1]) print ("x_pad[1,1] =", x_pad[1,1]) fig, axarr = plt.subplots(1, 2) axarr[0].set_title('x') axarr[0].imshow(x[0,:,:,0]) axarr[1].set_title('x_pad') axarr[1].imshow(x_pad[0,:,:,0]); ``` **Expected Output**: <table> <tr> <td> **x.shape**: </td> <td> (4, 3, 3, 2) </td> </tr> <tr> <td> **x_pad.shape**: </td> <td> (4, 7, 7, 2) </td> </tr> <tr> <td> **x[1,1]**: </td> <td> [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943] [-0.26788808 0.53035547]] </td> </tr> <tr> <td> **x_pad[1,1]**: </td> <td> [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]] </td> </tr> </table> ### 3.2 - Single step of convolution In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which: - Takes an input volume - Applies a filter at every position of the input - Outputs another volume (usually of different size) <img src="images/Convolution_schematic.gif" style="width:500px;height:300px;"> <caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'> : **Convolution operation**<br> with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide) </center></caption> In a computer vision application, each value in the matrix on the left corresponds to a single pixel value, and we convolve a 3x3 filter with the image by multiplying its values element-wise with the original matrix, then summing them up and adding a bias. In this first step of the exercise, you will implement a single step of convolution, corresponding to applying a filter to just one of the positions to get a single real-valued output. Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation. **Exercise**: Implement conv_single_step(). [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html). ``` # GRADED FUNCTION: conv_single_step def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev) b -- Bias parameters contained in a window - matrix of shape (1, 1, 1) Returns: Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data """ ### START CODE HERE ### (≈ 2 lines of code) # Element-wise product between a_slice and W. Do not add the bias yet. s = a_slice_prev * W # Sum over all entries of the volume s. Z = np.sum(s) # Add bias b to Z. Cast b to a float() so that Z results in a scalar value. Z += np.float(b) ### END CODE HERE ### return Z np.random.seed(1) a_slice_prev = np.random.randn(4, 4, 3) W = np.random.randn(4, 4, 3) b = np.random.randn(1, 1, 1) Z = conv_single_step(a_slice_prev, W, b) print("Z =", Z) ``` **Expected Output**: <table> <tr> <td> **Z** </td> <td> -6.99908945068 </td> </tr> </table> ### 3.3 - Convolutional Neural Networks - Forward pass In the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to get a 3D volume: <center> <video width="620" height="440" src="images/conv_kiank.mp4" type="video/mp4" controls> </video> </center> **Exercise**: Implement the function below to convolve the filters W on an input activation A_prev. This function takes as input A_prev, the activations output by the previous layer (for a batch of m inputs), F filters/weights denoted by W, and a bias vector denoted by b, where each filter has its own (single) bias. Finally you also have access to the hyperparameters dictionary which contains the stride and the padding. **Hint**: 1. To select a 2x2 slice at the upper left corner of a matrix "a_prev" (shape (5,5,3)), you would do: ```python a_slice_prev = a_prev[0:2,0:2,:] ``` This will be useful when you will define `a_slice_prev` below, using the `start/end` indexes you will define. 2. To define a_slice you will need to first define its corners `vert_start`, `vert_end`, `horiz_start` and `horiz_end`. This figure may be helpful for you to find how each of the corner can be defined using h, w, f and s in the code below. <img src="images/vert_horiz_kiank.png" style="width:400px;height:300px;"> <caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'> : **Definition of a slice using vertical and horizontal start/end (with a 2x2 filter)** <br> This figure shows only a single channel. </center></caption> **Reminder**: The formulas relating the output shape of the convolution to the input shape is: $$ n_H = \lfloor \frac{n_{H_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$ $$ n_W = \lfloor \frac{n_{W_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$ $$ n_C = \text{number of filters used in the convolution}$$ For this exercise, we won't worry about vectorization, and will just implement everything with for-loops. ``` # GRADED FUNCTION: conv_forward def conv_forward(A_prev, W, b, hparameters): """ Implements the forward propagation for a convolution function Arguments: A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) W -- Weights, numpy array of shape (f, f, n_C_prev, n_C) b -- Biases, numpy array of shape (1, 1, 1, n_C) hparameters -- python dictionary containing "stride" and "pad" Returns: Z -- conv output, numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward() function """ ### START CODE HERE ### # Retrieve dimensions from A_prev's shape (≈1 line) (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve dimensions from W's shape (≈1 line) (f, f, n_C_prev, n_C) = W.shape # Retrieve information from "hparameters" (≈2 lines) stride = hparameters['stride'] pad = hparameters['pad'] # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines) n_H = np.int((n_H_prev - f + 2 * pad) / stride) + 1 n_W = np.int((n_W_prev - f + 2 * pad) / stride) + 1 # Initialize the output volume Z with zeros. (≈1 line) Z = np.zeros((m, n_H, n_W, n_C)) # Create A_prev_pad by padding A_prev A_prev_pad = zero_pad(A_prev, pad) for i in range(m): # loop over the batch of training examples a_prev_pad = A_prev_pad[i] # Select ith training example's padded activation for h in range(n_W): # loop over vertical axis of the output volume for w in range(n_H): # loop over horizontal axis of the output volume for c in range(n_C): # loop over channels (= #filters) of the output volume # Find the corners of the current "slice" (≈4 lines) vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line) a_slice_prev = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end] # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line) Z[i, h, w, c] = conv_single_step(a_slice_prev, W[:, :, :, c], b[:, :, :, c]) ### END CODE HERE ### # Making sure your output shape is correct assert(Z.shape == (m, n_H, n_W, n_C)) # Save information in "cache" for the backprop cache = (A_prev, W, b, hparameters) return Z, cache np.random.seed(1) A_prev = np.random.randn(10,4,4,3) W = np.random.randn(2,2,3,8) b = np.random.randn(1,1,1,8) hparameters = {"pad" : 2, "stride": 2} Z, cache_conv = conv_forward(A_prev, W, b, hparameters) print("Z's mean =", np.mean(Z)) print("Z[3,2,1] =", Z[3,2,1]) print("cache_conv[0][1][2][3] =", cache_conv[0][1][2][3]) ``` **Expected Output**: <table> <tr> <td> **Z's mean** </td> <td> 0.0489952035289 </td> </tr> <tr> <td> **Z[3,2,1]** </td> <td> [-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437 5.18531798 8.75898442] </td> </tr> <tr> <td> **cache_conv[0][1][2][3]** </td> <td> [-0.20075807 0.18656139 0.41005165] </td> </tr> </table> Finally, CONV layer should also contain an activation, in which case we would add the following line of code: ```python # Convolve the window to get back one output neuron Z[i, h, w, c] = ... # Apply activation A[i, h, w, c] = activation(Z[i, h, w, c]) ``` You don't need to do it here. ## 4 - Pooling layer The pooling (POOL) layer reduces the height and width of the input. It helps reduce computation, as well as helps make feature detectors more invariant to its position in the input. The two types of pooling layers are: - Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output. - Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output. <table> <td> <img src="images/max_pool1.png" style="width:500px;height:300px;"> <td> <td> <img src="images/a_pool.png" style="width:500px;height:300px;"> <td> </table> These pooling layers have no parameters for backpropagation to train. However, they have hyperparameters such as the window size $f$. This specifies the height and width of the fxf window you would compute a max or average over. ### 4.1 - Forward Pooling Now, you are going to implement MAX-POOL and AVG-POOL, in the same function. **Exercise**: Implement the forward pass of the pooling layer. Follow the hints in the comments below. **Reminder**: As there's no padding, the formulas binding the output shape of the pooling to the input shape is: $$ n_H = \lfloor \frac{n_{H_{prev}} - f}{stride} \rfloor +1 $$ $$ n_W = \lfloor \frac{n_{W_{prev}} - f}{stride} \rfloor +1 $$ $$ n_C = n_{C_{prev}}$$ ``` # GRADED FUNCTION: pool_forward def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer Arguments: A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) hparameters -- python dictionary containing "f" and "stride" mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C) cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters """ # Retrieve dimensions from the input shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve hyperparameters from "hparameters" f = hparameters["f"] stride = hparameters["stride"] # Define the dimensions of the output n_H = int(1 + (n_H_prev - f) / stride) n_W = int(1 + (n_W_prev - f) / stride) n_C = n_C_prev # Initialize output matrix A A = np.zeros((m, n_H, n_W, n_C)) ### START CODE HERE ### for i in range(m): # loop over the training examples for h in range(n_H): # loop on the vertical axis of the output volume for w in range(n_W): # loop on the horizontal axis of the output volume for c in range (n_C): # loop over the channels of the output volume # Find the corners of the current "slice" (≈4 lines) vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line) a_prev_slice = A_prev[i, vert_start:vert_end, horiz_start:horiz_end, c] # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean. if mode == "max": A[i, h, w, c] = np.max(a_prev_slice) elif mode == "average": A[i, h, w, c] = np.average(a_prev_slice) ### END CODE HERE ### # Store the input and hparameters in "cache" for pool_backward() cache = (A_prev, hparameters) # Making sure your output shape is correct assert(A.shape == (m, n_H, n_W, n_C)) return A, cache np.random.seed(1) A_prev = np.random.randn(2, 4, 4, 3) hparameters = {"stride" : 2, "f": 3} A, cache = pool_forward(A_prev, hparameters) print("mode = max") print("A =", A) print() A, cache = pool_forward(A_prev, hparameters, mode = "average") print("mode = average") print("A =", A) ``` **Expected Output:** <table> <tr> <td> A = </td> <td> [[[[ 1.74481176 0.86540763 1.13376944]]] [[[ 1.13162939 1.51981682 2.18557541]]]] </td> </tr> <tr> <td> A = </td> <td> [[[[ 0.02105773 -0.20328806 -0.40389855]]] [[[-0.22154621 0.51716526 0.48155844]]]] </td> </tr> </table> Congratulations! You have now implemented the forward passes of all the layers of a convolutional network. The remainer of this notebook is optional, and will not be graded. ## 5 - Backpropagation in convolutional neural networks (OPTIONAL / UNGRADED) In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers don't need to bother with the details of the backward pass. The backward pass for convolutional networks is complicated. If you wish however, you can work through this optional portion of the notebook to get a sense of what backprop in a convolutional network looks like. When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in convolutional neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are not trivial and we did not derive them in lecture, but we briefly presented them below. ### 5.1 - Convolutional layer backward pass Let's start by implementing the backward pass for a CONV layer. #### 5.1.1 - Computing dA: This is the formula for computing $dA$ with respect to the cost for a certain filter $W_c$ and a given training example: $$ dA += \sum _{h=0} ^{n_H} \sum_{w=0} ^{n_W} W_c \times dZ_{hw} \tag{1}$$ Where $W_c$ is a filter and $dZ_{hw}$ is a scalar corresponding to the gradient of the cost with respect to the output of the conv layer Z at the hth row and wth column (corresponding to the dot product taken at the ith stride left and jth stride down). Note that at each time, we multiply the the same filter $W_c$ by a different dZ when updating dA. We do so mainly because when computing the forward propagation, each filter is dotted and summed by a different a_slice. Therefore when computing the backprop for dA, we are just adding the gradients of all the a_slices. In code, inside the appropriate for-loops, this formula translates into: ```python da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c] ``` #### 5.1.2 - Computing dW: This is the formula for computing $dW_c$ ($dW_c$ is the derivative of one filter) with respect to the loss: $$ dW_c += \sum _{h=0} ^{n_H} \sum_{w=0} ^ {n_W} a_{slice} \times dZ_{hw} \tag{2}$$ Where $a_{slice}$ corresponds to the slice which was used to generate the acitivation $Z_{ij}$. Hence, this ends up giving us the gradient for $W$ with respect to that slice. Since it is the same $W$, we will just add up all such gradients to get $dW$. In code, inside the appropriate for-loops, this formula translates into: ```python dW[:,:,:,c] += a_slice * dZ[i, h, w, c] ``` #### 5.1.3 - Computing db: This is the formula for computing $db$ with respect to the cost for a certain filter $W_c$: $$ db = \sum_h \sum_w dZ_{hw} \tag{3}$$ As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost. In code, inside the appropriate for-loops, this formula translates into: ```python db[:,:,:,c] += dZ[i, h, w, c] ``` **Exercise**: Implement the `conv_backward` function below. You should sum over all the training examples, filters, heights, and widths. You should then compute the derivatives using formulas 1, 2 and 3 above. ``` def conv_backward(dZ, cache): """ Implement the backward propagation for a convolution function Arguments: dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward(), output of conv_forward() Returns: dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev), numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) dW -- gradient of the cost with respect to the weights of the conv layer (W) numpy array of shape (f, f, n_C_prev, n_C) db -- gradient of the cost with respect to the biases of the conv layer (b) numpy array of shape (1, 1, 1, n_C) """ ### START CODE HERE ### # Retrieve information from "cache" (A_prev, W, b, hparameters) = cache # Retrieve dimensions from A_prev's shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve dimensions from W's shape (f, f, n_C_prev, n_C) = W.shape # Retrieve information from "hparameters" stride = hparameters['stride'] pad = hparameters['pad'] # Retrieve dimensions from dZ's shape (m, n_H, n_W, n_C) = dZ.shape # Initialize dA_prev, dW, db with the correct shapes dA_prev = np.zeros(A_prev.shape) dW = np.zeros(W.shape) db = np.zeros((1, 1, 1, n_C)) # Pad A_prev and dA_prev A_prev_pad = zero_pad(A_prev, pad) dA_prev_pad = zero_pad(dA_prev, pad) for i in range(m): # loop over the training examples # select ith training example from A_prev_pad and dA_prev_pad a_prev_pad = A_prev_pad[i] da_prev_pad = dA_prev_pad[i] for h in range(n_H): # loop over vertical axis of the output volume for w in range(n_W): # loop over horizontal axis of the output volume for c in range(n_C): # loop over the channels of the output volume # Find the corners of the current "slice" vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Use the corners to define the slice from a_prev_pad a_slice = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end] # Update gradients for the window and the filter's parameters using the code formulas given above da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:, :, :, c] * dZ[i, h, w, c] dW[:, :, :, c] += a_slice * dZ[i, h, w, c] db[:, :, :, c] += dZ[i, h, w, c] # Set the ith training example's dA_prev to the unpaded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :]) dA_prev[i, :, :, :] = da_prev_pad[pad:-pad, pad:-pad] ### END CODE HERE ### # Making sure your output shape is correct assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev)) return dA_prev, dW, db np.random.seed(1) dA, dW, db = conv_backward(Z, cache_conv) print("dA_mean =", np.mean(dA)) print("dW_mean =", np.mean(dW)) print("db_mean =", np.mean(db)) ``` ** Expected Output: ** <table> <tr> <td> **dA_mean** </td> <td> 1.45243777754 </td> </tr> <tr> <td> **dW_mean** </td> <td> 1.72699145831 </td> </tr> <tr> <td> **db_mean** </td> <td> 7.83923256462 </td> </tr> </table> ## 5.2 Pooling layer - backward pass Next, let's implement the backward pass for the pooling layer, starting with the MAX-POOL layer. Even though a pooling layer has no parameters for backprop to update, you still need to backpropagation the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer. ### 5.2.1 Max pooling - backward pass Before jumping into the backpropagation of the pooling layer, you are going to build a helper function called `create_mask_from_window()` which does the following: $$ X = \begin{bmatrix} 1 && 3 \\ 4 && 2 \end{bmatrix} \quad \rightarrow \quad M =\begin{bmatrix} 0 && 0 \\ 1 && 0 \end{bmatrix}\tag{4}$$ As you can see, this function creates a "mask" matrix which keeps track of where the maximum of the matrix is. True (1) indicates the position of the maximum in X, the other entries are False (0). You'll see later that the backward pass for average pooling will be similar to this but using a different mask. **Exercise**: Implement `create_mask_from_window()`. This function will be helpful for pooling backward. Hints: - [np.max()]() may be helpful. It computes the maximum of an array. - If you have a matrix X and a scalar x: `A = (X == x)` will return a matrix A of the same size as X such that: ``` A[i,j] = True if X[i,j] = x A[i,j] = False if X[i,j] != x ``` - Here, you don't need to consider cases where there are several maxima in a matrix. ``` def create_mask_from_window(x): """ Creates a mask from an input matrix x, to identify the max entry of x. Arguments: x -- Array of shape (f, f) Returns: mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x. """ ### START CODE HERE ### (≈1 line) mask = x == np.max(x) ### END CODE HERE ### return mask np.random.seed(1) x = np.random.randn(2,3) mask = create_mask_from_window(x) print('x = ', x) print("mask = ", mask) ``` **Expected Output:** <table> <tr> <td> **x =** </td> <td> [[ 1.62434536 -0.61175641 -0.52817175] <br> [-1.07296862 0.86540763 -2.3015387 ]] </td> </tr> <tr> <td> **mask =** </td> <td> [[ True False False] <br> [False False False]] </td> </tr> </table> Why do we keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is computing gradients with respect to the cost, so anything that influences the ultimate cost should have a non-zero gradient. So, backprop will "propagate" the gradient back to this particular input value that had influenced the cost. ### 5.2.2 - Average pooling - backward pass In max pooling, for each input window, all the "influence" on the output came from a single input value--the max. In average pooling, every element of the input window has equal influence on the output. So to implement backprop, you will now implement a helper function that reflects this. For example if we did average pooling in the forward pass using a 2x2 filter, then the mask you'll use for the backward pass will look like: $$ dZ = 1 \quad \rightarrow \quad dZ =\begin{bmatrix} 1/4 && 1/4 \\ 1/4 && 1/4 \end{bmatrix}\tag{5}$$ This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average. **Exercise**: Implement the function below to equally distribute a value dz through a matrix of dimension shape. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ones.html) ``` def distribute_value(dz, shape): """ Distributes the input value in the matrix of dimension shape Arguments: dz -- input scalar shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz Returns: a -- Array of size (n_H, n_W) for which we distributed the value of dz """ ### START CODE HERE ### # Retrieve dimensions from shape (≈1 line) (n_H, n_W) = shape # Compute the value to distribute on the matrix (≈1 line) average = dz / (n_H * n_W) # Create a matrix where every entry is the "average" value (≈1 line) a = np.ones(shape) * average ### END CODE HERE ### return a a = distribute_value(2, (2,2)) print('distributed value =', a) ``` **Expected Output**: <table> <tr> <td> distributed_value = </td> <td> [[ 0.5 0.5] <br\> [ 0.5 0.5]] </td> </tr> </table> ### 5.2.3 Putting it together: Pooling backward You now have everything you need to compute backward propagation on a pooling layer. **Exercise**: Implement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once again use 4 for-loops (iterating over training examples, height, width, and channels). You should use an `if/elif` statement to see if the mode is equal to `'max'` or `'average'`. If it is equal to 'average' you should use the `distribute_value()` function you implemented above to create a matrix of the same shape as `a_slice`. Otherwise, the mode is equal to '`max`', and you will create a mask with `create_mask_from_window()` and multiply it by the corresponding value of dZ. ``` def pool_backward(dA, cache, mode = "max"): """ Implements the backward pass of the pooling layer Arguments: dA -- gradient of cost with respect to the output of the pooling layer, same shape as A cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev """ ### START CODE HERE ### # Retrieve information from cache (≈1 line) (A_prev, hparameters) = cache # Retrieve hyperparameters from "hparameters" (≈2 lines) stride = hparameters['stride'] f = hparameters['f'] # Retrieve dimensions from A_prev's shape and dA's shape (≈2 lines) m, n_H_prev, n_W_prev, n_C_prev = A_prev.shape m, n_H, n_W, n_C = dA.shape # Initialize dA_prev with zeros (≈1 line) dA_prev = np.zeros(A_prev.shape) for i in range(m): # loop over the training examples # select training example from A_prev (≈1 line) a_prev = A_prev[i] for h in range(n_H): # loop on the vertical axis for w in range(n_W): # loop on the horizontal axis for c in range(n_C): # loop over the channels (depth) # Find the corners of the current "slice" (≈4 lines) vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Compute the backward propagation in both modes. if mode == "max": # Use the corners and "c" to define the current slice from a_prev (≈1 line) a_prev_slice = a_prev[vert_start:vert_end, horiz_start:horiz_end, c] # Create the mask from a_prev_slice (≈1 line) mask = create_mask_from_window(a_prev_slice) # Set dA_prev to be dA_prev + (the mask multiplied by the correct entry of dA) (≈1 line) dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += mask * dA[i, h, w, c] elif mode == "average": # Get the value a from dA (≈1 line) da = dA[i, h, w, c] # Define the shape of the filter as fxf (≈1 line) shape = (f, f) # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da. (≈1 line) dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += distribute_value(da, shape) ### END CODE ### # Making sure your output shape is correct assert(dA_prev.shape == A_prev.shape) return dA_prev np.random.seed(1) A_prev = np.random.randn(5, 5, 3, 2) hparameters = {"stride" : 1, "f": 2} A, cache = pool_forward(A_prev, hparameters) dA = np.random.randn(5, 4, 2, 2) dA_prev = pool_backward(dA, cache, mode = "max") print("mode = max") print('mean of dA = ', np.mean(dA)) print('dA_prev[1,1] = ', dA_prev[1,1]) print() dA_prev = pool_backward(dA, cache, mode = "average") print("mode = average") print('mean of dA = ', np.mean(dA)) print('dA_prev[1,1] = ', dA_prev[1,1]) ``` **Expected Output**: mode = max: <table> <tr> <td> **mean of dA =** </td> <td> 0.145713902729 </td> </tr> <tr> <td> **dA_prev[1,1] =** </td> <td> [[ 0. 0. ] <br> [ 5.05844394 -1.68282702] <br> [ 0. 0. ]] </td> </tr> </table> mode = average <table> <tr> <td> **mean of dA =** </td> <td> 0.145713902729 </td> </tr> <tr> <td> **dA_prev[1,1] =** </td> <td> [[ 0.08485462 0.2787552 ] <br> [ 1.26461098 -0.25749373] <br> [ 1.17975636 -0.53624893]] </td> </tr> </table> ### Congratulations ! Congratulation on completing this assignment. You now understand how convolutional neural networks work. You have implemented all the building blocks of a neural network. In the next assignment you will implement a ConvNet using TensorFlow.
github_jupyter
``` c1=open("stock_2018.csv","r") lines=c1.readlines() ``` ### 시험출력 ``` l1=[1,2,3,4,5,6,7,8,9,10] print(l1[4:6]) for line in lines[1:3]: print(line) ``` ## MIN_MAX SCALING ``` # min_max 스케일링 전에 전체 기간 범위에 대한 min값과 max값 추출 min_list=[] max_list=[] for line in lines[1:]: l_list=line.split(',') min_list.append(int(l_list[5])) # Low 행 max_list.append(int(l_list[4])) # High 행 print(max(max_list)) all_max=max(max_list) print(min(min_list)) all_min=min(min_list) # min_max 스케일링 # x'= ( x - min(x) ) / ( max(x) - min(x) ) new_list=[] new_list.append(lines[0]) for line in lines[1:]: l_list=line.split(',') #1번째 데이터일 경우 여기서 리스트로 만들고 mini_list=[] for l_num in range(len(l_list)): #0,1,2,8번째 열? 제외하고 스케일링 #리스트 개수를 범위로 해서 스케일링 if (l_num!=0) & (l_num!=1) & (l_num!=2) & (l_num!=8): mini_list.append(str((float(l_list[l_num])- all_min)/(all_max-all_min))) else: mini_list.append(l_list[l_num]) new_row=",".join(mini_list) new_list.append(new_row) ``` ## 100억이상인 데이터 필터링 ### 데이터의 컬럼리스트 만들어내기 ``` Code_list=new_list[0].split(',') #데이터의 Code리스트 new_code=[] new_code.append(Code_list[1]) new_code.append(Code_list[2]) for i in range(9, -1, -1): for num1 in Code_list[3:]: if num1=="Next_Change": continue else: new_code.append('D-'+str(i)+'_'+num1) new_code.append("Next_Change") new_code_s=",".join(new_code) ``` ### 컬럼명 확인 ``` print(new_code) print(len(new_code_s.split(','))) #new_list사용 new_csv=[] new_csv.append(new_code_s)#index목록을 새 데이터에 추가 standard=new_list[10].split(',') #최소 10번째 데이터 이후여야 하므로 기준이 되는 10번째 데이터를 변수에 저장 i=1#현재 몇번째 데이터인지? for line in new_list[1:]: new_data=[] l_list=line.split(',') date=l_list[2].replace("-","") #1번째 변수=코드 if int(date)>=int(standard[2].replace("-","")): #10번째 데이터가 되기 위한 최소날짜 now_code=l_list[1] pre=new_list[i-9].split(",") if pre[1]==now_code: #10개 전 데이터의 코드와 현재 코드 일치한지 if float(l_list[8])>=1.00E+10:#8번째:traiding_value가 100억이상 new_data.extend(l_list[1:3]) #2번째 for m in range(i-9,i): #(lines.index(line))=지금데이터번호 # 9일 전~당일 데이터를 추가 d_list=(new_list[m]).split(',') #m일 전 데이터를 리스트화 # 당일 데이터의 index~날짜 # 11번째가 Next_change new_data.extend(d_list[3:11]) new_data.extend(d_list[12:]) new_data.extend(l_list[3:11]) new_data.extend(l_list[12:]) new_data.append(l_list[11]) new_data_str=",".join(new_data) #새로 만들어진 행을 str(콤마(,)구문 행)로 new_csv.append(new_data_str) #새 파일에 저장될 행 추가 i+=1 ``` ### 시험 출력 ``` #print(len(new_csv[1].split(','))) print(new_csv[1]) ``` ### \n(줄바꿈 표시 삭제) ``` error="\n" for i in range(len(new_csv)): new_csv[i]=new_csv[i].replace(error,"") ``` ### 새로 만들어진 str행들을 다시 리스트 형태로 저장 ``` new_array=[] for new in new_csv: new_array.append([new]) print(new_array[1]) ``` ## 파일 저장 ``` import numpy as np np.savetxt("3w_scaling.csv",new_array,fmt='%s', delimiter=',') # ####메모####### # key를 code로,value를 해당되는 날짜들의 리스트로 해서 위치검색?(시간 오래걸림) # 4-딕셔너리-key를 Code로, Value를 날짜로?(value값에 나머지) # 4-맨 처음 행의 high, low를 max, min으로 설정하고 다음 행에서 더 크거나 작을 때 업데이트하는 식으로 max,min 값 추출 ```
github_jupyter
``` import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import seaborn as sns sns.set(color_codes=True) %matplotlib inline # ilk terimin covarianci hep 1 cikar -2 - -2 x = np.array([-2, -1, 0, 3.5, 4,]); y = np.array([4.1, 0.9, 2, 12.3, 15.8]) N = len(x) m = np.zeros((N)) print(x) print(y) print(m) sigma = np.cov(x, y) print(sigma) def cov(x1, x2): return np.exp(-1.0/2 * np.power(x1 - x2, 2)) K = np.zeros((N, N)) print(K) for i in range(N): for j in range(i, N): K[i][j] = cov(x[i], x[j]) K[j][i] = K[i][j] print(K) plt.scatter(x, y) cov(4, 4) # expected to be 1 def pred(xp): K2 = np.zeros((N+1, N+1)) N2 = N + 1 sigma22 = cov(xp, xp) K2[N2-1][N2-1] = sigma22 for i in range(N): for j in range(i, N): K2[i][j] = cov(x[i], y[j]) K2[j][i] = K2[i][j] for i in range(N): K2[N2-1][i]= cov(xp, x[i]) K2[i][N2-1]= cov(xp, x[i]) sigma12 = np.array(K2[:N2-1,N2-1]) sigma11 = np.mat(K) sigma21 = K[N-1:] print(sigma12) mp = (sigma12.T * sigma11.I) * np.mat(y).T # sigmap = sigma22 - np.mat(sigma12).T * sigma11.I * np.mat(sigma12) # return mp, sigmap return mp, sigma22 pred(4) plt.scatter(x, y) def p(): x = np.linspace(-5, 20, 200) y = np.zeros(200) yu = np.zeros(200) yb = np.zeros(200) for i in range(len(x)): yp, sigmap = pred(x[i]) yp = np.asarray(yp)[0][0] yu[i] = yp - np.sqrt(sigmap) y[i] = yp # plt.plot(x, yu) plt.plot(x, y) p() np.asarray(np.mat([[ 9.11765304e+27]]))[0][0] def cov(x1, x2): return np.exp(-1.0/2 * np.abs(x1 - x2)) def pred(xp): K2 = np.zeros((N+1, N+1)) N2 = N + 1 sigma22 = cov(xp, xp) K2[N2-1][N2-1] = sigma22 for i in range(N): for j in range(i, N): K2[i][j] = cov(x[i], y[j]) K2[j][i] = K2[i][j] for i in range(N): K2[N2-1][i]= cov(xp, x[i]) K2[i][N2-1]= cov(xp, x[i]) sigma12 = np.array(K2[:N2-1,N2-1]) sigma11 = np.mat(K) sigma21 = K[N-1:] # print(sigma12) # print(sigma11) mp = (sigma12.T * sigma11.I) * np.mat(y).T # sigmap = sigma11 - np.mat(sigma12) * sigma21.T return mp, sigma22 plt.scatter(x, y) def p(): x = np.linspace(-10, 10, 200) y = np.zeros(200) yu = np.zeros(200) yb = np.zeros(200) for i in range(len(x)): yp, sigmap = pred(x[i]) yp = np.asarray(yp)[0][0] yu[i] = yp - np.sqrt(sigmap) * 3 y[i] = yp # plt.plot(x, yu) plt.plot(x, y) p() K K[N-1:] ```
github_jupyter
### Content Based Recommendations In the previous notebook, you were introduced to a way to make recommendations using collaborative filtering. However, using this technique there are a large number of users who were left without any recommendations at all. Other users were left with fewer than the ten recommendations that were set up by our function to retrieve... In order to help these users out, let's try another technique **content based** recommendations. Let's start off where we were in the previous notebook. ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from collections import defaultdict from IPython.display import HTML import progressbar import tests as t import pickle %matplotlib inline # Read in the datasets movies = pd.read_csv('movies_clean.csv') reviews = pd.read_csv('reviews_clean.csv') del movies['Unnamed: 0'] del reviews['Unnamed: 0'] all_recs = pickle.load(open("all_recs.p", "rb")) ``` ### Datasets From the above, you now have access to three important items that you will be using throughout the rest of this notebook. `a.` **movies** - a dataframe of all of the movies in the dataset along with other content related information about the movies (genre and date) `b.` **reviews** - this was the main dataframe used before for collaborative filtering, as it contains all of the interactions between users and movies. `c.` **all_recs** - a dictionary where each key is a user, and the value is a list of movie recommendations based on collaborative filtering For the individuals in **all_recs** who did recieve 10 recommendations using collaborative filtering, we don't really need to worry about them. However, there were a number of individuals in our dataset who did not receive any recommendations. ----- `1.` To begin, let's start with finding all of the users in our dataset who didn't get all 10 ratings we would have liked them to have using collaborative filtering. ``` users_with_all_recs = [] for user, movie_recs in all_recs.items(): if len(movie_recs) > 9: users_with_all_recs.append(user) print("There are {} users with all reccomendations from collaborative filtering.".format(len(users_with_all_recs))) users = np.unique(reviews['user_id']) users_who_need_recs = np.setdiff1d(users, users_with_all_recs) print("There are {} users who still need recommendations.".format(len(users_who_need_recs))) print("This means that only {}% of users received all 10 of their recommendations using collaborative filtering".format(round(len(users_with_all_recs)/len(np.unique(reviews['user_id'])), 4)*100)) # Some test here might be nice assert len(users_with_all_recs) == 22187 print("That's right there were still another 31781 users who needed recommendations when we only used collaborative filtering!") ``` ### Content Based Recommendations You will be doing a bit of a mix of content and collaborative filtering to make recommendations for the users this time. This will allow you to obtain recommendations in many cases where we didn't make recommendations earlier. `2.` Before finding recommendations, rank the user's ratings from highest ratings to lowest ratings. You will move through the movies in this order looking for other similar movies. ``` # create a dataframe similar to reviews, but ranked by rating for each user ranked_reviews = reviews.sort_values(by=['user_id', 'rating'], ascending=False) ``` ### Similarities In the collaborative filtering sections, you became quite familiar with different methods of determining the similarity (or distance) of two users. We can perform similarities based on content in much the same way. In many cases, it turns out that one of the fastest ways we can find out how similar items are to one another (when our matrix isn't totally sparse like it was in the earlier section) is by simply using matrix multiplication. If you are not familiar with this, an explanation is available [here by 3blue1brown](https://www.youtube.com/watch?v=LyGKycYT2v0) and another quick explanation is provided [on the post here](https://math.stackexchange.com/questions/689022/how-does-the-dot-product-determine-similarity). For us to pull out a matrix that describes the movies in our dataframe in terms of content, we might just use the indicator variables related to **year** and **genre** for our movies. Then we can obtain a matrix of how similar movies are to one another by taking the dot product of this matrix with itself. Notice in the below that the dot product where our 1 values overlap gives a value of 2 indicating higher similarity. In the second dot product, the 1 values don't match up. This leads to a dot product of 0 indicating lower similarity. <img src="images/dotprod1.png" alt="Dot Product" height="500" width="500"> We can perform the dot product on a matrix of movies with content characteristics to provide a movie by movie matrix where each cell is an indication of how similar two movies are to one another. In the below image, you can see that movies 1 and 8 are most similar, movies 2 and 8 are most similar and movies 3 and 9 are most similar for this subset of the data. The diagonal elements of the matrix will contain the similarity of a movie with itself, which will be the largest possible similarity (which will also be the number of 1's in the movie row within the orginal movie content matrix. <img src="images/moviemat.png" alt="Dot Product" height="500" width="500"> `3.` Create a numpy array that is a matrix of indicator variables related to year (by century) and movie genres by movie. Perform the dot prodoct of this matrix with itself (transposed) to obtain a similarity matrix of each movie with every other movie. The final matrix should be 31245 x 31245. ``` # Subset so movie_content is only using the dummy variables for each genre and the 3 century based year dummy columns movie_content = np.array(movies.iloc[:,4:]) # Take the dot product to obtain a movie x movie matrix of similarities dot_prod_movies = movie_content.dot(np.transpose(movie_content)) # create checks for the dot product matrix assert dot_prod_movies.shape[0] == 31245 assert dot_prod_movies.shape[1] == 31245 assert dot_prod_movies[0, 0] == np.max(dot_prod_movies[0]) print("Looks like you passed all of the tests. Though they weren't very robust - if you want to write some of your own, I won't complain!") ``` ### For Each User... Now that you have a matrix where each user has their ratings ordered. You also have a second matrix where movies are each axis, and the matrix entries are larger where the two movies are more similar and smaller where the two movies are dissimilar. This matrix is a measure of content similarity. Therefore, it is time to get to the fun part. For each user, we will perform the following: i. For each movie, find the movies that are most similar that the user hasn't seen. ii. Continue through the available, rated movies until 10 recommendations or until there are no additional movies. As a final note, you may need to adjust the criteria for 'most similar' to obtain 10 recommendations. As a first pass, I used only movies with the highest possible similarity to one another as similar enough to add as a recommendation. `3.` In the below cell, complete each of the functions needed for making content based recommendations. ``` def find_similar_movies(movie_id): ''' INPUT movie_id - a movie_id OUTPUT similar_movies - an array of the most similar movies by title ''' # find the row of each movie id if not np.where(movies['movie_id']==210156)[0]: return np.array([]) movie_idx = np.where(movies['movie_id'] == movie_id)[0][0] # find the most similar movie indices - to start I said they need to be the same for all content similar_idxs = np.where(dot_prod_movies[movie_idx] == np.max(dot_prod_movies[movie_idx]))[0] # pull the movie titles based on the indices similar_movies = np.array(movies.iloc[similar_idxs, ]['movie']) return similar_movies def get_movie_names(movie_ids): ''' INPUT movie_ids - a list of movie_ids OUTPUT movies - a list of movie names associated with the movie_ids ''' movie_lst = list(movies[movies['movie_id'].isin(movie_ids)]['movie']) return movie_lst def make_recs(): ''' INPUT None OUTPUT recs - a dictionary with keys of the user and values of the recommendations ''' # Create dictionary to return with users and ratings recs = defaultdict(set) # How many users for progress bar n_users = len(users) # Create the progressbar cnter = 0 bar = progressbar.ProgressBar(maxval=n_users+1, widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) bar.start() # For each user for user in users: # Update the progress bar cnter+=1 bar.update(cnter) # Pull only the reviews the user has seen reviews_temp = ranked_reviews[ranked_reviews['user_id'] == user] movies_temp = np.array(reviews_temp['movie_id']) movie_names = np.array(get_movie_names(movies_temp)) # Look at each of the movies (highest ranked first), # pull the movies the user hasn't seen that are most similar # These will be the recommendations - continue until 10 recs # or you have depleted the movie list for the user for movie in movies_temp: rec_movies = find_similar_movies(movie) temp_recs = np.setdiff1d(rec_movies, movie_names) recs[user].update(temp_recs) # If there are more than if len(recs[user]) > 9: break bar.finish() return recs recs = make_recs() ``` ### How Did We Do? Now that you have made the recommendations, how did we do in providing everyone with a set of recommendations? `4.` Use the cells below to see how many individuals you were able to make recommendations for, as well as explore characteristics about individuals who you were not able to make recommendations for. ``` # Explore recommendations users_without_all_recs = [] users_with_all_recs = [] no_recs = [] for user, movie_recs in recs.items(): if len(movie_recs) < 10: users_without_all_recs.append(user) if len(movie_recs) > 9: users_with_all_recs.append(user) if len(movie_recs) == 0: no_recs.append(user) # Some characteristics of my content based recommendations print("There were {} users without all 10 recommendations we would have liked to have.".format(len(users_without_all_recs))) print("There were {} users with all 10 recommendations we would like them to have.".format(len(users_with_all_recs))) print("There were {} users with no recommendations at all!".format(len(no_recs))) # Closer look at individual user characteristics user_items = reviews[['user_id', 'movie_id', 'rating']] user_by_movie = user_items.groupby(['user_id', 'movie_id'])['rating'].max().unstack() def movies_watched(user_id): ''' INPUT: user_id - the user_id of an individual as int OUTPUT: movies - an array of movies the user has watched ''' movies = user_by_movie.loc[user_id][user_by_movie.loc[user_id].isnull() == False].index.values return movies movies_watched(189) cnter = 0 print("Some of the movie lists for users without any recommendations include:") for user_id in no_recs: print(user_id) print(get_movie_names(movies_watched(user_id))) cnter+=1 if cnter > 10: break ``` ### Now What? Well, if you were really strict with your criteria for how similar two movies (like I was initially), then you still have some users that don't have all 10 recommendations (and a small group of users who have no recommendations at all). As stated earlier, recommendation engines are a bit of an **art** and a **science**. There are a number of things we still could look into - how do our collaborative filtering and content based recommendations compare to one another? How could we incorporate user input along with collaborative filtering and/or content based recommendations to improve any of our recommendations? How can we truly gain recommendations for every user? `5.` In this last step feel free to explore any last ideas you have with the recommendation techniques we have looked at so far. You might choose to make the final needed recommendations using the first technique with just top ranked movies. You might also loosen up the strictness in the similarity needed between movies. Be creative and share your insights with your classmates! ``` # Cells for exploring ```
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from hfnet.datasets.hpatches import Hpatches from hfnet.evaluation.loaders import sift_loader, export_loader, fast_loader, harris_loader from hfnet.evaluation.local_descriptors import evaluate from hfnet.utils import tools %load_ext autoreload %autoreload 2 %matplotlib inline data_config = {'make_pairs': True, 'shuffle': True} dataset = Hpatches(**data_config) all_configs = { 'sift': { 'predictor': sift_loader, 'root': True, }, 'superpoint': { 'experiment': 'super_point_pytorch/hpatches', 'predictor': export_loader, 'do_nms': True, 'nms_thresh': 4, 'remove_borders': 4, }, 'superpoint_harris-kpts': { 'experiment': 'super_point_pytorch/hpatches', 'predictor': export_loader, 'keypoint_predictor': harris_loader, 'keypoint_config': { 'do_nms': True, 'nms_thresh': 4, }, }, 'netvlad_conv3-3': { 'experiment': 'netvlad/hpatches', 'predictor': export_loader, 'keypoint_predictor': export_loader, 'keypoint_config': { 'experiment': 'super_point_pytorch/hpatches', 'do_nms': True, 'nms_thresh': 4, 'remove_borders': 4, }, 'binarize': False, }, 'lfnet': { 'experiment': 'lfnet/hpatches_kpts-500', 'predictor': export_loader, }, } eval_config = { 'num_features': 300, 'do_ratio_test': True, 'correct_match_thresh': 3, 'correct_H_thresh': 3, } methods = ['sift', 'lfnet', 'superpoint', 'superpoint_harris-kpts', 'netvlad_conv3-3'] configs = {m: all_configs[m] for m in methods} pose_recalls, nn_pr = {}, {} for method, config in configs.items(): config = tools.dict_update(config, eval_config) data_iter = dataset.get_test_set() metrics, nn_precision, nn_recall, distances, pose_recall = evaluate(data_iter, config, is_2d=True) print('> {}'.format(method)) for k, v in metrics.items(): print('{:<25} {:.3f}'.format(k, v)) print(config) pose_recalls[method] = pose_recall nn_pr[method] = (nn_precision, nn_recall, distances) # NMS=4, N=300 # NMS=8, N=500 error_names = list(list(pose_recalls.values())[0].keys()) expers = list(pose_recalls.keys()) lim = {'homography': 7} thresh = {'homography': [1, 3, 5]} f, axes = plt.subplots(1, len(error_names), figsize=(8, 4), dpi=150) if len(error_names) == 1: axes = [axes] for error_name, ax in zip(error_names, axes): for exper in expers: steps, recall = pose_recalls[exper][error_name] ax.set_xlim([0, lim[error_name]]) ax.plot(steps, recall*100, label=exper); s = f'{error_name:^15} {exper:^25}' s += ''.join([f' {t:^5}: {recall[np.where(steps>t)[0].min()]:.2f} ' for t in thresh[error_name]]) print(s) ax.grid(color=[0.85]*3); ax.set_xlabel(error_name+' error'); ax.set_ylabel('Correctly localized queries (%)'); ax.legend(loc=4); plt.tight_layout() plt.gcf().subplots_adjust(left=0); # NMS=4, N=300 # NMS=8, N=500 ```
github_jupyter
# COCO Reader Reader operator that reads a COCO dataset (or subset of COCO), which consists of an annotation file and the images directory. `DALI_EXTRA_PATH` environment variable should point to the place where data from [DALI extra repository](https://github.com/NVIDIA/DALI_extra) is downloaded. Please make sure that the proper release tag is checked out. ``` from __future__ import print_function from nvidia.dali.pipeline import Pipeline import nvidia.dali.ops as ops import nvidia.dali.types as types import numpy as np from time import time import os.path test_data_root = os.environ['DALI_EXTRA_PATH'] file_root = os.path.join(test_data_root, 'db', 'coco', 'images') annotations_file = os.path.join(test_data_root, 'db', 'coco', 'instances.json') num_gpus = 1 batch_size = 16 class COCOPipeline(Pipeline): def __init__(self, batch_size, num_threads, device_id): super(COCOPipeline, self).__init__(batch_size, num_threads, device_id, seed = 15) self.input = ops.COCOReader(file_root = file_root, annotations_file = annotations_file, shard_id = device_id, num_shards = num_gpus, ratio=True) self.decode = ops.ImageDecoder(device = "mixed", output_type = types.RGB) def define_graph(self): inputs, bboxes, labels = self.input() images = self.decode(inputs) return (images, bboxes, labels) start = time() pipes = [COCOPipeline(batch_size=batch_size, num_threads=2, device_id = device_id) for device_id in range(num_gpus)] for pipe in pipes: pipe.build() total_time = time() - start print("Computation graph built and dataset loaded in %f seconds." % total_time) pipe_out = [pipe.run() for pipe in pipes] images_cpu = pipe_out[0][0].as_cpu() bboxes_cpu = pipe_out[0][1] labels_cpu = pipe_out[0][2] ``` Bounding boxes returned by the operator are lists of floats containing composed of **\[x, y, width, height]** (`ltrb` is set to `False` by default). ``` bboxes = bboxes_cpu.at(4) bboxes ``` Let's see the ground truth bounding boxes drawn on the image. ``` import matplotlib.pyplot as plt import matplotlib.patches as patches import random img_index = 4 img = images_cpu.at(img_index) H = img.shape[0] W = img.shape[1] fig,ax = plt.subplots(1) ax.imshow(img) bboxes = bboxes_cpu.at(img_index) labels = labels_cpu.at(img_index) categories_set = set() for label in labels: categories_set.add(label[0]) category_id_to_color = dict([ (cat_id , [random.uniform(0, 1) ,random.uniform(0, 1), random.uniform(0, 1)]) for cat_id in categories_set]) for bbox, label in zip(bboxes, labels): rect = patches.Rectangle((bbox[0]*W,bbox[1]*H),bbox[2]*W,bbox[3]*H,linewidth=1,edgecolor=category_id_to_color[label[0]],facecolor='none') ax.add_patch(rect) plt.show() ```
github_jupyter
<center><h1 style="font-size:40px;">Exercise III:<br> Image Classification using CNNs</h1></center> --- Welcome to the *fourth* lab for Deep Learning! In this lab an CNN network to classify RGB images. Image classification refers to classify classes from images. This labs the *dataset* consist of multiple images where each image have a target label for classification. All **tasks** include **TODO's** thare are expected to be done before the deadline. The highlighted **Question's** should be answered in the report. Keep the answers separated so it is easy to read for the grading. Some sections include asserts or an expected result to give a and expected results are given. Some sections does not contain any **TODO's** but is good to understand them. For the **report** we have prepared an *Report.ipynb* notebook. The report should act as a summary of your findings and motivate your choice of approach. A better motivation show your understanding of the lab. Dont forget to include all **parts** in the report! Good luck! --- # Import packages ``` #!pip install pycocotools-windows %load_ext autoreload %autoreload 2 # Hacky solution to acces the global utils package import sys,os sys.path.append(os.path.dirname(os.path.realpath(''))) # Torch packages import torch import torch.nn as nn import torch.nn.functional as F # local modules from torch.utils.data import DataLoader from utils.progressbar import LitProgressBar from utils.dataset import ClassificationDataset from utils.model import Model from config import LabConfig from collections import OrderedDict from utils import plot import pprint import torchmetrics import pytorch_lightning as pl import torchvision import pandas as pd import matplotlib.pyplot as plt import numpy as np ``` # Load config ``` cfg = LabConfig() cfg.todict() ``` # Example Task First we present an example task to get an idea of the implementation and how to structure the code. ## Example data First load the dataloaders for three datasets; train, validation and test. Feel free to test different augmentations, more can be found at the [pytorch doc](https://pytorch.org/vision/stable/transforms.html) Note that ToTensor and Rezise are required to reshape and transform the images correct. We do not want to apply augmentation to the test_transform that are applied on the validation and test dataloader. ### Augmentation ``` train_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Resize((cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)), ]) test_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Resize((cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)), #, ]) train_transform ``` ### Create dataloaders ``` train_dataloader = DataLoader(ClassificationDataset(cfg.training_img_dir, cfg.CLASSES, img_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),transform=train_transform), batch_size=cfg.BATCH_SIZE, shuffle=True, num_workers=cfg.NUM_WORKERS) valid_dataloader = DataLoader(ClassificationDataset(cfg.validation_img_dir, cfg.CLASSES, img_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),transform=test_transform), batch_size=cfg.BATCH_SIZE, shuffle=False, num_workers=cfg.NUM_WORKERS) test_dataloader = DataLoader(ClassificationDataset(cfg.testing_img_dir, cfg.CLASSES, img_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),transform=test_transform), batch_size=cfg.BATCH_SIZE, shuffle=False, num_workers=cfg.NUM_WORKERS) print("Data batch generators are created!") ``` ## Visualise data To get an idea of the dataset we visualise the data. ``` t_x, t_y = next(iter(train_dataloader)) print(f"x {tuple(t_x.shape)} {t_x.dtype} {t_x.min()} {t_x.max()}") print(f"y {tuple(t_y.shape)} {t_y.dtype} {t_y.min()} {t_y.max()}") plot.Classification.data(t_x, t_y, nimages=10,nrows=2) if False: # Set to true to visualise statistics of the data plot.show_statistics(cfg.training_img_dir, fineGrained=cfg.fineGrained, title=" Training Data Statistics ") plot.show_statistics(cfg.validation_img_dir, fineGrained=cfg.fineGrained, title=" Validation Data Statistics ") plot.show_statistics(cfg.testing_img_dir, fineGrained=cfg.fineGrained, title=" Testing Data Statistics ") ``` ## Create model Here is an simple architecture to train our network. ``` class SimpleModel(nn.Module): def __init__(self,num_channels:int=4, num_classes:int=3, input_shape=(10,10),**kwargs): super().__init__() self.conv_layer1 = self._conv_layer_set(num_channels, 32) self.conv_layer2 = self._conv_layer_set(32, 64) self.fc1 = nn.Linear(64*input_shape[1]//4*input_shape[1]//4, 64) # Calculated with the size. why //4 self.fc2 = nn.Linear(64, num_classes) self.drop = nn.Dropout(0.5) def _conv_layer_set(self, in_c, out_c): conv_layer = nn.Sequential(OrderedDict([ ('conv',nn.Conv2d(in_c, out_c, kernel_size=3, padding=1)), ('leakyrelu',nn.LeakyReLU()), ('maxpool',nn.MaxPool2d(2)), ])) return conv_layer def forward(self, x): # Set 1 print(x.shape) out = self.conv_layer1(x) out = self.conv_layer2(out) out = out.view(out.size(0), -1) # Flatten (batchsize, image size) out = self.fc1(out) out = self.drop(out) out = self.fc2(out) return out ``` ## Config ``` # Train model config = { 'optimizer':{ "type":torch.optim.Adam, "args":{ "lr":0.005, } }, 'criterion':torch.nn.CrossEntropyLoss(), # error function 'max_epochs':5, "train_metrics":torchmetrics.MetricCollection([ torchmetrics.Accuracy(num_classes=cfg.NUM_CLASSES,compute_on_step=False), ],postfix="_Train"), "validation_metrics":torchmetrics.MetricCollection([ torchmetrics.Accuracy(num_classes=cfg.NUM_CLASSES,compute_on_step=False), ],postfix="_Validation") } ``` ## Train ``` # Load model modelObj = Model(SimpleModel(num_classes=cfg.NUM_CLASSES, num_channels=cfg.IMAGE_CHANNEL, input_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)),**config) # Setup trainer trainer = pl.Trainer( max_epochs=config['max_epochs'], gpus=cfg.GPU, logger=pl.loggers.TensorBoardLogger(save_dir=cfg.TENSORBORD_DIR), callbacks=[LitProgressBar()], progress_bar_refresh_rate=1, weights_summary=None, # Can be None, top or full num_sanity_val_steps=10, ) # Train with the training and validation data- trainer.fit( modelObj, train_dataloader=train_dataloader, val_dataloaders=valid_dataloader ); ``` ## Test the network on the test dataset To test the performance for a qualitative estimation we can plot the input, target and the models prediction. This is a good approach to see the performance and understand if the model is close to a correct decision. However, for big data, we probobly want to focus on a qualitative estimation. Therefore we can analyse **Tensorboard** logs to get a better understanding of the model. ``` # Create iterable from the test dataset iter_dataloader = iter(test_dataloader) # Take one batch from the test dataset and predict! X, Y = next(iter_dataloader) preds = torch.argmax(modelObj.predict_step(X,0,0),dim=1) n_test = 10 df_result = pd.DataFrame({ 'Ground Truth': Y[:n_test], 'Predicted label': preds[:n_test]}) display(df_result.T) plot.Classification.results(X, preds) ``` # Exercises ## Metrics **TODO:** Does a high accuracy impy a good model, motivate your answer. **TODO:** Find an alternative metric which can show similar or better precision than accuracy. ### Accuracy #### Training ``` iter_train_dataloader = iter(train_dataloader) X_t, Y_t = next(iter_train_dataloader) train_preds = torch.argmax(modelObj.predict_step(X_t,0,0),dim=1) print("Train accuracy {}%".format(np.mean(Y_t.numpy() == train_preds.numpy())*100)) ``` #### Test ``` iter_dataloader = iter(test_dataloader) X, Y = next(iter_dataloader) preds = torch.argmax(modelObj.predict_step(X,0,0),dim=1) print("Test accuracy {}%".format(np.mean(Y.numpy() == preds.numpy())*100)) ``` ### Precision ``` from torchmetrics import Precision precision = Precision(average='macro', num_classes=cfg.todict()['NUM_CLASSES']) ``` #### Training ``` precision(train_preds, Y_t) ``` #### Test ``` precision(preds, Y) ``` ### Comparison between metrics, using tensorboard #### Config ``` # Train model config = { 'optimizer':{ "type":torch.optim.Adam, "args":{ "lr":0.005, } }, 'criterion':torch.nn.CrossEntropyLoss(), # error function 'max_epochs':5, "train_metrics":torchmetrics.MetricCollection([ torchmetrics.Accuracy(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.Precision(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.F1(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.AUROC(num_classes=cfg.NUM_CLASSES,compute_on_step=False), ],postfix="_Train"), "validation_metrics":torchmetrics.MetricCollection([ torchmetrics.Accuracy(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.Precision(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.F1(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.AUROC(num_classes=cfg.NUM_CLASSES,compute_on_step=False), ],postfix="_Validation") } ``` #### Train ``` # Load model modelObj = Model(SimpleModel(num_classes=cfg.NUM_CLASSES, num_channels=cfg.IMAGE_CHANNEL, input_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)),**config) # Setup trainer trainer = pl.Trainer( max_epochs=config['max_epochs'], gpus=cfg.GPU, logger=pl.loggers.TensorBoardLogger(save_dir=cfg.TENSORBORD_DIR), callbacks=[LitProgressBar()], progress_bar_refresh_rate=1, weights_summary=None, # Can be None, top or full num_sanity_val_steps=10, ) trainer.fit( modelObj, train_dataloader=train_dataloader, val_dataloaders=valid_dataloader ); ``` ## Architecture Modify the architecture of the SimpleModel to further increase the performance. Remember that very deep network allow the network to learn many features but if the dataset is to small the model will underfit. A simple dataset should not require a very deep network to learn good features. **TODO:** Modify the SimpleModel architecture. Force the network to overfit. How bad performance can you get from the network? **TODO:** Modify the SimpleModel and increase the complexity a little. Does the performance improve? If not, did you modify it to much or to little? **TODO:** Modify the SimpleModel architecture. Now combine the hyperparameter tuning and modification of the architecture to reach a performance that is close to the truth images. Explain in detail why the change was applied and if it improved the model a lot. ### The model ``` class SimpleModel(nn.Module): def __init__(self,num_channels:int=4, num_classes:int=3, input_shape=(10,10),**kwargs): super().__init__() conv_layers = 3 self.conv_layer1 = self._conv_layer_set(num_channels, 24) # 2 self.conv_layer2 = self._conv_layer_set(24, 24) # 4 self.conv_layer3 = self._conv_layer_set(24, 40) ## Look up how width and height should change between convolutional layers. self.fc1 = nn.Linear(40*input_shape[1]//np.power(2, conv_layers)*input_shape[1]//np.power(2, conv_layers), 64) # Calculated with the size. why //4 self.fc2 = nn.Linear(64, num_classes) self.drop = nn.Dropout(0.5) def _conv_layer_set(self, in_c, out_c): conv_layer = nn.Sequential(OrderedDict([ ('conv',nn.Conv2d(in_c, out_c, kernel_size=3, padding=1)), ('leakyrelu',nn.LeakyReLU()), ('maxpool',nn.MaxPool2d(2)), ])) return conv_layer def forward(self, x): # Set 1 out = self.conv_layer1(x) out = self.conv_layer2(out) out = self.conv_layer3(out) out = out.view(out.size(0), -1) # Flatten (batchsize, image size) out = self.fc1(out) out = self.drop(out) out = self.fc2(out) return out ``` ### Config ``` # Train model config = { 'drop':0.5, 'optimizer':{ "type":torch.optim.Adam, "args":{ "lr":0.007, 'weight_decay':0 } }, 'criterion':torch.nn.CrossEntropyLoss(), # error function 'max_epochs':5, "train_metrics":torchmetrics.MetricCollection([ torchmetrics.Accuracy(num_classes=cfg.NUM_CLASSES,compute_on_step=False), #torchmetrics.Precision(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.F1(num_classes=cfg.NUM_CLASSES,compute_on_step=False), #torchmetrics.AUROC(num_classes=cfg.NUM_CLASSES,compute_on_step=False), ],postfix="_Train"), "validation_metrics":torchmetrics.MetricCollection([ torchmetrics.Accuracy(num_classes=cfg.NUM_CLASSES,compute_on_step=False), #torchmetrics.Precision(num_classes=cfg.NUM_CLASSES,compute_on_step=False), torchmetrics.F1(num_classes=cfg.NUM_CLASSES,compute_on_step=False), #torchmetrics.AUROC(num_classes=cfg.NUM_CLASSES,compute_on_step=False), ],postfix="_Validation") } def train(): # Load model modelObj = Model(SimpleModel(num_classes=cfg.NUM_CLASSES, num_channels=cfg.IMAGE_CHANNEL, input_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)),**config) # Setup trainer trainer = pl.Trainer( max_epochs=config['max_epochs'], gpus=1, logger=pl.loggers.TensorBoardLogger(save_dir=cfg.TENSORBORD_DIR), callbacks=[pl.callbacks.progress.TQDMProgressBar()], progress_bar_refresh_rate=1, weights_summary=None, # Can be None, top or full num_sanity_val_steps=10, ) trainer.fit( modelObj, train_dataloader=train_dataloader, val_dataloaders=valid_dataloader ); ``` ### Todo1 **Version 17 in tensorboard logs**, removed dropout since it purpose is to introduce regularization. Ran for 40 epochs. ``` config['max_epochs'] = 40 train() ``` ### Todo2 ``` config['max_epochs'] = 5 train() ``` ### Todo3 ## Hyperparameter tuning ### Task 1 From the example approach we can see that the network performed very poorly. For the network to be consider "good" the truth images should match the predicted images. If the architecture can learn but is unstable (check loss/epoch in tensorboard), it is possible to tune the parameters of the network. This mostly involves changing the learning rate, optimizers, loss function etc. to better learn features. A network that have a to high learning rate create a increase in variance of the network weights which can make the network unstable. **TODO:** Perform hyperparameter tuning. Explain in detail why the parameters was changed and why it is considered "better". ### Todo1 ``` class SimpleModel(nn.Module): def __init__(self,num_channels:int=4, num_classes:int=3, input_shape=(10,10),**kwargs): super().__init__() nr_conv_layers = 3 conv_layers = [] self.conv_layer1 = self._conv_layer_set(num_channels, 32) # 2 self.conv_layer2 = self._conv_layer_set(32, 128) # 4 128 self.conv_layer3 = self._conv_layer_set(128, 150) # 128 (in) conv_layers.extend([self.conv_layer1, self.conv_layer2, self.conv_layer3]) #, self.conv_layer4]) self.convolve = nn.Sequential(*conv_layers) print(self.convolve) feedforward = [] self.fc1 = nn.Linear(150*input_shape[1]//np.power(2, nr_conv_layers)*input_shape[1]//np.power(2, nr_conv_layers), 150) # Calculated with the size. why //4 self.fc2 = nn.Linear(150, num_classes) self.drop = nn.Dropout(0.8) feedforward.append(self.fc1) feedforward.append(self.drop) feedforward.append(self.fc2) self.ffd = nn.Sequential(*feedforward) print(self.ffd) def _conv_layer_set(self, in_c, out_c): conv_layer = nn.Sequential(OrderedDict([ ('conv',nn.Conv2d(in_c, out_c, kernel_size=3, padding=1)), ('leakyrelu',nn.LeakyReLU()), ('maxpool',nn.MaxPool2d(2)), ])) return conv_layer def forward(self, x): # Set 1 out = self.convolve(x) out = out.view(out.size(0), -1) # Flatten (batchsize, image size) out = self.ffd(out) return out modelObj = Model(SimpleModel(num_classes=cfg.NUM_CLASSES, num_channels=cfg.IMAGE_CHANNEL, input_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)),**config) # Setup trainer trainer = pl.Trainer( max_epochs=config['max_epochs'], gpus=1, logger=pl.loggers.TensorBoardLogger(save_dir=cfg.TENSORBORD_DIR), callbacks=[pl.callbacks.progress.TQDMProgressBar()], progress_bar_refresh_rate=1, weights_summary=None, # Can be None, top or full num_sanity_val_steps=10, ) trainer.fit( modelObj, train_dataloader=train_dataloader, val_dataloaders=valid_dataloader ); iter_dataloader = iter(test_dataloader) X, Y = next(iter_dataloader) preds = torch.argmax(modelObj.predict_step(X,0,0),dim=1) print("Test accuracy {}%".format(np.mean(Y.numpy() == preds.numpy())*100)) confuTst = torchmetrics.functional.confusion_matrix(preds.detach().cpu(),Y.int().detach().cpu(), cfg.NUM_CLASSES) plot.confusion_matrix(cm = confuTst.numpy(), normalize = False, target_names = cfg.CLASSES, title = "Confusion Matrix: Test data") ``` ## Augmentation **TODO:** Test if data augmentation help. Note that if we want to apply augmentation we need to make sure that the input and target perform the same augmentation. Otherwise, the data will not be correct! ``` train_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.RandomHorizontalFlip(0.3), #torchvision.transforms.RandomVerticalFlip(), #torchvision.transforms.RandomRotation(15), torchvision.transforms.Resize((cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)), ]) test_transform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), # torchvision.transforms.RandomHorizontalFlip(0.3), #torchvision.transforms.RandomVerticalFlip(), #torchvision.transforms.RandomRotation(15), torchvision.transforms.Resize((cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)), #, ]) train_transform train_dataloader = DataLoader(ClassificationDataset(cfg.training_img_dir, cfg.CLASSES, img_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),transform=train_transform), batch_size=cfg.BATCH_SIZE, shuffle=True, num_workers=cfg.NUM_WORKERS) valid_dataloader = DataLoader(ClassificationDataset(cfg.validation_img_dir, cfg.CLASSES, img_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),transform=test_transform), batch_size=cfg.BATCH_SIZE, shuffle=False, num_workers=cfg.NUM_WORKERS) test_dataloader = DataLoader(ClassificationDataset(cfg.testing_img_dir, cfg.CLASSES, img_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),transform=test_transform), batch_size=cfg.BATCH_SIZE, shuffle=False, num_workers=cfg.NUM_WORKERS) #config['conv_out1'], config['conv_out2'], config['conv_out3'] = (32, 64, 128) #config['max_epochs'] = 20 modelObj = Model(SimpleModel(num_classes=cfg.NUM_CLASSES, num_channels=cfg.IMAGE_CHANNEL, input_shape=(cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)),**config) # Setup trainer trainer = pl.Trainer( max_epochs=config['max_epochs'], gpus=1, logger=pl.loggers.TensorBoardLogger(save_dir=cfg.TENSORBORD_DIR), callbacks=[pl.callbacks.progress.TQDMProgressBar()], progress_bar_refresh_rate=1, weights_summary=None, # Can be None, top or full num_sanity_val_steps=10, ) trainer.fit( modelObj, train_dataloader=train_dataloader, val_dataloaders=valid_dataloader ); iter_dataloader = iter(test_dataloader) X, Y = next(iter_dataloader) preds = torch.argmax(modelObj.predict_step(X,0,0),dim=1) print("Test accuracy {}%".format(np.mean(Y.numpy() == preds.numpy())*100)) confuTst = torchmetrics.functional.confusion_matrix(preds.detach().cpu(),Y.int().detach().cpu(), cfg.NUM_CLASSES) plot.confusion_matrix(cm = confuTst.numpy(), normalize = False, target_names = cfg.CLASSES, title = "Confusion Matrix: Test data") ``` **Question:** Did data augmentation improve the model? \ **Question:** What do you think have the greatest impact on the performance, why? \
github_jupyter
``` #hide from fastai.gen_doc.nbdoc import * ``` # A Neural Net from the Foundations This chapter begins a journey where we will dig deep into the internals of the models we used in the previous chapters. We will be covering many of the same things we've seen before, but this time around we'll be looking much more closely at the implementation details, and much less closely at the practical issues of how and why things are as they are. We will build everything from scratch, only using basic indexing into a tensor. We]ll write a neural net from the ground up, then implement backpropagation manually, so we know exactly what's happening in PyTorch when we call `loss.backward`. We'll also see how to extend PyTorch with custom *autograd* functions that allow us to specify our own forward and backward computations. ## Building a Neural Net Layer from Scratch Let's start by refreshing our understanding of how matrix multiplication is used in a basic neural network. Since we're building everything up from scratch, we'll use nothing but plain Python initially (except for indexing into PyTorch tensors), and then replace the plain Python with PyTorch functionality once we've seen how to create it. ### Modeling a Neuron A neuron receives a given number of inputs and has an internal weight for each of them. It sums those weighted inputs to produce an output and adds an inner bias. In math, this can be written as: $$ out = \sum_{i=1}^{n} x_{i} w_{i} + b$$ if we name our inputs $(x_{1},\dots,x_{n})$, our weights $(w_{1},\dots,w_{n})$, and our bias $b$. In code this translates into: ```python output = sum([x*w for x,w in zip(inputs,weights)]) + bias ``` This output is then fed into a nonlinear function called an *activation function* before being sent to another neuron. In deep learning the most common of these is the *rectified Linear unit*, or *ReLU*, which, as we've seen, is a fancy way of saying: ```python def relu(x): return x if x >= 0 else 0 ``` A deep learning model is then built by stacking a lot of those neurons in successive layers. We create a first layer with a certain number of neurons (known as *hidden size*) and link all the inputs to each of those neurons. Such a layer is often called a *fully connected layer* or a *dense layer* (for densely connected), or a *linear layer*. It requires to compute, for each `input` in our batch and each neuron with a give `weight`, the dot product: ```python sum([x*w for x,w in zip(input,weight)]) ``` If you have done a little bit of linear algebra, you may remember that having a lot of those dot products happens when you do a *matrix multiplication*. More precisely, if our inputs are in a matrix `x` with a size of `batch_size` by `n_inputs`, and if we have grouped the weights of our neurons in a matrix `w` of size `n_neurons` by `n_inputs` (each neuron must have the same number of weights as it has inputs) and all the biases in a vector `b` of size `n_neurons`, then the output of this fully connected layer is: ```python y = x @ w.t() + b ``` where `@` represents the matrix product and `w.t()` is the transpose matrix of `w`. The output `y` is then of size `batch_size` by `n_neurons`, and in position `(i,j)` we have (for the mathy folks out there): $$y_{i,j} = \sum_{k=1}^{n} x_{i,k} w_{k,j} + b_{j}$$ Or in code: ```python y[i,j] = sum([a * b for a,b in zip(x[i,:],w[j,:])]) + b[j] ``` The transpose is necessary because in the mathematical definition of the matrix product `m @ n`, the coefficient `(i,j)` is: ```python sum([a * b for a,b in zip(m[i,:],n[:,j])]) ``` So the very basic operation we need is a matrix multiplication, as it's what is hidden in the core of a neural net. ### Matrix Multiplication from Scratch Let's write a function that computes the matrix product of two tensors, before we allow ourselves to use the PyTorch version of it. We will only use the indexing in PyTorch tensors: ``` import torch from torch import tensor ``` We'll need three nested `for` loops: one for the row indices, one for the column indices, and one for the inner sum. `ac` and `ar` stand for number of columns of `a` and number of rows of `a`, respectively (the same convention is followed for `b`), and we make sure calculating the matrix product is possible by checking that `a` has as many columns as `b` has rows: ``` def matmul(a,b): ar,ac = a.shape # n_rows * n_cols br,bc = b.shape assert ac==br c = torch.zeros(ar, bc) for i in range(ar): for j in range(bc): for k in range(ac): c[i,j] += a[i,k] * b[k,j] return c ``` To test this out, we'll pretend (using random matrices) that we're working with a small batch of 5 MNIST images, flattened into 28×28 vectors, with linear model to turn them into 10 activations: ``` m1 = torch.randn(5,28*28) m2 = torch.randn(784,10) ``` Let's time our function, using the Jupyter "magic" command `%time`: ``` %time t1=matmul(m1, m2) ``` And see how that compares to PyTorch's built-in `@`: ``` %timeit -n 20 t2=m1@m2 ``` As we can see, in Python three nested loops is a very bad idea! Python is a slow language, and this isn't going to be very efficient. We see here that PyTorch is around 100,000 times faster than Python—and that's before we even start using the GPU! Where does this difference come from? PyTorch didn't write its matrix multiplication in Python, but rather in C++ to make it fast. In general, whenever we do computations on tensors we will need to *vectorize* them so that we can take advantage of the speed of PyTorch, usually by using two techniques: elementwise arithmetic and broadcasting. ### Elementwise Arithmetic All the basic operators (`+`, `-`, `*`, `/`, `>`, `<`, `==`) can be applied elementwise. That means if we write `a+b` for two tensors `a` and `b` that have the same shape, we will get a tensor composed of the sums the elements of `a` and `b`: ``` a = tensor([10., 6, -4]) b = tensor([2., 8, 7]) a + b ``` The Booleans operators will return an array of Booleans: ``` a < b ``` If we want to know if every element of `a` is less than the corresponding element in `b`, or if two tensors are equal, we need to combine those elementwise operations with `torch.all`: ``` (a < b).all(), (a==b).all() ``` Reduction operations like `all()`, `sum()` and `mean()` return tensors with only one element, called rank-0 tensors. If you want to convert this to a plain Python Boolean or number, you need to call `.item()`: ``` (a + b).mean().item() ``` The elementwise operations work on tensors of any rank, as long as they have the same shape: ``` m = tensor([[1., 2, 3], [4,5,6], [7,8,9]]) m*m ``` However you can't perform elementwise operations on tensors that don't have the same shape (unless they are broadcastable, as discussed in the next section): ``` n = tensor([[1., 2, 3], [4,5,6]]) m*n ``` With elementwise arithmetic, we can remove one of our three nested loops: we can multiply the tensors that correspond to the `i`-th row of `a` and the `j`-th column of `b` before summing all the elements, which will speed things up because the inner loop will now be executed by PyTorch at C speed. To access one column or row, we can simply write `a[i,:]` or `b[:,j]`. The `:` means take everything in that dimension. We could restrict this and take only a slice of that particular dimension by passing a range, like `1:5`, instead of just `:`. In that case, we would take the elements in columns or rows 1 to 4 (the second number is noninclusive). One simplification is that we can always omit a trailing colon, so `a[i,:]` can be abbreviated to `a[i]`. With all of that in mind, we can write a new version of our matrix multiplication: ``` def matmul(a,b): ar,ac = a.shape br,bc = b.shape assert ac==br c = torch.zeros(ar, bc) for i in range(ar): for j in range(bc): c[i,j] = (a[i] * b[:,j]).sum() return c %timeit -n 20 t3 = matmul(m1,m2) ``` We're already ~700 times faster, just by removing that inner `for` loop! And that's just the beginning—with broadcasting we can remove another loop and get an even more important speed up. ### Broadcasting As we discussed in <<chapter_mnist_basics>>, broadcasting is a term introduced by the [NumPy library](https://docs.scipy.org/doc/) that describes how tensors of different ranks are treated during arithmetic operations. For instance, it's obvious there is no way to add a 3×3 matrix with a 4×5 matrix, but what if we want to add one scalar (which can be represented as a 1×1 tensor) with a matrix? Or a vector of size 3 with a 3×4 matrix? In both cases, we can find a way to make sense of this operation. Broadcasting gives specific rules to codify when shapes are compatible when trying to do an elementwise operation, and how the tensor of the smaller shape is expanded to match the tensor of the bigger shape. It's essential to master those rules if you want to be able to write code that executes quickly. In this section, we'll expand our previous treatment of broadcasting to understand these rules. #### Broadcasting with a scalar Broadcasting with a scalar is the easiest type of broadcating. When we have a tensor `a` and a scalar, we just imagine a tensor of the same shape as `a` filled with that scalar and perform the operation: ``` a = tensor([10., 6, -4]) a > 0 ``` How are we able to do this comparison? `0` is being *broadcast* to have the same dimensions as `a`. Note that this is done without creating a tensor full of zeros in memory (that would be very inefficient). This is very useful if you want to normalize your dataset by subtracting the mean (a scalar) from the entire data set (a matrix) and dividing by the standard deviation (another scalar): ``` m = tensor([[1., 2, 3], [4,5,6], [7,8,9]]) (m - 5) / 2.73 ``` What if have different means for each row of the matrix? in that case you will need to broadcast a vector to a matrix. #### Broadcasting a vector to a matrix We can broadcast a vector to a matrix as follows: ``` c = tensor([10.,20,30]) m = tensor([[1., 2, 3], [4,5,6], [7,8,9]]) m.shape,c.shape m + c ``` Here the elements of `c` are expanded to make three rows that match, making the operation possible. Again, PyTorch doesn't actually create three copies of `c` in memory. This is done by the `expand_as` method behind the scenes: ``` c.expand_as(m) ``` If we look at the corresponding tensor, we can ask for its `storage` property (which shows the actual contents of the memory used for the tensor) to check there is no useless data stored: ``` t = c.expand_as(m) t.storage() ``` Even though the tensor officially has nine elements, only three scalars are stored in memory. This is possible thanks to the clever trick of giving that dimension a *stride* of 0 (which means that when PyTorch looks for the next row by adding the stride, it doesn't move): ``` t.stride(), t.shape ``` Since `m` is of size 3×3, there are two ways to do broadcasting. The fact it was done on the last dimension is a convention that comes from the rules of broadcasting and has nothing to do with the way we ordered our tensors. If instead we do this, we get the same result: ``` c + m ``` In fact, it's only possible to broadcast a vector of size `n` with a matrix of size `m` by `n`: ``` c = tensor([10.,20,30]) m = tensor([[1., 2, 3], [4,5,6]]) c+m ``` This won't work: ``` c = tensor([10.,20]) m = tensor([[1., 2, 3], [4,5,6]]) c+m ``` If we want to broadcast in the other dimension, we have to change the shape of our vector to make it a 3×1 matrix. This is done with the `unsqueeze` method in PyTorch: ``` c = tensor([10.,20,30]) m = tensor([[1., 2, 3], [4,5,6], [7,8,9]]) c = c.unsqueeze(1) m.shape,c.shape ``` This time, `c` is expanded on the column side: ``` c+m ``` Like before, only three scalars are stored in memory: ``` t = c.expand_as(m) t.storage() ``` And the expanded tensor has the right shape because the column dimension has a stride of 0: ``` t.stride(), t.shape ``` With broadcasting, by default if we need to add dimensions, they are added at the beginning. When we were broadcasting before, Pytorch was doing `c.unsqueeze(0)` behind the scenes: ``` c = tensor([10.,20,30]) c.shape, c.unsqueeze(0).shape,c.unsqueeze(1).shape ``` The `unsqueeze` command can be replaced by `None` indexing: ``` c.shape, c[None,:].shape,c[:,None].shape ``` You can always omit trailing colons, and `...` means all preceding dimensions: ``` c[None].shape,c[...,None].shape ``` With this, we can remove another `for` loop in our matrix multiplication function. Now, instead of multiplying `a[i]` with `b[:,j]`, we can multiply `a[i]` with the whole matrix `b` using broadcasting, then sum the results: ``` def matmul(a,b): ar,ac = a.shape br,bc = b.shape assert ac==br c = torch.zeros(ar, bc) for i in range(ar): # c[i,j] = (a[i,:] * b[:,j]).sum() # previous c[i] = (a[i ].unsqueeze(-1) * b).sum(dim=0) return c %timeit -n 20 t4 = matmul(m1,m2) ``` We're now 3,700 times faster than our first implementation! Before we move on, let's discuss the rules of broadcasting in a little more detail. #### Broadcasting rules When operating on two tensors, PyTorch compares their shapes elementwise. It starts with the *trailing dimensions* and works its way backward, adding 1 when it meets empty dimensions. Two dimensions are *compatible* when one of the following is true: - They are equal. - One of them is 1, in which case that dimension is broadcast to make it the same as the other. Arrays do not need to have the same number of dimensions. For example, if you have a 256×256×3 array of RGB values, and you want to scale each color in the image by a different value, you can multiply the image by a one-dimensional array with three values. Lining up the sizes of the trailing axes of these arrays according to the broadcast rules, shows that they are compatible: ``` Image (3d tensor): 256 x 256 x 3 Scale (1d tensor): (1) (1) 3 Result (3d tensor): 256 x 256 x 3 ``` However, a 2D tensor of size 256×256 isn't compatible with our image: ``` Image (3d tensor): 256 x 256 x 3 Scale (1d tensor): (1) 256 x 256 Error ``` In our earlier examples we had with a 3×3 matrix and a vector of size 3, broadcasting was done on the rows: ``` Matrix (2d tensor): 3 x 3 Vector (1d tensor): (1) 3 Result (2d tensor): 3 x 3 ``` As an exercise, try to determine what dimensions to add (and where) when you need to normalize a batch of images of size `64 x 3 x 256 x 256` with vectors of three elements (one for the mean and one for the standard deviation). Another useful wat of simplifying tensor manipulations is the use of Einstein summations convention. ### Einstein Summation Before using the PyTorch operation `@` or `torch.matmul`, there is one last way we can implement matrix multiplication: Einstein summation (`einsum`). This is a compact representation for combining products and sums in a general way. We write an equation like this: ``` ik,kj -> ij ``` The lefthand side represents the operands dimensions, separated by commas. Here we have two tensors that each have two dimensions (`i,k` and `k,j`). The righthand side represents the result dimensions, so here we have a tensor with two dimensions `i,j`. The rules of Einstein summation notation are as follows: 1. Repeated indices are implicitly summed over. 1. Each index can appear at most twice in any term. 1. Each term must contain identical nonrepeated indices. So in our example, since `k` is repeated, we sum over that index. In the end the formula represents the matrix obtained when we put in `(i,j)` the sum of all the coefficients `(i,k)` in the first tensor multiplied by the coefficients `(k,j)` in the second tensor... which is the matrix product! Here is how we can code this in PyTorch: ``` def matmul(a,b): return torch.einsum('ik,kj->ij', a, b) ``` Einstein summation is a very practical way of expressing operations involving indexing and sum of products. Note that you can have just one member on the lefthand side. For instance, this: ```python torch.einsum('ij->ji', a) ``` returns the transpose of the matrix `a`. You can also have three or more members. This: ```python torch.einsum('bi,ij,bj->b', a, b, c) ``` will return a vector of size `b` where the `k`-th coordinate is the sum of `a[k,i] b[i,j] c[k,j]`. This notation is particularly convenient when you have more dimensions because of batches. For example, if you have two batches of matrices and want compute the matrix product per batch, you would could this: ```python torch.einsum('bik,bkj->bij', a, b) ``` Let's go back to our new `matmul` implementation using `einsum` and look at its speed: ``` %timeit -n 20 t5 = matmul(m1,m2) ``` As you can see, not only is it practical, but it's *very* fast. `einsum` is often the fastest way to do custom operations in PyTorch, without diving into C++ and CUDA. (But it's generally not as fast as carefully optimized CUDA code, as you see from the results in "Matrix Multiplication from Scratch".) Now that we know how to implement a matrix multiplication from scratch, we are ready to build our neural net—specifically its forward and backward passes—using just matrix multiplications. ## The Forward and Backward Passes As we saw in <<chapter_mnist_basics>>, to train a model, we will need to compute all the gradients of a given a loss with respect to its parameters, which is known as the *backward pass*. The *forward pass* is where we compute the output of the model on a given input, based on the matrix products. As we define our first neural net, we will also delve into the problem of properly initializing the weights, which is crucial for making training start properly. ### Defining and Initializing a Layer We will take the example of a two-layer neural net first. As we've seen, one layer can be expressed as `y = x @ w + b`, with `x` our inputs, `y` our outputs, `w` the weights of the layer (which is of size number of inputs by number of neurons if we don't transpose like before), and `b` is the bias vector: ``` def lin(x, w, b): return x @ w + b ``` We can stack the second layer on top of the first, but since mathematically the composition of two linear operations is another linear operation, this only makes sense if we put something nonlinear in the middle, called an activation function. As mentioned at the beginning of the chapter, in deep learning applications the activation function most commonly used is a ReLU, which returns the maximum of `x` and `0`. We won't actually train our model in this chapter, so we'll use random tensors for our inputs and targets. Let's say our inputs are 200 vectors of size 100, which we group into one batch, and our targets are 200 random floats: ``` x = torch.randn(200, 100) y = torch.randn(200) ``` For our two-layer model we will need two weight matrices and two bias vectors. Let's say we have a hidden size of 50 and the output size is 1 (for one of our inputs, the corresponding output is one float in this toy example). We initialize the weights randomly and the bias at zero: ``` w1 = torch.randn(100,50) b1 = torch.zeros(50) w2 = torch.randn(50,1) b2 = torch.zeros(1) ``` Then the result of our first layer is simply: ``` l1 = lin(x, w1, b1) l1.shape ``` Note that this formula works with our batch of inputs, and returns a batch of hidden state: `l1` is a matrix of size 200 (our batch size) by 50 (our hidden size). There is a problem with the way our model was initialized, however. To understand it, we need to look at the mean and standard deviation (std) of `l1`: ``` l1.mean(), l1.std() ``` The mean is close to zero, which is understandable since both our input and weight matrices have means close to zero. But the standard deviation, which represents how far away our activations go from the mean, went from 1 to 10. This is a really big problem because that's with just one layer. Modern neural nets can have hundred of layers, so if each of them multiplies the scale of our activations by 10, by the end of the last layer we won't have numbers representable by a computer. Indeed, if we make just 50 multiplications between `x` and random matrices of size 100×100, we'll have: ``` x = torch.randn(200, 100) for i in range(50): x = x @ torch.randn(100,100) x[0:5,0:5] ``` The result is `nan`s everywhere. So maybe the scale of our matrix was too big, and we need to have smaller weights? But if we use too small weights, we will have the opposite problem—the scale of our activations will go from 1 to 0.1, and after 100 layers we'll be left with zeros everywhere: ``` x = torch.randn(200, 100) for i in range(50): x = x @ (torch.randn(100,100) * 0.01) x[0:5,0:5] ``` So we have to scale our weight matrices exactly right so that the standard deviation of our activations stays at 1. We can compute the exact value to use mathematically, as illustrated by Xavier Glorot and Yoshua Bengio in ["Understanding the Difficulty of Training Deep Feedforward Neural Networks"](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf). The right scale for a given layer is $1/\sqrt{n_{in}}$, where $n_{in}$ represents the number of inputs. In our case, if we have 100 inputs, we should scale our weight matrices by 0.1: ``` x = torch.randn(200, 100) for i in range(50): x = x @ (torch.randn(100,100) * 0.1) x[0:5,0:5] ``` Finally some numbers that are neither zeros nor `nan`s! Notice how stable the scale of our activations is, even after those 50 fake layers: ``` x.std() ``` If you play a little bit with the value for scale you'll notice that even a slight variation from 0.1 will get you either to very small or very large numbers, so initializing the weights properly is extremely important. Let's go back to our neural net. Since we messed a bit with our inputs, we need to redefine them: ``` x = torch.randn(200, 100) y = torch.randn(200) ``` And for our weights, we'll use the right scale, which is known as *Xavier initialization* (or *Glorot initialization*): ``` from math import sqrt w1 = torch.randn(100,50) / sqrt(100) b1 = torch.zeros(50) w2 = torch.randn(50,1) / sqrt(50) b2 = torch.zeros(1) ``` Now if we compute the result of the first layer, we can check that the mean and standard deviation are under control: ``` l1 = lin(x, w1, b1) l1.mean(),l1.std() ``` Very good. Now we need to go through a ReLU, so let's define one. A ReLU removes the negatives and replaces them with zeros, which is another way of saying it clamps our tensor at zero: ``` def relu(x): return x.clamp_min(0.) ``` We pass our activations through this: ``` l2 = relu(l1) l2.mean(),l2.std() ``` And we're back to square one: the mean of our activations has gone to 0.4 (which is understandable since we removed the negatives) and the std went down to 0.58. So like before, after a few layers we will probably wind up with zeros: ``` x = torch.randn(200, 100) for i in range(50): x = relu(x @ (torch.randn(100,100) * 0.1)) x[0:5,0:5] ``` This means our initialization wasn't right. Why? At the time Glorot and Bengio wrote their article, the popular activation in a neural net was the hyperbolic tangent (tanh, which is the one they used), and that initialization doesn't account for our ReLU. Fortunately, someone else has done the math for us and computed the right scale for us to use. In ["Delving Deep into Rectifiers: Surpassing Human-Level Performance"](https://arxiv.org/abs/1502.01852) (which we've seen before—it's the article that introduced the ResNet), Kaiming He et al. show that we should use the following scale instead: $\sqrt{2 / n_{in}}$, where $n_{in}$ is the number of inputs of our model. Let's see what this gives us: ``` x = torch.randn(200, 100) for i in range(50): x = relu(x @ (torch.randn(100,100) * sqrt(2/100))) x[0:5,0:5] ``` That's better: our numbers aren't all zeroed this time. So let's go back to the definition of our neural net and use this initialization (which is named *Kaiming initialization* or *He initialization*): ``` x = torch.randn(200, 100) y = torch.randn(200) w1 = torch.randn(100,50) * sqrt(2 / 100) b1 = torch.zeros(50) w2 = torch.randn(50,1) * sqrt(2 / 50) b2 = torch.zeros(1) ``` Let's look at the scale of our activations after going through the first linear layer and ReLU: ``` l1 = lin(x, w1, b1) l2 = relu(l1) l2.mean(), l2.std() ``` Much better! Now that our weights are properly initialized, we can define our whole model: ``` def model(x): l1 = lin(x, w1, b1) l2 = relu(l1) l3 = lin(l2, w2, b2) return l3 ``` This is the forward pass. Now all that's left to do is to compare our output to the labels we have (random numbers, in this example) with a loss function. In this case, we will use the mean squared error. (It's a toy problem, and this is the easiest loss function to use for what is next, computing the gradients.) The only subtlety is that our outputs and targets don't have exactly the same shape—after going though the model, we get an output like this: ``` out = model(x) out.shape ``` To get rid of this trailing 1 dimension, we use the `squeeze` function: ``` def mse(output, targ): return (output.squeeze(-1) - targ).pow(2).mean() ``` And now we are ready to compute our loss: ``` loss = mse(out, y) ``` That's all for the forward pass—let's now look at the gradients. ### Gradients and the Backward Pass We've seen that PyTorch computes all the gradient we need with a magic call to `loss.backward`, but let's explore what's happening behind the scenes. Now comes the part where we need to compute the gradients of the loss with respect to all the weights of our model, so all the floats in `w1`, `b1`, `w2`, and `b2`. For this, we will need a bit of math—specifically the *chain rule*. This is the rule of calculus that guides how we can compute the derivative of a composed function: $$(g \circ f)'(x) = g'(f(x)) f'(x)$$ > j: I find this notation very hard to wrap my head around, so instead I like to think of it as: if `y = g(u)` and `u=f(x)`; then `dy/dx = dy/du * du/dx`. The two notations mean the same thing, so use whatever works for you. Our loss is a big composition of different functions: mean squared error (which is in turn the composition of a mean and a power of two), the second linear layer, a ReLU and the first linear layer. For instance, if we want the gradients of the loss with respect to `b2` and our loss is defined by: ``` loss = mse(out,y) = mse(lin(l2, w2, b2), y) ``` The chain rule tells us that we have: $$\frac{\text{d} loss}{\text{d} b_{2}} = \frac{\text{d} loss}{\text{d} out} \times \frac{\text{d} out}{\text{d} b_{2}} = \frac{\text{d}}{\text{d} out} mse(out, y) \times \frac{\text{d}}{\text{d} b_{2}} lin(l_{2}, w_{2}, b_{2})$$ To compute the gradients of the loss with respect to $b_{2}$, we first need the gradients of the loss with respect to our output $out$. It's the same if we want the gradients of the loss with respect to $w_{2}$. Then, to get the gradients of the loss with respect to $b_{1}$ or $w_{1}$, we will need the gradients of the loss with respect to $l_{1}$, which in turn requires the gradients of the loss with respect to $l_{2}$, which will need the gradients of the loss with respect to $out$. So to compute all the gradients we need for the update, we need to begin from the output of the model and work our way *backward*, one layer after the other—which is why this step is known as *backpropagation*. We can automate it by having each function we implemented (`relu`, `mse`, `lin`) provide its backward step: that is, how to derive the gradients of the loss with respect to the input(s) from the gradients of the loss with respect to the output. Here we populate those gradients in an attribute of each tensor, a bit like PyTorch does with `.grad`. The first are the gradients of the loss with respect to the output of our model (which is the input of the loss function). We undo the `squeeze` we did in `mse`, then we use the formula that gives us the derivative of $x^{2}$: $2x$. The derivative of the mean is just $1/n$ where $n$ is the number of elements in our input: ``` def mse_grad(inp, targ): # grad of loss with respect to output of previous layer inp.g = 2. * (inp.squeeze() - targ).unsqueeze(-1) / inp.shape[0] ``` For the gradients of the ReLU and our linear layer, we use the gradients of the loss with respect to the output (in `out.g`) and apply the chain rule to compute the gradients of the loss with respect to the output (in `inp.g`). The chain rule tells us that `inp.g = relu'(inp) * out.g`. The derivative of `relu` is either 0 (when inputs are negative) or 1 (when inputs are positive), so this gives us: ``` def relu_grad(inp, out): # grad of relu with respect to input activations inp.g = (inp>0).float() * out.g ``` The scheme is the same to compute the gradients of the loss with respect to the inputs, weights, and bias in the linear layer: ``` def lin_grad(inp, out, w, b): # grad of matmul with respect to input inp.g = out.g @ w.t() w.g = inp.t() @ out.g b.g = out.g.sum(0) ``` We won't linger on the mathematical formulas that define them since they're not important for our purposes, but do check out Khan Academy's excellent calculus lessons if you're interested in this topic. ### Sidebar: SymPy SymPy is a library for symbolic computation that is extremely useful library when working with calculus. Per the [documentation](https://docs.sympy.org/latest/tutorial/intro.html): > : Symbolic computation deals with the computation of mathematical objects symbolically. This means that the mathematical objects are represented exactly, not approximately, and mathematical expressions with unevaluated variables are left in symbolic form. To do symbolic computation, we first define a *symbol*, and then do a computation, like so: ``` from sympy import symbols,diff sx,sy = symbols('sx sy') diff(sx**2, sx) ``` Here, SymPy has taken the derivative of `x**2` for us! It can take the derivative of complicated compound expressions, simplify and factor equations, and much more. There's really not much reason for anyone to do calculus manually nowadays—for calculating gradients, PyTorch does it for us, and for showing the equations, SymPy does it for us! ### End sidebar Once we have have defined those functions, we can use them to write the backward pass. Since each gradient is automatically populated in the right tensor, we don't need to store the results of those `_grad` functions anywhere—we just need to execute them in the reverse order of the forward pass, to make sure that in each function `out.g` exists: ``` def forward_and_backward(inp, targ): # forward pass: l1 = inp @ w1 + b1 l2 = relu(l1) out = l2 @ w2 + b2 # we don't actually need the loss in backward! loss = mse(out, targ) # backward pass: mse_grad(out, targ) lin_grad(l2, out, w2, b2) relu_grad(l1, l2) lin_grad(inp, l1, w1, b1) ``` And now we can access the gradients of our model parameters in `w1.g`, `b1.g`, `w2.g`, and `b2.g`. We have sucessfuly defined our model—now let's make it a bit more like a PyTorch module. ### Refactoring the Model The three functions we used have two associated functions: a forward pass and a backward pass. Instead of writing them separately, we can create a class to wrap them together. That class can also store the inputs and outputs for the backward pass. This way, we will just have to call `backward`: ``` class Relu(): def __call__(self, inp): self.inp = inp self.out = inp.clamp_min(0.) return self.out def backward(self): self.inp.g = (self.inp>0).float() * self.out.g ``` `__call__` is a magic name in Python that will make our class callable. This is what will be executed when we type `y = Relu()(x)`. We can do the same for our linear layer and the MSE loss: ``` class Lin(): def __init__(self, w, b): self.w,self.b = w,b def __call__(self, inp): self.inp = inp self.out = inp@self.w + self.b return self.out def backward(self): self.inp.g = self.out.g @ self.w.t() self.w.g = self.inp.t() @ self.out.g self.b.g = self.out.g.sum(0) class Mse(): def __call__(self, inp, targ): self.inp = inp self.targ = targ self.out = (inp.squeeze() - targ).pow(2).mean() return self.out def backward(self): x = (self.inp.squeeze()-self.targ).unsqueeze(-1) self.inp.g = 2.*x/self.targ.shape[0] ``` Then we can put everything in a model that we initiate with our tensors `w1`, `b1`, `w2`, `b2`: ``` class Model(): def __init__(self, w1, b1, w2, b2): self.layers = [Lin(w1,b1), Relu(), Lin(w2,b2)] self.loss = Mse() def __call__(self, x, targ): for l in self.layers: x = l(x) return self.loss(x, targ) def backward(self): self.loss.backward() for l in reversed(self.layers): l.backward() ``` What is really nice about this refactoring and registering things as layers of our model is that the forward and backward passes are now really easy to write. If we want to instantiate our model, we just need to write: ``` model = Model(w1, b1, w2, b2) ``` The forward pass can then be executed with: ``` loss = model(x, y) ``` And the backward pass with: ``` model.backward() ``` ### Going to PyTorch The `Lin`, `Mse` and `Relu` classes we wrote have a lot in common, so we could make them all inherit from the same base class: ``` class LayerFunction(): def __call__(self, *args): self.args = args self.out = self.forward(*args) return self.out def forward(self): raise Exception('not implemented') def bwd(self): raise Exception('not implemented') def backward(self): self.bwd(self.out, *self.args) ``` Then we just need to implement `forward` and `bwd` in each of our subclasses: ``` class Relu(LayerFunction): def forward(self, inp): return inp.clamp_min(0.) def bwd(self, out, inp): inp.g = (inp>0).float() * out.g class Lin(LayerFunction): def __init__(self, w, b): self.w,self.b = w,b def forward(self, inp): return inp@self.w + self.b def bwd(self, out, inp): inp.g = out.g @ self.w.t() self.w.g = self.inp.t() @ self.out.g self.b.g = out.g.sum(0) class Mse(LayerFunction): def forward (self, inp, targ): return (inp.squeeze() - targ).pow(2).mean() def bwd(self, out, inp, targ): inp.g = 2*(inp.squeeze()-targ).unsqueeze(-1) / targ.shape[0] ``` The rest of our model can be the same as before. This is getting closer and closer to what PyTorch does. Each basic function we need to differentiate is written as a `torch.autograd.Function` object that has a `forward` and a `backward` method. PyTorch will then keep trace of any computation we do to be able to properly run the backward pass, unless we set the `requires_grad` attribute of our tensors to `False`. Writing one of these is (almost) as easy as writing our original classes. The difference is that we choose what to save and what to put in a context variable (so that we make sure we don't save anything we don't need), and we return the gradients in the `backward` pass. It's very rare to have to write your own `Function` but if you ever need something exotic or want to mess with the gradients of a regular function, here is how to write one: ``` from torch.autograd import Function class MyRelu(Function): @staticmethod def forward(ctx, i): result = i.clamp_min(0.) ctx.save_for_backward(i) return result @staticmethod def backward(ctx, grad_output): i, = ctx.saved_tensors return grad_output * (i>0).float() ``` The structure used to build a more complex model that takes advantage of those `Function`s is a `torch.nn.Module`. This is the base structure for all models, and all the neural nets you have seen up until now were from that class. It mostly helps to register all the trainable parameters, which as we've seen can be used in the training loop. To implement an `nn.Module` you just need to: - Make sure the superclass `__init__` is called first when you initiliaze it. - Define any parameters of the model as attributes with `nn.Parameter`. - Define a `forward` function that returns the output of your model. As an example, here is the linear layer from scratch: ``` import torch.nn as nn class LinearLayer(nn.Module): def __init__(self, n_in, n_out): super().__init__() self.weight = nn.Parameter(torch.randn(n_out, n_in) * sqrt(2/n_in)) self.bias = nn.Parameter(torch.zeros(n_out)) def forward(self, x): return x @ self.weight.t() + self.bias ``` As you see, this class automatically keeps track of what parameters have been defined: ``` lin = LinearLayer(10,2) p1,p2 = lin.parameters() p1.shape,p2.shape ``` It is thanks to this feature of `nn.Module` that we can just say `opt.step()` and have an optimizer loop through the parameters and update each one. Note that in PyTorch, the weights are stored as an `n_out x n_in` matrix, which is why we have the transpose in the forward pass. By using the linear layer from PyTorch (which uses the Kaiming initialization as well), the model we have been building up during this chapter can be written like this: ``` class Model(nn.Module): def __init__(self, n_in, nh, n_out): super().__init__() self.layers = nn.Sequential( nn.Linear(n_in,nh), nn.ReLU(), nn.Linear(nh,n_out)) self.loss = mse def forward(self, x, targ): return self.loss(self.layers(x).squeeze(), targ) ``` fastai provides its own variant of `Module` that is identical to `nn.Module`, but doesn't require you to call `super().__init__()` (it does that for you automatically): ``` class Model(Module): def __init__(self, n_in, nh, n_out): self.layers = nn.Sequential( nn.Linear(n_in,nh), nn.ReLU(), nn.Linear(nh,n_out)) self.loss = mse def forward(self, x, targ): return self.loss(self.layers(x).squeeze(), targ) ``` In the last chapter, we will start from such a model and see how to build a training loop from scratch and refactor it to what we've been using in previous chapters. ## Conclusion In this chapter we explored the foundations of deep learning, beginning with matrix multiplication and moving on to implementing the forward and backward passes of a neural net from scratch. We then refactored our code to show how PyTorch works beneath the hood. Here are a few things to remember: - A neural net is basically a bunch of matrix multiplications with nonlinearities in between. - Python is slow, so to write fast code we have to vectorize it and take advantage of techniques such as elementwise arithmetic and broadcasting. - Two tensors are broadcastable if the dimensions starting from the end and going backward match (if they are the same, or one of them is 1). To make tensors broadcastable, we may need to add dimensions of size 1 with `unsqueeze` or a `None` index. - Properly initializing a neural net is crucial to get training started. Kaiming initialization should be used when we have ReLU nonlinearities. - The backward pass is the chain rule applied multiple times, computing the gradients from the output of our model and going back, one layer at a time. - When subclassing `nn.Module` (if not using fastai's `Module`) we have to call the superclass `__init__` method in our `__init__` method and we have to define a `forward` function that takes an input and returns the desired result. ## Questionnaire 1. Write the Python code to implement a single neuron. 1. Write the Python code to implement ReLU. 1. Write the Python code for a dense layer in terms of matrix multiplication. 1. Write the Python code for a dense layer in plain Python (that is, with list comprehensions and functionality built into Python). 1. What is the "hidden size" of a layer? 1. What does the `t` method do in PyTorch? 1. Why is matrix multiplication written in plain Python very slow? 1. In `matmul`, why is `ac==br`? 1. In Jupyter Notebook, how do you measure the time taken for a single cell to execute? 1. What is "elementwise arithmetic"? 1. Write the PyTorch code to test whether every element of `a` is greater than the corresponding element of `b`. 1. What is a rank-0 tensor? How do you convert it to a plain Python data type? 1. What does this return, and why? `tensor([1,2]) + tensor([1])` 1. What does this return, and why? `tensor([1,2]) + tensor([1,2,3])` 1. How does elementwise arithmetic help us speed up `matmul`? 1. What are the broadcasting rules? 1. What is `expand_as`? Show an example of how it can be used to match the results of broadcasting. 1. How does `unsqueeze` help us to solve certain broadcasting problems? 1. How can we use indexing to do the same operation as `unsqueeze`? 1. How do we show the actual contents of the memory used for a tensor? 1. When adding a vector of size 3 to a matrix of size 3×3, are the elements of the vector added to each row or each column of the matrix? (Be sure to check your answer by running this code in a notebook.) 1. Do broadcasting and `expand_as` result in increased memory use? Why or why not? 1. Implement `matmul` using Einstein summation. 1. What does a repeated index letter represent on the left-hand side of einsum? 1. What are the three rules of Einstein summation notation? Why? 1. What are the forward pass and backward pass of a neural network? 1. Why do we need to store some of the activations calculated for intermediate layers in the forward pass? 1. What is the downside of having activations with a standard deviation too far away from 1? 1. How can weight initialization help avoid this problem? 1. What is the formula to initialize weights such that we get a standard deviation of 1 for a plain linear layer, and for a linear layer followed by ReLU? 1. Why do we sometimes have to use the `squeeze` method in loss functions? 1. What does the argument to the `squeeze` method do? Why might it be important to include this argument, even though PyTorch does not require it? 1. What is the "chain rule"? Show the equation in either of the two forms presented in this chapter. 1. Show how to calculate the gradients of `mse(lin(l2, w2, b2), y)` using the chain rule. 1. What is the gradient of ReLU? Show it in math or code. (You shouldn't need to commit this to memory—try to figure it using your knowledge of the shape of the function.) 1. In what order do we need to call the `*_grad` functions in the backward pass? Why? 1. What is `__call__`? 1. What methods must we implement when writing a `torch.autograd.Function`? 1. Write `nn.Linear` from scratch, and test it works. 1. What is the difference between `nn.Module` and fastai's `Module`? ### Further Research 1. Implement ReLU as a `torch.autograd.Function` and train a model with it. 1. If you are mathematically inclined, find out what the gradients of a linear layer are in mathematical notation. Map that to the implementation we saw in this chapter. 1. Learn about the `unfold` method in PyTorch, and use it along with matrix multiplication to implement your own 2D convolution function. Then train a CNN that uses it. 1. Implement everything in this chapter using NumPy instead of PyTorch.
github_jupyter
# VacationPy ---- #### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import gmaps import os # Import API key from api_keys import g_key ``` ### Store Part I results into DataFrame * Load the csv exported in Part I to a DataFrame ``` output_data_file = "../WeatherPy/output_data/city_weather.csv" df = pd.read_csv(output_data_file) weather_data = df.drop(columns=["Unnamed: 0"]) weather_data ``` ### Humidity Heatmap * Configure gmaps. * Use the Lat and Lng as locations and Humidity as the weight. * Add Heatmap layer to map. ``` locations = weather_data[["Lat", "Lng"]] humidity = weather_data['Humidity'].astype(float) gmaps.configure(api_key=g_key) fig = gmaps.figure() heat_layer = gmaps.heatmap_layer(locations, weights=humidity, dissipating=False, max_intensity=100, point_radius = 1) fig.add_layer(heat_layer) fig ``` ### Create new DataFrame fitting weather criteria * Narrow down the cities to fit weather conditions. * Drop any rows will null values. ``` sunny_cities = weather_data.loc[(weather_data["Max Temp"] < 90) & (weather_data["Max Temp"] > 75) & (weather_data['Windspeed'] <= 10) & (weather_data['Cloudiness'] == 0)] sunny_cities = sunny_cities.dropna() #narrowed_city_df = narrowed_city_df.reset_index() sunny_cities ``` ### Hotel Map * Store into variable named `hotel_df`. * Add a "Hotel Name" column to the DataFrame. * Set parameters to search for hotels with 5000 meters. * Hit the Google Places API for each city's coordinates. * Store the first Hotel result into the DataFrame. * Plot markers on top of the heatmap. ``` sunny_cities['Nearest Hotel Name'] = '' hotel_df = sunny_cities hotel_df.head() params = { "radius": 5000, "types": "lodging", "key": g_key} for index, row in hotel_df.iterrows(): lat = row["Lat"] lng = row["Lng"] params['location'] = f"{lat},{lng}" base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" try: response = requests.get(base_url, params=params).json() results = response['results'] hotel_df.loc[index, 'Nearest Hotel Name'] = results[0]['name'] except (KeyError, IndexError): print("City not found. Skipping...") hotel_df['Nearest Hotel Name'] = hotel_df['Nearest Hotel Name'].replace('', np.nan) hotel_df = hotel_df.dropna() hotel_df # NOTE: Do not change any of the code in this cell # Using the template add the hotel marks to the heatmap info_box_template = """ <dl> <dt>Name</dt><dd>{Nearest Hotel Name}</dd> <dt>City</dt><dd>{City}</dd> <dt>Country</dt><dd>{Country}</dd> </dl> """ # Store the DataFrame Row # NOTE: be sure to update with your DataFrame name hotel_info = [info_box_template.format(**row) for index, row in hotel_df.iterrows()] locations = hotel_df[["Lat", "Lng"]] # Add marker layer ontop of heat map markers = gmaps.marker_layer(locations, info_box_content=hotel_info) fig.add_layer(markers) # Display Map fig ```
github_jupyter
``` # The magic commands below allow reflecting the changes in an imported module without restarting the kernel. %load_ext autoreload %autoreload 2 import sys print(f'Python version: {sys.version.splitlines()[0]}') print(f'Environment: {sys.exec_prefix}') ``` Shell commands are prefixed with `!` ``` !pwd !echo hello jupyter hello = !echo hello jupyter type(hello) ``` More info at IPython [docs](https://ipython.readthedocs.io/en/stable/api/generated/IPython.utils.text.html#IPython.utils.text.SList) Alternatively, try inline help or `?` ``` from IPython.utils.text import SList help(SList) SList?? !catt readme = !cat /home/keceli/README print(readme) files = !ls ./ezHPC/ files files = !ls -l ./ezHPC/ files files.fields(0) files.fields(-1) pyvar = 'demo' !echo $pyvar !echo $HOSTNAME !echo $(whoami) !echo ~ ``` * So far we have used basic linux commands. * Now, we will demonstrate job submission on JupyterHub. * Job submission on Theta is handled with [Cobalt](https://trac.mcs.anl.gov/projects/cobalt/). * We need to write an executable script to submit a job. * Check ALCF Theta [documentation](https://alcf.anl.gov/support-center/theta/submit-job-theta) for more details. * "Best Practices for Queueing and Running Jobs on Theta" [webinar](https://alcf.anl.gov/events/best-practices-queueing-and-running-jobs-theta) ``` jobscript="""#!/bin/bash -x aprun -n 1 -N 1 echo hello jupyter""" !echo -e "$jobscript" > testjob.sh !chmod u+x testjob.sh !cat testjob.sh !echo -e "#!/bin/bash -x \n aprun -n 1 -N 1 echo hello jupyter" > testjob.sh !chmod u+x testjob.sh !cat testjob.sh #!man qsub !qsub -n 1 -t 10 -A datascience -q debug-flat-quad testjob.sh # Earlier job id: 475482 !qstat -u `whoami` jobid = 475482 !ls "$jobid".* !head "$jobid".* # %load https://raw.githubusercontent.com/keceli/ezHPC/main/ez_cobalt.py #%%writefile ezHPC/ez_cobalt.py #Uncomment to write the file #%load https://raw.githubusercontent.com/keceli/ezHPC/main/ez_theta.py #Uncomment to load the file def qstat(user='', jobid='', header='JobID:User:Score:WallTime:RunTime:Nodes:Queue:Est_Start_Time', extra='', verbose=False): """ Query about jobs submitted to queue manager with `qstat`. Parameters: ------------ user: str, username jobid: str, cobalt job id, if more than one, seperate with a space header: str, customize info using headers other header options: QueuedTime:TimeRemaining:State:Location:Mode:Procs:Preemptable:Index """ import os import getpass cmd = '' if jobid: cmd = f'--header={header} {jobid}' else: if user == '': user = getpass.getuser() #user = '$(whoami)' cmd = f'-u {user} --header={header}' elif user.lower() == 'all': cmd = f'--header={header}' else: cmd = f'-u {user} --header={header}' if verbose: cmd = f'qstat -f -l {cmd}' else: cmd = f'qstat {cmd}' if extra: cmd += ' ' + extra print(f'Running...\n {cmd}\n') stream = os.popen(cmd).read() if stream: print(stream) else: print('No active jobs') return def i_qstat(): """ Query about jobs submitted to queue manager with `qstat`. """ from ipywidgets import interact_manual, widgets import getpass im = interact_manual(qstat, user=getpass.getuser()) app_button = im.widget.children[5] app_button.description = 'qstat' return def qdel(jobid=''): """ Delete job(s) with the given id(s). """ cmd = f'qdel {jobid}' process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE) out, err = process.communicate() print(f'stdout: {out}') print(f'stderr: {err}') return def i_qdel(): """ Delete job(s) with the given id(s). """ from ipywidgets import interact_manual, widgets im = interact_manual(qdel) app_button = im.widget.children[1] app_button.description = 'qdel' return def i_show_logs(job_prefix): """ """ from ipywidgets import widgets, Layout from IPython.display import display, clear_output from os.path import isfile outfile = f'{job_prefix}.output' errfile = f'{job_prefix}.error' logfile = f'{job_prefix}.cobaltlog' if (isfile(outfile)): with open(outfile, 'r') as f: out = f.read() with open(errfile, 'r') as f: err = f.read() with open(logfile, 'r') as f: log = f.read() children = [widgets.Textarea(value=val, layout=Layout(flex= '1 1 auto', width='100%',height='400px')) for name,val in [(outfile,out), (errfile,err), (logfile,log)]] tab = widgets.Tab(children=children,layout=Layout(flex= '1 1 auto', width='100%',height='auto')) #ow = widgets.Textarea(value=out,description=outfile) #ew = widgets.Textarea(value=err,description=errfile) #lw = widgets.Textarea(value=log,description=logfile) tab.set_title(0, outfile) tab.set_title(1, errfile) tab.set_title(2, logfile) display(tab) return def parse_cobaltlog(prefix='', verbose=True): """ Return a dictionary with the content parsed from <prefix>.cobaltlog file """ from os.path import isfile from dateutil.parser import parse from pprint import pprint logfile = f'{prefix}.cobaltlog' d = {} if isfile(logfile): with open(logfile, 'r') as f: lines = f.readlines() for line in lines: if line.startswith('Jobid'): jobid = line.split()[-1].strip() d['jobid'] = jobid elif line.startswith('qsub'): cmd = line.strip() d['qsub_cmd'] = cmd elif 'submitted with cwd set to' in line: d['work_dir'] = line.split()[-1].strip() d['submit_time'] = parse(line.split('submitted')[0].strip()) elif 'INFO: Starting Resource_Prologue' in line: d['init_time'] = parse(line.split('INFO:')[0].strip()) d['queue_time'] = d['init_time'] - d['submit_time'].replace(tzinfo=None) d['queue_seconds'] = d['queue_time'].seconds elif 'Command:' in line: d['script'] = line.split(':')[-1].strip() d['start_time'] = parse(line.split('Command:')[0].strip()) d['boot_time'] = d['start_time'].replace(tzinfo=None) - d['init_time'] d['boot_seconds'] = d['boot_time'].seconds elif 'COBALT_PARTCORES' in line: d['partcores'] = line.split('=')[-1].strip() elif 'SHELL=' in line: d['shell'] = line.split('=')[-1].strip() elif 'COBALT_PROJECT' in line: d['project'] = line.split('=')[-1].strip() elif 'COBALT_PARTNAME' in line: d['partname'] = line.split('=')[-1].strip() elif 'LOGNAME=' in line: d['logname'] = line.split('=')[-1].strip() elif 'USER=' in line: d['user'] = line.split('=')[-1].strip() elif 'COBALT_STARTTIME' in line: d['cobalt_starttime'] = line.split('=')[-1].strip() elif 'COBALT_ENDTIME' in line: d['cobalt_endtime'] = line.split('=')[-1].strip() elif 'COBALT_PARTSIZE' in line: d['partsize'] = line.split('=')[-1].strip() elif 'HOME=' in line: d['home'] = line.split('=')[-1].strip() elif 'COBALT_JOBSIZE' in line: d['jobsize'] = line.split('=')[-1].strip() elif 'COBALT_QUEUE' in line: d['queue'] = line.split('=')[-1].strip() elif 'Info: stdin received from' in line: d['stdin'] = line.split()[-1].strip() elif 'Info: stdout sent to' in line: d['stdout'] = line.split()[-1].strip() elif 'Info: stderr sent to' in line: d['stderr'] = line.split()[-1].strip() elif 'with an exit code' in line: d['exit_code'] = line.split(';')[-1].split()[-1] d['end_time'] = parse(line.split('Info:')[0].strip()) d['job_time'] = d['end_time'] - d['start_time'] d['wall_seconds'] = d['job_time'].seconds else: print(f'{logfile} is not found.') if verbose: pprint(d) return d def print_cobalt_times(prefix=''): """ Print timings from Cobalt logfile """ d = parse_cobaltlog(prefix=prefix, verbose=False) for key, val in d.items(): if '_time' in key or 'seconds' in key: print(f'{key}: {val}') def get_job_script(nodes=1, ranks_per_node=1, affinity='-d 1 -j 1 --cc depth', command='',verbose=True): """ Returns Cobalt job script with the given parameters TODO: add rules for affinity """ script = '#!/bin/bash -x \n' ranks = ranks_per_node * nodes script += f'aprun -n {ranks} -N {ranks_per_node} {affinity} {command}' if verbose: print(script) return script def i_get_job_script_manual(): from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='rank_per_nodes', disabled=False) im = interact_manual(get_job_script, nodes=inodes, ranks_per_node=irank_per_nodes) get_job_script_button = im.widget.children[4] get_job_script_button.description = 'get_job_script' return def i_get_job_script(): from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='ranks/node', disabled=False) iaffinity = widgets.Text(value='-d 1 -j 1 --cc depth',description='affinity') icommand = widgets.Text(value='',description='executable and args') out = widgets.interactive_output(get_job_script, {'nodes': inodes, 'ranks_per_node': iranks_per_node, 'affinity': iaffinity, 'command': icommand}) box = widgets.VBox([widgets.VBox([inodes, iranks_per_node, iaffinity, icommand]), out]) display(box) return def validate_theta_job(queue='', nodes=1, wall_minutes=10): """ Return True if given <queue> <nodes> <wall_minutes> are valid for a job on Theta, Return False and print the reason otherwise. See https://alcf.anl.gov/support-center/theta/job-scheduling-policy-theta Parameters ---------- queue: str, queue name, can be: 'default', 'debug-cache-quad', 'debug-flat-quad', 'backfill' nodes: int, Number of nodes, can be an integer from 1 to 4096 depending on the queue. wall_minutes: int, max wall time in minutes, depends on the queue and the number of nodes, max 1440 minutes """ isvalid = True if queue.startswith('debug'): if wall_minutes > 60: print(f'Max wall time for {queue} queue is 60 minutes') isvalid = False if nodes > 8: print(f'Max number of nodes for {queue} queue is 8') isvalid = False else: if nodes < 128: print(f'Min number of nodes for {queue} queue is 128') isvalid = False else: if wall_minutes < 30: print(f'Min wall time for {queue} queue is 30 minutes') isvalid = False if nodes < 256 and wall_minutes > 180: print(f'Max wall time for {queue} queue is 180 minutes') isvalid = False elif nodes < 384 and wall_minutes > 360: print(f'Max wall time for {queue} queue is 360 minutes') isvalid = False elif nodes < 640 and wall_minutes > 540: print(f'Max wall time for {queue} queue is 540 minutes') isvalid = False elif nodes < 902 and wall_minutes > 720: print(f'Max wall time for {queue} queue is 720 minutes') isvalid = False elif wall_minutes > 1440: print('Max wall time on Theta is 1440 minutes') isvalid = False else: isvalid = True return isvalid def qsub(project='', script='', script_file='', queue='debug-cache-quad', nodes=1, wall_minutes=30, attrs='ssds=required:ssd_size=128', workdir='', jobname='', stdin='', stdout=''): """ Submits a job to the queue with the given parameters. Returns Cobalt Job Id if submitted succesfully. Returns 0 otherwise. Parameters ---------- project: str, name of the project to be charged queue: str, queue name, can be: 'default', 'debug-cache-quad', 'debug-flat-quad', 'backfill' nodes: int, Number of nodes, can be an integer from 1 to 4096 depending on the queue. wall_minutes: int, max wall time in minutes, depends on the queue and the number of nodes, max 1440 minutes """ import os import stat import time from subprocess import Popen, PIPE from os.path import isfile valid = validate_theta_job(queue=queue, nodes=nodes, wall_minutes=wall_minutes) if not valid: print('Job is not valid, change queue, nodes, or wall_minutes.') return 0 with open(script_file, 'w') as f: f.write(script) time.sleep(1) exists = isfile(script_file) if exists: print(f'Created {script_file} on {os.path.abspath(script_file)}.') st = os.stat(script_file) os.chmod(script_file, st.st_mode | stat.S_IEXEC) time.sleep(1) cmd = f'qsub -A {project} -q {queue} -n {nodes} -t {wall_minutes} --attrs {attrs} ' if workdir: cmd += f' --cwd {workdir}' if jobname: cmd += f' --jobname {jobname}' if stdin: cmd += f' -i {stdin}' if stdout: cmd += f' -o {stdout}' cmd += f' {script_file}' print(f'Submitting: \n {cmd} ...\n') process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE) out, err = process.communicate() print(f'job id: {out.decode("utf-8")}') print(f'stderr: {err.decode("utf-8")}') return out.decode("utf-8") def i_qsub(): """ Submits a job to the queue with the given parameters. """ from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='rank/nodes', disabled=False) iqueue = widgets.Dropdown(options=['debug-flat-quad','debug-cache-quad','default', 'backfill'], description='queue', value='debug-cache-quad') iwall_minutes = widgets.BoundedIntText(value=10, min=10, max=1440, step=10, description='wall minutes', disabled=False) iscript = widgets.Textarea(value='#!/bin/bash -x \n', description='job script', layout=Layout(flex= '0 0 auto', width='auto',height='200px')) iscript_file= widgets.Text(value='',description='job script file name') iproject= widgets.Text(value='',description='project') isave = widgets.Checkbox(value=False,description='save', indent=True) isubmit = widgets.Button( value=False, description='submit', disabled=False, button_style='success', tooltip='submit job', icon='') output = widgets.Output() display(iproject, inodes, iqueue, iwall_minutes, iscript_file, iscript, isubmit, output) jobid = '' def submit_clicked(b): with output: clear_output() jobid = qsub(project=iproject.value, script=iscript.value, script_file=iscript_file.value, queue=iqueue.value, nodes=inodes.value, wall_minutes=iwall_minutes.value) isubmit.on_click(submit_clicked) return qstat?? i_qstat() i_get_job_script() i_qsub() jobid=475487 i_show_logs(job_prefix=jobid) jobinfo = parse_cobaltlog(prefix=jobid) print_cobalt_times(prefix=jobid) ``` * There is 1 min overhead for a single node job, more with more number of nodes
github_jupyter
# Frequentist Inference Case Study - Part A ## 1. Learning objectives Welcome to part A of the Frequentist inference case study! The purpose of this case study is to help you apply the concepts associated with Frequentist inference in Python. Frequentist inference is the process of deriving conclusions about an underlying distribution via the observation of data. In particular, you'll practice writing Python code to apply the following statistical concepts: * the _z_-statistic * the _t_-statistic * the difference and relationship between the two * the Central Limit Theorem, including its assumptions and consequences * how to estimate the population mean and standard deviation from a sample * the concept of a sampling distribution of a test statistic, particularly for the mean * how to combine these concepts to calculate a confidence interval ## Prerequisites To be able to complete this notebook, you are expected to have a basic understanding of: * what a random variable is (p.400 of Professor Spiegelhalter's *The Art of Statistics, hereinafter AoS*) * what a population, and a population distribution, are (p. 397 of *AoS*) * a high-level sense of what the normal distribution is (p. 394 of *AoS*) * what the t-statistic is (p. 275 of *AoS*) Happily, these should all be concepts with which you are reasonably familiar after having read ten chapters of Professor Spiegelhalter's book, *The Art of Statistics*. We'll try to relate the concepts in this case study back to page numbers in *The Art of Statistics* so that you can focus on the Python aspects of this case study. The second part (part B) of this case study will involve another, more real-world application of these tools. For this notebook, we will use data sampled from a known normal distribution. This allows us to compare our results with theoretical expectations. ## 2. An introduction to sampling from the normal distribution First, let's explore the ways we can generate the normal distribution. While there's a fair amount of interest in [sklearn](https://scikit-learn.org/stable/) within the machine learning community, you're likely to have heard of [scipy](https://docs.scipy.org/doc/scipy-0.15.1/reference/index.html) if you're coming from the sciences. For this assignment, you'll use [scipy.stats](https://docs.scipy.org/doc/scipy-0.15.1/reference/tutorial/stats.html) to complete your work. This assignment will require some digging around and getting your hands dirty (your learning is maximized that way)! You should have the research skills and the tenacity to do these tasks independently, but if you struggle, reach out to your immediate community and your mentor for help. ``` from scipy.stats import norm from scipy.stats import t import numpy as np from numpy.random import seed import matplotlib.pyplot as plt ``` __Q1:__ Call up the documentation for the `norm` function imported above. (Hint: that documentation is [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html)). What is the second listed method? __A:__ Probability density function. pdf(x, loc=0, scale=1) __Q2:__ Use the method that generates random variates to draw five samples from the standard normal distribution. __A:__ Random variates. rvs(loc=0, scale=1, size=1, random_state=None) ``` seed(47) # draw five samples here samples = norm.rvs(size=5) print(samples) ``` __Q3:__ What is the mean of this sample? Is it exactly equal to the value you expected? Hint: the sample was drawn from the standard normal distribution. If you want a reminder of the properties of this distribution, check out p. 85 of *AoS*. __A:__ About 0.19. This is what I expected because the normal distribution should be spread around 1. Then 1 is divided by the size (5 samples). ``` # Calculate and print the mean here, hint: use np.mean() np.mean(samples) ``` __Q4:__ What is the standard deviation of these numbers? Calculate this manually here as $\sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n}}$ (This is just the definition of **standard deviation** given by Professor Spiegelhalter on p.403 of *AoS*). Hint: np.sqrt() and np.sum() will be useful here and remember that numPy supports [broadcasting](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). __A:__ Approximately 0.96. ``` np.sqrt(np.sum((samples - samples.mean()) ** 2) / len(samples)) ``` Here we have calculated the actual standard deviation of a small data set (of size 5). But in this case, this small data set is actually a sample from our larger (infinite) population. In this case, the population is infinite because we could keep drawing our normal random variates until our computers die! In general, the sample mean we calculate will not be equal to the population mean (as we saw above). A consequence of this is that the sum of squares of the deviations from the _population_ mean will be bigger than the sum of squares of the deviations from the _sample_ mean. In other words, the sum of squares of the deviations from the _sample_ mean is too small to give an unbiased estimate of the _population_ variance. An example of this effect is given [here](https://en.wikipedia.org/wiki/Bessel%27s_correction#Source_of_bias). Scaling our estimate of the variance by the factor $n/(n-1)$ gives an unbiased estimator of the population variance. This factor is known as [Bessel's correction](https://en.wikipedia.org/wiki/Bessel%27s_correction). The consequence of this is that the $n$ in the denominator is replaced by $n-1$. You can see Bessel's correction reflected in Professor Spiegelhalter's definition of **variance** on p. 405 of *AoS*. __Q5:__ If all we had to go on was our five samples, what would be our best estimate of the population standard deviation? Use Bessel's correction ($n-1$ in the denominator), thus $\sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n-1}}$. __A:__ Approximately 1.07. ``` np.sqrt(np.sum((samples - samples.mean()) ** 2) / (len(samples) - 1)) ``` __Q6:__ Now use numpy's std function to calculate the standard deviation of our random samples. Which of the above standard deviations did it return? __A:__ The first (regular) standard deviation calculation. ``` np.std(samples) ``` __Q7:__ Consult the documentation for np.std() to see how to apply the correction for estimating the population parameter and verify this produces the expected result. __A:__ The ddof parameter of 1 returns the same result of about 1.07 as above. ``` # np.std? only returns the help in the Jupyter console. help(np.std) np.std(samples, ddof=1) ``` ### Summary of section In this section, you've been introduced to the scipy.stats package and used it to draw a small sample from the standard normal distribution. You've calculated the average (the mean) of this sample and seen that this is not exactly equal to the expected population parameter (which we know because we're generating the random variates from a specific, known distribution). You've been introduced to two ways of calculating the standard deviation; one uses $n$ in the denominator and the other uses $n-1$ (Bessel's correction). You've also seen which of these calculations np.std() performs by default and how to get it to generate the other. You use $n$ as the denominator if you want to calculate the standard deviation of a sequence of numbers. You use $n-1$ if you are using this sequence of numbers to estimate the population parameter. This brings us to some terminology that can be a little confusing. The population parameter is traditionally written as $\sigma$ and the sample statistic as $s$. Rather unhelpfully, $s$ is also called the sample standard deviation (using $n-1$) whereas the standard deviation of the sample uses $n$. That's right, we have the sample standard deviation and the standard deviation of the sample and they're not the same thing! The sample standard deviation \begin{equation} s = \sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n-1}} \approx \sigma, \end{equation} is our best (unbiased) estimate of the population parameter ($\sigma$). If your dataset _is_ your entire population, you simply want to calculate the population parameter, $\sigma$, via \begin{equation} \sigma = \sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n}} \end{equation} as you have complete, full knowledge of your population. In other words, your sample _is_ your population. It's worth noting that we're dealing with what Professor Spiegehalter describes on p. 92 of *AoS* as a **metaphorical population**: we have all the data, and we act as if the data-point is taken from a population at random. We can think of this population as an imaginary space of possibilities. If, however, you have sampled _from_ your population, you only have partial knowledge of the state of your population. In this case, the standard deviation of your sample is not an unbiased estimate of the standard deviation of the population, in which case you seek to estimate that population parameter via the sample standard deviation, which uses the $n-1$ denominator. Great work so far! Now let's dive deeper. ## 3. Sampling distributions So far we've been dealing with the concept of taking a sample from a population to infer the population parameters. One statistic we calculated for a sample was the mean. As our samples will be expected to vary from one draw to another, so will our sample statistics. If we were to perform repeat draws of size $n$ and calculate the mean of each, we would expect to obtain a distribution of values. This is the sampling distribution of the mean. **The Central Limit Theorem (CLT)** tells us that such a distribution will approach a normal distribution as $n$ increases (the intuitions behind the CLT are covered in full on p. 236 of *AoS*). For the sampling distribution of the mean, the standard deviation of this distribution is given by \begin{equation} \sigma_{mean} = \frac{\sigma}{\sqrt n} \end{equation} where $\sigma_{mean}$ is the standard deviation of the sampling distribution of the mean and $\sigma$ is the standard deviation of the population (the population parameter). This is important because typically we are dealing with samples from populations and all we know about the population is what we see in the sample. From this sample, we want to make inferences about the population. We may do this, for example, by looking at the histogram of the values and by calculating the mean and standard deviation (as estimates of the population parameters), and so we are intrinsically interested in how these quantities vary across samples. In other words, now that we've taken one sample of size $n$ and made some claims about the general population, what if we were to take another sample of size $n$? Would we get the same result? Would we make the same claims about the general population? This brings us to a fundamental question: _when we make some inference about a population based on our sample, how confident can we be that we've got it 'right'?_ We need to think about **estimates and confidence intervals**: those concepts covered in Chapter 7, p. 189, of *AoS*. Now, the standard normal distribution (with its variance equal to its standard deviation of one) would not be a great illustration of a key point. Instead, let's imagine we live in a town of 50,000 people and we know the height of everyone in this town. We will have 50,000 numbers that tell us everything about our population. We'll simulate these numbers now and put ourselves in one particular town, called 'town 47', where the population mean height is 172 cm and population standard deviation is 5 cm. ``` seed(47) pop_heights = norm.rvs(172, 5, size=50000) _ = plt.hist(pop_heights, bins=30) _ = plt.xlabel('height (cm)') _ = plt.ylabel('number of people') _ = plt.title('Distribution of heights in entire town population') _ = plt.axvline(172, color='r') _ = plt.axvline(172+5, color='r', linestyle='--') _ = plt.axvline(172-5, color='r', linestyle='--') _ = plt.axvline(172+10, color='r', linestyle='-.') _ = plt.axvline(172-10, color='r', linestyle='-.') ``` Now, 50,000 people is rather a lot to chase after with a tape measure. If all you want to know is the average height of the townsfolk, then can you just go out and measure a sample to get a pretty good estimate of the average height? ``` def townsfolk_sampler(n): return np.random.choice(pop_heights, n) ``` Let's say you go out one day and randomly sample 10 people to measure. ``` seed(47) daily_sample1 = townsfolk_sampler(10) _ = plt.hist(daily_sample1, bins=10) _ = plt.xlabel('height (cm)') _ = plt.ylabel('number of people') _ = plt.title('Distribution of heights in sample size 10') ``` The sample distribution doesn't resemble what we take the population distribution to be. What do we get for the mean? ``` np.mean(daily_sample1) ``` And if we went out and repeated this experiment? ``` daily_sample2 = townsfolk_sampler(10) np.mean(daily_sample2) ``` __Q8:__ Simulate performing this random trial every day for a year, calculating the mean of each daily sample of 10, and plot the resultant sampling distribution of the mean. __A:__ ``` seed(47) # take your samples here for day in range(365): print(f"Sample for day {day + 1} was {np.mean(townsfolk_sampler(10))}") seed(47) # Or the Pythonic way daily_sample_means = np.array([np.mean(townsfolk_sampler(10)) for i in range(365)]) _ = plt.hist(daily_sample_means, bins=10) _ = plt.xlabel('height (cm)') _ = plt.ylabel('number of people') _ = plt.title('Distribution of heights in sample size 10') ``` The above is the distribution of the means of samples of size 10 taken from our population. The Central Limit Theorem tells us the expected mean of this distribution will be equal to the population mean, and standard deviation will be $\sigma / \sqrt n$, which, in this case, should be approximately 1.58. __Q9:__ Verify the above results from the CLT. __A:__ This is approximately 1.58. ``` np.std(daily_sample_means, ddof=1) ``` Remember, in this instance, we knew our population parameters, that the average height really is 172 cm and the standard deviation is 5 cm, and we see some of our daily estimates of the population mean were as low as around 168 and some as high as 176. __Q10:__ Repeat the above year's worth of samples but for a sample size of 50 (perhaps you had a bigger budget for conducting surveys that year)! Would you expect your distribution of sample means to be wider (more variable) or narrower (more consistent)? Compare your resultant summary statistics to those predicted by the CLT. __A:__ The larger sample size of 50 is more normally distributed with a narrower range. This is expected as the sample size becomes more representative of the population. ``` seed(47) # calculate daily means from the larger sample size here daily_sample_means_50 = np.array([np.mean(townsfolk_sampler(50)) for i in range(365)]) _ = plt.hist(daily_sample_means_50, bins=10) _ = plt.xlabel('height (cm)') _ = plt.ylabel('number of people') _ = plt.title('Distribution of heights in sample size 10') np.std(daily_sample_means_50, ddof=1) ``` What we've seen so far, then, is that we can estimate population parameters from a sample from the population, and that samples have their own distributions. Furthermore, the larger the sample size, the narrower are those sampling distributions. ### Normally testing time! All of the above is well and good. We've been sampling from a population we know is normally distributed, we've come to understand when to use $n$ and when to use $n-1$ in the denominator to calculate the spread of a distribution, and we've seen the Central Limit Theorem in action for a sampling distribution. All seems very well behaved in Frequentist land. But, well, why should we really care? Remember, we rarely (if ever) actually know our population parameters but we still have to estimate them somehow. If we want to make inferences to conclusions like "this observation is unusual" or "my population mean has changed" then we need to have some idea of what the underlying distribution is so we can calculate relevant probabilities. In frequentist inference, we use the formulae above to deduce these population parameters. Take a moment in the next part of this assignment to refresh your understanding of how these probabilities work. Recall some basic properties of the standard normal distribution, such as that about 68% of observations are within plus or minus 1 standard deviation of the mean. Check out the precise definition of a normal distribution on p. 394 of *AoS*. __Q11:__ Using this fact, calculate the probability of observing the value 1 or less in a single observation from the standard normal distribution. Hint: you may find it helpful to sketch the standard normal distribution (the familiar bell shape) and mark the number of standard deviations from the mean on the x-axis and shade the regions of the curve that contain certain percentages of the population. __A:__ ``` 1 - ((1 - 0.68) / 2) ``` Calculating this probability involved calculating the area under the curve from the value of 1 and below. To put it in mathematical terms, we need to *integrate* the probability density function. We could just add together the known areas of chunks (from -Inf to 0 and then 0 to $+\sigma$ in the example above). One way to do this is to look up tables (literally). Fortunately, scipy has this functionality built in with the cdf() function. __Q12:__ Use the cdf() function to answer the question above again and verify you get the same answer. __A:__ The two answers are the same. ``` norm.cdf(1) ``` __Q13:__ Using our knowledge of the population parameters for our townsfolks' heights, what is the probability of selecting one person at random and their height being 177 cm or less? Calculate this using both of the approaches given above. NOTE: Assuming the following questions are using the actual population mean (172) and standard deviation (5) given in the description above. __A:__ There is about an 84% chance of selecting someone that is 177 cm or less from this population. ``` norm(172, 5).cdf(177) ``` __Q14:__ Turning this question around — suppose we randomly pick one person and measure their height and find they are 2.00 m tall. How surprised should we be at this result, given what we know about the population distribution? In other words, how likely would it be to obtain a value at least as extreme as this? Express this as a probability. __A:__ This is VERY surprising. There is almost has no probability of it happening. It could be a measurement error or someone from out of town. ``` 1 - norm(172, 5).cdf(200) ``` What we've just done is calculate the ***p-value*** of the observation of someone 2.00m tall (review *p*-values if you need to on p. 399 of *AoS*). We could calculate this probability by virtue of knowing the population parameters. We were then able to use the known properties of the relevant normal distribution to calculate the probability of observing a value at least as extreme as our test value. We're about to come to a pinch, though. We've said a couple of times that we rarely, if ever, know the true population parameters; we have to estimate them from our sample and we cannot even begin to estimate the standard deviation from a single observation. This is very true and usually we have sample sizes larger than one. This means we can calculate the mean of the sample as our best estimate of the population mean and the standard deviation as our best estimate of the population standard deviation. In other words, we are now coming to deal with the sampling distributions we mentioned above as we are generally concerned with the properties of the sample means we obtain. Above, we highlighted one result from the CLT, whereby the sampling distribution (of the mean) becomes narrower and narrower with the square root of the sample size. We remind ourselves that another result from the CLT is that _even if the underlying population distribution is not normal, the sampling distribution will tend to become normal with sufficiently large sample size_. (**Check out p. 199 of AoS if you need to revise this**). This is the key driver for us 'requiring' a certain sample size, for example you may frequently see a minimum sample size of 30 stated in many places. In reality this is simply a rule of thumb; if the underlying distribution is approximately normal then your sampling distribution will already be pretty normal, but if the underlying distribution is heavily skewed then you'd want to increase your sample size. __Q15:__ Let's now start from the position of knowing nothing about the heights of people in our town. * Use the random seed of 47, to randomly sample the heights of 50 townsfolk * Estimate the population mean using np.mean * Estimate the population standard deviation using np.std (remember which denominator to use!) * Calculate the (95%) [margin of error](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/hypothesis-testing/margin-of-error/#WhatMofE) (use the exact critial z value to 2 decimal places - [look this up](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/find-critical-values/) or use norm.ppf()) Recall that the ***margin of error*** is mentioned on p. 189 of the *AoS* and discussed in depth in that chapter). * Calculate the 95% Confidence Interval of the mean (***confidence intervals*** are defined on p. 385 of *AoS*) * Does this interval include the true population mean? __A:__ ``` seed(47) sample_size = 50 # take your sample now sample = townsfolk_sampler(sample_size) mean_sample = np.mean(sample) print(f"Mean is: {mean_sample}.") std_sample = np.std(sample) print(f"Standard deviation is: {std_sample}.") # 95% margin of error has 2 tails of rejection: # 1) 100% - 95% = 5%. 2) 5% / 2 = 0.025. 3) 1 - 0.025 = 0.975. critical_value = norm.ppf(0.975) std_error = std_sample / np.sqrt(sample_size) margin_of_error = critical_value * std_error print(f"Margin of error is: {margin_of_error}.") lower = mean_sample - margin_of_error upper = mean_sample + margin_of_error ci = np.array([lower, upper]) print(f"The 95% confidence interval is: {ci}.") ``` __Q16:__ Above, we calculated the confidence interval using the critical z value. What is the problem with this? What requirement, or requirements, are we (strictly) failing? __A:__ Only using one sample. This may or may not accurately reflect the population. The t distribution is most likely better to find the confidence interval. __Q17:__ Calculate the 95% confidence interval for the mean using the _t_ distribution. Is this wider or narrower than that based on the normal distribution above? If you're unsure, you may find this [resource](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/confidence-interval/) useful. For calculating the critical value, remember how you could calculate this for the normal distribution using norm.ppf(). __A:__ The confidence interval using the t distribution is a little wider. ### Steps to calculate a Confidence Interval For a Sample 1) Subtract 1 from your sample size. 2) Subtract the confidence level from 1 and then divide by two. 3) Lookup answers from step 1 and 2 in t-distribution table or calculate them. 4) Divide sample standard deviation by the square root of the sample size. 5) Multiple step 3 and 4. 6) Subtract step 5 from the sample mean for the lower end of the range. 7) Add step 5 from the sample mean for the upper end of the range. ``` # 50- 1 = 49. first_steps = t(49).ppf([0.025, 0.975]) step_4 = std_sample / np.sqrt(sample_size) step_5 = first_steps * step_4 last_steps = step_5 + mean_sample last_steps ``` This is slightly wider than the previous confidence interval. This reflects the greater uncertainty given that we are estimating population parameters from a sample. ## 4. Learning outcomes Having completed this project notebook, you now have hands-on experience: * sampling and calculating probabilities from a normal distribution * identifying the correct way to estimate the standard deviation of a population (the population parameter) from a sample * with sampling distribution and now know how the Central Limit Theorem applies * with how to calculate critical values and confidence intervals
github_jupyter
``` #week-4,l-10 #DICTIONARY:- # A Simple dictionary alien_0={'color': 'green','points': 5} print(alien_0['color']) print(alien_0['points']) #accessing value in a dictionary: alien_0={'color':'green','points': 5} new_points=alien_0['points'] print(f"you just eand {new_points} points") #adding new.key-value pairs:- alien_0={'color':'green','points': 5} print(alien_0) alien_0['x_position']=0 alien_0['t_position']=25 print(alien_0) # empyt dictionary:- alien_0={} alien_0['color']='green' alien_0['points']=5 print(alien_0) # Modifie value in a dictionary:- alien_0={'color': 'green','points': 5} print(f"the alien is {alien_0['color']}") alien_0['color']='yellow' print(f"the alien is new {alien_0['color']}") # Example:- alien_0={'x_position': 0,'y_position': 25,'speed': 'medium'} print(f"original position {alien_0['x_position']}") if alien_0['speed']=='slow': x_increment=1 elif alien_0['speed']=='medium': x_increment=1 else: x_increment=3 alien_0['x_position']=alien_0['x_position']+x_increment print(f"new position {alien_0['x_position']}") alien_0={'color': 'green','points': 5} print(alien_0) del alien_0['points'] print(alien_0) # Example- favorite_language={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } language=favorite_language['jen'] print(f"jen's favorite language is {language}") # error value of no key in list:- alien_0={'color': 'green','speed': 'slow'} print(alien_0['points'] # Example:- alien_0={'color': 'green','speed': 'slow'} points_value=alien_0.get('points','no points value aasigned.') print(points_value) # Loop through a dictionary:- # Example:- 1 user_0={ 'username': 'efermi', 'first': 'enrika', 'last': 'fermi' } for key,value in user_0.items(): print(f"\nkey: {key}") print(f"value: {value}") #Example:-2 favorite_language={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phin': 'python' } for name,language in favorite_language.items(): print(f"\n{name.title()}'s favrote language is {language.title()}") # if you print only keys:- favorite_language={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } for name in favorite_language.keys(): print(name.title()) # if you print a message with the any value:- favorite_languages={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } friends=['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: language=(favorite_languages[name].title()) print(f"{name.title()},i see you love {language}") # print a message if not keys in dict.... favorite_languages={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } if 'earimed' not in favorite_languages.keys(): print("earimed, pleaseb take our poll.") # if you print in ordered:- favorite_languages={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } for name in sorted(favorite_language.keys()): print(f"{name.title()}.thank you for taking the poll.") # if you print only value:- favorite_languages={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } print("The following language have been mentioned") for language in favorite_languages.values(): print(language.title()) # use set methon and print unique language:- favorite_languages={ 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } print("The following language have been mentioned") for language in set(favorite_languages.values()): print(language.title()) # NESTING(MULTIPLE DICT):- # A list of Dictionaries- alien_0={'color': 'green','points': 5} alien_1={'color': 'yellow','points': 10} alien_2={'color':'red','points': 15} aliens=[alien_0,alien_1,alien_2] for alien in aliens: print(alien) # For empty list:- aliens=[] for alien_number in range(30): new_alien={'color':'green','points': 5,'speed': 'slow'} aliens.append(new_alien) for alien in aliens[:5]: print(alien) print(f"\nTotal no of alien {len(aliens)}") # if you want to prin 1st 3 aliens is yellow:- liens=[] for alien_number in range(30): new_alien={'color':'green','points': 5,'speed': 'slow'} aliens.append(new_alien) for alien in aliens[:3]: if alien['color']=='green': alien['color']='yellow' alien['speed']='mediam' alien['points']='10' for alien in aliens[:5]: print(alien) # if you want to prin 1st 3 aliens is yellow:- liens=[] for alien_number in range(30): new_alien={'color':'green','points': 5,'speed': 'slow'} aliens.append(new_alien) for alien in aliens[:3]: if alien['color']=='green': alien['color']='yellow' alien['speed']='mediam' alien['points']=10 for alien in aliens[:5]: print(alien) # store imfomation about a pizza bieng ordered:- pizza={ 'crust': 'thick', 'topping': ['moshroom','extracheese'] } print(f"you ordered a {pizza['crust']}-crust pizza with the following topping" ) for topping in pizza['topping']: print("\t" + topping) # for multiple favorite languagees:- favorite_languages={ 'jen': ['python','ruby'], 'sahar': ['c'], 'edward': ['ruby','go'], 'phil': ['python','hashell'] } for name,language in favorite_languages.items(): print(f"{name}'s favorite language are") for language in language: print(language) # A DICTIONAY IN A DICTIONARY:- user={ 'aeintein':{ 'first': 'albert', 'last': 'aeintein', 'location':'princetion', }, 'mcurie':{ 'first': 'marie', 'last': 'curie', 'location': 'paris', } } for username,user_info in user.items(): print(f"\nusername:{username}") full_name=(f"{user_info['first']}{user_info['last']}") print(f"full_name: {full_name.title()}") print(f"location: {location.title()}") #OPERATION ON DICTIONARY:- capital={'India': 'New delhi','Usa': 'Washington dc','Franch': 'Paris','Sri lanka': 'Colombo'} print(capital['India']) print(capital.get('Uk', 'unknown')) capital['Uk']='London' print(capital['Uk']) print(capital.keys()) print(capital.values()) print(len(capital)) print('Usa' in capital) print('russia' in capital) del capital['Usa'] print(capital) capital['Sri lanka']='Sri Jayawardenepura Kotte' print(capital) countries=[] for k in capital: countries.append(k) countries.sort() print(countries) # L-12. # USER INPUT AND WHILOE LOOPS:- # How the input() funtion:- message=input("Tell me something,and i will repeat it back to you:") name=input("please enter your name:") print(f"\nHello,{name}!") prompt="if you tell us who are you,we can personalize the message you se." prompt="\nwhat is you name?" name=input(prompt) print(f"\nHello,{name}!") #accept numerical input age=input("how old are ypu?.") age=int(age) print(age>=18) # example:- height=input("How tall are you, in inches") height=int(height) if height>=48: print("\nyou are tall enough to ride") else: print("\nyou'll be able to ride when you're a little older") # print even number or odd:- number=input("Enter the number,and i'll tell you if it's even or odd number") number=int(number) if number%2==0: print(f"\nThe number {number} is even.") else: print(f"\nThe number {number} is odd") #INTRIDUCSCING WHILE LOOPS- # The while loop in action: current_number=1 while current_number<=5: print(current_number) current_number +=1 # example:- prompt="Tell me something, and i will repeat it back to you:" prompt+="\nEnter 'quit' to end the program." message="" while message!='quit': message=input(prompt) if message!='quit': print(message) #Using break to exot a loop prompt="\nPlease enter the name of a city you have visited." prompt+="\nenter 'quit' when you are finished" while True: city=input(prompt) if city=='quit': break else: print(f"i'd love to go to {city.title()}") #Example:- current_number=0 while current_number<10: current_number+=1 if current_number%2==0: continue print(current_number) x=1 while x<=5: print(x) x+=1 ```
github_jupyter
# House Prices: Advanced Regression Techniques ### **Goal** It is your job to predict the sales price for each house. For each Id in the test set, you must predict the value of the SalePrice variable. ### **Metric** Submissions are evaluated on Root-Mean-Squared-Error (RMSE) between the logarithm of the predicted value and the logarithm of the observed sales price. (Taking logs means that errors in predicting expensive houses and cheap houses will affect the result equally.) ### **Submission File Format** The file should contain a header and have the following format: Id,SalePrice 1461,169000.1 1462,187724.1233 1463,175221 etc. <https://www.kaggle.com/c/house-prices-advanced-regression-techniques/> ``` import pandas as pd import numpy as np import sklearn as sk import matplotlib.pyplot as plt import seaborn as sns from pylab import * import scipy.stats as stats train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') sample_submission = pd.read_csv('sample_submission.csv') def multi_levene(df, col_names, target): group_df = df.pivot(columns = col_names, values = target) pvals = [] for i in range(len(group_df.columns)-1): pval = stats.levene(group_df.iloc[:,i].dropna(), group_df.iloc[:,i+1].dropna()).pvalue pvals.append(pval) return max(pvals) text_columns = train.columns[train.dtypes == object] train['total_SF'] = train[['TotalBsmtSF','1stFlrSF','2ndFlrSF']].sum(axis=1) train['price_per_SF'] = train['SalePrice']/train['total_SF'] levene_df = pd.DataFrame() for col in text_columns: levene_df = levene_df.append([[col,multi_levene(train, col, 'price_per_SF')]]) levene_df.columns = ['feature','score'] irrelevant_cols = levene_df.loc[levene_df['score']<0.05,'feature'] train_dummies = pd.get_dummies(train[text_columns]) train_corr = train.drop('price_per_SF',axis=1).corr() target_variables = train_corr.nlargest(11, 'SalePrice').index.tolist() target_vars = [word for word in target_variables if word != 'SalePrice'] from sklearn.model_selection import train_test_split X = train[target_vars].join(train_dummies) y = train['SalePrice'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=42) from sklearn import linear_model reg = linear_model.LinearRegression() reg.fit(X_train, y_train) import sklearn.metrics as metrics def regression_results(y_true, y_pred): # Regression metrics explained_variance=metrics.explained_variance_score(y_true, y_pred) mean_absolute_error=metrics.mean_absolute_error(y_true, y_pred) mse=metrics.mean_squared_error(y_true, y_pred) mean_squared_log_error=metrics.mean_squared_log_error(y_true, y_pred) median_absolute_error=metrics.median_absolute_error(y_true, y_pred) r2=metrics.r2_score(y_true, y_pred) print('explained_variance: ', round(explained_variance,4)) print('mean_squared_log_error: ', round(mean_squared_log_error,4)) print('r2: ', round(r2,4)) print('MAE: ', round(mean_absolute_error,4)) print('MSE: ', round(mse,4)) print('RMSE: ', round(np.sqrt(mse),4)) y_pred = reg.predict(X_test) regression_results(y_test, y_pred) plt.figure(figsize=(10,5)) sns.distplot(y_test-y_pred) plt.title('Distance Between Real Price and Predicted Price') plt.show() ```
github_jupyter
## Dictionaries Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. ## Accessing Values in Dictionary To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print("dict1['Name']: ", dict1['Name']) print("dict1['Age']: ", dict1['Age']) ``` If we attempt to access a data item with a key, which is not a part of the dictionary, we get a `KeyError`. ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print("dict1['Alice']: ", dict1['Alice']) ``` ## Updating Dictionary You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown in a simple example given below. ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict1['Age'] = 8; # update existing entry dict1['School'] = "DPS School" # Add new entry print("dict1['Age']: ", dict1['Age']) print("dict1['School']: ", dict1['School']) print(dict1) ``` ## Delete Dictionary Elements ou can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the `del` statement. ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict1 ``` Remove entry with key 'Name' ``` del dict1['Name'] dict1 ``` Remove all entries in dict ``` dict1.clear() dict1 ``` Delete entire dictionary ``` del dict1 ``` ## Properties of Dictionary Keys Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. There are two important points to remember about dictionary keys More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate keys are encountered during assignment, the last assignment wins. ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print("dict1['Name']: ", dict1['Name']) ``` Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. ``` dict1 = {['Name']: 'Zara', 'Age': 7} print("dict1['Name']: ", dict1['Name']) ``` ## Built-in Dictionary Functions Python includes the following dictionary functions. `len(dict)` gives the total length of the dictionary. This would be equal to the number of items in the dictionary. ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} len(dict1) ``` `str(dict)` produces a printable string representation of a dictionary ``` dict1 = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} str(dict1) ``` `type(variable)` returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. ``` dict1 = {'Name': 'Zara', 'Age': 7} type(dict1) ``` Python includes many dictionary methods. Here are some of them. `dict.get(key, default=None)` for key key, returns value or default if key not in dictionary ``` dict1 = {'Name': 'Zara', 'Age': 7} dict1.get('Sex', 'Female') ``` `dict.keys()` returns list of dictionary dict's keys ``` dict1 = {'Name': 'Zara', 'Age': 7} dict1.keys() ``` `dict.values()` returns list of dictionary dict's values ``` dict1 = {'Name': 'Zara', 'Age': 7} dict1.values() ``` `dict.items()` returns a list of dict's (key, value) tuple pairs ``` dict1 = {'Name': 'Zara', 'Age': 7} dict1.items() ```
github_jupyter
``` import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns %matplotlib inline df = pd.read_csv('boston_house_prices.csv') ``` <b>Explanation of Features</b> * CRIM: per capita crime rate per town (assumption: if CRIM high, target small) * ZN: proportion of residential land zoned for lots over 25,000 sq. ft (assumption: if ZN high, target big) * INDUS: proportion of non-retail business acres per town (assumption: if INDUS high, target small) * CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) (categorical! assumption: if 1, target high) * NOX: nitrogen oxides concentration (parts per 10 million) (assumption: if NOX high, target small) * RM: average number of rooms per dwelling.(assumption: if RM high, target big) * AGE: proportion of owner-occupied units built prior to 1940. (assumption: if AGE high, target big) * DIS: weighted mean of distances to five Boston employment centres. (assumption: if DIS high, target small) * RAD: index of accessibility to radial highways. (assumption: if RAD high, target big) * TAX: full-value property-tax rate per \$10,000. (assumption: if TAX high, target big) * PTRATIO: pupil-teacher ratio by town. (assumption: if PTRATIO high, target big) * B: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town. (assumption: if B high, target small) * LSTAT: lower status of the population (percent). (assumption: if LSTAT high, target small) * MEDV: median value of owner-occupied homes in \$1000s. (target) ``` df.head() #get number of rows and columns df.shape #get overview of dataset values df.describe() df.info() df.isnull().sum() #check distribution of target variable #looks like normal distribution, no need to do logarithm sns.distplot(df.MEDV, kde=False) #get number of rows in df n = len(df) #calculate proportions for training, validation and testing datasets n_val = int(0.2 * n) n_test = int(0.2 * n) n_train = n - (n_val + n_test) #fix the random seed, so that results are reproducible np.random.seed(2) #create a numpy array with indices from 0 to (n-1) and shuffle it idx = np.arange(n) np.random.shuffle(idx) #use the array with indices 'idx' to get a shuffled dataframe #idx now becomes the index of the df, #and order of rows in df is according to order of rows in idx df_shuffled = df.iloc[idx] #split shuffled df into train, validation and test #e.g. for train: program starts from index 0 #until the index, that is defined by variable (n_train -1) df_train = df_shuffled.iloc[:n_train].copy() df_val = df_shuffled.iloc[n_train:n_train+n_val].copy() df_test = df_shuffled.iloc[n_train+n_val:].copy() #keep df's with target value df_train_incl_target = df_shuffled.iloc[:n_train].copy() df_val_incl_target = df_shuffled.iloc[n_train:n_train+n_val].copy() df_test_incl_target = df_shuffled.iloc[n_train+n_val:].copy() #create target variable arrays y_train = df_train.MEDV.values y_val = df_val.MEDV.values y_test = df_test.MEDV.values #remove target variable form df's del df_train['MEDV'] del df_val['MEDV'] del df_test['MEDV'] #define first numerical features #new training set only contains the selected base columns #training set is transformed to matrix array with 'value' method base = ['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD'] df_num = df_train[base] X_train = df_num.values #return the weights def linear_regression(X, y): ones = np.ones(X.shape[0]) X = np.column_stack([ones, X]) XTX = X.T.dot(X) XTX_inv = np.linalg.inv(XTX) w = XTX_inv.dot(X.T).dot(y) return w[0], w[1:] w_0, w = linear_regression(X_train, y_train) #prediction of target variable, based on training set y_pred = w_0 + X_train.dot(w) #the plot shows difference between distribution of #real target variable and predicted target variable sns.distplot(y_pred, label='pred') sns.distplot(y_train, label='target') plt.legend() #calculation of root mean squared error #based on difference between distribution of #real target variable and predicted target variable def rmse(y, y_pred): error = y_pred - y mse = (error ** 2).mean() return np.sqrt(mse) rmse(y_train, y_pred) ``` Validating the Model ``` #create X_val matrix array df_num = df_val[base] X_val = df_num.values #take the bias and the weights (w_0 and w), what we got from the linear regression #and get the prediction of the target variable for the validation dataset y_pred = w_0 + X_val.dot(w) #compare y_pred with real target values 'y_val' #that number should be used for comparing models rmse(y_val, y_pred) ``` <b>prepare_X</b> function converts dataframe to matrix array ``` #this function takes in feature variables (base), #and returns a matrix array with 'values' method def prepare_X(df): df_num = df[base] X = df_num.values return X #traub the model by calculating the weights X_train = prepare_X(df_train) w_0, w = linear_regression(X_train, y_train) #apply model to validation dataset X_val = prepare_X(df_val) y_pred = w_0 + X_val.dot(w) #compute RMSE on validation dataset print('validation', rmse(y_val, y_pred)) ``` Feature engineering: Add more features to the model<br> We use the validation framework to see whether more features improve the model ``` #use prepare_X function to add more features def prepare_X(df): df = df.copy() base_02 = ['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'] df_num = df[base_02] X = df_num.values return X #check if adding 4 more numerical features can improve the model #X_train should now be a matrix array with totally 12 numerical features #train the model X_train = prepare_X(df_train) w_0, w = linear_regression(X_train, y_train) #apply model to validation dataset X_val = prepare_X(df_val) y_pred = w_0 + X_val.dot(w) #computer RMSE on validation dataset print('validation:', rmse(y_val, y_pred)) #above we can see that the RMSE decreased a bit #plot distribution of real target values (target) #and the predicted target values (pred) #after we considered 12 feature variables sns.distplot(y_pred, label='pred') sns.distplot(y_val, label='target') plt.legend() ``` Feature engineering: Add the CHAS feature to the model <br> Actually it is a categorical variable, but it has only 2 values (0 and 1) <br> So there is no need to do one-hot encoding <br> We use the validation framework to see whether this additional feature improves the model ``` base_02 = ['CRIM', 'ZN', 'INDUS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'] #use prepare_X function to add CHAS as a feature def prepare_X(df): df = df.copy() features = base_02.copy() features.append('CHAS') df_num = df[features] X = df_num.values return X #check if adding 'CHAS' as a feature can improve the model #X_train should now be a matrix array with totally 12 numerical features and 1 categorical feature #train the model X_train = prepare_X(df_train) w_0, w = linear_regression(X_train, y_train) #apply model to validation dataset X_val = prepare_X(df_val) y_pred = w_0 + X_val.dot(w) #computer RMSE on validation dataset print('validation:', rmse(y_val, y_pred)) #above we can see that the RMSE decreased a bit #compared to the plot above, the amount of predicted values for '30' #gets closer to the amount of real values for '30' #plot distribution of real target values (target) #and the predicted target values (pred) #after we considered 12 feature variables sns.distplot(y_pred, label='pred') sns.distplot(y_val, label='target') plt.legend() #we could try regularization in case the data is 'noisy' #regularize with the parameter r def linear_regression_reg(X, y, r=0.01): ones = np.ones(X.shape[0]) X = np.column_stack([ones, X]) XTX = X.T.dot(X) #add r to main diagonal of XTX reg = r * np.eye(XTX.shape[0]) XTX = XTX + reg XTX_inv = np.linalg.inv(XTX) w = XTX_inv.dot(X.T).dot(y) return w[0], w[1:] #the bigger r (alpha), the smaller the weights (the denominator becomes bigger) #on the left 'column', you can see r, that growths with each step #in the other columns, there are written the weights for r in [0, 0.001, 0.01, 0.1, 1, 10]: w_0, w = linear_regression_reg(X_train, y_train, r=r) print('%5s, %.2f, %.2f, %.2f' % (r, w_0, w[3], w[5])) #calculate the RMSE after we used ridge regression X_train = prepare_X(df_train) w_0, w = linear_regression_reg(X_train, y_train, r=0.001) X_val = prepare_X(df_val) y_pred = w_0 + X_val.dot(w) print('validation:', rmse(y_val, y_pred)) #run a grid search to identify the best value of r X_train = prepare_X(df_train) X_val = prepare_X(df_val) for r in [0.000001, 0.0001, 0.001, 0.01, 0.1, 1, 5, 10]: w_0, w = linear_regression_reg(X_train, y_train, r=r) y_pred = w_0 + X_val.dot(w) print('%6s' %r, rmse(y_val, y_pred)) ``` as we can see from the new rmse, the ridge regression has no positive effect Now we can help the user to predict the price of a real estate in Boston ``` df_test_incl_target.head(10) #create a dictionary from rows #delete target value pred_price_list = [] z = 0 while z < 10: ad = df_test_incl_target.iloc[z].to_dict() del ad['MEDV'] #dt_test is a dataframe with one row (contains above dict info) df_test = pd.DataFrame([ad]) X_test = prepare_X(df_test) #train model without ridge regression w_0, w = linear_regression(X_train, y_train) #prediction of the price y_pred = w_0 + X_test.dot(w) pred_price_list.append(y_pred) z = z + 1 pred_price_list real_price = df_test_incl_target.MEDV.tolist() #get average of difference between real price and predicted price y = 0 diff_list = [] while y < 10: diff = real_price[y] - pred_price_list[y] diff_list.append(diff) y += 1 sum(diff_list) / len(diff_list) ``` later on, we can also try other models and see, if the rmse can be further reduced<br> Lastly, I want to check how increased or decreaesed feature variables will influence the target variable ``` ad = df_test_incl_target.iloc[0].to_dict() ad ad_test = {'CRIM': 0.223, 'ZN': 0, 'INDUS': 9.69, 'CHAS': 0, 'NOX': 0.585, 'RM': 6.025, 'AGE': 79.9, 'DIS': 2.4982, 'RAD': 6.0, 'TAX': 391.0, 'PTRATIO': 19.2, 'B': 396.9, 'LSTAT': 14.33} #dt_test is a dataframe with one row (contains above dict info) df_test = pd.DataFrame([ad_test]) X_test = prepare_X(df_test) #train model without ridge regression w_0, w = linear_regression(X_train, y_train) #prediction of the price y_pred = w_0 + X_test.dot(w) y_pred ``` <b>Explanation of Features</b> * CRIM: per capita crime rate per town (assumption: if CRIM high, target small --> correct) * ZN: proportion of residential land zoned for lots over 25,000 sq. ft (assumption: if ZN high, target big --> correct) * INDUS: proportion of non-retail business acres per town (assumption: if INDUS high, target small --> correct) * CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) (categorical! assumption: if 1, target high --> correct) * NOX: nitrogen oxides concentration (parts per 10 million) (assumption: if NOX high, target small --> correct) * RM: average number of rooms per dwelling.(assumption: if RM high, target big --> correct) * AGE: proportion of owner-occupied units built prior to 1940. (assumption: if AGE high, target big --> not clear) * DIS: weighted mean of distances to five Boston employment centres. (assumption: if DIS high, target small --> correct) * RAD: index of accessibility to radial highways. (assumption: if RAD high, target big --> correct) * TAX: full-value property-tax rate per \$10,000. (assumption: if TAX high, target big --> not correct) * PTRATIO: pupil-teacher ratio by town. (assumption: if PTRATIO high, target small--> correct) * B: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town. (assumption: if B high, target small--> not correct) * LSTAT: lower status of the population (percent). (assumption: if LSTAT high, target small --> correct) * MEDV: median value of owner-occupied homes in \$1000s. (target) ``` #check the against test dataset to see if model works X_train = prepare_X(df_train) w_0, w = linear_regression(X_train, y_train) X_val = prepare_X(df_val) y_pred = w_0 + X_val.dot(w) print('validation:', rmse(y_val, y_pred)) X_test = prepare_X(df_test) y_pred = w_0 + X_test.dot(w) print('test:', rmse(y_test, y_pred)) ```
github_jupyter
Let's go through the known systems in [Table 1](https://www.aanda.org/articles/aa/full_html/2018/01/aa30655-17/T1.html) of Jurysek+(2018) ``` # 11 systems listed in their Table 1 systems = ['RW Per', 'IU Aur', 'AH Cep', 'AY Mus', 'SV Gem', 'V669 Cyg', 'V685 Cen', 'V907 Sco', 'SS Lac', 'QX Cas', 'HS Hya'] P_EB = [13.1989, 1.81147, 1.7747, 3.2055, 4.0061, 1.5515, 1.19096, 3.77628, 14.4161, 6.004709, 1.568024] ``` I already know about some... - [HS Hya](https://github.com/jradavenport/HS-Hya) (yes, the final eclipses!) - [IU Aur](IU_Aur.ipynb) (yes, still eclipsing) - [QX Cas](https://github.com/jradavenport/QX-Cas) (yes, but not eclipsing, though new eclipses present...) - V907 Sco (yes, not sure if eclipsing still) 1. Go through each system. Check [MAST](https://mast.stsci.edu/portal/Mashup/Clients/Mast/Portal.html) (has 2-min data), data could be pulled with [lightkurve](https://docs.lightkurve.org/tutorials/), 2. if not check for general coverage with the [Web Viewing Tool](https://heasarc.gsfc.nasa.gov/cgi-bin/tess/webtess/wtv.py) 3. and try to generate a 30-min lightcurve from pixel-level data with [Eleanor](https://adina.feinste.in/eleanor/getting_started/tutorial.html) 4. For every system w/ TESS data, make some basic light curves. Is eclipse still there? Is there rotation? 5. For each, find best paper(s) that characterize the system. Start w/ references in Table 1 ``` from IPython.display import Image import warnings warnings.filterwarnings('ignore') import eleanor import numpy as np from astropy import units as u import matplotlib.pyplot as plt from astropy.coordinates import SkyCoord import matplotlib matplotlib.rcParams.update({'font.size':18}) matplotlib.rcParams.update({'font.family':'serif'}) for k in range(len(systems)): try: star = eleanor.Source(name=systems[k]) print(star.name, star.tic, star.gaia, star.tess_mag) data = eleanor.TargetData(star) q = (data.quality == 0) plt.figure() plt.plot(data.time[q], data.raw_flux[q]/np.nanmedian(data.raw_flux[q]), 'k') # plt.plot(data.time[q], data.corr_flux[q]/np.nanmedian(data.corr_flux[q]) + 0.03, 'r') plt.ylabel('Normalized Flux') plt.xlabel('Time [BJD - 2457000]') plt.title(star.name) plt.show() plt.figure() plt.scatter((data.time[q] % P_EB[k])/P_EB[k], data.raw_flux[q]/np.nanmedian(data.raw_flux[q])) # plt.plot(data.time[q], data.corr_flux[q]/np.nanmedian(data.corr_flux[q]) + 0.03, 'r') plt.ylabel('Normalized Flux') plt.xlabel('Phase (P='+str(P_EB[k])+')') plt.title(star.name) plt.show() except: print('Sorry '+systems[k]) ```
github_jupyter
A common use case requires the forecaster to regularly update with new data and make forecasts on a rolling basis. This is especially useful if the same kind of forecast has to be made at regular time points, e.g., daily or weekly. sktime forecasters support this type of deployment workflow via the update and update_predict methods. The update method can be called when a forecaster is already fitted, to ingest new data and make updated forecasts - this is referred to as an “update step”. After the update, the forecaster’s internal “now” state (the cutoff) is set to the latest time stamp seen in the update batch (assumed to be later than previously seen data). The general pattern is as follows: 1. specify a forecasting strategy 2. specify a relative forecasting horizon 3. fit the forecaster to an initial batch of data using fit 4. make forecasts for the relative forecasting horizon, using predict 5. obtain new data; use update to ingest new data 6. make forecasts using predict for the updated data 7. repeat 5 and 6 as often as required Example: suppose that, in the airline example, we want to make forecasts a year ahead, but every month, starting December 1957. The first few months, forecasts would be made as follows: ``` import pandas as pd from sktime.forecasting.ets import AutoETS from sktime.utils.plotting import plot_series import numpy as np # we prepare the full data set for convenience # note that in the scenario we will "know" only part of this at certain time points df = pd.read_csv("../../data/later/profile_growth.csv") #df.columns followers = df[['Date', 'Followers']] followers['Date'] = pd.PeriodIndex(pd.DatetimeIndex(followers['Date']), freq='D') y = followers.set_index('Date').sort_index() from sktime.forecasting.naive import NaiveForecaster forecaster = NaiveForecaster(strategy="last") # December 1957 # this is the data known in December 1975 y_1957Dec = y[:-36] # step 1: specifying the forecasting strategy #forecaster = AutoETS(auto=True, sp=7, n_jobs=-1) # step 2: specifying the forecasting horizon: one year ahead, all months fh = np.arange(1, 13) # step 3: this is the first time we use the model, so we fit it forecaster.fit(y_1957Dec) # step 4: obtaining the first batch of forecasts for Jan 1958 - Dec 1958 y_pred_1957Dec = forecaster.predict(fh) # plotting predictions and past data plot_series(y_1957Dec, y_pred_1957Dec, labels=["y_1957Dec", "y_pred_1957Dec"]) # January 1958 # new data is observed: y_1958Jan = y[:-36] # step 5: we update the forecaster with the new data forecaster.update(y_1958Jan) # step 6: making forecasts with the updated data y_pred_1958Jan = forecaster.predict(fh) # note that the fh is relative, so forecasts are automatically for 1 month later # i.e., from Feb 1958 to Jan 1959 y_pred_1958Jan # plotting predictions and past data plot_series( y[:-35], y_pred_1957Dec, y_pred_1958Jan, labels=["y_1957Dec", "y_pred_1957Dec", "y_pred_1958Jan"], ) # February 1958 # new data is observed: y_1958Feb = y[:-35] # step 5: we update the forecaster with the new data forecaster.update(y_1958Feb) # step 6: making forecasts with the updated data y_pred_1958Feb = forecaster.predict(fh) # plotting predictions and past data plot_series( y[:-35], y_pred_1957Dec, y_pred_1958Jan, y_pred_1958Feb, labels=["y_1957Dec", "y_pred_1957Dec", "y_pred_1958Jan", "y_pred_1958Feb"], ) ``` … and so on. A shorthand for running first update and then predict is update_predict_single - for some algorithms, this may be more efficient than the separate calls to update and predict: ``` # March 1958 # new data is observed: y_1958Mar = y[:-34] # step 5&6: update/predict in one step forecaster.update_predict_single(y_1958Mar, fh=fh) ``` In the rolling deployment mode, may be useful to move the estimator’s “now” state (the cutoff) to later, for example if no new data was observed, but time has progressed; or, if computations take too long, and forecasts have to be queried. The update interface provides an option for this, via the update_params argument of update and other update funtions. If update_params is set to False, no model update computations are performed; only data is stored, and the internal “now” state (the cutoff) is set to the most recent date. ``` # April 1958 # new data is observed: y_1958Apr = y[:-33] # step 5: perform an update without re-computing the model parameters forecaster.update(y_1958Apr, update_params=False) ``` sktime can also simulate the update/predict deployment mode with a full batch of data. This is not useful in deployment, as it requires all data to be available in advance; however, it is useful in playback, such as for simulations or model evaluation. The update/predict playback mode can be called using update_predict and a re-sampling constructor which encodes the precise walk-forward scheme. To evaluate forecasters with respect to their performance in rolling forecasting, the forecaster needs to be tested in a set-up mimicking rolling forecasting, usually on past data. Note that the batch back-testing as in Section 1.3 would not be an appropriate evaluation set-up for rolling deployment, as that tests only a single forecast batch. The advanced evaluation workflow can be carried out using the evaluate benchmarking function. evalute takes as arguments: - a forecaster to be evaluated - a scikit-learn re-sampling strategy for temporal splitting (cv below), e.g., ExpandingWindowSplitter or SlidingWindowSplitter - a strategy (string): whether the forecaster should be always be refitted or just fitted once and then updated ``` #from sktime.forecasting.arima import AutoARIMA from sktime.forecasting.ets import AutoETS from sktime.forecasting.model_evaluation import evaluate from sktime.forecasting.model_selection import ExpandingWindowSplitter #forecaster = AutoARIMA(sp=12, suppress_warnings=True) forecaster = AutoETS(auto=True, sp=12, n_jobs=-1) #forecaster = NaiveForecaster(strategy="last") cv = ExpandingWindowSplitter( step_length=12, fh=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], initial_window=72 ) df = evaluate(forecaster=forecaster, y=y, cv=cv, strategy="refit", return_data=True) df.iloc[:, :5] # visualization of a forecaster evaluation fig, ax = plot_series( y, df["y_pred"].iloc[0], df["y_pred"].iloc[1], df["y_pred"].iloc[2], df["y_pred"].iloc[3], df["y_pred"].iloc[4], df["y_pred"].iloc[5], markers=["o", "", "", "", "", "", ""], labels=["y_true"] + ["y_pred (Backtest " + str(x) + ")" for x in range(6)], ) ax.legend(); df["y_pred"].iloc[0] df["y_pred"].iloc[1] ```
github_jupyter
# Parameters in QCoDeS A `Parameter` is the basis of measurements and control within QCoDeS. Anything that you want to either measure or control within QCoDeS should satisfy the `Parameter` interface. You may read more about the `Parameter` [here](http://qcodes.github.io/Qcodes/user/intro.html#parameter). ``` import numpy as np from qcodes.instrument.parameter import Parameter, ArrayParameter, MultiParameter, ManualParameter from qcodes.utils import validators ``` QCoDeS provides the following classes of built-in parameters: - `Parameter` represents a single value at a time - Example: voltage - `ParameterWithSetpoints` is intended for array-values parameters. This Parameter class is intended for anything where a call to the instrument returns an array of values. [This notebook](Simple-Example-of-ParameterWithSetpoints.ipynb) gives more detailed examples of how this parameter can be used. - `ArrayParameter` represents an array of values of all the same type that are returned all at once. - Example: voltage vs time waveform - **NOTE:** This is an older base class for array-valued parameters. For any new driver we strongly recommend using `ParameterWithSetpoints` class which is both more flexible and significantly easier to use. Refer to notebook on [writing drivers with ParameterWithSetpoints](Simple-Example-of-ParameterWithSetpoints.ipynb) - `MultiParameter` represents a collection of values with different meaning and possibly different dimension - Example: I and Q, or I vs time and Q vs time Parameters are described in detail in the [Creating Instrument Drivers](../writing_drivers/Creating-Instrument-Drivers.ipynb) tutorial. ## Parameter Most of the time you can use `Parameter` directly; even if you have custom `get`/`set` functions, but sometimes it's useful to subclass `Parameter`. Note that since the superclass `Parameter` actually wraps these functions (to include some extra nice-to-have functionality), your subclass should define `get_raw` and `set_raw` rather than `get` and `set`. ``` class MyCounter(Parameter): def __init__(self, name): # only name is required super().__init__(name, label='Times this has been read', vals=validators.Ints(min_value=0), docstring='counts how many times get has been called ' 'but can be reset to any integer >= 0 by set') self._count = 0 # you must provide a get method, a set method, or both. def get_raw(self): self._count += 1 return self._count def set_raw(self, val): self._count = val c = MyCounter('c') c2 = MyCounter('c2') # c() is equivalent to c.get() print('first call:', c()) print('second call:', c()) # c2(val) is equivalent to c2.set(val) c2(22) ``` ## ArrayParameter **NOTE:** This is an older base class for array-valued parameters. For any new driver we strongly recommend using `ParameterWithSetpoints` class which is both more flexible and significantly easier to use. Refer to notebook on [writing drivers with ParameterWithSetpoints](Simple-Example-of-ParameterWithSetpoints.ipynb). We have kept the documentation shown below of `ArrayParameter` for the legacy purpose. For actions that create a whole array of values at once. When you use it in a `Loop`, it makes a single `DataArray` with the array returned by `get` nested inside extra dimension(s) for the loop. `ArrayParameter` is, for now, only gettable. ``` class ArrayCounter(ArrayParameter): def __init__(self): # only name and shape are required # the setpoints I'm giving here are identical to the defaults # this param would get but I'll give them anyway for # demonstration purposes super().__init__('array_counter', shape=(3, 2), label='Total number of values provided', unit='', # first setpoint array is 1D, second is 2D, etc... setpoints=((0, 1, 2), ((0, 1), (0, 1), (0, 1))), setpoint_names=('index0', 'index1'), setpoint_labels=('Outer param index', 'Inner param index'), docstring='fills a 3x2 array with increasing integers') self._val = 0 def get_raw(self): # here I'm returning a nested list, but any sequence type will do. # tuple, np.array, DataArray... out = [[self._val + 2 * i + j for j in range(2)] for i in range(3)] self._val += 6 return out array_counter = ArrayCounter() # simple get print('first call:', array_counter()) ``` ## MultiParameter Return multiple items at once, where each item can be a single value or an array. NOTE: Most of the kwarg names here are the plural of those used in `Parameter` and `ArrayParameter`. In particular, `MultiParameter` is the ONLY one that uses `units`, all the others use `unit`. `MultiParameter` is, for now, only gettable. ``` class SingleIQPair(MultiParameter): def __init__(self, scale_param): # only name, names, and shapes are required # this version returns two scalars (shape = `()`) super().__init__('single_iq', names=('I', 'Q'), shapes=((), ()), labels=('In phase amplitude', 'Quadrature amplitude'), units=('V', 'V'), # including these setpoints is unnecessary here, but # if you have a parameter that returns a scalar alongside # an array you can represent the scalar as an empty sequence. setpoints=((), ()), docstring='param that returns two single values, I and Q') self._scale_param = scale_param def get_raw(self): scale_val = self._scale_param() return (scale_val, scale_val / 2) scale = ManualParameter('scale', initial_value=2) iq = SingleIQPair(scale_param=scale) # simple get print('simple get:', iq()) class IQArray(MultiParameter): def __init__(self, scale_param): # names, labels, and units are the same super().__init__('iq_array', names=('I', 'Q'), shapes=((5,), (5,)), labels=('In phase amplitude', 'Quadrature amplitude'), units=('V', 'V'), # note that EACH item needs a sequence of setpoint arrays # so a 1D item has its setpoints wrapped in a length-1 tuple setpoints=(((0, 1, 2, 3, 4),), ((0, 1, 2, 3, 4),)), docstring='param that returns two single values, I and Q') self._scale_param = scale_param self._indices = np.array([0, 1, 2, 3, 4]) def get_raw(self): scale_val = self._scale_param() return (self._indices * scale_val, self._indices * scale_val / 2) iq_array = IQArray(scale_param=scale) # simple get print('simple get', iq_array()) ```
github_jupyter
``` import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline ``` # Discussion: Week 2 ``` # Import the NumPy module ``` ## Exercise: Capital Evolution in the Solow Model Suppose that capital per worker $k_t$ evolves according to the following equation: \begin{align} k_{t+1} & = 0.12 \cdot 100 \cdot k_t^{1/3} + 0.9\cdot k_t, \tag{1} \end{align} where the first term on the right-hand side implies that the economy has a 12 percent savings rate, that total factor productivity equals 100, and that there is no growth in technology (or "labor efficiency"). The second term implies that the rate of capital depreciation is 10 percent (i.e., $1-\delta = 0.9 \Rightarrow \delta = 0.1$). Assume that capital per worker in the initial period $k_0$ is given. The *steady state* quantity of capital per worker is the number $k^*$ such that if $k_t = k^*$, $k_{t+1} = k^*$. Find $k^*$ by dropping the time subscripts in equation (1) and solving for $k$. Obtain: \begin{align} k^* & = \left(\frac{0.1}{0.12\cdot 100}\right)^{3/2} = 1{,}314.53414 \tag{2} \end{align} ### Part (a): Simulate 100 Periods ``` # Create a variable called 'k0' that stores the initial quantity of capital in the economy. Set 'k0' to 400 # Create a variable called 'T' equal to the number of periods after 0 to simulate. Set T = 100 # Use the function np.zeros to create a variable called 'capital' equal to an array of zeros of length T+1 # Print the value of 'capital' # Set the first element of 'capital' to the value in k0 # Print the value of 'capital' # Use a for loop to iterate over the additional elemnts of the 'capital' array that need to be computed. # Hint: capital has length T+1. The first value is filled, so you need fill the remaining T values. # Print the value of 'capital' # Print the value of the last element of 'capital' # Plot the simulated capital per worker ``` ### Part (b): Simulate 1,000 Periods ``` # Create a variable called 'T' equal to the number of periods after 0 to simulate. Set T = 1000 # Use the function np.zeros to create a variable called 'capital' equal to an array of zeros of length T+1 # Set the first element of 'capital' to the value in k0 # Use a for loop to iterate over the additional elemnts of the 'capital' array that need to be computed. # Print the value of the last element of 'capital' ``` ### Part (c): Evaluation Provide answers to the follow questions in the next cell. **Question** 1. Why is the final value of capital computed in Part (b) closer to the true steady state than the value computed in Part (a)? **Answer** 1.
github_jupyter
# 基于注意力的神经机器翻译 此笔记本训练一个将卡比尔语翻译为英语的序列到序列(sequence to sequence,简写为 seq2seq)模型。此例子难度较高,需要对序列到序列模型的知识有一定了解。 训练完此笔记本中的模型后,你将能够输入一个卡比尔语句子,例如 *"Times!"*,并返回其英语翻译 *"Fire!"* 对于一个简单的例子来说,翻译质量令人满意。但是更有趣的可能是生成的注意力图:它显示在翻译过程中,输入句子的哪些部分受到了模型的注意。 <img src="https://tensorflow.google.cn/images/spanish-english.png" alt="spanish-english attention plot"> 请注意:运行这个例子用一个 P100 GPU 需要花大约 10 分钟。 ``` import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.ticker as ticker from sklearn.model_selection import train_test_split import unicodedata import re import numpy as np import os import io import time ``` ## 下载和准备数据集 我们将使用 http://www.manythings.org/anki/ 提供的一个语言数据集。这个数据集包含如下格式的语言翻译对: ``` May I borrow this book? ¿Puedo tomar prestado este libro? ``` 这个数据集中有很多种语言可供选择。我们将使用英语 - 卡比尔语数据集。为方便使用,我们在谷歌云上提供了此数据集的一份副本。但是你也可以自己下载副本。下载完数据集后,我们将采取下列步骤准备数据: 1. 给每个句子添加一个 *开始* 和一个 *结束* 标记(token)。 2. 删除特殊字符以清理句子。 3. 创建一个单词索引和一个反向单词索引(即一个从单词映射至 id 的词典和一个从 id 映射至单词的词典)。 4. 将每个句子填充(pad)到最大长度。 ``` ''' # 下载文件 path_to_zip = tf.keras.utils.get_file( 'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip', extract=True) path_to_file = os.path.dirname(path_to_zip)+"/spa-eng/spa.txt" ''' path_to_file = "./lan/kab.txt" # 将 unicode 文件转换为 ascii def unicode_to_ascii(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') def preprocess_sentence(w): w = unicode_to_ascii(w.lower().strip()) # 在单词与跟在其后的标点符号之间插入一个空格 # 例如: "he is a boy." => "he is a boy ." # 参考:https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation w = re.sub(r"([?.!,¿])", r" \1 ", w) w = re.sub(r'[" "]+', " ", w) # 除了 (a-z, A-Z, ".", "?", "!", ","),将所有字符替换为空格 w = re.sub(r"[^a-zA-Z?.!,¿]+", " ", w) w = w.rstrip().strip() # 给句子加上开始和结束标记 # 以便模型知道何时开始和结束预测 w = '<start> ' + w + ' <end>' return w en_sentence = u"May I borrow this book?" sp_sentence = u"¿Puedo tomar prestado este libro?" print(preprocess_sentence(en_sentence)) print(preprocess_sentence(sp_sentence).encode('utf-8')) # 1. 去除重音符号 # 2. 清理句子 # 3. 返回这样格式的单词对:[ENGLISH, SPANISH] def create_dataset(path, num_examples): lines = io.open(path, encoding='UTF-8').read().strip().split('\n') word_pairs = [[preprocess_sentence(w) for w in l.split('\t')] for l in lines[:num_examples]] return zip(*word_pairs) en, sp = create_dataset(path_to_file, None) print(en[-1]) print(sp[-1]) def max_length(tensor): return max(len(t) for t in tensor) def tokenize(lang): lang_tokenizer = tf.keras.preprocessing.text.Tokenizer( filters='') lang_tokenizer.fit_on_texts(lang) tensor = lang_tokenizer.texts_to_sequences(lang) tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor, padding='post') return tensor, lang_tokenizer def load_dataset(path, num_examples=None): # 创建清理过的输入输出对 targ_lang, inp_lang = create_dataset(path, num_examples) input_tensor, inp_lang_tokenizer = tokenize(inp_lang) target_tensor, targ_lang_tokenizer = tokenize(targ_lang) return input_tensor, target_tensor, inp_lang_tokenizer, targ_lang_tokenizer ``` ### 限制数据集的大小以加快实验速度(可选) 在超过 10 万个句子的完整数据集上训练需要很长时间。为了更快地训练,我们可以将数据集的大小限制为 3 万个句子(当然,翻译质量也会随着数据的减少而降低): ``` # 尝试实验不同大小的数据集 num_examples = 30000 input_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples) # 计算目标张量的最大长度 (max_length) max_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor) # 采用 80 - 20 的比例切分训练集和验证集 input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2) # 显示长度 print(len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val)) def convert(lang, tensor): for t in tensor: if t!=0: print ("%d ----> %s" % (t, lang.index_word[t])) print ("Input Language; index to word mapping") convert(inp_lang, input_tensor_train[0]) print () print ("Target Language; index to word mapping") convert(targ_lang, target_tensor_train[0]) ``` ### 创建一个 tf.data 数据集 ``` BUFFER_SIZE = len(input_tensor_train) BATCH_SIZE = 64 steps_per_epoch = len(input_tensor_train)//BATCH_SIZE embedding_dim = 256 units = 1024 vocab_inp_size = len(inp_lang.word_index)+1 vocab_tar_size = len(targ_lang.word_index)+1 dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE) dataset = dataset.batch(BATCH_SIZE, drop_remainder=True) example_input_batch, example_target_batch = next(iter(dataset)) example_input_batch.shape, example_target_batch.shape ``` ## 编写编码器 (encoder) 和解码器 (decoder) 模型 实现一个基于注意力的编码器 - 解码器模型。关于这种模型,你可以阅读 TensorFlow 的 [神经机器翻译 (序列到序列) 教程](https://github.com/tensorflow/nmt)。本示例采用一组更新的 API。此笔记本实现了上述序列到序列教程中的 [注意力方程式](https://github.com/tensorflow/nmt#background-on-the-attention-mechanism)。下图显示了注意力机制为每个输入单词分配一个权重,然后解码器将这个权重用于预测句子中的下一个单词。下图和公式是 [Luong 的论文](https://arxiv.org/abs/1508.04025v5)中注意力机制的一个例子。 <img src="https://tensorflow.google.cn/images/seq2seq/attention_mechanism.jpg" width="500" alt="attention mechanism"> 输入经过编码器模型,编码器模型为我们提供形状为 *(批大小,最大长度,隐藏层大小)* 的编码器输出和形状为 *(批大小,隐藏层大小)* 的编码器隐藏层状态。 下面是所实现的方程式: <img src="https://tensorflow.google.cn/images/seq2seq/attention_equation_0.jpg" alt="attention equation 0" width="800"> <img src="https://tensorflow.google.cn/images/seq2seq/attention_equation_1.jpg" alt="attention equation 1" width="800"> 本教程的编码器采用 [Bahdanau 注意力](https://arxiv.org/pdf/1409.0473.pdf)。在用简化形式编写之前,让我们先决定符号: * FC = 完全连接(密集)层 * EO = 编码器输出 * H = 隐藏层状态 * X = 解码器输入 以及伪代码: * `score = FC(tanh(FC(EO) + FC(H)))` * `attention weights = softmax(score, axis = 1)`。 Softmax 默认被应用于最后一个轴,但是这里我们想将它应用于 *第一个轴*, 因为分数 (score) 的形状是 *(批大小,最大长度,隐藏层大小)*。最大长度 (`max_length`) 是我们的输入的长度。因为我们想为每个输入分配一个权重,所以 softmax 应该用在这个轴上。 * `context vector = sum(attention weights * EO, axis = 1)`。选择第一个轴的原因同上。 * `embedding output` = 解码器输入 X 通过一个嵌入层。 * `merged vector = concat(embedding output, context vector)` * 此合并后的向量随后被传送到 GRU 每个步骤中所有向量的形状已在代码的注释中阐明: ``` class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz): super(Encoder, self).__init__() self.batch_sz = batch_sz self.enc_units = enc_units self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim) self.gru = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') def call(self, x, hidden): x = self.embedding(x) output, state = self.gru(x, initial_state = hidden) return output, state def initialize_hidden_state(self): return tf.zeros((self.batch_sz, self.enc_units)) encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE) # 样本输入 sample_hidden = encoder.initialize_hidden_state() sample_output, sample_hidden = encoder(example_input_batch, sample_hidden) print ('Encoder output shape: (batch size, sequence length, units) {}'.format(sample_output.shape)) print ('Encoder Hidden state shape: (batch size, units) {}'.format(sample_hidden.shape)) class BahdanauAttention(tf.keras.layers.Layer): def __init__(self, units): super(BahdanauAttention, self).__init__() self.W1 = tf.keras.layers.Dense(units) self.W2 = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) def call(self, query, values): # 隐藏层的形状 == (批大小,隐藏层大小) # hidden_with_time_axis 的形状 == (批大小,1,隐藏层大小) # 这样做是为了执行加法以计算分数 hidden_with_time_axis = tf.expand_dims(query, 1) # 分数的形状 == (批大小,最大长度,1) # 我们在最后一个轴上得到 1, 因为我们把分数应用于 self.V # 在应用 self.V 之前,张量的形状是(批大小,最大长度,单位) score = self.V(tf.nn.tanh( self.W1(values) + self.W2(hidden_with_time_axis))) # 注意力权重 (attention_weights) 的形状 == (批大小,最大长度,1) attention_weights = tf.nn.softmax(score, axis=1) # 上下文向量 (context_vector) 求和之后的形状 == (批大小,隐藏层大小) context_vector = attention_weights * values context_vector = tf.reduce_sum(context_vector, axis=1) return context_vector, attention_weights attention_layer = BahdanauAttention(10) attention_result, attention_weights = attention_layer(sample_hidden, sample_output) print("Attention result shape: (batch size, units) {}".format(attention_result.shape)) print("Attention weights shape: (batch_size, sequence_length, 1) {}".format(attention_weights.shape)) class Decoder(tf.keras.Model): def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz): super(Decoder, self).__init__() self.batch_sz = batch_sz self.dec_units = dec_units self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim) self.gru = tf.keras.layers.GRU(self.dec_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') self.fc = tf.keras.layers.Dense(vocab_size) # 用于注意力 self.attention = BahdanauAttention(self.dec_units) def call(self, x, hidden, enc_output): # 编码器输出 (enc_output) 的形状 == (批大小,最大长度,隐藏层大小) context_vector, attention_weights = self.attention(hidden, enc_output) # x 在通过嵌入层后的形状 == (批大小,1,嵌入维度) x = self.embedding(x) # x 在拼接 (concatenation) 后的形状 == (批大小,1,嵌入维度 + 隐藏层大小) x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1) # 将合并后的向量传送到 GRU output, state = self.gru(x) # 输出的形状 == (批大小 * 1,隐藏层大小) output = tf.reshape(output, (-1, output.shape[2])) # 输出的形状 == (批大小,vocab) x = self.fc(output) return x, state, attention_weights decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE) sample_decoder_output, _, _ = decoder(tf.random.uniform((64, 1)), sample_hidden, sample_output) print ('Decoder output shape: (batch_size, vocab size) {}'.format(sample_decoder_output.shape)) ``` ## 定义优化器和损失函数 ``` optimizer = tf.keras.optimizers.Adam() loss_object = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True, reduction='none') def loss_function(real, pred): mask = tf.math.logical_not(tf.math.equal(real, 0)) loss_ = loss_object(real, pred) mask = tf.cast(mask, dtype=loss_.dtype) loss_ *= mask return tf.reduce_mean(loss_) ``` ## 检查点(基于对象保存) ``` checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt") checkpoint = tf.train.Checkpoint(optimizer=optimizer, encoder=encoder, decoder=decoder) ``` ## 训练 1. 将 *输入* 传送至 *编码器*,编码器返回 *编码器输出* 和 *编码器隐藏层状态*。 2. 将编码器输出、编码器隐藏层状态和解码器输入(即 *开始标记*)传送至解码器。 3. 解码器返回 *预测* 和 *解码器隐藏层状态*。 4. 解码器隐藏层状态被传送回模型,预测被用于计算损失。 5. 使用 *教师强制 (teacher forcing)* 决定解码器的下一个输入。 6. *教师强制* 是将 *目标词* 作为 *下一个输入* 传送至解码器的技术。 7. 最后一步是计算梯度,并将其应用于优化器和反向传播。 ``` @tf.function def train_step(inp, targ, enc_hidden): loss = 0 with tf.GradientTape() as tape: enc_output, enc_hidden = encoder(inp, enc_hidden) dec_hidden = enc_hidden dec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1) # 教师强制 - 将目标词作为下一个输入 for t in range(1, targ.shape[1]): # 将编码器输出 (enc_output) 传送至解码器 predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output) loss += loss_function(targ[:, t], predictions) # 使用教师强制 dec_input = tf.expand_dims(targ[:, t], 1) batch_loss = (loss / int(targ.shape[1])) variables = encoder.trainable_variables + decoder.trainable_variables gradients = tape.gradient(loss, variables) optimizer.apply_gradients(zip(gradients, variables)) return batch_loss EPOCHS = 10 for epoch in range(EPOCHS): start = time.time() enc_hidden = encoder.initialize_hidden_state() total_loss = 0 for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)): batch_loss = train_step(inp, targ, enc_hidden) total_loss += batch_loss if batch % 100 == 0: print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1, batch, batch_loss.numpy())) # 每 2 个周期(epoch),保存(检查点)一次模型 if (epoch + 1) % 2 == 0: checkpoint.save(file_prefix = checkpoint_prefix) print('Epoch {} Loss {:.4f}'.format(epoch + 1, total_loss / steps_per_epoch)) print('Time taken for 1 epoch {} sec\n'.format(time.time() - start)) ``` ## 翻译 * 评估函数类似于训练循环,不同之处在于在这里我们不使用 *教师强制*。每个时间步的解码器输入是其先前的预测、隐藏层状态和编码器输出。 * 当模型预测 *结束标记* 时停止预测。 * 存储 *每个时间步的注意力权重*。 请注意:对于一个输入,编码器输出仅计算一次。 ``` def evaluate(sentence): attention_plot = np.zeros((max_length_targ, max_length_inp)) sentence = preprocess_sentence(sentence) inputs = [inp_lang.word_index[i] for i in sentence.split(' ')] inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs], maxlen=max_length_inp, padding='post') inputs = tf.convert_to_tensor(inputs) result = '' hidden = [tf.zeros((1, units))] enc_out, enc_hidden = encoder(inputs, hidden) dec_hidden = enc_hidden dec_input = tf.expand_dims([targ_lang.word_index['<start>']], 0) for t in range(max_length_targ): predictions, dec_hidden, attention_weights = decoder(dec_input, dec_hidden, enc_out) # 存储注意力权重以便后面制图 attention_weights = tf.reshape(attention_weights, (-1, )) attention_plot[t] = attention_weights.numpy() predicted_id = tf.argmax(predictions[0]).numpy() result += targ_lang.index_word[predicted_id] + ' ' if targ_lang.index_word[predicted_id] == '<end>': return result, sentence, attention_plot # 预测的 ID 被输送回模型 dec_input = tf.expand_dims([predicted_id], 0) return result, sentence, attention_plot # 注意力权重制图函数 def plot_attention(attention, sentence, predicted_sentence): fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1) ax.matshow(attention, cmap='viridis') fontdict = {'fontsize': 14} ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90) ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show() def translate(sentence): result, sentence, attention_plot = evaluate(sentence) print('Input: %s' % (sentence)) print('Predicted translation: {}'.format(result)) attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))] plot_attention(attention_plot, sentence.split(' '), result.split(' ')) ``` ## 恢复最新的检查点并验证 ``` # 恢复检查点目录 (checkpoint_dir) 中最新的检查点 checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir)) translate(u'hace mucho frio aqui.') translate(u'esta es mi vida.') translate(u'¿todavia estan en casa?') # 错误的翻译 translate(u'trata de averiguarlo.') ```
github_jupyter
# Scenario Construction Demand and dispatch data are obtained from the Australian Energy Market Operator's (AEMO's) Market Management System Database Model (MMSDM) [1], and a k-means clustering algorithm is implemented using the method outlined in [2] to create a reduced set of representative operating scenarios. The dataset described in [3,4] is used to identify specific generators, and assign historic power injections or withdrawals to individual nodes. In this analysis data for 2017 is considered, with demand and dispatch time series re-sampled to 30min intervals, corresponding to the length of a trading interval within Australia's National Electricity Market (NEM). Using these data a reduced set of 48 operating conditions are constructed. These operating scenarios are comprised on demand, intermittent renewable injections, and fixed power injections from hydro generators. ## Import packages ``` import os import math import pickle import random import zipfile from io import BytesIO import numpy as np import pandas as pd import matplotlib.pyplot as plt # Initialise random number generator random.seed(1) # Used to slice pandas DataFrames idx = pd.IndexSlice ``` ## Paths to files ``` # Contains network information and generator parameters data_dir = os.path.join(os.path.curdir, os.path.pardir, os.path.pardir, 'data') # MMSDM historic demand and dispatch signals archive_dir = r'D:\nemweb\Reports\Data_Archive\MMSDM\zipped' # Location for output files output_dir = os.path.join(os.path.curdir, 'output') ``` ## Import generator and network information ``` # Generator information df_g = pd.read_csv(os.path.join(data_dir, 'generators.csv'), index_col='DUID', dtype={'NODE': int}) # Network node information df_n = pd.read_csv(os.path.join(data_dir, 'network_nodes.csv'), index_col='NODE_ID') ``` ## Extract data Functions used to extract data from MMSDM tables. ``` def dispatch_unit_scada(file): """Extract generator dispatch data Params ------ file : bytes IO object Zipped CSV file of given MMSDM table Returns ------- df : pandas DataFrame MMSDM table in formatted pandas DataFrame """ # Columns to extract cols = ['DUID', 'SCADAVALUE', 'SETTLEMENTDATE'] # Read in data df = pd.read_csv(file, usecols=cols, parse_dates=['SETTLEMENTDATE'], skiprows=1) # Drop rows without DUIDs, apply pivot df = df.dropna(subset=['DUID']).pivot(index='SETTLEMENTDATE', columns='DUID', values='SCADAVALUE') return df def tradingregionsum(file): """Extract half-hourly load data for each NEM region Params ------ file : bytes IO object Zipped CSV file of given MMSDM table Returns ------- df : pandas DataFrame MMSDM table in formatted pandas DataFrame """ # Columns to extract cols = ['REGIONID', 'TOTALDEMAND', 'SETTLEMENTDATE'] # Read in data df = pd.read_csv(file, usecols=cols, parse_dates=['SETTLEMENTDATE'], skiprows=1) # Drop rows without DUIDs, apply pivot df = df.dropna(subset=['REGIONID']).pivot(index='SETTLEMENTDATE', columns='REGIONID', values='TOTALDEMAND') return df def get_data(archive_path, table_name, extractor_function): """Open CSV archive and extract data from zipped file Parameters ---------- archive_path : str Path to MMSDM archive containing data for given year table_name : str Name of table in MMSDM archive from which data is to be extracted extractor_function : func Function that takes a bytes object of the unzipped table and returns a formatted DataFrame Returns ------- df : pandas DataFrame Formatted DataFrame of the desired MMSDM table """ # Open MMSDM archive for a given year with zipfile.ZipFile(archive_path) as myzip: # All files of a particular type in archive (e.g. dispatch, quantity bids, price bands, load) zip_names = [f for f in myzip.filelist if (table_name in f.filename) and ('.zip' in f.filename)] # Check that only one zip file is returned, else raise exception if len(zip_names) != 1: raise Exception('Encounted {0} files in archive, should only encounter 1'.format(len(zip_names))) # Get name of csv in zipped folder csv_name = zip_names[0].filename.replace('.zip', '.CSV').split('/')[-1] # Convert zip files to BytesIO object zip_data = BytesIO(myzip.read(zip_names[0])) # Open inner zipfile and extract data using supplied function with zipfile.ZipFile(zip_data) as z: with z.open(csv_name) as f: df = extractor_function(f) return df # Historic demand and dispatch data demand = [] dispatch = [] for i in range(1, 13): # Archive name and path from which data will be extracted archive_name = 'MMSDM_2017_{0:02}.zip'.format(i) archive_path = os.path.join(archive_dir, archive_name) # Extract data dispatch.append(get_data(archive_path, 'DISPATCH_UNIT_SCADA', dispatch_unit_scada)) demand.append(get_data(archive_path, 'TRADINGREGIONSUM', tradingregionsum)) # Concatenate data from individual months into single DataFrames for load and dispatch df_demand = pd.concat(demand, sort=True) # Demand df_dispatch = pd.concat(dispatch, sort=True) # Dispatch # Fill missing values df_demand = df_demand.fillna(0) # Resample to get average power output over 30min trading interval (instead of 5min) dispatch intervals df_dispatch = df_dispatch.resample('30min', label='right', closed='right').mean() ``` Re-index and format data: 1. identify intermittent generators (wind and solar); 2. identify hydro generators; 3. compute nodal demand; 4. concatenate demand, hydro dispatch, and intermittent renewables dispatch into a single DataFrame. ``` # Intermittent generators mask_intermittent = df_g['FUEL_CAT'].isin(['Wind', 'Solar']) df_g[mask_intermittent] # Intermittent dispatch at each node df_intermittent = (df_dispatch .T .join(df_g.loc[mask_intermittent, 'NODE'], how='left') .groupby('NODE').sum() .reindex(df_n.index, fill_value=0)) df_intermittent['level'] = 'intermittent' # Hydro generators mask_hydro = df_g['FUEL_CAT'].isin(['Hydro']) df_g[mask_hydro] # Hydro dispatch at each node df_hydro = (df_dispatch .T .join(df_g.loc[mask_hydro, 'NODE'], how='left') .groupby('NODE').sum() .reindex(df_n.index, fill_value=0)) df_hydro['level'] = 'hydro' # Demand at each node def node_demand(row): return df_demand[row['NEM_REGION']] * row['PROP_REG_D'] df_node_demand = df_n.apply(node_demand, axis=1) df_node_demand['level'] = 'demand' # Concatenate intermittent, hydro, and demand series, add level to index df_o = (pd.concat([df_node_demand, df_intermittent, df_hydro]) .set_index('level', append=True) .reorder_levels(['level', 'NODE_ID'])) ``` ## K-nearest neighbours Construct clustering algorithm to transform the set of trading intervals into a reduced set of representative operating scenarios. ``` def create_scenarios(df, k=1, max_iterations=100, stopping_tolerance=0): """Create representative demand and fixed power injection operating scenarios Parameters ---------- df : pandas DataFrame Input DataFrame from which representative operating conditions should be constructed k : int Number of clusters max_iterations : int Max number of iterations used to find centroid stopping_tolerance : float Max total difference between successive centroid iteration DataFrames Returns ------- df_clustered : pandas DataFrame Operating scenario centroids and their associated duration. centroid_history : dict Dictionary where keys are the iteration number and values are a DataFrame describing the allocation of operating conditions to centroids, and the distance between these values. """ # Random time periods used to initialise centroids random_periods = random.sample(list(df.columns), k) df_centroids = df[random_periods] # Rename centroid DataFrame columns and keep track of initial labels timestamp_map = {timestamp: timestamp_key + 1 for timestamp_key, timestamp in enumerate(df_centroids.columns)} df_centroids = df_centroids.rename(columns=timestamp_map) def compute_distance(col): """Compute distance between each data associated with each trading interval, col, and all centroids. Return closest centroid. Params ------ col : pandas Series Operating condition for trading interval Returns ------- closest_centroid_ID : pandas Series Series with ID of closest centroid and the distance to that centroid """ # Initialise minimum distance between data constituting a trading interval and all centroids to an # arbitrarily large number min_distance = 9e9 # Initially no centroid is defined as being closest to the given trading interval closest_centroid = None # Compute Euclidean (2-norm) distance between the data describing a trading interval, col, and # all centroids. Identify the closest centroid for the given trading interval. for centroid in df_centroids.columns: distance = math.sqrt(sum((df_centroids[centroid] - col) ** 2)) # If present value less than minimum distance, update minimum distance and record centroid if distance <= min_distance: min_distance = distance closest_centroid = centroid # Return ID of closest centroid closest_centroid_ID = pd.Series(data={'closest_centroid': closest_centroid, 'distance': min_distance}) return closest_centroid_ID def update_centroids(row): "Update centroids by taking element-wise mean value of all vectors in cluster" return df[row['SETTLEMENTDATE']].mean(axis=1) # History of computed centroids centroid_history = dict() for i in range(max_iterations): # Get closest centroids for each trading interval and save result to dictionary df_closest_centroids = df.apply(compute_distance) centroid_history[i] = df_closest_centroids # Timestamps belonging to each cluster clustered_timestamps = (df_closest_centroids.loc['closest_centroid'] .to_frame() .reset_index() .groupby('closest_centroid').agg(lambda x: list(x))) # Update centroids by computing average nodal values across series in each cluster df_centroids = clustered_timestamps.apply(update_centroids, axis=1).T # If first iteration, set total absolute distance to arbitrarily large number if i == 0: total_absolute_distance = 1e7 # Lagged DataFrame in next iteration = DataFrame in current iteration df_centroids_lag = df_centroids else: # Element-wise absolute difference between current and previous centroid DataFrames df_centroids_update_distance = abs(df_centroids - df_centroids_lag) # Max total element-wise distance total_absolute_distance = df_centroids_update_distance.sum().sum() # Stopping condition if total_absolute_distance <= stopping_tolerance: print('Iteration number: {0} - Total absolute distance: {1}. Stopping criterion satisfied. Exiting loop.'.format(i+1, total_absolute_distance)) break else: # Continue loop df_centroids_lag = df_centroids print('Iteration number: {0} - Difference between iterations: {1}'.format(i+1, total_absolute_distance)) # Raise warning if loop terminates before stopping condition met if i == (max_iterations - 1): print('Max iteration limit exceeded before stopping tolerance satisfied.') # Get duration for each scenario # ------------------------------ # Length of each trading interval (hours) interval_length = 0.5 # Total number of hours for each scenario scenario_hours = (clustered_timestamps.apply(lambda x: len(x['SETTLEMENTDATE']), axis=1) .to_frame().T .mul(interval_length)) # Renaming and setting duration index values scenario_hours = scenario_hours.rename(index={0: 'hours'}) scenario_hours['level'] = 'duration' scenario_hours.set_index('level', append=True, inplace=True) # Final DataFrame with clustered values df_clustered = pd.concat([df_centroids, scenario_hours]) # Convert column labels to type int df_clustered.columns = df_clustered.columns.astype(int) return df_clustered, centroid_history ``` ## Create operating scenarios Create operating scenarios for different numbers of clusters and save to file. ``` # Create operating scenarios for different numbers of clusters for k in [48, 100]: # Create operating scenarios df_clustered, _ = create_scenarios(df=df_o, k=k, max_iterations=int(9e9), stopping_tolerance=0) # Save scenarios with open(os.path.join(output_dir, '{0}_scenarios.pickle'.format(k)), 'wb') as f: pickle.dump(df_clustered, f) ``` ## References [1] - Australian Energy Markets Operator. Data Archive (2018). at [http://www.nemweb.com.au/#mms-data-model:download](http://www.nemweb.com.au/#mms-data-model:download) [2] - Baringo L., Conejo, A. J., Correlated wind-power production and electric load scenarios for investment decisions. Applied Energy (2013). [3] - Xenophon A. K., Hill D. J., Geospatial modelling of Australia's National Electricity Market allowing backtesting against historic data. Scientific Data (2018). [4] - Xenophon A. K., Hill D. J., Geospatial Modelling of Australia's National Electricity Market - Dataset (Version v1.3) [Data set]. Zenodo. [http://doi.org/10.5281/zenodo.1326942](http://doi.org/10.5281/zenodo.1326942)
github_jupyter
<div align="center"> <h1><img width="30" src="https://madewithml.com/static/images/rounded_logo.png">&nbsp;<a href="https://madewithml.com/">Made With ML</a></h1> Applied ML · MLOps · Production <br> Join 30K+ developers in learning how to responsibly <a href="https://madewithml.com/about/">deliver value</a> with ML. <br> </div> <br> <div align="center"> <a target="_blank" href="https://newsletter.madewithml.com"><img src="https://img.shields.io/badge/Subscribe-30K-brightgreen"></a>&nbsp; <a target="_blank" href="https://github.com/GokuMohandas/MadeWithML"><img src="https://img.shields.io/github/stars/GokuMohandas/MadeWithML.svg?style=social&label=Star"></a>&nbsp; <a target="_blank" href="https://www.linkedin.com/in/goku"><img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social"></a>&nbsp; <a target="_blank" href="https://twitter.com/GokuMohandas"><img src="https://img.shields.io/twitter/follow/GokuMohandas.svg?label=Follow&style=social"></a> <br> 🔥&nbsp; Among the <a href="https://github.com/topics/deep-learning" target="_blank">top ML</a> repositories on GitHub </div> <br> <hr> # Transformers In this lesson we will learn how to implement the Transformer architecture to extract contextual embeddings for our text classification task. <div align="left"> <a target="_blank" href="https://madewithml.com/courses/foundations/transformers/"><img src="https://img.shields.io/badge/📖 Read-blog post-9cf"></a>&nbsp; <a href="https://github.com/GokuMohandas/MadeWithML/blob/main/notebooks/15_Transformers.ipynb" role="button"><img src="https://img.shields.io/static/v1?label=&amp;message=View%20On%20GitHub&amp;color=586069&amp;logo=github&amp;labelColor=2f363d"></a>&nbsp; <a href="https://colab.research.google.com/github/GokuMohandas/MadeWithML/blob/main/notebooks/15_Transformers.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> </div> # Overview Transformers are a very popular architecture that leverage and extend the concept of self-attention to create very useful representations of our input data for a downstream task. - **advantages**: - better representation for our input tokens via contextual embeddings where the token representation is based on the specific neighboring tokens using self-attention. - sub-word tokens, as opposed to character tokens, since they can hold more meaningful representation for many of our keywords, prefixes, suffixes, etc. - attend (in parallel) to all the tokens in our input, as opposed to being limited by filter spans (CNNs) or memory issues from sequential processing (RNNs). - **disadvantages**: - computationally intensive - required large amounts of data (mitigated using pretrained models) <div align="left"> <img src="https://madewithml.com/static/images/foundations/transformers/architecture.png" width="800"> </div> <div align="left"> <small><a href="https://arxiv.org/abs/1706.03762" target="_blank">Attention Is All You Need</a></small> </div> # Set up ``` !pip install transformers==3.0.2 -q import numpy as np import pandas as pd import random import torch import torch.nn as nn SEED = 1234 def set_seeds(seed=1234): """Set seeds for reproducibility.""" np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # multi-GPU# Set seeds for reproducibility set_seeds(seed=SEED) # Set seeds for reproducibility set_seeds(seed=SEED) # Set device cuda = True device = torch.device("cuda" if ( torch.cuda.is_available() and cuda) else "cpu") torch.set_default_tensor_type("torch.FloatTensor") if device.type == "cuda": torch.set_default_tensor_type("torch.cuda.FloatTensor") print (device) ``` ## Load data We will download the [AG News dataset](http://www.di.unipi.it/~gulli/AG_corpus_of_news_articles.html), which consists of 120K text samples from 4 unique classes (`Business`, `Sci/Tech`, `Sports`, `World`) ``` import numpy as np import pandas as pd import re import urllib # Load data url = "https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/datasets/news.csv" df = pd.read_csv(url, header=0) # load df = df.sample(frac=1).reset_index(drop=True) # shuffle df.head() # Reduce data size (too large to fit in Colab's limited memory) df = df[:10000] print (len(df)) ``` ## Preprocessing We're going to clean up our input data first by doing operations such as lower text, removing stop (filler) words, filters using regular expressions, etc. ``` import nltk from nltk.corpus import stopwords from nltk.stem import PorterStemmer import re nltk.download("stopwords") STOPWORDS = stopwords.words("english") print (STOPWORDS[:5]) porter = PorterStemmer() def preprocess(text, stopwords=STOPWORDS): """Conditional preprocessing on our text unique to our task.""" # Lower text = text.lower() # Remove stopwords pattern = re.compile(r'\b(' + r'|'.join(stopwords) + r')\b\s*') text = pattern.sub('', text) # Remove words in paranthesis text = re.sub(r'\([^)]*\)', '', text) # Spacing and filters text = re.sub(r"([-;;.,!?<=>])", r" \1 ", text) text = re.sub('[^A-Za-z0-9]+', ' ', text) # remove non alphanumeric chars text = re.sub(' +', ' ', text) # remove multiple spaces text = text.strip() return text # Sample text = "Great week for the NYSE!" preprocess(text=text) # Apply to dataframe preprocessed_df = df.copy() preprocessed_df.title = preprocessed_df.title.apply(preprocess) print (f"{df.title.values[0]}\n\n{preprocessed_df.title.values[0]}") ``` ## Split data ``` import collections from sklearn.model_selection import train_test_split TRAIN_SIZE = 0.7 VAL_SIZE = 0.15 TEST_SIZE = 0.15 def train_val_test_split(X, y, train_size): """Split dataset into data splits.""" X_train, X_, y_train, y_ = train_test_split(X, y, train_size=TRAIN_SIZE, stratify=y) X_val, X_test, y_val, y_test = train_test_split(X_, y_, train_size=0.5, stratify=y_) return X_train, X_val, X_test, y_train, y_val, y_test # Data X = preprocessed_df["title"].values y = preprocessed_df["category"].values # Create data splits X_train, X_val, X_test, y_train, y_val, y_test = train_val_test_split( X=X, y=y, train_size=TRAIN_SIZE) print (f"X_train: {X_train.shape}, y_train: {y_train.shape}") print (f"X_val: {X_val.shape}, y_val: {y_val.shape}") print (f"X_test: {X_test.shape}, y_test: {y_test.shape}") print (f"Sample point: {X_train[0]} → {y_train[0]}") ``` ## Label encoder ``` class LabelEncoder(object): """Label encoder for tag labels.""" def __init__(self, class_to_index={}): self.class_to_index = class_to_index self.index_to_class = {v: k for k, v in self.class_to_index.items()} self.classes = list(self.class_to_index.keys()) def __len__(self): return len(self.class_to_index) def __str__(self): return f"<LabelEncoder(num_classes={len(self)})>" def fit(self, y): classes = np.unique(y) for i, class_ in enumerate(classes): self.class_to_index[class_] = i self.index_to_class = {v: k for k, v in self.class_to_index.items()} self.classes = list(self.class_to_index.keys()) return self def encode(self, y): y_one_hot = np.zeros((len(y), len(self.class_to_index)), dtype=int) for i, item in enumerate(y): y_one_hot[i][self.class_to_index[item]] = 1 return y_one_hot def decode(self, y): classes = [] for i, item in enumerate(y): index = np.where(item == 1)[0][0] classes.append(self.index_to_class[index]) return classes def save(self, fp): with open(fp, "w") as fp: contents = {'class_to_index': self.class_to_index} json.dump(contents, fp, indent=4, sort_keys=False) @classmethod def load(cls, fp): with open(fp, "r") as fp: kwargs = json.load(fp=fp) return cls(**kwargs) # Encode label_encoder = LabelEncoder() label_encoder.fit(y_train) num_classes = len(label_encoder) label_encoder.class_to_index # Class weights counts = np.bincount([label_encoder.class_to_index[class_] for class_ in y_train]) class_weights = {i: 1.0/count for i, count in enumerate(counts)} print (f"counts: {counts}\nweights: {class_weights}") # Convert labels to tokens print (f"y_train[0]: {y_train[0]}") y_train = label_encoder.encode(y_train) y_val = label_encoder.encode(y_val) y_test = label_encoder.encode(y_test) print (f"y_train[0]: {y_train[0]}") print (f"decode([y_train[0]]): {label_encoder.decode([y_train[0]])}") ``` ## Tokenizer We'll be using the [BertTokenizer](https://huggingface.co/transformers/model_doc/bert.html#berttokenizer) to tokenize our input text in to sub-word tokens. ``` from transformers import DistilBertTokenizer from transformers import BertTokenizer # Load tokenizer and model # tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") tokenizer = BertTokenizer.from_pretrained("allenai/scibert_scivocab_uncased") vocab_size = len(tokenizer) print (vocab_size) # Tokenize inputs encoded_input = tokenizer(X_train.tolist(), return_tensors="pt", padding=True) X_train_ids = encoded_input["input_ids"] X_train_masks = encoded_input["attention_mask"] print (X_train_ids.shape, X_train_masks.shape) encoded_input = tokenizer(X_val.tolist(), return_tensors="pt", padding=True) X_val_ids = encoded_input["input_ids"] X_val_masks = encoded_input["attention_mask"] print (X_val_ids.shape, X_val_masks.shape) encoded_input = tokenizer(X_test.tolist(), return_tensors="pt", padding=True) X_test_ids = encoded_input["input_ids"] X_test_masks = encoded_input["attention_mask"] print (X_test_ids.shape, X_test_masks.shape) # Decode print (f"{X_train_ids[0]}\n{tokenizer.decode(X_train_ids[0])}") # Sub-word tokens print (tokenizer.convert_ids_to_tokens(ids=X_train_ids[0])) ``` ## Datasets We're going to create Datasets and DataLoaders to be able to efficiently create batches with our data splits. ``` class TransformerTextDataset(torch.utils.data.Dataset): def __init__(self, ids, masks, targets): self.ids = ids self.masks = masks self.targets = targets def __len__(self): return len(self.targets) def __str__(self): return f"<Dataset(N={len(self)})>" def __getitem__(self, index): ids = torch.tensor(self.ids[index], dtype=torch.long) masks = torch.tensor(self.masks[index], dtype=torch.long) targets = torch.FloatTensor(self.targets[index]) return ids, masks, targets def create_dataloader(self, batch_size, shuffle=False, drop_last=False): return torch.utils.data.DataLoader( dataset=self, batch_size=batch_size, shuffle=shuffle, drop_last=drop_last, pin_memory=False) # Create datasets train_dataset = TransformerTextDataset(ids=X_train_ids, masks=X_train_masks, targets=y_train) val_dataset = TransformerTextDataset(ids=X_val_ids, masks=X_val_masks, targets=y_val) test_dataset = TransformerTextDataset(ids=X_test_ids, masks=X_test_masks, targets=y_test) print ("Data splits:\n" f" Train dataset:{train_dataset.__str__()}\n" f" Val dataset: {val_dataset.__str__()}\n" f" Test dataset: {test_dataset.__str__()}\n" "Sample point:\n" f" ids: {train_dataset[0][0]}\n" f" masks: {train_dataset[0][1]}\n" f" targets: {train_dataset[0][2]}") # Create dataloaders batch_size = 128 train_dataloader = train_dataset.create_dataloader( batch_size=batch_size) val_dataloader = val_dataset.create_dataloader( batch_size=batch_size) test_dataloader = test_dataset.create_dataloader( batch_size=batch_size) batch = next(iter(train_dataloader)) print ("Sample batch:\n" f" ids: {batch[0].size()}\n" f" masks: {batch[1].size()}\n" f" targets: {batch[2].size()}") ``` ## Trainer Let's create the `Trainer` class that we'll use to facilitate training for our experiments. ``` import torch.nn.functional as F class Trainer(object): def __init__(self, model, device, loss_fn=None, optimizer=None, scheduler=None): # Set params self.model = model self.device = device self.loss_fn = loss_fn self.optimizer = optimizer self.scheduler = scheduler def train_step(self, dataloader): """Train step.""" # Set model to train mode self.model.train() loss = 0.0 # Iterate over train batches for i, batch in enumerate(dataloader): # Step batch = [item.to(self.device) for item in batch] # Set device inputs, targets = batch[:-1], batch[-1] self.optimizer.zero_grad() # Reset gradients z = self.model(inputs) # Forward pass J = self.loss_fn(z, targets) # Define loss J.backward() # Backward pass self.optimizer.step() # Update weights # Cumulative Metrics loss += (J.detach().item() - loss) / (i + 1) return loss def eval_step(self, dataloader): """Validation or test step.""" # Set model to eval mode self.model.eval() loss = 0.0 y_trues, y_probs = [], [] # Iterate over val batches with torch.inference_mode(): for i, batch in enumerate(dataloader): # Step batch = [item.to(self.device) for item in batch] # Set device inputs, y_true = batch[:-1], batch[-1] z = self.model(inputs) # Forward pass J = self.loss_fn(z, y_true).item() # Cumulative Metrics loss += (J - loss) / (i + 1) # Store outputs y_prob = F.softmax(z).cpu().numpy() y_probs.extend(y_prob) y_trues.extend(y_true.cpu().numpy()) return loss, np.vstack(y_trues), np.vstack(y_probs) def predict_step(self, dataloader): """Prediction step.""" # Set model to eval mode self.model.eval() y_probs = [] # Iterate over val batches with torch.inference_mode(): for i, batch in enumerate(dataloader): # Forward pass w/ inputs inputs, targets = batch[:-1], batch[-1] z = self.model(inputs) # Store outputs y_prob = F.softmax(z).cpu().numpy() y_probs.extend(y_prob) return np.vstack(y_probs) def train(self, num_epochs, patience, train_dataloader, val_dataloader): best_val_loss = np.inf for epoch in range(num_epochs): # Steps train_loss = self.train_step(dataloader=train_dataloader) val_loss, _, _ = self.eval_step(dataloader=val_dataloader) self.scheduler.step(val_loss) # Early stopping if val_loss < best_val_loss: best_val_loss = val_loss best_model = self.model _patience = patience # reset _patience else: _patience -= 1 if not _patience: # 0 print("Stopping early!") break # Logging print( f"Epoch: {epoch+1} | " f"train_loss: {train_loss:.5f}, " f"val_loss: {val_loss:.5f}, " f"lr: {self.optimizer.param_groups[0]['lr']:.2E}, " f"_patience: {_patience}" ) return best_model ``` # Transformer ## Scaled dot-product attention The most popular type of self-attention is scaled dot-product attention from the widely-cited [Attention is all you need](https://arxiv.org/abs/1706.03762) paper. This type of attention involves projecting our encoded input sequences onto three matrices, queries (Q), keys (K) and values (V), whose weights we learn. $ inputs \in \mathbb{R}^{NXMXH} $ ($N$ = batch size, $M$ = sequence length, $H$ = hidden dim) $ Q = XW_q $ where $ W_q \in \mathbb{R}^{HXd_q} $ $ K = XW_k $ where $ W_k \in \mathbb{R}^{HXd_k} $ $ V = XW_v $ where $ W_v \in \mathbb{R}^{HXd_v} $ $ attention (Q, K, V) = softmax( \frac{Q K^{T}}{\sqrt{d_k}} )V \in \mathbb{R}^{MXd_v} $ ## Multi-head attention Instead of applying self-attention only once across the entire encoded input, we can also separate the input and apply self-attention in parallel (heads) to each input section and concatenate them. This allows the different head to learn unique representations while maintaining the complexity since we split the input into smaller subspaces. $ MultiHead(Q, K, V) = concat({head}_1, ..., {head}_{h})W_O $ * ${head}_i = attention(Q_i, K_i, V_i) $ * $h$ = # of self-attention heads * $W_O \in \mathbb{R}^{hd_vXH} $ * $H$ = hidden dim. (or dimension of the model $d_{model}$) ## Positional encoding With self-attention, we aren't able to account for the sequential position of our input tokens. To address this, we can use positional encoding to create a representation of the location of each token with respect to the entire sequence. This can either be learned (with weights) or we can use a fixed function that can better extend to create positional encoding for lengths during inference that were not observed during training. $ PE_{(pos,2i)} = sin({pos}/{10000^{2i/H}}) $ $ PE_{(pos,2i+1)} = cos({pos}/{10000^{2i/H}}) $ where: * $pos$ = position of the token $(1...M)$ * $i$ = hidden dim $(1..H)$ This effectively allows us to represent each token's relative position using a fixed function for very large sequences. And because we've constrained the positional encodings to have the same dimensions as our encoded inputs, we can simply concatenate them before feeding them into the multi-head attention heads. ## Architecture And here's how it all fits together! It's an end-to-end architecture that creates these contextual representations and uses an encoder-decoder architecture to predict the outcomes (one-to-one, many-to-one, many-to-many, etc.) Due to the complexity of the architecture, they require massive amounts of data for training without overfitting, however, they can be leveraged as pretrained models to finetune with smaller datasets that are similar to the larger set it was initially trained on. <div align="left"> <img src="https://madewithml.com/static/images/foundations/transformers/architecture.png" width="800"> </div> <div align="left"> <small><a href="https://arxiv.org/abs/1706.03762" target="_blank">Attention Is All You Need</a></small> </div> > We're not going to the implement the Transformer [from scratch](https://nlp.seas.harvard.edu/2018/04/03/attention.html) but we will use the[ Hugging Face library](https://github.com/huggingface/transformers) to load a pretrained [BertModel](https://huggingface.co/transformers/model_doc/bert.html#bertmodel) , which we'll use as a feature extractor and fine-tune on our own dataset. ## Model We're going to use a pretrained [BertModel](https://huggingface.co/transformers/model_doc/bert.html#bertmodel) to act as a feature extractor. We'll only use the encoder to receive sequential and pooled outputs (`is_decoder=False` is default). ``` from transformers import BertModel # transformer = BertModel.from_pretrained("distilbert-base-uncased") # embedding_dim = transformer.config.dim transformer = BertModel.from_pretrained("allenai/scibert_scivocab_uncased") embedding_dim = transformer.config.hidden_size class Transformer(nn.Module): def __init__(self, transformer, dropout_p, embedding_dim, num_classes): super(Transformer, self).__init__() self.transformer = transformer self.dropout = torch.nn.Dropout(dropout_p) self.fc1 = torch.nn.Linear(embedding_dim, num_classes) def forward(self, inputs): ids, masks = inputs seq, pool = self.transformer(input_ids=ids, attention_mask=masks) z = self.dropout(pool) z = self.fc1(z) return z ``` > We decided to work with the pooled output, but we could have just as easily worked with the sequential output (encoder representation for each sub-token) and applied a CNN (or other decoder options) on top of it. ``` # Initialize model dropout_p = 0.5 model = Transformer( transformer=transformer, dropout_p=dropout_p, embedding_dim=embedding_dim, num_classes=num_classes) model = model.to(device) print (model.named_parameters) ``` ## Training ``` # Arguments lr = 1e-4 num_epochs = 100 patience = 10 # Define loss class_weights_tensor = torch.Tensor(np.array(list(class_weights.values()))) loss_fn = nn.BCEWithLogitsLoss(weight=class_weights_tensor) # Define optimizer & scheduler optimizer = torch.optim.Adam(model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, mode="min", factor=0.1, patience=5) # Trainer module trainer = Trainer( model=model, device=device, loss_fn=loss_fn, optimizer=optimizer, scheduler=scheduler) # Train best_model = trainer.train(num_epochs, patience, train_dataloader, val_dataloader) ``` ## Evaluation ``` import json from sklearn.metrics import precision_recall_fscore_support def get_performance(y_true, y_pred, classes): """Per-class performance metrics.""" # Performance performance = {"overall": {}, "class": {}} # Overall performance metrics = precision_recall_fscore_support(y_true, y_pred, average="weighted") performance["overall"]["precision"] = metrics[0] performance["overall"]["recall"] = metrics[1] performance["overall"]["f1"] = metrics[2] performance["overall"]["num_samples"] = np.float64(len(y_true)) # Per-class performance metrics = precision_recall_fscore_support(y_true, y_pred, average=None) for i in range(len(classes)): performance["class"][classes[i]] = { "precision": metrics[0][i], "recall": metrics[1][i], "f1": metrics[2][i], "num_samples": np.float64(metrics[3][i]), } return performance # Get predictions test_loss, y_true, y_prob = trainer.eval_step(dataloader=test_dataloader) y_pred = np.argmax(y_prob, axis=1) # Determine performance performance = get_performance( y_true=np.argmax(y_true, axis=1), y_pred=y_pred, classes=label_encoder.classes) print (json.dumps(performance["overall"], indent=2)) # Save artifacts from pathlib import Path dir = Path("transformers") dir.mkdir(parents=True, exist_ok=True) label_encoder.save(fp=Path(dir, "label_encoder.json")) torch.save(best_model.state_dict(), Path(dir, "model.pt")) with open(Path(dir, "performance.json"), "w") as fp: json.dump(performance, indent=2, sort_keys=False, fp=fp) ``` ## Inference ``` def get_probability_distribution(y_prob, classes): """Create a dict of class probabilities from an array.""" results = {} for i, class_ in enumerate(classes): results[class_] = np.float64(y_prob[i]) sorted_results = {k: v for k, v in sorted( results.items(), key=lambda item: item[1], reverse=True)} return sorted_results # Load artifacts device = torch.device("cpu") tokenizer = BertTokenizer.from_pretrained("allenai/scibert_scivocab_uncased") label_encoder = LabelEncoder.load(fp=Path(dir, "label_encoder.json")) transformer = BertModel.from_pretrained("allenai/scibert_scivocab_uncased") embedding_dim = transformer.config.hidden_size model = Transformer( transformer=transformer, dropout_p=dropout_p, embedding_dim=embedding_dim, num_classes=num_classes) model.load_state_dict(torch.load(Path(dir, "model.pt"), map_location=device)) model.to(device); # Initialize trainer trainer = Trainer(model=model, device=device) # Create datasets train_dataset = TransformerTextDataset(ids=X_train_ids, masks=X_train_masks, targets=y_train) val_dataset = TransformerTextDataset(ids=X_val_ids, masks=X_val_masks, targets=y_val) test_dataset = TransformerTextDataset(ids=X_test_ids, masks=X_test_masks, targets=y_test) print ("Data splits:\n" f" Train dataset:{train_dataset.__str__()}\n" f" Val dataset: {val_dataset.__str__()}\n" f" Test dataset: {test_dataset.__str__()}\n" "Sample point:\n" f" ids: {train_dataset[0][0]}\n" f" masks: {train_dataset[0][1]}\n" f" targets: {train_dataset[0][2]}") # Dataloader text = "The final tennis tournament starts next week." X = preprocess(text) encoded_input = tokenizer(X, return_tensors="pt", padding=True).to(torch.device("cpu")) ids = encoded_input["input_ids"] masks = encoded_input["attention_mask"] y_filler = label_encoder.encode([label_encoder.classes[0]]*len(ids)) dataset = TransformerTextDataset(ids=ids, masks=masks, targets=y_filler) dataloader = dataset.create_dataloader(batch_size=int(batch_size)) # Inference y_prob = trainer.predict_step(dataloader) y_pred = np.argmax(y_prob, axis=1) label_encoder.index_to_class[y_pred[0]] # Class distributions prob_dist = get_probability_distribution(y_prob=y_prob[0], classes=label_encoder.classes) print (json.dumps(prob_dist, indent=2)) ``` ## Interpretability Let's visualize the self-attention weights from each of the attention heads in the encoder. ``` import sys !rm -r bertviz_repo !test -d bertviz_repo || git clone https://github.com/jessevig/bertviz bertviz_repo if not "bertviz_repo" in sys.path: sys.path += ["bertviz_repo"] from bertviz import head_view # Print input ids print (ids) print (tokenizer.batch_decode(ids)) # Get encoder attentions seq, pool, attn = model.transformer(input_ids=ids, attention_mask=masks, output_attentions=True) print (len(attn)) # 12 attention layers (heads) print (attn[0].shape) # HTML set up def call_html(): import IPython display(IPython.core.display.HTML(''' <script src="/static/components/requirejs/require.js"></script> <script> requirejs.config({ paths: { base: '/static/base', "d3": "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.8/d3.min", jquery: '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min', }, }); </script> ''')) # Visualize self-attention weights call_html() tokens = tokenizer.convert_ids_to_tokens(ids[0]) head_view(attention=attn, tokens=tokens) ``` > Now you're ready to start the [MLOps lessons](https://madewithml.com/#mlops) to learn how to apply all this foundational modeling knowledge to responsibly deliver value.
github_jupyter
# Creating a Sentiment Analysis Web App ## Using PyTorch and SageMaker _Deep Learning Nanodegree Program | Deployment_ --- Now that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to enter a movie review. The web page will then send the review off to our deployed model which will predict the sentiment of the entered review. ## Instructions Some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this notebook. You will not need to modify the included code beyond what is requested. Sections that begin with '**TODO**' in the header indicate that you need to complete or implement some portion within them. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `# TODO: ...` comment. Please be sure to read the instructions carefully! In addition to implementing code, there will be questions for you to answer which relate to the task and your implementation. Each section where you will answer a question is preceded by a '**Question:**' header. Carefully read each question and provide your answer below the '**Answer:**' header by editing the Markdown cell. > **Note**: Code and Markdown cells can be executed using the **Shift+Enter** keyboard shortcut. In addition, a cell can be edited by typically clicking it (double-click for Markdown cells) or by pressing **Enter** while it is highlighted. ## General Outline Recall the general outline for SageMaker projects using a notebook instance. 1. Download or otherwise retrieve the data. 2. Process / Prepare the data. 3. Upload the processed data to S3. 4. Train a chosen model. 5. Test the trained model (typically using a batch transform job). 6. Deploy the trained model. 7. Use the deployed model. For this project, you will be following the steps in the general outline with some modifications. First, you will not be testing the model in its own step. You will still be testing the model, however, you will do it by deploying your model and then using the deployed model by sending the test data to it. One of the reasons for doing this is so that you can make sure that your deployed model is working correctly before moving forward. In addition, you will deploy and use your trained model a second time. In the second iteration you will customize the way that your trained model is deployed by including some of your own code. In addition, your newly deployed model will be used in the sentiment analysis web app. ## Step 1: Downloading the data As in the XGBoost in SageMaker notebook, we will be using the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/) > Maas, Andrew L., et al. [Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/data/sentiment/). In _Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies_. Association for Computational Linguistics, 2011. ``` %mkdir ../data !wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz !tar -zxf ../data/aclImdb_v1.tar.gz -C ../data ``` ## Step 2: Preparing and Processing the data Also, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a training set and a testing set. ``` import os import glob def read_imdb_data(data_dir='../data/aclImdb'): data = {} labels = {} for data_type in ['train', 'test']: data[data_type] = {} labels[data_type] = {} for sentiment in ['pos', 'neg']: data[data_type][sentiment] = [] labels[data_type][sentiment] = [] path = os.path.join(data_dir, data_type, sentiment, '*.txt') files = glob.glob(path) for f in files: with open(f) as review: data[data_type][sentiment].append(review.read()) # Here we represent a positive review by '1' and a negative review by '0' labels[data_type][sentiment].append(1 if sentiment == 'pos' else 0) assert len(data[data_type][sentiment]) == len(labels[data_type][sentiment]), \ "{}/{} data size does not match labels size".format(data_type, sentiment) return data, labels data, labels = read_imdb_data() print("IMDB reviews: train = {} pos / {} neg, test = {} pos / {} neg".format( len(data['train']['pos']), len(data['train']['neg']), len(data['test']['pos']), len(data['test']['neg']))) ``` Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records. ``` from sklearn.utils import shuffle def prepare_imdb_data(data, labels): """Prepare training and test sets from IMDb movie reviews.""" #Combine positive and negative reviews and labels data_train = data['train']['pos'] + data['train']['neg'] data_test = data['test']['pos'] + data['test']['neg'] labels_train = labels['train']['pos'] + labels['train']['neg'] labels_test = labels['test']['pos'] + labels['test']['neg'] #Shuffle reviews and corresponding labels within training and test sets data_train, labels_train = shuffle(data_train, labels_train) data_test, labels_test = shuffle(data_test, labels_test) # Return a unified training data, test data, training labels, test labets return data_train, data_test, labels_train, labels_test train_X, test_X, train_y, test_y = prepare_imdb_data(data, labels) print("IMDb reviews (combined): train = {}, test = {}".format(len(train_X), len(test_X))) ``` Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loaded correctly. ``` print(train_X[100]) print(len(train_X[100])) print(train_y[100]) ``` The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis. ``` import nltk from nltk.corpus import stopwords from nltk.stem.porter import * import re from bs4 import BeautifulSoup def review_to_words(review): nltk.download("stopwords", quiet=True) stemmer = PorterStemmer() text = BeautifulSoup(review, "html.parser").get_text() # Remove HTML tags text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower()) # Convert to lower case words = text.split() # Split string into words words = [w for w in words if w not in stopwords.words("english")] # Remove stopwords words = [PorterStemmer().stem(w) for w in words] # stem return words ``` The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set. ``` # TODO: Apply review_to_words to a review (train_X[100] or any other review) review_to_words(train_X[100]) ``` **Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do to the input? **Answer:** Beside removing HTML formatting and word tokenization (stemming), it removes punctuation marks, converts all letters to lowercase and removes English stopwords (e.g. and, the, a, etc.) The method below applies the `review_to_words` method to each of the reviews in the training and testing datasets. In addition it caches the results. This is because performing this processing step can take a long time. This way if you are unable to complete the notebook in the current session, you can come back without needing to process the data a second time. ``` import pickle cache_dir = os.path.join("../cache", "sentiment_analysis") # where to store cache files os.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists def preprocess_data(data_train, data_test, labels_train, labels_test, cache_dir=cache_dir, cache_file="preprocessed_data.pkl"): """Convert each review to words; read from cache if available.""" # If cache_file is not None, try to read from it first cache_data = None if cache_file is not None: try: with open(os.path.join(cache_dir, cache_file), "rb") as f: cache_data = pickle.load(f) print("Read preprocessed data from cache file:", cache_file) except: pass # unable to read from cache, but that's okay # If cache is missing, then do the heavy lifting if cache_data is None: # Preprocess training and test data to obtain words for each review #words_train = list(map(review_to_words, data_train)) #words_test = list(map(review_to_words, data_test)) words_train = [review_to_words(review) for review in data_train] words_test = [review_to_words(review) for review in data_test] # Write to cache file for future runs if cache_file is not None: cache_data = dict(words_train=words_train, words_test=words_test, labels_train=labels_train, labels_test=labels_test) with open(os.path.join(cache_dir, cache_file), "wb") as f: pickle.dump(cache_data, f) print("Wrote preprocessed data to cache file:", cache_file) else: # Unpack data loaded from cache file words_train, words_test, labels_train, labels_test = (cache_data['words_train'], cache_data['words_test'], cache_data['labels_train'], cache_data['labels_test']) return words_train, words_test, labels_train, labels_test # Preprocess data train_X, test_X, train_y, test_y = preprocess_data(train_X, test_X, train_y, test_y) ``` ## Transform the data In the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of course, some of the words that appear in the reviews occur very infrequently and so likely don't contain much information for the purposes of sentiment analysis. The way we will deal with this problem is that we will fix the size of our working vocabulary and we will only include the words that appear most frequently. We will then combine all of the infrequent words into a single category and, in our case, we will label it as `1`. Since we will be using a recurrent neural network, it will be convenient if the length of each review is the same. To do this, we will fix a size for our reviews and then pad short reviews with the category 'no word' (which we will label `0`) and truncate long reviews. ### (TODO) Create a word dictionary To begin with, we need to construct a way to map words that appear in the reviews to integers. Here we fix the size of our vocabulary (including the 'no word' and 'infrequent' categories) to be `5000` but you may wish to change this to see how it affects the model. > **TODO:** Complete the implementation for the `build_dict()` method below. Note that even though the vocab_size is set to `5000`, we only want to construct a mapping for the most frequently appearing `4998` words. This is because we want to reserve the special labels `0` for 'no word' and `1` for 'infrequent word'. ``` import numpy as np from collections import Counter def build_dict(data, vocab_size = 5000): """Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.""" # TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a # sentence is a list of words. words = [j for i in data for j in i] word_count = {} # A dict storing the words that appear in the reviews along with how often they occur word_count = Counter(words) # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and # sorted_words[-1] is the least frequently appearing word. sorted_words = sorted(word_count, key=word_count.get, reverse=True) word_dict = {} # This is what we are building, a dictionary that translates words into integers for idx, word in enumerate(sorted_words[:vocab_size - 2]): # The -2 is so that we save room for the 'no word' word_dict[word] = idx + 2 # 'infrequent' labels return word_dict word_dict = build_dict(train_X) ``` **Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set? **Answer:** The five most frequently appearing words in the training set are: 'movi', 'film', 'one', 'like' and 'time'. Since the reviews are all about movies, this makes total sense ``` # TODO: Use this space to determine the five most frequently appearing words in the training set. print(word_dict) ``` ### Save `word_dict` Later on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use. ``` data_dir = '../data/pytorch' # The folder we will use for storing data if not os.path.exists(data_dir): # Make sure that the folder exists os.makedirs(data_dir) with open(os.path.join(data_dir, 'word_dict.pkl'), "wb") as f: pickle.dump(word_dict, f) ``` ### Transform the reviews Now that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`. ``` def convert_and_pad(word_dict, sentence, pad=500): NOWORD = 0 # We will use 0 to represent the 'no word' category INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict working_sentence = [NOWORD] * pad for word_index, word in enumerate(sentence[:pad]): if word in word_dict: working_sentence[word_index] = word_dict[word] else: working_sentence[word_index] = INFREQ return working_sentence, min(len(sentence), pad) def convert_and_pad_data(word_dict, data, pad=500): result = [] lengths = [] for sentence in data: converted, leng = convert_and_pad(word_dict, sentence, pad) result.append(converted) lengths.append(leng) return np.array(result), np.array(lengths) train_X, train_X_len = convert_and_pad_data(word_dict, train_X) test_X, test_X_len = convert_and_pad_data(word_dict, test_X) ``` As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set? ``` # Use this cell to examine one of the processed reviews to make sure everything is working as intended. print(train_X[100]) print() print(len(train_X[100])) ``` **Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem? **Answer:** Passing the training and testing sets through mentioned functions has its own set of advantages and disadvantages. For instance, preprocessing the data removes noise from datasets which makes the model more accurate and the training process more computationally efficient since it doesn't deal with useless data. However, truncating the data might affect the model understanding of a review sentiment as the indicating words of a particular review might be at the very end of it. ## Step 3: Upload the data to S3 As in the XGBoost notebook, we will need to upload the training dataset to S3 in order for our training code to access it. For now we will save it locally and we will upload to S3 later on. ### Save the processed training dataset locally It is important to note the format of the data that we are saving as we will need to know it when we write the training code. In our case, each row of the dataset has the form `label`, `length`, `review[500]` where `review[500]` is a sequence of `500` integers representing the words in the review. ``` import pandas as pd pd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \ .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False) ``` ### Uploading the training data Next, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model. ``` import sagemaker sagemaker_session = sagemaker.Session() bucket = sagemaker_session.default_bucket() prefix = 'sagemaker/sentiment_rnn' role = sagemaker.get_execution_role() input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix) ``` **NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also in the S3 training bucket) and that we will need to make sure it gets saved in the model directory. ## Step 4: Build and Train the PyTorch Model In the XGBoost notebook we discussed what a model is in the SageMaker framework. In particular, a model comprises three objects - Model Artifacts, - Training Code, and - Inference Code, each of which interact with one another. In the XGBoost example we used training and inference code that was provided by Amazon. Here we will still be using containers provided by Amazon with the added benefit of being able to include our own custom code. We will start by implementing our own neural network in PyTorch along with a training script. For the purposes of this project we have provided the necessary model object in the `model.py` file, inside of the `train` folder. You can see the provided implementation by running the cell below. ``` !pygmentize train/model.py ``` The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training script so that if we wish to modify them we do not need to modify the script itself. We will see how to do this later on. To start we will write some of the training code in the notebook so that we can more easily diagnose any issues that arise. First we will load a small portion of the training data set to use as a sample. It would be very time consuming to try and train the model completely in the notebook as we do not have access to a gpu and the compute instance that we are using is not particularly powerful. However, we can work on a small bit of the data to get a feel for how our training script is behaving. ``` import torch import torch.utils.data # Read in only the first 250 rows train_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250) # Turn the input pandas dataframe into tensors train_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze() train_sample_X = torch.from_numpy(train_sample.drop([0], axis=1).values).long() # Build the dataset train_sample_ds = torch.utils.data.TensorDataset(train_sample_X, train_sample_y) # Build the dataloader train_sample_dl = torch.utils.data.DataLoader(train_sample_ds, batch_size=50) ``` ### (TODO) Writing the training method Next we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later. ``` def train(model, train_loader, epochs, optimizer, loss_fn, device): for epoch in range(1, epochs + 1): model.train() total_loss = 0 for batch in train_loader: batch_X, batch_y = batch batch_X = batch_X.to(device) batch_y = batch_y.to(device) # TODO: Complete this train method to train the model provided. model.zero_grad() output = model(batch_X) loss = loss_fn(output, batch_y) loss.backward() optimizer.step() total_loss += loss.data.item() print("Epoch: {}, BCELoss: {}".format(epoch, total_loss / len(train_loader))) ``` Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early when they are easier to diagnose. ``` import torch.optim as optim from train.model import LSTMClassifier device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = LSTMClassifier(32, 100, 5000).to(device) optimizer = optim.Adam(model.parameters()) loss_fn = torch.nn.BCELoss() train(model, train_sample_dl, 5, optimizer, loss_fn, device) ``` In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one) for a `requirements.txt` file and install any required Python libraries, after which the training script will be run. ### (TODO) Training the model When a PyTorch model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained. Inside of the `train` directory is a file called `train.py` which has been provided and which contains most of the necessary code to train our model. The only thing that is missing is the implementation of the `train()` method which you wrote earlier in this notebook. **TODO**: Copy the `train()` method written above and paste it into the `train/train.py` file where required. The way that SageMaker passes hyperparameters to the training script is by way of arguments. These arguments can then be parsed and used in the training script. To see how this is done take a look at the provided `train/train.py` file. ``` from sagemaker.pytorch import PyTorch estimator = PyTorch(entry_point="train.py", source_dir="train", role=role, framework_version='0.4.0', train_instance_count=1, train_instance_type='ml.p2.xlarge', hyperparameters={ 'epochs': 9, 'hidden_dim': 200, }) estimator.fit({'training': input_data}) ``` ## Step 5: Testing the model As mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly. ## Step 6: Deploy the model for testing Now that we have trained our model, we would like to test it to see how it performs. Currently our model takes input of the form `review_length, review[500]` where `review[500]` is a sequence of `500` integers which describe the words present in the review, encoded using `word_dict`. Fortunately for us, SageMaker provides built-in inference code for models with simple inputs such as this. There is one thing that we need to provide, however, and that is a function which loads the saved model. This function must be called `model_fn()` and takes as its only parameter a path to the directory where the model artifacts are stored. This function must also be present in the python file which we specified as the entry point. In our case the model loading function has been provided and so no changes need to be made. **NOTE**: When the built-in inference code is run it must import the `model_fn()` method from the `train.py` file. This is why the training code is wrapped in a main guard ( ie, `if __name__ == '__main__':` ) Since we don't need to change anything in the code that was uploaded during training, we can simply deploy the current model as-is. **NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important to know since the cost of a deployed endpoint depends on how long it has been running for. In other words **If you are no longer using a deployed endpoint, shut it down!** **TODO:** Deploy the trained model. ``` # TODO: Deploy the trained model predictor = estimator.deploy(initial_instance_count=1, instance_type='ml.p2.xlarge') ``` ## Step 7 - Use the model for testing Once deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is. ``` test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1) # We split the data into chunks and send each chunk seperately, accumulating the results. def predict(data, rows=512): split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1)) predictions = np.array([]) for array in split_array: predictions = np.append(predictions, predictor.predict(array)) return predictions predictions = predict(test_X.values) predictions = [round(num) for num in predictions] from sklearn.metrics import accuracy_score accuracy_score(test_y, predictions) ``` **Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis? **Answer:** Recall that the XGBoost model accuracy is 0.85696, we can say that the difference between the two models in terms of accuracy isn't that great, however, I'd prefer the LSTM implementation more than the BoW's implementation since LSTM's keep track of previous inputs. ### (TODO) More testing We now have a trained model which has been deployed and which we can send processed reviews to and which returns the predicted sentiment. However, ultimately we would like to be able to send our model an unprocessed review. That is, we would like to send the review itself as a string. For example, suppose we wish to send the following review to our model. ``` test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.' ``` The question we now need to answer is, how do we send this review to our model? Recall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews. - Removed any html tags and stemmed the input - Encoded the review as a sequence of integers using `word_dict` In order process the review we will need to repeat these two steps. **TODO**: Using the `review_to_words` and `convert_and_pad` methods from section one, convert `test_review` into a numpy array `test_data` suitable to send to our model. Remember that our model expects input of the form `review_length, review[500]`. ``` # TODO: Convert test_review into a form usable by the model and save the results in test_data test_review_words = review_to_words(test_review) test_review_words, length = convert_and_pad(word_dict, test_review_words) test_data = np.array([[length] + test_review_words]) ``` Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review. ``` predictor.predict(test_data) ``` Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive. ### Delete the endpoint Of course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delete it. ``` estimator.delete_endpoint() ``` ## Step 6 (again) - Deploy the model for the web app Now that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review. As we saw above, by default the estimator which we created, when deployed, will use the entry script and directory which we provided when creating the model. However, since we now wish to accept a string as input and our model expects a processed review, we need to write some custom inference code. We will store the code that we write in the `serve` directory. Provided in this directory is the `model.py` file that we used to construct our model, a `utils.py` file which contains the `review_to_words` and `convert_and_pad` pre-processing functions which we used during the initial data processing, and `predict.py`, the file which will contain our custom inference code. Note also that `requirements.txt` is present which will tell SageMaker what Python libraries are required by our custom inference code. When deploying a PyTorch model in SageMaker, you are expected to provide four functions which the SageMaker inference container will use. - `model_fn`: This function is the same function that we used in the training script and it tells SageMaker how to load our model. - `input_fn`: This function receives the raw serialized input that has been sent to the model's endpoint and its job is to de-serialize and make the input available for the inference code. - `output_fn`: This function takes the output of the inference code and its job is to serialize this output and return it to the caller of the model's endpoint. - `predict_fn`: The heart of the inference script, this is where the actual prediction is done and is the function which you will need to complete. For the simple website that we are constructing during this project, the `input_fn` and `output_fn` methods are relatively straightforward. We only require being able to accept a string as input and we expect to return a single value as output. You might imagine though that in a more complex application the input or output may be image data or some other binary data which would require some effort to serialize. ### (TODO) Writing inference code Before writing our custom inference code, we will begin by taking a look at the code which has been provided. ``` !pygmentize serve/predict.py ``` As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory. **TODO**: Complete the `predict_fn()` method in the `serve/predict.py` file. ### Deploying the model Now that the custom inference code has been written, we will create and deploy our model. To begin with, we need to construct a new PyTorchModel object which points to the model artifacts created during training and also points to the inference code that we wish to use. Then we can call the deploy method to launch the deployment container. **NOTE**: The default behaviour for a deployed PyTorch model is to assume that any input passed to the predictor is a `numpy` array. In our case we want to send a string so we need to construct a simple wrapper around the `RealTimePredictor` class to accomodate simple strings. In a more complicated situation you may want to provide a serialization object, for example if you wanted to sent image data. ``` from sagemaker.predictor import RealTimePredictor from sagemaker.pytorch import PyTorchModel class StringPredictor(RealTimePredictor): def __init__(self, endpoint_name, sagemaker_session): super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain') model = PyTorchModel(model_data=estimator.model_data, role = role, framework_version='0.4.0', entry_point='predict.py', source_dir='serve', predictor_cls=StringPredictor) predictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge') ``` ### Testing the model Now that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is that the amount of time it takes for our model to process the input and then perform inference is quite long and so testing the entire data set would be prohibitive. ``` import glob def test_reviews(data_dir='../data/aclImdb', stop=250): results = [] ground = [] # We make sure to test both positive and negative reviews for sentiment in ['pos', 'neg']: path = os.path.join(data_dir, 'test', sentiment, '*.txt') files = glob.glob(path) files_read = 0 print('Starting ', sentiment, ' files') # Iterate through the files and send them to the predictor for f in files: with open(f) as review: # First, we store the ground truth (was the review positive or negative) if sentiment == 'pos': ground.append(1) else: ground.append(0) # Read in the review and convert to 'utf-8' for transmission via HTTP review_input = review.read().encode('utf-8') # Send the review to the predictor and store the results results.append(float(predictor.predict(review_input))) # Sending reviews to our endpoint one at a time takes a while so we # only send a small number of reviews files_read += 1 if files_read == stop: break return ground, results ground, results = test_reviews() from sklearn.metrics import accuracy_score accuracy_score(ground, results) ``` As an additional test, we can try sending the `test_review` that we looked at earlier. ``` predictor.predict(test_review) ``` Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back. ## Step 7 (again): Use the model for the web app > **TODO:** This entire section and the next contain tasks for you to complete, mostly using the AWS console. So far we have been accessing our model endpoint by constructing a predictor object which uses the endpoint and then just using the predictor object to perform inference. What if we wanted to create a web app which accessed our model? The way things are set up currently makes that not possible since in order to access a SageMaker endpoint the app would first have to authenticate with AWS using an IAM role which included access to SageMaker endpoints. However, there is an easier way! We just need to use some additional AWS services. <img src="Web App Diagram.svg"> The diagram above gives an overview of how the various services will work together. On the far right is the model which we trained above and which is deployed using SageMaker. On the far left is our web app that collects a user's movie review, sends it off and expects a positive or negative sentiment in return. In the middle is where some of the magic happens. We will construct a Lambda function, which you can think of as a straightforward Python function that can be executed whenever a specified event occurs. We will give this function permission to send and recieve data from a SageMaker endpoint. Lastly, the method we will use to execute the Lambda function is a new endpoint that we will create using API Gateway. This endpoint will be a url that listens for data to be sent to it. Once it gets some data it will pass that data on to the Lambda function and then return whatever the Lambda function returns. Essentially it will act as an interface that lets our web app communicate with the Lambda function. ### Setting up a Lambda function The first thing we are going to do is set up a Lambda function. This Lambda function will be executed whenever our public API has data sent to it. When it is executed it will receive the data, perform any sort of processing that is required, send the data (the review) to the SageMaker endpoint we've created and then return the result. #### Part A: Create an IAM Role for the Lambda function Since we want the Lambda function to call a SageMaker endpoint, we need to make sure that it has permission to do so. To do this, we will construct a role that we can later give the Lambda function. Using the AWS Console, navigate to the **IAM** page and click on **Roles**. Then, click on **Create role**. Make sure that the **AWS service** is the type of trusted entity selected and choose **Lambda** as the service that will use this role, then click **Next: Permissions**. In the search box type `sagemaker` and select the check box next to the **AmazonSageMakerFullAccess** policy. Then, click on **Next: Review**. Lastly, give this role a name. Make sure you use a name that you will remember later on, for example `LambdaSageMakerRole`. Then, click on **Create role**. #### Part B: Create a Lambda function Now it is time to actually create the Lambda function. Using the AWS Console, navigate to the AWS Lambda page and click on **Create a function**. When you get to the next page, make sure that **Author from scratch** is selected. Now, name your Lambda function, using a name that you will remember later on, for example `sentiment_analysis_func`. Make sure that the **Python 3.6** runtime is selected and then choose the role that you created in the previous part. Then, click on **Create Function**. On the next page you will see some information about the Lambda function you've just created. If you scroll down you should see an editor in which you can write the code that will be executed when your Lambda function is triggered. In our example, we will use the code below. ```python # We need to use the low-level library to interact with SageMaker since the SageMaker API # is not available natively through Lambda. import boto3 def lambda_handler(event, context): # The SageMaker runtime is what allows us to invoke the endpoint that we've created. runtime = boto3.Session().client('sagemaker-runtime') # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given response = runtime.invoke_endpoint(EndpointName = '**ENDPOINT NAME HERE**', # The name of the endpoint we created ContentType = 'text/plain', # The data format that is expected Body = event['body']) # The actual review # The response is an HTTP response whose body contains the result of our inference result = response['Body'].read().decode('utf-8') return { 'statusCode' : 200, 'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' }, 'body' : result } ``` Once you have copy and pasted the code above into the Lambda code editor, replace the `**ENDPOINT NAME HERE**` portion with the name of the endpoint that we deployed earlier. You can determine the name of the endpoint using the code cell below. ``` predictor.endpoint ``` Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function. ### Setting up API Gateway Now that our Lambda function is set up, it is time to create a new API using API Gateway that will trigger the Lambda function we have just created. Using AWS Console, navigate to **Amazon API Gateway** and then click on **Get started**. On the next page, make sure that **New API** is selected and give the new api a name, for example, `sentiment_analysis_api`. Then, click on **Create API**. Now we have created an API, however it doesn't currently do anything. What we want it to do is to trigger the Lambda function that we created earlier. Select the **Actions** dropdown menu and click **Create Method**. A new blank method will be created, select its dropdown menu and select **POST**, then click on the check mark beside it. For the integration point, make sure that **Lambda Function** is selected and click on the **Use Lambda Proxy integration**. This option makes sure that the data that is sent to the API is then sent directly to the Lambda function with no processing. It also means that the return value must be a proper response object as it will also not be processed by API Gateway. Type the name of the Lambda function you created earlier into the **Lambda Function** text entry box and then click on **Save**. Click on **OK** in the pop-up box that then appears, giving permission to API Gateway to invoke the Lambda function you created. The last step in creating the API Gateway is to select the **Actions** dropdown and click on **Deploy API**. You will need to create a new Deployment stage and name it anything you like, for example `prod`. You have now successfully set up a public API to access your SageMaker model. Make sure to copy or write down the URL provided to invoke your newly created public API as this will be needed in the next step. This URL can be found at the top of the page, highlighted in blue next to the text **Invoke URL**. ## Step 4: Deploying our web app Now that we have a publicly available API, we can start using it in a web app. For our purposes, we have provided a simple static html file which can make use of the public api you created earlier. In the `website` folder there should be a file called `index.html`. Download the file to your computer and open that file up in a text editor of your choice. There should be a line which contains **\*\*REPLACE WITH PUBLIC API URL\*\***. Replace this string with the url that you wrote down in the last step and then save the file. Now, if you open `index.html` on your local computer, your browser will behave as a local web server and you can use the provided site to interact with your SageMaker model. If you'd like to go further, you can host this html file anywhere you'd like, for example using github or hosting a static site on Amazon's S3. Once you have done this you can share the link with anyone you'd like and have them play with it too! > **Important Note** In order for the web app to communicate with the SageMaker endpoint, the endpoint has to actually be deployed and running. This means that you are paying for it. Make sure that the endpoint is running when you want to use the web app but that you shut it down when you don't need it, otherwise you will end up with a surprisingly large AWS bill. **TODO:** Make sure that you include the edited `index.html` file in your project submission. Now that your web app is working, trying playing around with it and see how well it works. **Question**: Give an example of a review that you entered into your web app. What was the predicted sentiment of your example review? **Answer:** **_Example Review:_** In my opinion the greatest comedy ever made! Daniels and Carrey work magic together in this film that more than 20 years later is finally considered a classic. When it first came out it was labeled as complete garbage and toilet humour. But to those people I say it is the best garbage and toilet humour you could ask for. What do you expect to see when the title of the film is ''Dumb and Dumber''. The quick back and forth between the two lead actors and not so subtle chirping often goes unnoticed because your'e laughing so hard from the previous scene.the jokes and dialogue are so good and Carey and Daniels deliver them with such authenticity. It's because of this reason that I am able to watch this movie countless times and still be entertained, as I listen to funny remarks that I missed on the previous 100 viewings. What's truly great about this film is that even people who say they hate it will always without fail crack a laugh or two when re-watching it. They just don't want to admit that they find this nonsense to be funny...but it is. More than 20 years later and I still have not seen a buddy comedy that comes close to matching it. _[Source: Dumb and Dumber, IMDB]_ **_Predicted Sentiment:_** POSITIVE ### Delete the endpoint Remember to always shut down your endpoint if you are no longer using it. You are charged for the length of time that the endpoint is running so if you forget and leave it on you could end up with an unexpectedly large bill. ``` predictor.delete_endpoint() ```
github_jupyter
# Day and Night Image Classifier --- The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images. We'd like to build a classifier that can accurately label these images as day or night, and that relies on finding distinguishing features between the two types of images! *Note: All images come from the [AMOS dataset](http://cs.uky.edu/~jacobs/datasets/amos/) (Archive of Many Outdoor Scenes).* ### Import resources Before you get started on the project code, import the libraries and resources that you'll need. ``` import cv2 # computer vision library import helpers import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg %matplotlib inline ``` ## Training and Testing Data The 200 day/night images are separated into training and testing datasets. * 60% of these images are training images, for you to use as you create a classifier. * 40% are test images, which will be used to test the accuracy of your classifier. First, we set some variables to keep track of some where our images are stored: image_dir_training: the directory where our training image data is stored image_dir_test: the directory where our test image data is stored ``` # Image data directories image_dir_training = "day_night_images/training/" image_dir_test = "day_night_images/test/" ``` ## Load the datasets These first few lines of code will load the training day/night images and store all of them in a variable, `IMAGE_LIST`. This list contains the images and their associated label ("day" or "night"). For example, the first image-label pair in `IMAGE_LIST` can be accessed by index: ``` IMAGE_LIST[0][:]```. ``` # Using the load_dataset function in helpers.py # Load training data IMAGE_LIST = helpers.load_dataset(image_dir_training) ``` ## Construct a `STANDARDIZED_LIST` of input images and output labels. This function takes in a list of image-label pairs and outputs a **standardized** list of resized images and numerical labels. ``` # Standardize all training images STANDARDIZED_LIST = helpers.standardize(IMAGE_LIST) ``` ## Visualize the standardized data Display a standardized image from STANDARDIZED_LIST. ``` # Display a standardized image and its label # Select an image by index image_num = 0 selected_image = STANDARDIZED_LIST[image_num][0] selected_label = STANDARDIZED_LIST[image_num][1] # Display image and data about it plt.imshow(selected_image) print("Shape: "+str(selected_image.shape)) print("Label [1 = day, 0 = night]: " + str(selected_label)) ``` # Feature Extraction Create a feature that represents the brightness in an image. We'll be extracting the **average brightness** using HSV colorspace. Specifically, we'll use the V channel (a measure of brightness), add up the pixel values in the V channel, then divide that sum by the area of the image to get the average Value of the image. --- ### Find the average brightness using the V channel This function takes in a **standardized** RGB image and returns a feature (a single value) that represent the average level of brightness in the image. We'll use this value to classify the image as day or night. ``` # Find the average Value or brightness of an image def avg_brightness(rgb_image): # Convert image to HSV hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) # Add up all the pixel values in the V channel sum_brightness = np.sum(hsv[:,:,2]) area = 600*1100.0 # pixels # find the avg avg = sum_brightness/area return avg # Testing average brightness levels # Look at a number of different day and night images and think about # what average brightness value separates the two types of images # As an example, a "night" image is loaded in and its avg brightness is displayed image_num = 190 test_im = STANDARDIZED_LIST[image_num][0] avg = avg_brightness(test_im) print('Avg brightness: ' + str(avg)) plt.imshow(test_im) ``` # Classification and Visualizing Error In this section, we'll turn our average brightness feature into a classifier that takes in a standardized image and returns a `predicted_label` for that image. This `estimate_label` function should return a value: 0 or 1 (night or day, respectively). --- ### TODO: Build a complete classifier Set a threshold that you think will separate the day and night images by average brightness. ``` # This function should take in RGB image input def estimate_label(rgb_image): ## TODO: extract average brightness feature from an RGB image # Use the avg brightness feature to predict a label (0, 1) predicted_label = 0 ## TODO: set the value of a threshold that will separate day and night images threshold = 100 ## TODO: Return the predicted_label (0 or 1) based on whether the avg is # above or below the threshold if avg_brightness(rgb_image) > threshold: predicted_label = 1 return predicted_label ## Test out your code by calling the above function and seeing # how some of your training data is classified estimate_label(test_im) ```
github_jupyter
Here is an illustration of the IFS T42 issue. ``` import xarray as xr import matplotlib.pyplot as plt from src.score import * # This is the regridded ERA data DATADIR = '/data/weather-benchmark/5.625deg/' z500_valid = load_test_data(f'{DATADIR}geopotential_500', 'z') t850_valid = load_test_data(f'{DATADIR}temperature_850', 't') era = xr.merge([z500_valid, t850_valid]).drop('level') era # This is the data that was regridded by Peter t42_raw = xr.open_dataset(f'/media/rasp/Elements/weather-benchmark/IFS_T42/output_42_pl_5.625.nc') # Make longitude dimensions match t42_raw['lat'] = -era.lat t42_raw = t42_raw.roll(lon=32) t42_raw['lon'] = era.lon t42_raw ``` Let's now plot the initial conditions of the first forecast. ``` # Plot for Z500 with difference fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.z.isel(time=0).sel(lev=5e4).plot(ax=axs[0]); era.z.isel(time=0).plot(ax=axs[1]) (t42_raw.z.isel(time=0).sel(lev=5e4)-era.z.isel(time=0)).plot(ax=axs[2]); # Same for T850 fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.t.isel(time=0).sel(lev=8.5e4).plot(ax=axs[0]); era.t.isel(time=0).plot(ax=axs[1]) (t42_raw.t.isel(time=0).sel(lev=8.5e4)-era.t.isel(time=0)).plot(ax=axs[2]); ``` We can see that the ERA field is a lot noisier that the smooth T42 field. This is obviously worse for T than for Z, which causes the RMSE for T to be much worse. ``` # Now for a 5 day forecast fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.z.isel(time=5*24//6).sel(lev=5e4).plot(ax=axs[0]); era.z.isel(time=5*24).plot(ax=axs[1]) (t42_raw.z.isel(time=5*24//6).sel(lev=5e4)-era.z.isel(time=5*24)).plot(ax=axs[2]); # Same for T850 fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.t.isel(time=5*24//6).sel(lev=8.5e4).plot(ax=axs[0]); era.t.isel(time=5*24).plot(ax=axs[1]) (t42_raw.t.isel(time=5*24//6).sel(lev=8.5e4)-era.t.isel(time=5*24)).plot(ax=axs[2]); ``` So one weird thing here is that we have a 30(!) degree temperature error in the forecast. That doesn't seem physical, right? Since T42 is started from ERA ICs the question is: Why is it so much smoother? Does it have to do with the interpolation. To check that, let's do the same analysis for the 2.8125 degree data. ``` # This is the regridded ERA data DATADIR = '/media/rasp/Elements/weather-benchmark/2.8125deg/' z500_valid = load_test_data(f'{DATADIR}geopotential', 'z') t850_valid = load_test_data(f'{DATADIR}temperature', 't') era = xr.merge([z500_valid, t850_valid]) era # This is the data that was regridded by Peter t42_raw = xr.open_dataset(f'/media/rasp/Elements/weather-benchmark/IFS_T42/output_42_pl_2.8125.nc') # Make longitude dimensions match t42_raw['lat'] = -era.lat t42_raw = t42_raw.roll(lon=64) t42_raw['lon'] = era.lon t42_raw ``` Let's now plot the initial conditions of the first forecast. ``` # Plot for Z500 with difference fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.z.isel(time=0).sel(lev=5e4).plot(ax=axs[0]); era.z.isel(time=0).plot(ax=axs[1]) (t42_raw.z.isel(time=0).sel(lev=5e4)-era.z.isel(time=0)).plot(ax=axs[2]); # Same for T850 fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.t.isel(time=0).sel(lev=8.5e4).plot(ax=axs[0]); era.t.isel(time=0).plot(ax=axs[1]) (t42_raw.t.isel(time=0).sel(lev=8.5e4)-era.t.isel(time=0)).plot(ax=axs[2]); ``` As you can see the T42 forecasts are still much smoother. So why is that? ``` # Now for a 5 day forecast fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.z.isel(time=5*24//6).sel(lev=5e4).plot(ax=axs[0]); era.z.isel(time=5*24).plot(ax=axs[1]) (t42_raw.z.isel(time=5*24//6).sel(lev=5e4)-era.z.isel(time=5*24)).plot(ax=axs[2]); # Same for T850 fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.t.isel(time=5*24//6).sel(lev=8.5e4).plot(ax=axs[0]); era.t.isel(time=5*24).plot(ax=axs[1]) (t42_raw.t.isel(time=5*24//6).sel(lev=8.5e4)-era.t.isel(time=5*24)).plot(ax=axs[2]); # Same for T850; now for 1 forecast lead time t = 24 fig, axs = plt.subplots(1, 3, figsize=(15, 4)) t42_raw.t.isel(time=t//6).sel(lev=8.5e4).plot(ax=axs[0]); era.t.isel(time=t).plot(ax=axs[1]) (t42_raw.t.isel(time=t//6).sel(lev=8.5e4)-era.t.isel(time=t)).plot(ax=axs[2]); ``` We still have that huge temperature error. Let's check where that is. ``` import cartopy.crs as ccrs diff = t42_raw.t.isel(time=5*24//6).sel(lev=8.5e4)-era.t.isel(time=5*24).load() ax = plt.axes(projection=ccrs.PlateCarree()) diff.plot(ax=ax, transform=ccrs.PlateCarree()) ax.set_global(); ax.coastlines() ``` So the huge error is over Eastern China? I almost suspect that this is the main reason for the bad RMSEs.
github_jupyter
# Введение в координатный спуск (coordinate descent): теория и приложения ## Постановка задачи и основное предположение $$ \min_{x \in \mathbb{R}^n} f(x) $$ - $f$ выпуклая функция - Если по каждой координате будет выполнено $f(x + \varepsilon e_i) \geq f(x)$, будет ли это означать, что $x$ точка минимума? - Если $f$ гладкая, то да, по критерию первого порядка $f'(x) = 0$ - Если $f$ негладкая, то нет, так как условие может быть выполнено в "угловых" точках, которые не являются точками минимума - Если $f$ негладкая, но композитная с сепарабельной негладкой частью, то есть $$ f(x) = g(x) + \sum_{i=1}^n h_i(x_i), $$ то да. Почему? - Для любого $y$ и $x$, в котором выполнено условие оптимальности по каждому направлению, выполнено $$ f(y) - f(x) = g(y) - g(x) + \sum_{i=1}^n (h_i(y_i) - h_i(x_i)) \geq \langle g'(x), y - x \rangle+ \sum_{i=1}^n (h_i(y_i) - h_i(x_i)) = \sum_{i=1}^n [g'_i(x)(y_i - x_i) + h_i(y_i) - h_i(x_i)] \geq 0 $$ - Значит для функций такого вида поиск минимума можно проводить покоординатно, а в результате всё равно получить точку минимума ### Вычислительные нюансы - На этапе вычисления $i+1$ координаты используются обновлённые значения $1, 2, \ldots, i$ координат при последовательном переборе координат - Вспомните разницу между методами Якоби и Гаусса-Зейделя для решения линейных систем! - Порядок выбора координат имеет значение - Сложность обновления полного вектора $\sim$ сложности обновления $n$ его компонент, то есть для покоординатного обновления целевой переменной не требуется оперировать с полным градиентом! ## Простой пример - $f(x) = \frac12 \|Ax - b\|_2^2$, где $A \in \mathbb{R}^{m \times n}$ и $m \gg n$ - Выберем некоторую координату $i$ - Тогда покоординатное условие оптимальности $[f'(x)]_i = A^{\top}_i(Ax - b) = A^{\top}_i(A_{-i} x_{-i} + A_ix_i - b) = 0$ - Откуда $x_i = \dfrac{A^{\top}_i (b - A_{-i} x_{-i})}{\|A_i\|_2^2}$ - сложность $O(nm)$, что сопоставимо с вычислением полного градиента. Можно ли быстрее? - Да, можно! Для этого необходимо заметить следующее $$ x_i = \dfrac{A^{\top}_i (b - A_{-i} x_{-i})}{\|A_i\|_2^2} = \dfrac{A^{\top}_i (b - Ax + A_{i}x_i)}{\|A_i\|_2^2} = x_i - \dfrac{A^{\top}_i r}{\|A_i\|_2^2}, $$ где $r = Ax - b$ - Обновление $r$ - $\mathcal{O}(m)$, вычисление $A^{\top}_i r$ - $\mathcal{O}(m)$ - В итоге, обновить одну координату стоит $\mathcal{O}(m)$, то есть сложность обновления всех координат сопоставима с вычислением полного градиента $\mathcal{O}(mn)$ ## Как выбирать координаты? - По циклы от 1 до $n$ - Случайной перестановкой - Правило Gauss-Southwell: $i = \arg\max_k |f'_k(x)|$ - потенциально более дорогое чем остальные ``` import numpy as np import matplotlib.pyplot as plt plt.rc("text", usetex=True) m = 1000 n = 100 A = np.random.randn(m, n) u, s, v = np.linalg.svd(A, compute_uv=True, full_matrices=False) print(s) s[-1] = 2 A = u @ np.diag(s) @ v print(np.linalg.cond(A)) print(np.linalg.cond(A.T @ A)) x_true = np.random.randn(n) b = A @ x_true + 1e-7 * np.random.randn(m) def coordinate_descent_lsq(x0, num_iter, sampler="sequential"): conv = [x0] x = x0.copy() r = A @ x0 - b grad = A.T @ r if sampler == "sequential" or sampler == "GS": perm = np.arange(x.shape[0]) elif sampler == "random": perm = np.random.permutation(x.shape[0]) else: raise ValueError("Unknown sampler!") for i in range(num_iter): for idx in perm: if sampler == "GS": idx = np.argmax(np.abs(grad)) new_x_idx = x[idx] - A[:, idx] @ r / (A[:, idx] @ A[:, idx]) r = r + A[:, idx] * (new_x_idx - x[idx]) if sampler == "GS": grad = A.T @ r x[idx] = new_x_idx if sampler == "random": perm = np.random.permutation(x.shape[0]) conv.append(x.copy()) # print(np.linalg.norm(A @ x - b)) return x, conv x0 = np.random.randn(n) num_iter = 500 x_cd_seq, conv_cd_seq = coordinate_descent_lsq(x0, num_iter) x_cd_rand, conv_cd_rand = coordinate_descent_lsq(x0, num_iter, "random") x_cd_gs, conv_cd_gs = coordinate_descent_lsq(x0, num_iter, "GS") # !pip install git+https://github.com/amkatrutsa/liboptpy import liboptpy.unconstr_solvers as methods import liboptpy.step_size as ss def f(x): res = A @ x - b return 0.5 * res @ res def gradf(x): res = A @ x - b return A.T @ res L = np.max(np.linalg.eigvalsh(A.T @ A)) gd = methods.fo.GradientDescent(f, gradf, ss.ConstantStepSize(1 / L)) x_gd = gd.solve(x0=x0, max_iter=num_iter) acc_gd = methods.fo.AcceleratedGD(f, gradf, ss.ConstantStepSize(1 / L)) x_accgd = acc_gd.solve(x0=x0, max_iter=num_iter) plt.figure(figsize=(15, 10)) plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_cd_rand], label="Random") plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_cd_seq], label="Sequential") plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_cd_gs], label="GS") plt.semilogy([np.linalg.norm(A @ x - b) for x in gd.get_convergence()], label="GD") plt.semilogy([np.linalg.norm(A @ x - b) for x in acc_gd.get_convergence()], label="Nesterov") plt.legend(fontsize=20) plt.xlabel("Number of iterations", fontsize=24) plt.ylabel("$\|Ax - b\|_2$", fontsize=24) plt.grid(True) plt.xticks(fontsize=18) plt.yticks(fontsize=18) plt.show() plt.semilogy([np.linalg.norm(x - x_true) for x in conv_cd_rand], label="Random") plt.semilogy([np.linalg.norm(x - x_true) for x in conv_cd_seq], label="Sequential") plt.semilogy([np.linalg.norm(x - x_true) for x in conv_cd_gs], label="GS") plt.semilogy([np.linalg.norm(x - x_true) for x in gd.get_convergence()], label="GD") plt.semilogy([np.linalg.norm(x - x_true) for x in acc_gd.get_convergence()], label="Nesterov") plt.legend(fontsize=20) plt.xlabel("Number of iterations", fontsize=24) plt.ylabel("$\|x - x^*\|_2$", fontsize=24) plt.grid(True) plt.xticks(fontsize=18) plt.yticks(fontsize=18) plt.show() ``` ## Сходимость - Сублинейная для выпуклых гладких с Липшицевым градиентом - Линейная для сильно выпуклых функций - Прямая аналогия с градиентным спуском - Но много особенностей использования ## Типичные примеры использования - Lasso (снова) - SMO метод обучения SVM - блочный координатный спуск с размером блока равным 2 - Вывод в графических моделях
github_jupyter
# Principal Component Analysis in Shogun #### By Abhijeet Kislay (GitHub ID: <a href='https://github.com/kislayabhi'>kislayabhi</a>) This notebook is about finding Principal Components (<a href="http://en.wikipedia.org/wiki/Principal_component_analysis">PCA</a>) of data (<a href="http://en.wikipedia.org/wiki/Unsupervised_learning">unsupervised</a>) in Shogun. Its <a href="http://en.wikipedia.org/wiki/Dimensionality_reduction">dimensional reduction</a> capabilities are further utilised to show its application in <a href="http://en.wikipedia.org/wiki/Data_compression">data compression</a>, image processing and <a href="http://en.wikipedia.org/wiki/Facial_recognition_system">face recognition</a>. ``` %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all shogun classes from shogun import * ``` ## Some Formal Background (Skip if you just want code examples) PCA is a useful statistical technique that has found application in fields such as face recognition and image compression, and is a common technique for finding patterns in data of high dimension. In machine learning problems data is often high dimensional - images, bag-of-word descriptions etc. In such cases we cannot expect the training data to densely populate the space, meaning that there will be large parts in which little is known about the data. Hence it is expected that only a small number of directions are relevant for describing the data to a reasonable accuracy. The data vectors may be very high dimensional, they will therefore typically lie closer to a much lower dimensional 'manifold'. Here we concentrate on linear dimensional reduction techniques. In this approach a high dimensional datapoint $\mathbf{x}$ is 'projected down' to a lower dimensional vector $\mathbf{y}$ by: $$\mathbf{y}=\mathbf{F}\mathbf{x}+\text{const}.$$ where the matrix $\mathbf{F}\in\mathbb{R}^{\text{M}\times \text{D}}$, with $\text{M}<\text{D}$. Here $\text{M}=\dim(\mathbf{y})$ and $\text{D}=\dim(\mathbf{x})$. From the above scenario, we assume that * The number of principal components to use is $\text{M}$. * The dimension of each data point is $\text{D}$. * The number of data points is $\text{N}$. We express the approximation for datapoint $\mathbf{x}^n$ as:$$\mathbf{x}^n \approx \mathbf{c} + \sum\limits_{i=1}^{\text{M}}y_i^n \mathbf{b}^i \equiv \tilde{\mathbf{x}}^n.$$ * Here the vector $\mathbf{c}$ is a constant and defines a point in the lower dimensional space. * The $\mathbf{b}^i$ define vectors in the lower dimensional space (also known as 'principal component coefficients' or 'loadings'). * The $y_i^n$ are the low dimensional co-ordinates of the data. Our motive is to find the reconstruction $\tilde{\mathbf{x}}^n$ given the lower dimensional representation $\mathbf{y}^n$(which has components $y_i^n,i = 1,...,\text{M})$. For a data space of dimension $\dim(\mathbf{x})=\text{D}$, we hope to accurately describe the data using only a small number $(\text{M}\ll \text{D})$ of coordinates of $\mathbf{y}$. To determine the best lower dimensional representation it is convenient to use the square distance error between $\mathbf{x}$ and its reconstruction $\tilde{\mathbf{x}}$:$$\text{E}(\mathbf{B},\mathbf{Y},\mathbf{c})=\sum\limits_{n=1}^{\text{N}}\sum\limits_{i=1}^{\text{D}}[x_i^n - \tilde{x}_i^n]^2.$$ * Here the basis vectors are defined as $\mathbf{B} = [\mathbf{b}^1,...,\mathbf{b}^\text{M}]$ (defining $[\text{B}]_{i,j} = b_i^j$). * Corresponding low dimensional coordinates are defined as $\mathbf{Y} = [\mathbf{y}^1,...,\mathbf{y}^\text{N}].$ * Also, $x_i^n$ and $\tilde{x}_i^n$ represents the coordinates of the data points for the original and the reconstructed data respectively. * The bias $\mathbf{c}$ is given by the mean of the data $\sum_n\mathbf{x}^n/\text{N}$. Therefore, for simplification purposes we centre our data, so as to set $\mathbf{c}$ to zero. Now we concentrate on finding the optimal basis $\mathbf{B}$( which has the components $\mathbf{b}^i, i=1,...,\text{M} $). #### Deriving the optimal linear reconstruction To find the best basis vectors $\mathbf{B}$ and corresponding low dimensional coordinates $\mathbf{Y}$, we may minimize the sum of squared differences between each vector $\mathbf{x}$ and its reconstruction $\tilde{\mathbf{x}}$: $\text{E}(\mathbf{B},\mathbf{Y}) = \sum\limits_{n=1}^{\text{N}}\sum\limits_{i=1}^{\text{D}}\left[x_i^n - \sum\limits_{j=1}^{\text{M}}y_j^nb_i^j\right]^2 = \text{trace} \left( (\mathbf{X}-\mathbf{B}\mathbf{Y})^T(\mathbf{X}-\mathbf{B}\mathbf{Y}) \right)$ where $\mathbf{X} = [\mathbf{x}^1,...,\mathbf{x}^\text{N}].$ Considering the above equation under the orthonormality constraint $\mathbf{B}^T\mathbf{B} = \mathbf{I}$ (i.e the basis vectors are mutually orthogonal and of unit length), we differentiate it w.r.t $y_k^n$. The squared error $\text{E}(\mathbf{B},\mathbf{Y})$ therefore has zero derivative when: $y_k^n = \sum_i b_i^kx_i^n$ By substituting this solution in the above equation, the objective becomes $\text{E}(\mathbf{B}) = (\text{N}-1)\left[\text{trace}(\mathbf{S}) - \text{trace}\left(\mathbf{S}\mathbf{B}\mathbf{B}^T\right)\right],$ where $\mathbf{S}$ is the sample covariance matrix of the data. To minimise equation under the constraint $\mathbf{B}^T\mathbf{B} = \mathbf{I}$, we use a set of Lagrange Multipliers $\mathbf{L}$, so that the objective is to minimize: $-\text{trace}\left(\mathbf{S}\mathbf{B}\mathbf{B}^T\right)+\text{trace}\left(\mathbf{L}\left(\mathbf{B}^T\mathbf{B} - \mathbf{I}\right)\right).$ Since the constraint is symmetric, we can assume that $\mathbf{L}$ is also symmetric. Differentiating with respect to $\mathbf{B}$ and equating to zero we obtain that at the optimum $\mathbf{S}\mathbf{B} = \mathbf{B}\mathbf{L}$. This is a form of eigen-equation so that a solution is given by taking $\mathbf{L}$ to be diagonal and $\mathbf{B}$ as the matrix whose columns are the corresponding eigenvectors of $\mathbf{S}$. In this case, $\text{trace}\left(\mathbf{S}\mathbf{B}\mathbf{B}^T\right) =\text{trace}(\mathbf{L}),$ which is the sum of the eigenvalues corresponding to the eigenvectors forming $\mathbf{B}$. Since we wish to minimise $\text{E}(\mathbf{B})$, we take the eigenvectors with the largest corresponding eigenvalues. Whilst the solution to this eigen-problem is unique, this only serves to define the solution subspace since one may rotate and scale $\mathbf{B}$ and $\mathbf{Y}$ such that the value of the squared loss is exactly the same. The justification for choosing the non-rotated eigen solution is given by the additional requirement that the principal components corresponds to directions of maximal variance. #### Maximum variance criterion We aim to find that single direction $\mathbf{b}$ such that, when the data is projected onto this direction, the variance of this projection is maximal amongst all possible such projections. The projection of a datapoint onto a direction $\mathbf{b}$ is $\mathbf{b}^T\mathbf{x}^n$ for a unit length vector $\mathbf{b}$. Hence the sum of squared projections is: $$\sum\limits_{n}\left(\mathbf{b}^T\mathbf{x}^n\right)^2 = \mathbf{b}^T\left[\sum\limits_{n}\mathbf{x}^n(\mathbf{x}^n)^T\right]\mathbf{b} = (\text{N}-1)\mathbf{b}^T\mathbf{S}\mathbf{b} = \lambda(\text{N} - 1)$$ which ignoring constants, is simply the negative of the equation for a single retained eigenvector $\mathbf{b}$(with $\mathbf{S}\mathbf{b} = \lambda\mathbf{b}$). Hence the optimal single $\text{b}$ which maximises the projection variance is given by the eigenvector corresponding to the largest eigenvalues of $\mathbf{S}.$ The second largest eigenvector corresponds to the next orthogonal optimal direction and so on. This explains why, despite the squared loss equation being invariant with respect to arbitrary rotation of the basis vectors, the ones given by the eigen-decomposition have the additional property that they correspond to directions of maximal variance. These maximal variance directions found by PCA are called the $\text{principal} $ $\text{directions}.$ There are two eigenvalue methods through which shogun can perform PCA namely * Eigenvalue Decomposition Method. * Singular Value Decomposition. #### EVD vs SVD * The EVD viewpoint requires that one compute the eigenvalues and eigenvectors of the covariance matrix, which is the product of $\mathbf{X}\mathbf{X}^\text{T}$, where $\mathbf{X}$ is the data matrix. Since the covariance matrix is symmetric, the matrix is diagonalizable, and the eigenvectors can be normalized such that they are orthonormal: $\mathbf{S}=\frac{1}{\text{N}-1}\mathbf{X}\mathbf{X}^\text{T},$ where the $\text{D}\times\text{N}$ matrix $\mathbf{X}$ contains all the data vectors: $\mathbf{X}=[\mathbf{x}^1,...,\mathbf{x}^\text{N}].$ Writing the $\text{D}\times\text{N}$ matrix of eigenvectors as $\mathbf{E}$ and the eigenvalues as an $\text{N}\times\text{N}$ diagonal matrix $\mathbf{\Lambda}$, the eigen-decomposition of the covariance $\mathbf{S}$ is $\mathbf{X}\mathbf{X}^\text{T}\mathbf{E}=\mathbf{E}\mathbf{\Lambda}\Longrightarrow\mathbf{X}^\text{T}\mathbf{X}\mathbf{X}^\text{T}\mathbf{E}=\mathbf{X}^\text{T}\mathbf{E}\mathbf{\Lambda}\Longrightarrow\mathbf{X}^\text{T}\mathbf{X}\tilde{\mathbf{E}}=\tilde{\mathbf{E}}\mathbf{\Lambda},$ where we defined $\tilde{\mathbf{E}}=\mathbf{X}^\text{T}\mathbf{E}$. The final expression above represents the eigenvector equation for $\mathbf{X}^\text{T}\mathbf{X}.$ This is a matrix of dimensions $\text{N}\times\text{N}$ so that calculating the eigen-decomposition takes $\mathcal{O}(\text{N}^3)$ operations, compared with $\mathcal{O}(\text{D}^3)$ operations in the original high-dimensional space. We then can therefore calculate the eigenvectors $\tilde{\mathbf{E}}$ and eigenvalues $\mathbf{\Lambda}$ of this matrix more easily. Once found, we use the fact that the eigenvalues of $\mathbf{S}$ are given by the diagonal entries of $\mathbf{\Lambda}$ and the eigenvectors by $\mathbf{E}=\mathbf{X}\tilde{\mathbf{E}}\mathbf{\Lambda}^{-1}$ * On the other hand, applying SVD to the data matrix $\mathbf{X}$ follows like: $\mathbf{X}=\mathbf{U}\mathbf{\Sigma}\mathbf{V}^\text{T}$ where $\mathbf{U}^\text{T}\mathbf{U}=\mathbf{I}_\text{D}$ and $\mathbf{V}^\text{T}\mathbf{V}=\mathbf{I}_\text{N}$ and $\mathbf{\Sigma}$ is a diagonal matrix of the (positive) singular values. We assume that the decomposition has ordered the singular values so that the upper left diagonal element of $\mathbf{\Sigma}$ contains the largest singular value. Attempting to construct the covariance matrix $(\mathbf{X}\mathbf{X}^\text{T})$from this decomposition gives: $\mathbf{X}\mathbf{X}^\text{T} = \left(\mathbf{U}\mathbf{\Sigma}\mathbf{V}^\text{T}\right)\left(\mathbf{U}\mathbf{\Sigma}\mathbf{V}^\text{T}\right)^\text{T}$ $\mathbf{X}\mathbf{X}^\text{T} = \left(\mathbf{U}\mathbf{\Sigma}\mathbf{V}^\text{T}\right)\left(\mathbf{V}\mathbf{\Sigma}\mathbf{U}^\text{T}\right)$ and since $\mathbf{V}$ is an orthogonal matrix $\left(\mathbf{V}^\text{T}\mathbf{V}=\mathbf{I}\right),$ $\mathbf{X}\mathbf{X}^\text{T}=\left(\mathbf{U}\mathbf{\Sigma}^\mathbf{2}\mathbf{U}^\text{T}\right)$ Since it is in the form of an eigen-decomposition, the PCA solution given by performing the SVD decomposition of $\mathbf{X}$, for which the eigenvectors are then given by $\mathbf{U}$, and corresponding eigenvalues by the square of the singular values. #### [CPCA](http://www.shogun-toolbox.org/doc/en/3.0.0/classshogun_1_1CPCA.html) Class Reference (Shogun) CPCA class of Shogun inherits from the [CPreprocessor](http://www.shogun-toolbox.org/doc/en/3.0.0/classshogun_1_1CPreprocessor.html) class. Preprocessors are transformation functions that doesn't change the domain of the input features. Specifically, CPCA performs principal component analysis on the input vectors and keeps only the specified number of eigenvectors. On preprocessing, the stored covariance matrix is used to project vectors into eigenspace. Performance of PCA depends on the algorithm used according to the situation in hand. Our PCA preprocessor class provides 3 method options to compute the transformation matrix: * $\text{PCA(EVD)}$ sets $\text{PCAmethod == EVD}$ : Eigen Value Decomposition of Covariance Matrix $(\mathbf{XX^T}).$ The covariance matrix $\mathbf{XX^T}$ is first formed internally and then its eigenvectors and eigenvalues are computed using QR decomposition of the matrix. The time complexity of this method is $\mathcal{O}(D^3)$ and should be used when $\text{N > D.}$ * $\text{PCA(SVD)}$ sets $\text{PCAmethod == SVD}$ : Singular Value Decomposition of feature matrix $\mathbf{X}$. The transpose of feature matrix, $\mathbf{X^T}$, is decomposed using SVD. $\mathbf{X^T = UDV^T}.$ The matrix V in this decomposition contains the required eigenvectors and the diagonal entries of the diagonal matrix D correspond to the non-negative eigenvalues.The time complexity of this method is $\mathcal{O}(DN^2)$ and should be used when $\text{N < D.}$ * $\text{PCA(AUTO)}$ sets $\text{PCAmethod == AUTO}$ : This mode automagically chooses one of the above modes for the user based on whether $\text{N>D}$ (chooses $\text{EVD}$) or $\text{N<D}$ (chooses $\text{SVD}$) ## PCA on 2D data #### Step 1: Get some data We will generate the toy data by adding orthogonal noise to a set of points lying on an arbitrary 2d line. We expect PCA to recover this line, which is a one-dimensional linear sub-space. ``` #number of data points. n=100 #generate a random 2d line(y1 = mx1 + c) m = random.randint(1,10) c = random.randint(1,10) x1 = random.random_integers(-20,20,n) y1=m*x1+c #generate the noise. noise=random.random_sample([n]) * random.random_integers(-35,35,n) #make the noise orthogonal to the line y=mx+c and add it. x=x1 + noise*m/sqrt(1+square(m)) y=y1 + noise/sqrt(1+square(m)) twoD_obsmatrix=array([x,y]) #to visualise the data we must plot it. rcParams['figure.figsize'] = 7, 7 figure,axis=subplots(1,1) xlim(-50,50) ylim(-50,50) axis.plot(twoD_obsmatrix[0,:],twoD_obsmatrix[1,:],'o',color='green',markersize=6) #the line from which we generated the data is plotted in red axis.plot(x1[:],y1[:],linewidth=0.3,color='red') title('One-Dimensional sub-space with noise') xlabel("x axis") _=ylabel("y axis") ``` #### Step 2: Subtract the mean. For PCA to work properly, we must subtract the mean from each of the data dimensions. The mean subtracted is the average across each dimension. So, all the $x$ values have $\bar{x}$ subtracted, and all the $y$ values have $\bar{y}$ subtracted from them, where:$$\bar{\mathbf{x}} = \frac{\sum\limits_{i=1}^{n}x_i}{n}$$ $\bar{\mathbf{x}}$ denotes the mean of the $x_i^{'s}$ ##### Shogun's way of doing things : Preprocessor PCA performs principial component analysis on input feature vectors/matrices. It provides an interface to set the target dimension by $\text{put('target_dim', target_dim) method}.$ When the $\text{init()}$ method in $\text{PCA}$ is called with proper feature matrix $\text{X}$ (with say $\text{N}$ number of vectors and $\text{D}$ feature dimension), a transformation matrix is computed and stored internally.It inherenty also centralizes the data by subtracting the mean from it. ``` #convert the observation matrix into dense feature matrix. train_features = features(twoD_obsmatrix) #PCA(EVD) is choosen since N=100 and D=2 (N>D). #However we can also use PCA(AUTO) as it will automagically choose the appropriate method. preprocessor = PCA(EVD) #since we are projecting down the 2d data, the target dim is 1. But here the exhaustive method is detailed by #setting the target dimension to 2 to visualize both the eigen vectors. #However, in future examples we will get rid of this step by implementing it directly. preprocessor.put('target_dim', 2) #Centralise the data by subtracting its mean from it. preprocessor.init(train_features) #get the mean for the respective dimensions. mean_datapoints=preprocessor.get_real_vector('mean_vector') mean_x=mean_datapoints[0] mean_y=mean_datapoints[1] ``` #### Step 3: Calculate the covariance matrix To understand the relationship between 2 dimension we define $\text{covariance}$. It is a measure to find out how much the dimensions vary from the mean $with$ $respect$ $to$ $each$ $other.$$$cov(X,Y)=\frac{\sum\limits_{i=1}^{n}(X_i-\bar{X})(Y_i-\bar{Y})}{n-1}$$ A useful way to get all the possible covariance values between all the different dimensions is to calculate them all and put them in a matrix. Example: For a 3d dataset with usual dimensions of $x,y$ and $z$, the covariance matrix has 3 rows and 3 columns, and the values are this: $$\mathbf{S} = \quad\begin{pmatrix}cov(x,x)&cov(x,y)&cov(x,z)\\cov(y,x)&cov(y,y)&cov(y,z)\\cov(z,x)&cov(z,y)&cov(z,z)\end{pmatrix}$$ #### Step 4: Calculate the eigenvectors and eigenvalues of the covariance matrix Find the eigenvectors $e^1,....e^M$ of the covariance matrix $\mathbf{S}$. ##### Shogun's way of doing things : Step 3 and Step 4 are directly implemented by the PCA preprocessor of Shogun toolbar. The transformation matrix is essentially a $\text{D}$$\times$$\text{M}$ matrix, the columns of which correspond to the eigenvectors of the covariance matrix $(\text{X}\text{X}^\text{T})$ having top $\text{M}$ eigenvalues. ``` #Get the eigenvectors(We will get two of these since we set the target to 2). E = preprocessor.get_real_matrix('transformation_matrix') #Get all the eigenvalues returned by PCA. eig_value=preprocessor.get_real_vector('eigenvalues_vector') e1 = E[:,0] e2 = E[:,1] eig_value1 = eig_value[0] eig_value2 = eig_value[1] ``` #### Step 5: Choosing components and forming a feature vector. Lets visualize the eigenvectors and decide upon which to choose as the $principle$ $component$ of the data set. ``` #find out the M eigenvectors corresponding to top M number of eigenvalues and store it in E #Here M=1 #slope of e1 & e2 m1=e1[1]/e1[0] m2=e2[1]/e2[0] #generate the two lines x1=range(-50,50) x2=x1 y1=multiply(m1,x1) y2=multiply(m2,x2) #plot the data along with those two eigenvectors figure, axis = subplots(1,1) xlim(-50, 50) ylim(-50, 50) axis.plot(x[:], y[:],'o',color='green', markersize=5, label="green") axis.plot(x1[:], y1[:], linewidth=0.7, color='black') axis.plot(x2[:], y2[:], linewidth=0.7, color='blue') p1 = Rectangle((0, 0), 1, 1, fc="black") p2 = Rectangle((0, 0), 1, 1, fc="blue") legend([p1,p2],["1st eigenvector","2nd eigenvector"],loc='center left', bbox_to_anchor=(1, 0.5)) title('Eigenvectors selection') xlabel("x axis") _=ylabel("y axis") ``` In the above figure, the blue line is a good fit of the data. It shows the most significant relationship between the data dimensions. It turns out that the eigenvector with the $highest$ eigenvalue is the $principle$ $component$ of the data set. Form the matrix $\mathbf{E}=[\mathbf{e}^1,...,\mathbf{e}^M].$ Here $\text{M}$ represents the target dimension of our final projection ``` #The eigenvector corresponding to higher eigenvalue(i.e eig_value2) is choosen (i.e e2). #E is the feature vector. E=e2 ``` #### Step 6: Projecting the data to its Principal Components. This is the final step in PCA. Once we have choosen the components(eigenvectors) that we wish to keep in our data and formed a feature vector, we simply take the vector and multiply it on the left of the original dataset. The lower dimensional representation of each data point $\mathbf{x}^n$ is given by $\mathbf{y}^n=\mathbf{E}^T(\mathbf{x}^n-\mathbf{m})$ Here the $\mathbf{E}^T$ is the matrix with the eigenvectors in rows, with the most significant eigenvector at the top. The mean adjusted data, with data items in each column, with each row holding a seperate dimension is multiplied to it. ##### Shogun's way of doing things : Step 6 can be performed by shogun's PCA preprocessor as follows: The transformation matrix that we got after $\text{init()}$ is used to transform all $\text{D-dim}$ feature matrices (with $\text{D}$ feature dimensions) supplied, via $\text{apply_to_feature_matrix methods}$.This transformation outputs the $\text{M-Dim}$ approximation of all these input vectors and matrices (where $\text{M}$ $\leq$ $\text{min(D,N)}$). ``` #transform all 2-dimensional feature matrices to target-dimensional approximations. yn=preprocessor.apply_to_feature_matrix(train_features) #Since, here we are manually trying to find the eigenvector corresponding to the top eigenvalue. #The 2nd row of yn is choosen as it corresponds to the required eigenvector e2. yn1=yn[1,:] ``` Step 5 and Step 6 can be applied directly with Shogun's PCA preprocessor (from next example). It has been done manually here to show the exhaustive nature of Principal Component Analysis. #### Step 7: Form the approximate reconstruction of the original data $\mathbf{x}^n$ The approximate reconstruction of the original datapoint $\mathbf{x}^n$ is given by : $\tilde{\mathbf{x}}^n\approx\text{m}+\mathbf{E}\mathbf{y}^n$ ``` x_new=(yn1 * E[0]) + tile(mean_x,[n,1]).T[0] y_new=(yn1 * E[1]) + tile(mean_y,[n,1]).T[0] ``` The new data is plotted below ``` figure, axis = subplots(1,1) xlim(-50, 50) ylim(-50, 50) axis.plot(x[:], y[:],'o',color='green', markersize=5, label="green") axis.plot(x_new, y_new, 'o', color='blue', markersize=5, label="red") title('PCA Projection of 2D data into 1D subspace') xlabel("x axis") ylabel("y axis") #add some legend for information p1 = Rectangle((0, 0), 1, 1, fc="r") p2 = Rectangle((0, 0), 1, 1, fc="g") p3 = Rectangle((0, 0), 1, 1, fc="b") legend([p1,p2,p3],["normal projection","2d data","1d projection"],loc='center left', bbox_to_anchor=(1, 0.5)) #plot the projections in red: for i in range(n): axis.plot([x[i],x_new[i]],[y[i],y_new[i]] , color='red') ``` ## PCA on a 3d data. #### Step1: Get some data We generate points from a plane and then add random noise orthogonal to it. The general equation of a plane is: $$\text{a}\mathbf{x}+\text{b}\mathbf{y}+\text{c}\mathbf{z}+\text{d}=0$$ ``` rcParams['figure.figsize'] = 8,8 #number of points n=100 #generate the data a=random.randint(1,20) b=random.randint(1,20) c=random.randint(1,20) d=random.randint(1,20) x1=random.random_integers(-20,20,n) y1=random.random_integers(-20,20,n) z1=-(a*x1+b*y1+d)/c #generate the noise noise=random.random_sample([n])*random.random_integers(-30,30,n) #the normal unit vector is [a,b,c]/magnitude magnitude=sqrt(square(a)+square(b)+square(c)) normal_vec=array([a,b,c]/magnitude) #add the noise orthogonally x=x1+noise*normal_vec[0] y=y1+noise*normal_vec[1] z=z1+noise*normal_vec[2] threeD_obsmatrix=array([x,y,z]) #to visualize the data, we must plot it. from mpl_toolkits.mplot3d import Axes3D fig = pyplot.figure() ax=fig.add_subplot(111, projection='3d') #plot the noisy data generated by distorting a plane ax.scatter(x, y, z,marker='o', color='g') ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_zlabel('z label') legend([p2],["3d data"],loc='center left', bbox_to_anchor=(1, 0.5)) title('Two dimensional subspace with noise') xx, yy = meshgrid(range(-30,30), range(-30,30)) zz=-(a * xx + b * yy + d) / c ``` #### Step 2: Subtract the mean. ``` #convert the observation matrix into dense feature matrix. train_features = features(threeD_obsmatrix) #PCA(EVD) is choosen since N=100 and D=3 (N>D). #However we can also use PCA(AUTO) as it will automagically choose the appropriate method. preprocessor = PCA(EVD) #If we set the target dimension to 2, Shogun would automagically preserve the required 2 eigenvectors(out of 3) according to their #eigenvalues. preprocessor.put('target_dim', 2) preprocessor.init(train_features) #get the mean for the respective dimensions. mean_datapoints=preprocessor.get_real_vector('mean_vector') mean_x=mean_datapoints[0] mean_y=mean_datapoints[1] mean_z=mean_datapoints[2] ``` #### Step 3 & Step 4: Calculate the eigenvectors of the covariance matrix ``` #get the required eigenvectors corresponding to top 2 eigenvalues. E = preprocessor.get_real_matrix('transformation_matrix') ``` #### Steps 5: Choosing components and forming a feature vector. Since we performed PCA for a target $\dim = 2$ for the $3 \dim$ data, we are directly given the two required eigenvectors in $\mathbf{E}$ E is automagically filled by setting target dimension = M. This is different from the 2d data example where we implemented this step manually. #### Step 6: Projecting the data to its Principal Components. ``` #This can be performed by shogun's PCA preprocessor as follows: yn=preprocessor.apply_to_feature_matrix(train_features) ``` #### Step 7: Form the approximate reconstruction of the original data $\mathbf{x}^n$ The approximate reconstruction of the original datapoint $\mathbf{x}^n$ is given by : $\tilde{\mathbf{x}}^n\approx\text{m}+\mathbf{E}\mathbf{y}^n$ ``` new_data=dot(E,yn) x_new=new_data[0,:]+tile(mean_x,[n,1]).T[0] y_new=new_data[1,:]+tile(mean_y,[n,1]).T[0] z_new=new_data[2,:]+tile(mean_z,[n,1]).T[0] #all the above points lie on the same plane. To make it more clear we will plot the projection also. fig=pyplot.figure() ax=fig.add_subplot(111, projection='3d') ax.scatter(x, y, z,marker='o', color='g') ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_zlabel('z label') legend([p1,p2,p3],["normal projection","3d data","2d projection"],loc='center left', bbox_to_anchor=(1, 0.5)) title('PCA Projection of 3D data into 2D subspace') for i in range(100): ax.scatter(x_new[i], y_new[i], z_new[i],marker='o', color='b') ax.plot([x[i],x_new[i]],[y[i],y_new[i]],[z[i],z_new[i]],color='r') ``` #### PCA Performance Uptill now, we were using the EigenValue Decomposition method to compute the transformation matrix$\text{(N>D)}$ but for the next example $\text{(N<D)}$ we will be using Singular Value Decomposition. ## Practical Example : Eigenfaces The problem with the image representation we are given is its high dimensionality. Two-dimensional $\text{p} \times \text{q}$ grayscale images span a $\text{m=pq}$ dimensional vector space, so an image with $\text{100}\times\text{100}$ pixels lies in a $\text{10,000}$ dimensional image space already. The question is, are all dimensions really useful for us? $\text{Eigenfaces}$ are based on the dimensional reduction approach of $\text{Principal Component Analysis(PCA)}$. The basic idea is to treat each image as a vector in a high dimensional space. Then, $\text{PCA}$ is applied to the set of images to produce a new reduced subspace that captures most of the variability between the input images. The $\text{Pricipal Component Vectors}$(eigenvectors of the sample covariance matrix) are called the $\text{Eigenfaces}$. Every input image can be represented as a linear combination of these eigenfaces by projecting the image onto the new eigenfaces space. Thus, we can perform the identfication process by matching in this reduced space. An input image is transformed into the $\text{eigenspace,}$ and the nearest face is identified using a $\text{Nearest Neighbour approach.}$ #### Step 1: Get some data. Here data means those Images which will be used for training purposes. ``` rcParams['figure.figsize'] = 10, 10 import os def get_imlist(path): """ Returns a list of filenames for all jpg images in a directory""" return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.pgm')] #set path of the training images path_train=os.path.join(SHOGUN_DATA_DIR, 'att_dataset/training/') #set no. of rows that the images will be resized. k1=100 #set no. of columns that the images will be resized. k2=100 filenames = get_imlist(path_train) filenames = array(filenames) #n is total number of images that has to be analysed. n=len(filenames) ``` Lets have a look on the data: ``` # we will be using this often to visualize the images out there. def showfig(image): imgplot=imshow(image, cmap='gray') imgplot.axes.get_xaxis().set_visible(False) imgplot.axes.get_yaxis().set_visible(False) from PIL import Image from scipy import misc # to get a hang of the data, lets see some part of the dataset images. fig = pyplot.figure() title('The Training Dataset') for i in range(49): fig.add_subplot(7,7,i+1) train_img=array(Image.open(filenames[i]).convert('L')) train_img=misc.imresize(train_img, [k1,k2]) showfig(train_img) ``` Represent every image $I_i$ as a vector $\Gamma_i$ ``` #To form the observation matrix obs_matrix. #read the 1st image. train_img = array(Image.open(filenames[0]).convert('L')) #resize it to k1 rows and k2 columns train_img=misc.imresize(train_img, [k1,k2]) #since features accepts only data of float64 datatype, we do a type conversion train_img=array(train_img, dtype='double') #flatten it to make it a row vector. train_img=train_img.flatten() # repeat the above for all images and stack all those vectors together in a matrix for i in range(1,n): temp=array(Image.open(filenames[i]).convert('L')) temp=misc.imresize(temp, [k1,k2]) temp=array(temp, dtype='double') temp=temp.flatten() train_img=vstack([train_img,temp]) #form the observation matrix obs_matrix=train_img.T ``` #### Step 2: Subtract the mean It is very important that the face images $I_1,I_2,...,I_M$ are $centered$ and of the $same$ size We observe here that the no. of $\dim$ for each image is far greater than no. of training images. This calls for the use of $\text{SVD}$. Setting the $\text{PCA}$ in the $\text{AUTO}$ mode does this automagically according to the situation. ``` train_features = features(obs_matrix) preprocessor=PCA(AUTO) preprocessor.put('target_dim', 100) preprocessor.init(train_features) mean=preprocessor.get_real_vector('mean_vector') ``` #### Step 3 & Step 4: Calculate the eigenvectors and eigenvalues of the covariance matrix. ``` #get the required eigenvectors corresponding to top 100 eigenvalues E = preprocessor.get_real_matrix('transformation_matrix') #lets see how these eigenfaces/eigenvectors look like: fig1 = pyplot.figure() title('Top 20 Eigenfaces') for i in range(20): a = fig1.add_subplot(5,4,i+1) eigen_faces=E[:,i].reshape([k1,k2]) showfig(eigen_faces) ``` These 20 eigenfaces are not sufficient for a good image reconstruction. Having more eigenvectors gives us the most flexibility in the number of faces we can reconstruct. Though we are adding vectors with low variance, they are in directions of change nonetheless, and an external image that is not in our database could in fact need these eigenvectors to get even relatively close to it. But at the same time we must also keep in mind that adding excessive eigenvectors results in addition of little or no variance, slowing down the process. Clearly a tradeoff is required. We here set for M=100. #### Step 5: Choosing components and forming a feature vector. Since we set target $\dim = 100$ for this $n \dim$ data, we are directly given the $100$ required eigenvectors in $\mathbf{E}$ E is automagically filled. This is different from the 2d data example where we implemented this step manually. #### Step 6: Projecting the data to its Principal Components. The lower dimensional representation of each data point $\mathbf{x}^n$ is given by $$\mathbf{y}^n=\mathbf{E}^T(\mathbf{x}^n-\mathbf{m})$$ ``` #we perform the required dot product. yn=preprocessor.apply_to_feature_matrix(train_features) ``` #### Step 7: Form the approximate reconstruction of the original image $I_n$ The approximate reconstruction of the original datapoint $\mathbf{x}^n$ is given by : $\mathbf{x}^n\approx\text{m}+\mathbf{E}\mathbf{y}^n$ ``` re=tile(mean,[n,1]).T[0] + dot(E,yn) #lets plot the reconstructed images. fig2 = pyplot.figure() title('Reconstructed Images from 100 eigenfaces') for i in range(1,50): re1 = re[:,i].reshape([k1,k2]) fig2.add_subplot(7,7,i) showfig(re1) ``` ## Recognition part. In our face recognition process using the Eigenfaces approach, in order to recognize an unseen image, we proceed with the same preprocessing steps as applied to the training images. Test images are represented in terms of eigenface coefficients by projecting them into face space$\text{(eigenspace)}$ calculated during training. Test sample is recognized by measuring the similarity distance between the test sample and all samples in the training. The similarity measure is a metric of distance calculated between two vectors. Traditional Eigenface approach utilizes $\text{Euclidean distance}$. ``` #set path of the training images path_train=os.path.join(SHOGUN_DATA_DIR, 'att_dataset/testing/') test_files=get_imlist(path_train) test_img=array(Image.open(test_files[0]).convert('L')) rcParams.update({'figure.figsize': (3, 3)}) #we plot the test image , for which we have to identify a good match from the training images we already have fig = pyplot.figure() title('The Test Image') showfig(test_img) #We flatten out our test image just the way we have done for the other images test_img=misc.imresize(test_img, [k1,k2]) test_img=array(test_img, dtype='double') test_img=test_img.flatten() #We centralise the test image by subtracting the mean from it. test_f=test_img-mean ``` Here we have to project our training image as well as the test image on the PCA subspace. The Eigenfaces method then performs face recognition by: 1. Projecting all training samples into the PCA subspace. 2. Projecting the query image into the PCA subspace. 3. Finding the nearest neighbour between the projected training images and the projected query image. ``` #We have already projected our training images into pca subspace as yn. train_proj = yn #Projecting our test image into pca subspace test_proj = dot(E.T, test_f) ``` ##### Shogun's way of doing things: Shogun uses [CEuclideanDistance](http://www.shogun-toolbox.org/doc/en/3.0.0/classshogun_1_1CEuclideanDistance.html) class to compute the familiar Euclidean distance for real valued features. It computes the square root of the sum of squared disparity between the corresponding feature dimensions of two data points. $\mathbf{d(x,x')=}$$\sqrt{\mathbf{\sum\limits_{i=0}^{n}}|\mathbf{x_i}-\mathbf{x'_i}|^2}$ ``` #To get Eucledian Distance as the distance measure use EuclideanDistance. workfeat = features(mat(train_proj)) testfeat = features(mat(test_proj).T) RaRb=EuclideanDistance(testfeat, workfeat) #The distance between one test image w.r.t all the training is stacked in matrix d. d=empty([n,1]) for i in range(n): d[i]= RaRb.distance(0,i) #The one having the minimum distance is found out min_distance_index = d.argmin() iden=array(Image.open(filenames[min_distance_index])) title('Identified Image') showfig(iden) ``` ## References: [1] David Barber. Bayesian Reasoning and Machine Learning. [2] Lindsay I Smith. A tutorial on Principal Component Analysis. [3] Philipp Wanger. Face Recognition with GNU Octave/MATLAB.
github_jupyter
``` # Making our own objects class Foo: def hi(self): # self is the first parameter by convention print(self) # self is a pointer to the object f = Foo() # create Foo class object f.hi() f Foo.hi # Constructor class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name} is {self.age} years old.' person = Person('Mahin', 22) str(person) # note: call str(object) calls obj.__str__() dir(person) # showing all of the methods in person object. # litle test class Person: def __init__(self, name, age): self.name = name self.age = age """__len__ return integer """ def __len__(self): return len(self.name) + 10 person = Person('Mahin', 23) print(len(person)) # Haha 15. That's works. # Fields class Person: """name and age are fileds, that are accessed by dot""" def __init__(self, name, age): self.name = name self.age = age def grow_up(self): self.age = self.age + 1 person = Person('Mahin', 22) person.age # access by dot person.grow_up() person.age # __init__ vs __new__ ################### 1 ################################# class Test: """ cls: class Test itself. Not object of class Test. It class itself """ def __new__(cls, x): print(f'__new__, cls={cls}') # return super().__new__(cls) def __init__(self, x): print(f'__init__, self={self}') self.x = x test = Test(2) test.x # see the difference ############################### 2 ###################### class Test: """ cls: class Test itself. Not object of class Test. It class itself """ def __new__(cls, x): print(f'__new__, cls={cls}') return super().__new__(cls) def __init__(self, x): print(f'__init__, self={self}') self.x = x test = Test(3) test.x ######################## 3 #################### class Test: """ cls: class Test itself. Not object of class Test. It class itself """ def __new__(cls, x): print(f'__new__, cls={cls}') return super().__new__(cls) def __init__(self, x): print(f'__init__, self={self}') self.x = x def __repr__(self): return 'Are you kidding me!!!' test = Test(4) test.x # eveything is an object type(1) type(1).mro() # Method Resolution Order. Show Inheritance Hierarchy type('name').mro() type(print).mro() 'hi' == 'hi' id('hi') 'hi'.__eq__('hi') 1 == 2 (1).__eq__(2) # Duck Typing def reverse(string): out = str() for i in string: out = i + out return out print(reverse('hello')) print(reverse(343)) print(reverse(['a', 'b', 'cd'])) # unexpected behavior. Did you get it??? type(dict()).__dict__ ```
github_jupyter
# Forecasting in statsmodels This notebook describes forecasting using time series models in statsmodels. **Note**: this notebook applies only to the state space model classes, which are: - `sm.tsa.SARIMAX` - `sm.tsa.UnobservedComponents` - `sm.tsa.VARMAX` - `sm.tsa.DynamicFactor` ``` %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt macrodata = sm.datasets.macrodata.load_pandas().data macrodata.index = pd.period_range('1959Q1', '2009Q3', freq='Q') ``` ## Basic example A simple example is to use an AR(1) model to forecast inflation. Before forecasting, let's take a look at the series: ``` endog = macrodata['infl'] endog.plot(figsize=(15, 5)) ``` ### Constructing and estimating the model The next step is to formulate the econometric model that we want to use for forecasting. In this case, we will use an AR(1) model via the `SARIMAX` class in statsmodels. After constructing the model, we need to estimate its parameters. This is done using the `fit` method. The `summary` method produces several convenient tables showing the results. ``` # Construct the model mod = sm.tsa.SARIMAX(endog, order=(1, 0, 0), trend='c') # Estimate the parameters res = mod.fit() print(res.summary()) ``` ### Forecasting Out-of-sample forecasts are produced using the `forecast` or `get_forecast` methods from the results object. The `forecast` method gives only point forecasts. ``` # The default is to get a one-step-ahead forecast: print(res.forecast()) ``` The `get_forecast` method is more general, and also allows constructing confidence intervals. ``` # Here we construct a more complete results object. fcast_res1 = res.get_forecast() # Most results are collected in the `summary_frame` attribute. # Here we specify that we want a confidence level of 90% print(fcast_res1.summary_frame(alpha=0.10)) ``` The default confidence level is 95%, but this can be controlled by setting the `alpha` parameter, where the confidence level is defined as $(1 - \alpha) \times 100\%$. In the example above, we specified a confidence level of 90%, using `alpha=0.10`. ### Specifying the number of forecasts Both of the functions `forecast` and `get_forecast` accept a single argument indicating how many forecasting steps are desired. One option for this argument is always to provide an integer describing the number of steps ahead you want. ``` print(res.forecast(steps=2)) fcast_res2 = res.get_forecast(steps=2) # Note: since we did not specify the alpha parameter, the # confidence level is at the default, 95% print(fcast_res2.summary_frame()) ``` However, **if your data included a Pandas index with a defined frequency** (see the section at the end on Indexes for more information), then you can alternatively specify the date through which you want forecasts to be produced: ``` print(res.forecast('2010Q2')) fcast_res3 = res.get_forecast('2010Q2') print(fcast_res3.summary_frame()) ``` ### Plotting the data, forecasts, and confidence intervals Often it is useful to plot the data, the forecasts, and the confidence intervals. There are many ways to do this, but here's one example ``` fig, ax = plt.subplots(figsize=(15, 5)) # Plot the data (here we are subsetting it to get a better look at the forecasts) endog.loc['1999':].plot(ax=ax) # Construct the forecasts fcast = res.get_forecast('2011Q4').summary_frame() fcast['mean'].plot(ax=ax, style='k--') ax.fill_between(fcast.index, fcast['mean_ci_lower'], fcast['mean_ci_upper'], color='k', alpha=0.1); ``` ### Note on what to expect from forecasts The forecast above may not look very impressive, as it is almost a straight line. This is because this is a very simple, univariate forecasting model. Nonetheless, keep in mind that these simple forecasting models can be extremely competitive. ## Prediction vs Forecasting The results objects also contain two methods that all for both in-sample fitted values and out-of-sample forecasting. They are `predict` and `get_prediction`. The `predict` method only returns point predictions (similar to `forecast`), while the `get_prediction` method also returns additional results (similar to `get_forecast`). In general, if your interest is out-of-sample forecasting, it is easier to stick to the `forecast` and `get_forecast` methods. ## Cross validation **Note**: some of the functions used in this section were first introduced in statsmodels v0.11.0. A common use case is to cross-validate forecasting methods by performing h-step-ahead forecasts recursively using the following process: 1. Fit model parameters on a training sample 2. Produce h-step-ahead forecasts from the end of that sample 3. Compare forecasts against test dataset to compute error rate 4. Expand the sample to include the next observation, and repeat Economists sometimes call this a pseudo-out-of-sample forecast evaluation exercise, or time-series cross-validation. ### Example We will conduct a very simple exercise of this sort using the inflation dataset above. The full dataset contains 203 observations, and for expositional purposes we'll use the first 80% as our training sample and only consider one-step-ahead forecasts. A single iteration of the above procedure looks like the following: ``` # Step 1: fit model parameters w/ training sample training_obs = int(len(endog) * 0.8) training_endog = endog[:training_obs] training_mod = sm.tsa.SARIMAX( training_endog, order=(1, 0, 0), trend='c') training_res = training_mod.fit() # Print the estimated parameters print(training_res.params) # Step 2: produce one-step-ahead forecasts fcast = training_res.forecast() # Step 3: compute root mean square forecasting error true = endog.reindex(fcast.index) error = true - fcast # Print out the results print(pd.concat([true.rename('true'), fcast.rename('forecast'), error.rename('error')], axis=1)) ``` To add on another observation, we can use the `append` or `extend` results methods. Either method can produce the same forecasts, but they differ in the other results that are available: - `append` is the more complete method. It always stores results for all training observations, and it optionally allows refitting the model parameters given the new observations (note that the default is *not* to refit the parameters). - `extend` is a faster method that may be useful if the training sample is very large. It *only* stores results for the new observations, and it does not allow refitting the model parameters (i.e. you have to use the parameters estimated on the previous sample). If your training sample is relatively small (less than a few thousand observations, for example) or if you want to compute the best possible forecasts, then you should use the `append` method. However, if that method is infeasible (for example, because you have a very large training sample) or if you are okay with slightly suboptimal forecasts (because the parameter estimates will be slightly stale), then you can consider the `extend` method. A second iteration, using the `append` method and refitting the parameters, would go as follows (note again that the default for `append` does not refit the parameters, but we have overridden that with the `refit=True` argument): ``` # Step 1: append a new observation to the sample and refit the parameters append_res = training_res.append(endog[training_obs:training_obs + 1], refit=True) # Print the re-estimated parameters print(append_res.params) ``` Notice that these estimated parameters are slightly different than those we originally estimated. With the new results object, `append_res`, we can compute forecasts starting from one observation further than the previous call: ``` # Step 2: produce one-step-ahead forecasts fcast = append_res.forecast() # Step 3: compute root mean square forecasting error true = endog.reindex(fcast.index) error = true - fcast # Print out the results print(pd.concat([true.rename('true'), fcast.rename('forecast'), error.rename('error')], axis=1)) ``` Putting it altogether, we can perform the recursive forecast evaluation exercise as follows: ``` # Setup forecasts nforecasts = 3 forecasts = {} # Get the number of initial training observations nobs = len(endog) n_init_training = int(nobs * 0.8) # Create model for initial training sample, fit parameters init_training_endog = endog.iloc[:n_init_training] mod = sm.tsa.SARIMAX(training_endog, order=(1, 0, 0), trend='c') res = mod.fit() # Save initial forecast forecasts[training_endog.index[-1]] = res.forecast(steps=nforecasts) # Step through the rest of the sample for t in range(n_init_training, nobs): # Update the results by appending the next observation updated_endog = endog.iloc[t:t+1] res = res.append(updated_endog, refit=False) # Save the new set of forecasts forecasts[updated_endog.index[0]] = res.forecast(steps=nforecasts) # Combine all forecasts into a dataframe forecasts = pd.concat(forecasts, axis=1) print(forecasts.iloc[:5, :5]) ``` We now have a set of three forecasts made at each point in time from 1999Q2 through 2009Q3. We can construct the forecast errors by subtracting each forecast from the actual value of `endog` at that point. ``` # Construct the forecast errors forecast_errors = forecasts.apply(lambda column: endog - column).reindex(forecasts.index) print(forecast_errors.iloc[:5, :5]) ``` To evaluate our forecasts, we often want to look at a summary value like the root mean square error. Here we can compute that for each horizon by first flattening the forecast errors so that they are indexed by horizon and then computing the root mean square error fore each horizon. ``` # Reindex the forecasts by horizon rather than by date def flatten(column): return column.dropna().reset_index(drop=True) flattened = forecast_errors.apply(flatten) flattened.index = (flattened.index + 1).rename('horizon') print(flattened.iloc[:3, :5]) # Compute the root mean square error rmse = (flattened**2).mean(axis=1)**0.5 print(rmse) ``` #### Using `extend` We can check that we get similar forecasts if we instead use the `extend` method, but that they are not exactly the same as when we use `append` with the `refit=True` argument. This is because `extend` does not re-estimate the parameters given the new observation. ``` # Setup forecasts nforecasts = 3 forecasts = {} # Get the number of initial training observations nobs = len(endog) n_init_training = int(nobs * 0.8) # Create model for initial training sample, fit parameters init_training_endog = endog.iloc[:n_init_training] mod = sm.tsa.SARIMAX(training_endog, order=(1, 0, 0), trend='c') res = mod.fit() # Save initial forecast forecasts[training_endog.index[-1]] = res.forecast(steps=nforecasts) # Step through the rest of the sample for t in range(n_init_training, nobs): # Update the results by appending the next observation updated_endog = endog.iloc[t:t+1] res = res.extend(updated_endog) # Save the new set of forecasts forecasts[updated_endog.index[0]] = res.forecast(steps=nforecasts) # Combine all forecasts into a dataframe forecasts = pd.concat(forecasts, axis=1) print(forecasts.iloc[:5, :5]) # Construct the forecast errors forecast_errors = forecasts.apply(lambda column: endog - column).reindex(forecasts.index) print(forecast_errors.iloc[:5, :5]) # Reindex the forecasts by horizon rather than by date def flatten(column): return column.dropna().reset_index(drop=True) flattened = forecast_errors.apply(flatten) flattened.index = (flattened.index + 1).rename('horizon') print(flattened.iloc[:3, :5]) # Compute the root mean square error rmse = (flattened**2).mean(axis=1)**0.5 print(rmse) ``` By not re-estimating the parameters, our forecasts are slightly worse (the root mean square error is higher at each horizon). However, the process is faster, even with only 200 datapoints. Using the `%%timeit` cell magic on the cells above, we found a runtime of 570ms using `extend` versus 1.7s using `append` with `refit=True`. (Note that using `extend` is also faster than using `append` with `refit=False`). ## Indexes Throughout this notebook, we have been making use of Pandas date indexes with an associated frequency. As you can see, this index marks our data as at a quarterly frequency, between 1959Q1 and 2009Q3. ``` print(endog.index) ``` In most cases, if your data has an associated data/time index with a defined frequency (like quarterly, monthly, etc.), then it is best to make sure your data is a Pandas series with the appropriate index. Here are three examples of this: ``` # Annual frequency, using a PeriodIndex index = pd.period_range(start='2000', periods=4, freq='A') endog1 = pd.Series([1, 2, 3, 4], index=index) print(endog1.index) # Quarterly frequency, using a DatetimeIndex index = pd.date_range(start='2000', periods=4, freq='QS') endog2 = pd.Series([1, 2, 3, 4], index=index) print(endog2.index) # Monthly frequency, using a DatetimeIndex index = pd.date_range(start='2000', periods=4, freq='M') endog3 = pd.Series([1, 2, 3, 4], index=index) print(endog3.index) ``` In fact, if your data has an associated date/time index, it is best to use that even if does not have a defined frequency. An example of that kind of index is as follows - notice that it has `freq=None`: ``` index = pd.DatetimeIndex([ '2000-01-01 10:08am', '2000-01-01 11:32am', '2000-01-01 5:32pm', '2000-01-02 6:15am']) endog4 = pd.Series([0.2, 0.5, -0.1, 0.1], index=index) print(endog4.index) ``` You can still pass this data to statsmodels' model classes, but you will get the following warning, that no frequency data was found: ``` mod = sm.tsa.SARIMAX(endog4) res = mod.fit() ``` What this means is that you cannot specify forecasting steps by dates, and the output of the `forecast` and `get_forecast` methods will not have associated dates. The reason is that without a given frequency, there is no way to determine what date each forecast should be assigned to. In the example above, there is no pattern to the date/time stamps of the index, so there is no way to determine what the next date/time should be (should it be in the morning of 2000-01-02? the afternoon? or maybe not until 2000-01-03?). For example, if we forecast one-step-ahead: ``` res.forecast(1) ``` The index associated with the new forecast is `4`, because if the given data had an integer index, that would be the next value. A warning is given letting the user know that the index is not a date/time index. If we try to specify the steps of the forecast using a date, we will get the following exception: KeyError: 'The `end` argument could not be matched to a location related to the index of the data.' ``` # Here we'll catch the exception to prevent printing too much of # the exception trace output in this notebook try: res.forecast('2000-01-03') except KeyError as e: print(e) ``` Ultimately there is nothing wrong with using data that does not have an associated date/time frequency, or even using data that has no index at all, like a Numpy array. However, if you can use a Pandas series with an associated frequency, you'll have more options for specifying your forecasts and get back results with a more useful index.
github_jupyter
# Ex2 - Getting and Knowing your Data Check out [Chipotle Exercises Video Tutorial](https://www.youtube.com/watch?v=lpuYZ5EUyS8&list=PLgJhDSE2ZLxaY_DigHeiIDC1cD09rXgJv&index=2) to watch a data scientist go through the exercises This time we are going to pull data directly from the internet. Special thanks to: https://github.com/justmarkham for sharing the dataset and materials. ### Step 1. Import the necessary libraries ``` import pandas as pd import numpy as np ``` ### Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv). ### Step 3. Assign it to a variable called chipo. ``` url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv' chipo = pd.read_csv(url, sep = '\t') ``` ### Step 4. See the first 10 entries ``` chipo.head(10) ``` ### Step 5. What is the number of observations in the dataset? ``` # Solution 1 chipo.shape[0] # entries <= 4622 observations # Solution 2 chipo.info() # entries <= 4622 observations ``` ### Step 6. What is the number of columns in the dataset? ``` chipo.shape[1] ``` ### Step 7. Print the name of all the columns. ``` chipo.columns ``` ### Step 8. How is the dataset indexed? ``` chipo.index ``` ### Step 9. Which was the most-ordered item? ``` c = chipo.groupby('item_name') c = c.sum() c = c.sort_values(['quantity'], ascending=False) c.head(1) ``` ### Step 10. For the most-ordered item, how many items were ordered? ``` c = chipo.groupby('item_name') c = c.sum() c = c.sort_values(['quantity'], ascending=False) c.head(1) ``` ### Step 11. What was the most ordered item in the choice_description column? ``` c = chipo.groupby('choice_description').sum() c = c.sort_values(['quantity'], ascending=False) c.head(1) # Diet Coke 159 ``` ### Step 12. How many items were orderd in total? ``` total_items_orders = chipo.quantity.sum() total_items_orders ``` ### Step 13. Turn the item price into a float #### Step 13.a. Check the item price type ``` chipo.item_price.dtype ``` #### Step 13.b. Create a lambda function and change the type of item price ``` dollarizer = lambda x: float(x[1:-1]) chipo.item_price = chipo.item_price.apply(dollarizer) ``` #### Step 13.c. Check the item price type ``` chipo.item_price.dtype ``` ### Step 14. How much was the revenue for the period in the dataset? ``` revenue = (chipo['quantity']* chipo['item_price']).sum() print('Revenue was: $' + str(np.round(revenue,2))) ``` ### Step 15. How many orders were made in the period? ``` orders = chipo.order_id.value_counts().count() orders ``` ### Step 16. What is the average revenue amount per order? ``` # Solution 1 chipo['revenue'] = chipo['quantity'] * chipo['item_price'] order_grouped = chipo.groupby(by=['order_id']).sum() order_grouped.mean()['revenue'] # Solution 2 chipo.groupby(by=['order_id']).sum().mean()['revenue'] ``` ### Step 17. How many different items are sold? ``` chipo.item_name.value_counts().count() ```
github_jupyter
# Tensor shape After the raw and waveform data are loaded from external files, they are stored as Numpy array. However, to use those data in Pytorch, we need to further convert the Numpy arrays to Pytorch tensors. Conversion from Numpy array to Pytorch tensor is straightforward (see [Pytorch tutorial](https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#numpy-bridge)). However, what is difficult is that different Pytorch APIs may expect different tensor shapes. In this notebook, we mainly explain the semantics of tensor dimension for this NSF Pytorch project. **Tensor shape**: we assume all tensors are in shape **(batchsize, length, dim-1, dim-2, ...)**, where * batchsize: batch size of a data batch; * length: maximum length of data sequences in the batch; * dim-1: dimension of feature vector in one time step; * dim-2: when a feature vector per time step has more than 1 dimension; Note that *Length* is equivalent to the number of frames or number of waveform sampling points. <!-- Hidden layers should not change **batchsize** and **length** of input tensors unless specified (e.g., in down-sampling, up-sampling layers) --> ### 1. Examples on tensor shape ``` # At the begining, let's load packages from __future__ import absolute_import from __future__ import print_function import sys import numpy as np import torch import tool_lib import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['figure.figsize'] = (10, 5) # load mel and F0 mel_dim = 80 input_mel = tool_lib.read_raw_mat("data_models/acoustic_features/hn_nsf/slt_arctic_b0474.mfbsp", mel_dim) # convert it into the required tensor format input_mel_tensor = torch.tensor(input_mel).unsqueeze(0) print("Shape of original data: " + str(input_mel.shape)) print("Shape of data as tensor: " + str(input_mel_tensor.shape)) input_mel_tensor[0] - input_mel ``` In the example above, the input_mel_tensor has shape (1, 554, 80), where * 1: this batch has only one data * 554: the data has 554 frames * 80: each frame has 80 dimensions ### 2. Note In the tutorial notebooks, we manually add the dimension corresponding to batch and create tensors from the Numpy array. In NSF project-NN-Pytorch-scripts, the default data io wrapped over [torch.utils.data.Dataset](https://pytorch.org/docs/stable/data.html#map-style-datasets) and [torch.utils.data.DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) will automatically create tensor in (batchsize, N, M). Users just need to store the raw data in correct float32 format, the default data IO will automatically handle the conversion. <!-- When all the data files in the dataset have the same shape \[N, M\], the default IO can return a mini-batch (batchsize>1, N, M). Otherwise, it can only put a single sample in each mini-batch. --> In the tutorial notebooks, we may use batchsize>1 for demonstrations. In NSF project-NN-Pytorch-scripts, we only use batchsize=1 for NSF models training. ### 3. Misc Here is one function to plot tensors of shape (batchsize, length, dim) ``` import plot_lib import torch data = torch.zeros([2, 5, 3]) data[0] = torch.tensor([[1,2,3], [4,5,6], [7,8,9], [10,11,12],[13,14,15]]) data[1] = torch.tensor([[1,2,3], [4,5,6], [7,8,9], [10,11,12],[13,14,15]]) # example 1 plot_lib.plot_tensor(data.numpy(), color_on_value=True, shift=0.1, title='data in shape %s' % (str(data.shape))) plot_lib.plot_tensor(data[0:1], color_on_value=True, title='data[0:1]') plot_lib.plot_tensor(data[0:1].view(1, -1).unsqueeze(0), color_on_value=True, title='data[0:1].view(1,-1).unsqueeze(0)') # example 2 # plot_lib.plot_tensor(torch.tensor([[1,2,3,4,5]]).unsqueeze(0).permute(0, 2, 1), color_on_value=True) ``` The end
github_jupyter
### SketchGraphs demo In this notebook, we'll first go through various ways of representing and inspecting sketches in SketchGraphs. We'll then take a look at using Onshape's API in order to solve sketch constraints. ``` %load_ext autoreload %autoreload 2 import os import json from copy import deepcopy %matplotlib inline from matplotlib import pyplot as plt import numpy as np # cd to top-level directory if os.path.isdir('../sketchgraphs/'): os.chdir('../') import sketchgraphs.data as datalib from sketchgraphs.data import flat_array import sketchgraphs.onshape.call as onshape_call ``` Let's first load in some sketch construction sequences. In this example, we'll be using the [validation set](https://sketchgraphs.cs.princeton.edu/sequence/sg_t16_validation.npy) (see [documentation](https://princetonlips.github.io/SketchGraphs/data) for details). This notebook assumes the data file is already downloaded and located in a directory `sequence_data`. ``` seq_data = flat_array.load_dictionary_flat('sequence_data/sg_t16_validation.npy') seq_data['sequences'] ``` This file has 315,228 sequences. Let's take a look at some of the operations in one of the sequences. ``` seq = seq_data['sequences'][1327] print(*seq[:20], sep='\n') ``` We see that a construction sequence is a list of `NodeOp` and `EdgeOp` instances denoting the addition of primitives (also referred to as entities) and constraints, respectively. Now let's instantiate a `Sketch` object from this sequence and render it. ``` sketch = datalib.sketch_from_sequence(seq) datalib.render_sketch(sketch); ``` We can also render the sketch with a hand-drawn appearance using matplotlib's xkcd drawing mode. ``` datalib.render_sketch(sketch, hand_drawn=True); ``` Next, we'll build a graph representation of the sketch and visualize it with pygraphviz. ``` G = datalib.pgvgraph_from_sequence(seq) datalib.render_graph(G, '/tmp/my_graph.png') img = plt.imread('/tmp/my_graph.png') fig = plt.figure(dpi=500) plt.imshow(img[:, 500:1700]) plt.axis('off'); ``` The full graph image for this example is large so we only display a portion of it above. Node labels that begin with `SN` are _subnodes_, specifying a point on some primitive (e.g., an endpoint of a line segment). ### Solving We'll now take a look at how we can interact with Onshape's API in order to pass sketches to a geometric constraint solver. Various command line utilities for the API are defined in `sketchgraphs/onshape/call.py`. Onshape developer credentials are required for this. Visit https://princetonlips.github.io/SketchGraphs/onshape_setup for directions. The default path for credentials is `sketchgraphs/onshape/creds/creds.json`. We need to specify the URL of the Onshape document/PartStudio we'll be using. You should set the following `url` for your own document accordingly. ``` url = R'https://cad.onshape.com/documents/6f6d14f8facf0bba02184e88/w/66a5db71489c81f4893101ed/e/120c56983451157d26a7102d' ``` Let's test out Onshape's solver. We'll first make a copy of our sketch, remove its constraints, and manually add noise to the entity positions within Onshape's GUI. ``` no_constraint_sketch = deepcopy(sketch) no_constraint_sketch.constraints.clear() onshape_call.add_feature(url, no_constraint_sketch.to_dict(), 'No_Constraints_Sketch') ``` Before running the next code block, manually "mess up" the entities a bit in the GUI, i.e., drag the entities in order to leave the original constraints unsatisfied. The more drastic the change, the more difficult it will be for the solver to find a solution. Now we retrieve the noisy sketch. ``` unsolved_sketch_info = onshape_call.get_info(url, 'No_Constraints_Sketch') unsolved_sketch = datalib.Sketch.from_info(unsolved_sketch_info['geomEntities']) datalib.render_sketch(unsolved_sketch); ``` Next, let's add the constraints back in and (attempt to) solve them. ``` with_constraints_sketch = deepcopy(unsolved_sketch) with_constraints_sketch.constraints = sketch.constraints onshape_call.add_feature(url, with_constraints_sketch.to_dict(), 'With_Constraints_Sketch') solved_sketch_info = onshape_call.get_info(url, 'With_Constraints_Sketch') solved_sketch = datalib.Sketch.from_info(solved_sketch_info['geomEntities']) datalib.render_sketch(solved_sketch); ```
github_jupyter
``` import sqlite3 import pandas as pd def run_query(query): with sqlite3.connect('AreaOvitrap.db') as conn: return pd.read_sql(query,conn) def run_command(command): with sqlite3.connect('AreaOvitrap.db') as conn: conn.execute('PRAGMA foreign_keys = ON;') conn.isolation_level = None conn.execute(command) def show_tables(): query = ''' SELECT name, type From sqlite_master WHERE type IN ("type","view"); ''' return run_query(query) def district_code_generator(area): num_range = len(district_only[district_only['area_id'] == area]) for i in range(1,num_range+1): yield area + "D{:02d}".format(i) def location_code_generator(district_id): num_range = len(locations[locations['District_id'] == district_id]) for i in range(1,num_range+1): yield district_id + "{:02d}".format(i) def match_district(area_districts): for index,value in enumerate(locations['Eng']): for key, item in area_districts.items(): if value in item: locations.loc[index,'District'] = key return locations data = pd.read_csv("Area_Ovitrap_Index_Jan2008-Jul2018.csv") all_districts = { 'HK':{ 'Central Western':{'Central and Admiralty','Sai Wan','Sheung Wan and Sai Ying Pun'}, 'Eastern':{'Chai Wan West','Shau Kei Wan & Sai Wan Ho','North Point'}, 'Southern':{'Aberdeen and Ap Lei Chau','Pokfulam','Deep Water Bay & Repulse Bay'}, 'Wanchai':{'Tin Hau','Wan Chai North','Happy Valley'} }, 'KL':{ 'Yau Tsim':{'Tsim Sha Tsui','Tsim Sha Tsui East'}, 'Mong Kok':{'Mong Kok'}, 'Sham Shui Po':{'Cheung Sha Wan','Lai Chi Kok','Sham Shui Po East'}, 'Kowloon City':{'Ho Man Tin','Kowloon City North','Hung Hom','Lok Fu West','Kai Tak North'}, 'Wong Tai Sin':{'Wong Tai Sin Central','Diamond Hill','Ngau Chi Wan'}, 'Kwun Tong':{'Kwun Tong Central','Lam Tin','Yau Tong','Kowloon Bay'} }, 'NT':{ 'Sai Kung':{'Tseung Kwan O South','Tseung Kwan O North','Sai Kung Town'}, 'Sha Tin':{'Tai Wai','Yuen Chau Kok','Ma On Shan','Lek Yuen','Wo Che'}, 'Tai Po':{'Tai Po'}, 'North':{'Fanling','Sheung Shui'}, 'Yuen Long':{'Tin Shui Wai','Yuen Kong','Yuen Long Town'}, 'Tuen Mun':{'Tuen Mun North','Tuen Mun South','Tuen Mun West','So Kwun Wat'}, 'Tsuen Wan':{'Tsuen Wan Town','Tsuen Wan West','Ma Wan','Sheung Kwai Chung'}, 'Kwai Tsing':{'Kwai Chung','Lai King','Tsing Yi North','Tsing Yi South'} }, 'IL':{ 'Islands':{'Cheung Chau','Tung Chung'} } } # matching the Chinese and English names of the districts into variable "translations" chi_district = ['中西區','東區','南區','灣仔區','油尖區','旺角區','深水埗區','九龍城區','黃大仙區','觀塘區','西貢區','沙田區','大埔區','北區','元朗區','屯門區','荃灣區','葵青區','離島區'] eng_district = [] for area, district in all_districts.items(): for key, _ in district.items(): eng_district.append(key) translations = list(zip(eng_district,chi_district)) # group the districts into their corresponding area area_district = [] for area, district in all_districts.items(): for key,value in district.items(): area_district.append([area,key]) for index, value in enumerate(translations): area_district[index].append(value[1]) area_district # create a pandas dataframe for the data of all districts district_only = pd.DataFrame(area_district,columns=['area_id','eng_district','chi_district']) hk_code = district_code_generator('HK') # generate ID for main area "Hong Kong Island" kl_code = district_code_generator('KL') # generate ID for main area "Kowloon" nt_code = district_code_generator('NT') # generate ID for main area "New Territories" il_code = district_code_generator('IL') # generate ID for main area "Islands" district_code = [hk_code,kl_code,nt_code,il_code] for index,value in enumerate(district_only['area_id']): for i, area in enumerate(['HK','KL','NT','IL']): if value == area: district_only.loc[index,'District_id'] = next(district_code[i]) cols = district_only.columns.tolist() cols = cols[-1:]+cols[:-1] district_only = district_only[cols] area_dict = {'area_id':['HK','KL','IL','NT'], 'eng_area':['Hong Kong Island','Kowloon','Islands','New Territories'], 'chi_area':['香港島','九龍','離島','新界']} t_area = ''' CREATE TABLE IF NOT EXISTS area( area_id TEXT PRIMARY KEY, eng_area TEXT, chi_area TEXT ) ''' run_command(t_area) area = pd.DataFrame(area_dict) with sqlite3.connect("AreaOviTrap.db") as conn: area.to_sql('area',conn,if_exists='append',index=False) run_query("SELECT * FROM area") t_district = ''' CREATE TABLE IF NOT EXISTS district( district_id TEXT PRIMARY KEY, area_id TEXT, eng_district TEXT, chi_district TEXT, FOREIGN KEY (area_id) REFERENCES area(area_id) ) ''' run_command(t_district) with sqlite3.connect("AreaOviTrap.db") as conn: district_only.to_sql('district',conn,if_exists='append',index=False) run_query("SELECT * FROM district") # extracting unique location from the data eng_loc = data['Eng'].unique() chi_loc = data['Chi'].unique() locations = pd.DataFrame({'District':'','Eng':eng_loc,'Chi':chi_loc}) hk_districts = all_districts['HK'] kl_districts = all_districts['KL'] nt_districts = all_districts['NT'] il_districts = all_districts['IL'] four_district = [hk_districts,kl_districts,nt_districts,il_districts] # match the location with the correpsonding district for each in four_district: locations = match_district(each) # match the location with corresponding district_id for index, value in enumerate(locations['District']): for i, district in enumerate(district_only['eng_district']): if value == district: locations.loc[index,'District_id'] = district_only.loc[i,'District_id'] # generate Location_id by using location_code_generator unique_district_id = locations['District_id'].unique().tolist() for each in unique_district_id: code = location_code_generator(each) for index,value in enumerate(locations['District_id']): if value == each: locations.loc[index,'Location_id'] = next(code) locations.head() for index,value in enumerate(data['Eng']): for i, name in enumerate(locations['Eng']): if value == name: data.loc[index,'District_id'] = locations.loc[i,'District_id'] data.loc[index,'Location_id'] = locations.loc[i,'Location_id'] with sqlite3.connect('AreaOvitrap.db') as conn: data.to_sql('origin',conn,index=False) data.head(20) with sqlite3.connect('AreaOvitrap.db') as conn: data.to_sql('origin',conn,index=False) t_location = ''' CREATE TABLE IF NOT EXISTS location( location_id TEXT PRIMARY KEY, eng_location TEXT, chi_location TEXT, district_id, FOREIGN KEY (district_id) REFERENCES district(district_id) ) ''' location_data = ''' INSERT OR IGNORE INTO location SELECT DISTINCT Location_id, Eng, Chi, District_id FROM origin ''' run_command(t_location) run_command(location_data) t_aoi = ''' CREATE TABLE IF NOT EXISTS area_ovitrap_index( ID INTEGER PRIMARY KEY AUTOINCREMENT, location_id TEXT, date TEXT, AOI FLOAT, Classification INTEGER, FOREIGN KEY (location_id) REFERENCES location(location_id) ) ''' aoi_data = ''' INSERT OR IGNORE INTO area_ovitrap_index (location_id, date, AOI, Classification) SELECT Location_id, DATE, AOI, Classification FROM origin ''' run_command(t_aoi) run_command(aoi_data) run_command("DROP TABLE IF EXISTS origin") show_tables() ```
github_jupyter
# Load Data Bilder einlesen und Dateinamen anpassen ``` # OPTIONAL: Load the "autoreload" extension so that code can change %load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets loaded %autoreload 2 from src.data import make_dataset import warnings import pandas as pd # Deals with data excel_readings = pd.read_excel('../data/raw/moroweg_strom_gas.xlsx') excel_readings.head() manual_readings = excel_readings.iloc[:,[0,1,3,5]] manual_readings = manual_readings.melt(id_vars=["Date", "Kommentar"], var_name="Meter Type", value_name="Value") manual_readings[["Meter Type", "Unit"]] = manual_readings['Meter Type'].str.split(' ',expand=True) manual_readings = manual_readings[["Date", "Meter Type", "Unit", "Value", "Kommentar"]] manual_readings ## Code Snippet for exifread for a sample image import exifread import os #path_name = os.path.join(os.pardir, 'data', 'raw', '2017', '2017-03-03 15.06.47.jpg') path_name = "..\data\processed\gas\IMG_20200405_173910.jpg" # Open image file for reading (binary mode) f = open(path_name, 'rb') # Return Exif tags tags = exifread.process_file(f) # Show Tags for tag in tags.keys(): if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote'): print("Key: %s, value %s" % (tag, tags[tag])) def extract_file_meta(file_path): basename = os.path.basename(file_path) # Open image file for reading (binary mode) f = open(file_path, 'rb') # Read EXIF tags = exifread.process_file(f) try: exif_datetime = str(tags["EXIF DateTimeOriginal"]) except KeyError: warnings.warn("File {file_path} does not appear to have a date in EXIF Tags.".format(file_path=file_path)) return() #exif_datetime = "2020:01:01 00:00:00" # Format Date datetime = pd.to_datetime(exif_datetime, format = "%Y:%m:%d %H:%M:%S") date = pd.to_datetime(datetime.date()) return(basename, datetime, date, file_path) def meta_from_files(files): files_meta = [] for file_path in files: files_meta.append(extract_file_meta(file_path)) df = pd.DataFrame.from_records(files_meta, columns = ("Filename", "Datetime", "Date", "Filepath")) return(df) def meta_from_dir(dir_path): files = [top + os.sep + f for top, dirs, files in os.walk(dir_path) for f in files] files_meta = meta_from_files(files) return(files_meta) gas_dir = os.path.join(os.pardir, "data", "processed", "gas") gas_files_meta = meta_from_dir(gas_dir) gas_files_meta strom_dir = os.path.join(os.pardir, "data", "processed", "strom") strom_files_meta = meta_from_dir(strom_dir) strom_files_meta ``` ## Add Flag if Picture has been Labelled ``` gas_label_dir = os.path.join(os.pardir, "data", "labelled", "gas", "vott-json-export") gas_labelled_files = [os.path.basename(f) for top, dirs, files in os.walk(gas_label_dir) for f in files] gas_files_meta["Labelled"] = gas_files_meta.apply(lambda row: True if row["Filename"] in gas_labelled_files else False, axis=1) gas_files_meta strom_label_dir = os.path.join(os.pardir, "data", "labelled", "strom", "vott-json-export") strom_labelled_files = [os.path.basename(f) for top, dirs, files in os.walk(strom_label_dir) for f in files] strom_files_meta["Labelled"] = strom_files_meta.apply(lambda row: True if row["Filename"] in strom_labelled_files else False, axis=1) strom_files_meta ``` ## Join Picture Data with Manual Readings ### Strom ``` manual_readings.head(2) strom_readings_manual = manual_readings[manual_readings["Meter Type"] == "Strom"] strom_readings_manual.head(2) strom_files_meta.head(2) strom = strom_files_meta.merge(strom_readings_manual, left_on="Date", right_on="Date") strom ``` ### Gas ``` manual_readings.head(2) gas_readings_manual = manual_readings[manual_readings["Meter Type"] == "Gas"] gas_readings_manual.head(2) gas_files_meta.head(2) gas = gas_files_meta.merge(gas_readings_manual, left_on="Date", right_on="Date") gas ``` ## Return one dataframe in the end ``` dataset = pd.concat([strom, gas]) dataset dataset.to_csv("../data/processed/dataset.csv") ```
github_jupyter
``` %matplotlib inline from pyvista import set_plot_theme set_plot_theme('document') ``` Slicing {#slice_example} ======= Extract thin planar slices from a volume. ``` # sphinx_gallery_thumbnail_number = 2 import pyvista as pv from pyvista import examples import matplotlib.pyplot as plt import numpy as np ``` PyVista meshes have several slicing filters bound directly to all datasets. These filters allow you to slice through a volumetric dataset to extract and view sections through the volume of data. One of the most common slicing filters used in PyVista is the `pyvista.DataSetFilters.slice_orthogonal`{.interpreted-text role="func"} filter which creates three orthogonal slices through the dataset parallel to the three Cartesian planes. For example, let\'s slice through the sample geostatistical training image volume. First, load up the volume and preview it: ``` mesh = examples.load_channels() # define a categorical colormap cmap = plt.cm.get_cmap("viridis", 4) mesh.plot(cmap=cmap) ``` Note that this dataset is a 3D volume and there might be regions within this volume that we would like to inspect. We can create slices through the mesh to gain further insight about the internals of the volume. ``` slices = mesh.slice_orthogonal() slices.plot(cmap=cmap) ``` The orthogonal slices can be easily translated throughout the volume: ``` slices = mesh.slice_orthogonal(x=20, y=20, z=30) slices.plot(cmap=cmap) ``` We can also add just a single slice of the volume by specifying the origin and normal of the slicing plane with the `pyvista.DataSetFilters.slice`{.interpreted-text role="func"} filter: ``` # Single slice - origin defaults to the center of the mesh single_slice = mesh.slice(normal=[1, 1, 0]) p = pv.Plotter() p.add_mesh(mesh.outline(), color="k") p.add_mesh(single_slice, cmap=cmap) p.show() ``` Adding slicing planes uniformly across an axial direction can also be automated with the `pyvista.DataSetFilters.slice_along_axis`{.interpreted-text role="func"} filter: ``` slices = mesh.slice_along_axis(n=7, axis="y") slices.plot(cmap=cmap) ``` Slice Along Line ================ We can also slice a dataset along a `pyvista.Spline`{.interpreted-text role="func"} or `pyvista.Line`{.interpreted-text role="func"} using the `DataSetFilters.slice_along_line`{.interpreted-text role="func"} filter. First, define a line source through the dataset of interest. Please note that this type of slicing is computationally expensive and might take a while if there are a lot of points in the line - try to keep the resolution of the line low. ``` model = examples.load_channels() def path(y): """Equation: x = a(y-h)^2 + k""" a = 110.0 / 160.0 ** 2 x = a * y ** 2 + 0.0 return x, y x, y = path(np.arange(model.bounds[2], model.bounds[3], 15.0)) zo = np.linspace(9.0, 11.0, num=len(y)) points = np.c_[x, y, zo] spline = pv.Spline(points, 15) spline ``` Then run the filter ``` slc = model.slice_along_line(spline) slc p = pv.Plotter() p.add_mesh(slc, cmap=cmap) p.add_mesh(model.outline()) p.show(cpos=[1, -1, 1]) ``` Multiple Slices in Vector Direction =================================== Slice a mesh along a vector direction perpendicularly. ``` mesh = examples.download_brain() # Create vector vec = np.random.rand(3) # Normalize the vector normal = vec / np.linalg.norm(vec) # Make points along that vector for the extent of your slices a = mesh.center + normal * mesh.length / 3.0 b = mesh.center - normal * mesh.length / 3.0 # Define the line/points for the slices n_slices = 5 line = pv.Line(a, b, n_slices) # Generate all of the slices slices = pv.MultiBlock() for point in line.points: slices.append(mesh.slice(normal=normal, origin=point)) p = pv.Plotter() p.add_mesh(mesh.outline(), color="k") p.add_mesh(slices, opacity=0.75) p.add_mesh(line, color="red", line_width=5) p.show() ``` Slice At Different Bearings =========================== From [pyvista-support\#23](https://github.com/pyvista/pyvista-support/issues/23) An example of how to get many slices at different bearings all centered around a user-chosen location. Create a point to orient slices around ``` ranges = np.array(model.bounds).reshape(-1, 2).ptp(axis=1) point = np.array(model.center) - ranges*0.25 ``` Now generate a few normal vectors to rotate a slice around the z-axis. Use equation for circle since its about the Z-axis. ``` increment = np.pi/6. # use a container to hold all the slices slices = pv.MultiBlock() # treat like a dictionary/list for theta in np.arange(0, np.pi, increment): normal = np.array([np.cos(theta), np.sin(theta), 0.0]).dot(np.pi/2.) name = f'Bearing: {np.rad2deg(theta):.2f}' slices[name] = model.slice(origin=point, normal=normal) slices ``` And now display it! ``` p = pv.Plotter() p.add_mesh(slices, cmap=cmap) p.add_mesh(model.outline()) p.show() ```
github_jupyter
# Exporing Graph Datasets in Jupyter Juypter notebooks are perfect environments for both carrying out and capturing exporatory work. Even on moderate sizes datasets they provide an interactive environement that can drive both local and remote computational tasks. In this example, we will load a datatset using pandas, visualise it using the Graphistry graph service and import that into NetworkX so we can examine thje data and run analytics on the graph. ### Python Package Network Our raw python module requriements data comes in the form of a csv, which we use pands to load and cresate a DataFrame for us. Each python module (Node) is related to another via a version number (Edge) ``` import pandas rawgraph = pandas.read_csv('./requirements.csv') ``` We also print out the first 15 rows of the data and we can see it contains ``` print('Number of Entries', rawgraph.count()) rawgraph.head(15) ``` We notice straight away that our dataset has some NaN values for packages that have no requirements, this is a shortcoming of our dataset and we want to prevent those NaN's from propagating. There are a few ways to handle this depending on whether we want to preserve the nodes in the graph or not, in this example we'll just drop that data using pandas. ``` rawgraph.dropna(inplace=True) rawgraph.head(15) ``` ## Visualizing the Graph Efficient visualiations of anything but small graphs can be challenging in a local python environment, there are multiple ways around this but here we'll use a libreary and cloud based service called Graphisty. First we'll start up Graphistry using our API key in order to access the cloud based rendering service. ``` from os import environ from dotenv import load_dotenv, find_dotenv import graphistry load_dotenv(find_dotenv()) graphistry.register(key=environ.get("GRAPHISTRY_API_KEY")) ``` Next we'll plot the raw graph. Graphistry provides an awesome interactive plot widget in Juypter that of couerse allows us to interact with the graph itself but have more options. If you have tiome to play check out in particular: - Full screen mode - Layout settings (via the cogs icon) - Histograms and Data Table - The Workbook which launches an cloud based instance of Graphistry outside of Jupyter - Visual Clustering! ``` plotter = graphistry.bind(source="requirement", destination="package_name") plotter.plot(rawgraph) ``` Next we'll load our raw graph data into a NetworkX graph and run some analytics on the network. This dataset is heavily weighted by packages with a few requirements. Note: We are loading this as a DirectedGraph which will allow the direction of dependencies to be preserved. ``` import networkx as nx G = nx.from_pandas_dataframe(rawgraph, 'package_name', 'requirement', edge_attr='package_version', create_using=nx.DiGraph()) print('Nodes:', G.number_of_nodes()) print('Edges:', G.number_of_edges()) import numpy as np import matplotlib.pyplot as plt degrees = np.array(nx.degree_histogram(G)) plt.bar(range(1,20), degrees[1:20]) plt.xlabel('# requirements') plt.ylabel('# packages') plt.title('Degree - Dependencies per Package') plt.grid(True) plt.show() ``` We can see this network is dominated with packages with a single requirement, accounting for 37% of the nodes. ``` print('% of packages with only 1 requirement', '{:.1f}%'.format(100 * degrees[1] / G.number_of_nodes()), ',', degrees[1], 'packages total') highestDegree = len(degrees) - 1 nodesByDegree = G.degree() mostConnectedNode = [n for n in nodesByDegree if nodesByDegree[n] == highestDegree][0] print(mostConnectedNode) print('The package with most requirements is >',mostConnectedNode, '< having a total of', len(degrees), 'first order dependencies') ``` However, we are looking at all connections to requests in this directed graph, so this is a combination of it's dependencies and packages that are dependent on it. We can see how that is split by looking at the in and out degree. ``` print('Depencencies:', G.out_degree([mostConnectedNode])[mostConnectedNode]) print('Dependants:', G.in_degree([mostConnectedNode])[mostConnectedNode]) ``` So rather than having a lot of requirements, we've discovered that `requests` actually has few requirements and is instead a heavily used module. we can take a closer look by extracting a sub-graph of `requests`' immedate neighbours and visualising this. ``` R = G.subgraph([mostConnectedNode]+G.neighbors(mostConnectedNode)+G.predecessors(mostConnectedNode)) graphistry.bind(source="requirement", destination="package_name").plot(R) ``` Note the visualizaton above was created by plotting the sub graph then using Grapistry's Visual Clustering to do its stuff.
github_jupyter
# Forest Fire Mini Project > in this file, you can find analysis for this project. For the final report please visit `Report.ipynb` ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet from sklearn.preprocessing import LabelEncoder from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.ensemble import RandomForestRegressor from sklearn.feature_selection import RFE from sklearn.svm import SVR import warnings warnings.filterwarnings('ignore') %matplotlib inline ``` ## Introduction ### Data Information The Forest Fires data is available at UCI, to reach it please click [here](http://archive.ics.uci.edu/ml/datasets/Forest+Fires). The citation to this data set: [Cortez and Morais, 2007] P. Cortez and A. Morais. A Data Mining Approach to Predict Forest Fires using Meteorological Data. In J. Neves, M. F. Santos and J. Machado Eds., New Trends in Artificial Intelligence, Proceedings of the 13th EPIA 2007 - Portuguese Conference on Artificial Intelligence, December, Guimarães, Portugal, pp. 512-523, 2007. APPIA, ISBN-13 978-989-95618-0-9. Available at: [http://www.dsi.uminho.pt/~pcortez/fires.pdf](http://www3.dsi.uminho.pt/pcortez/fires.pdf) #### Attributes: 1. `X` - x-axis spatial coordinate within the Montesinho park map: 1 to 9 2. `Y` - y-axis spatial coordinate within the Montesinho park map: 2 to 9 3. `month` - month of the year: 'jan' to 'dec' 4. `day` - day of the week: 'mon' to 'sun' 5. `FFMC` - FFMC index from the FWI system: 18.7 to 96.20 6. `DMC` - DMC index from the FWI system: 1.1 to 291.3 7. `DC` - DC index from the FWI system: 7.9 to 860.6 8. `ISI` - ISI index from the FWI system: 0.0 to 56.10 9. `temp` - temperature in Celsius degrees: 2.2 to 33.30 10. `RH` - relative humidity in %: 15.0 to 100 11. `wind` - wind speed in km/h: 0.40 to 9.40 12. `rain` - outside rain in mm/m2 : 0.0 to 6.4 13. `area` - the burned area of the forest (in ha): 0.00 to 1090.84 #### Model and Feature Selection Process: I will also try predict the `area` variable via regression models. - First, I fit the data with all features to Random Forest Regression with pruned `depth` hyperparameters. - Then I will use to Lasso(L1 regularization) Regression and ElasticNet(L1+L2 regularization) Regression to select features. I will not use Ridge(L2 regularization) since it does not any exact zero weigthed features. - As last step, I will fit the data to Random Forest Regression with pruned `depth` hyperparameters onto both features selected by Lasso and ElasticNet. ``` # load the dataset: forestfires = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv") # Write the data frame to a csv file: forestfires.to_csv("../data/forestfires.csv", encoding='utf-8', index=False) forestfires.head() forestfires.describe() forestfires.info() ``` ### Response Variable and Predictors: **Response Variable:** `area` which is the burned area in forest. - We see the original paper used this variable after log transformation since *variable is very skewed towards 0.0*. After fitting the models, the outputs were post-processed with the inverse of the ln(x+1) transform **Predictiors:** We need to assign dummy variables for categorical variables `month` and `day`. ``` # histogram for area response variable: plt.hist(forestfires.area) plt.title("Burned Area") plt.savefig('../results/AreaBeforeTransformation.png') ## after log transformation : plt.hist(np.log(forestfires.area+1)) plt.title("Log Transformed Burned Area") plt.savefig('../results/AreaAfterTransformation.png') ``` > As we can see from the histograms, log transformation helps the area variable to spread out. ``` ## Encode the categorical Variables : # one way is: #le = LabelEncoder() #forestfires["month"] = le.fit_transform(forestfires["month"]) #forestfires["day"] = le.fit_transform(forestfires["day"]) forestfires = pd.get_dummies(forestfires, prefix='m', columns=['month']) forestfires = pd.get_dummies(forestfires, prefix='d', columns=['day']) ## after encoding: forestfires.head() ## X is perdictors' dataframe ## y is response' vector X = forestfires.loc[:, forestfires.columns != "area"] y = np.log(forestfires.area +1) ## save them into csv X.to_csv("../results/X.csv", encoding='utf-8', index=False) y.to_csv("../results/y.csv", encoding='utf-8', index=False) ## split the data: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=19) ``` ### Random Forest with all features: ``` randomforestscores = [] randf = RandomForestRegressor(max_depth=5) randf.fit(X_train,y_train) randomforestscores.append(randf.score(X_test,y_test)) ``` ### Lasso Regression (L1 Regularization): ``` alpha_settings = [10**-4,10**-3,10**-2,10**-1,1,10**1,10**2,10**3,10**4] Train_errorL = [] Valid_errorL = [] Nonzeros = [] for alp in alpha_settings: clfLasso = Lasso(alpha=alp) clfLasso.fit(X_train, y_train) Train_errorL.append(np.sqrt(mean_squared_error(y_train, clfLasso.predict(X_train)))) Valid_errorL.append(np.sqrt(mean_squared_error(y_test, clfLasso.predict(X_test)))) #Train_error.append(1- clf.score(X,y)) #Valid_error.append(1- clf.score(Xvalidate,yvalidate)) print("For alpha value of ", alp) print("RMSE Training error:", np.sqrt(mean_squared_error(y_train, clfLasso.predict(X_train)))) print("RMSE Validation error:", np.sqrt(mean_squared_error(y_test, clfLasso.predict(X_test)))) print("Number of non-zero features",np.count_nonzero(clfLasso.coef_)) Nonzeros.append(np.count_nonzero(clfLasso.coef_)) print("-------------------------------------------") plt.semilogx(alpha_settings, Train_errorL, label="training error") plt.semilogx(alpha_settings, Valid_errorL, label="test error") plt.legend() plt.ylabel("RMSE") plt.xlabel("Alpha") plt.title("Lasso") plt.savefig('../results/LassoError.png') print("---Optimal alpha for Lasso is",alpha_settings[np.argmin(Valid_errorL)]) plt.figure() plt.semilogx(alpha_settings,Nonzeros) plt.title("Number of Non-zero Features vs Alpha") plt.xlabel("Alpha") plt.ylabel("Number of non-zero Features") ``` > Lasso gives `alpha =0.01` as optimum value. So, let's choose alpha as 0.01 and select variables which are not zero with this value of alpha. ``` clfLasso = Lasso(alpha=0.01) clfLasso.fit(X_train, y_train) np.count_nonzero(clfLasso.coef_) # Lasso Selected Variables: rfe = RFE(Lasso(alpha=0.01),n_features_to_select = 18 ) rfe.fit(X_train,y_train) rfe.score(X_test,y_test) X.columns[rfe.support_] Xlasso = X[(X.columns[rfe.support_])] #save Xlasso into csv Xlasso.to_csv("../results/Xlasso.csv", encoding='utf-8', index=False) ``` ### ElasticNet Regression (L1+L2 Regularization): ``` alpha_settings = [10**-4,10**-3,10**-2,10**-1,1,10**1,10**2,10**3,10**4] Train_errorEN = [] Valid_errorEN = [] Nonzeros = [] for alp in alpha_settings: clfElasticNet = ElasticNet(alpha=alp,normalize =True) clfElasticNet.fit(X_train, y_train) # mean_squared_err = lambda y, yhat: np.mean((y-yhat)**2) Train_errorEN.append(np.sqrt(mean_squared_error(y_train, clfElasticNet.predict(X_train)))) Valid_errorEN.append(np.sqrt(mean_squared_error(y_test, clfElasticNet.predict(X_test)))) #Train_error.append(1- clf.score(X,y)) #Valid_error.append(1- clf.score(Xvalidate,yvalidate)) print("For alpha value of ", alp) print("RMSE Training error:", np.sqrt(mean_squared_error(y_train, clfElasticNet.predict(X_train)))) print("RMSE Validation error:", np.sqrt(mean_squared_error(y_test, clfElasticNet.predict(X_test)))) print("Number of non-zero features",np.count_nonzero(clfElasticNet.coef_)) Nonzeros.append(np.count_nonzero(clfElasticNet.coef_)) print("-----------------------") plt.semilogx(alpha_settings, Train_errorEN, label="training error") plt.semilogx(alpha_settings, Valid_errorEN, label="test error") plt.legend() plt.ylabel("RMSE") plt.xlabel("Alpha") plt.title("ElasticNet") plt.savefig('../results/ElasticNetError.png') print("---Optimal alpha for Elastic Net is",alpha_settings[np.argmin(Valid_errorEN)]) plt.figure() plt.semilogx(alpha_settings,Nonzeros) plt.title("Number of Non-zero Features vs Alpha for ElasticNet") plt.xlabel("Alpha") plt.ylabel("Number of non-zero Features") clfElasticNet = ElasticNet(alpha=0.01) clfElasticNet.fit(X_train, y_train) np.count_nonzero(clfElasticNet.coef_) # ElasticNet Selected Variables: rfe = RFE(ElasticNet(alpha=0.01), n_features_to_select=22) rfe.fit(X_train,y_train) rfe.score(X_test,y_test) X.columns[rfe.support_] XelasticNet = X[(X.columns[rfe.support_])] #save Xlasso into csv XelasticNet.to_csv("../results/XElasticNet.csv", encoding='utf-8', index=False) ``` ### Random Forest Regressions with only Selected Features from Lasso and ElasticNet ``` ## for Lasso features: X_train, X_test, y_train, y_test = train_test_split(Xlasso, y, test_size=0.33, random_state=19) randf = RandomForestRegressor(max_depth=5) randf.fit(X_train,y_train) randomforestscores.append(randf.score(X_test,y_test)) ## for ElasticNet features: X_train, X_test, y_train, y_test = train_test_split(XelasticNet, y, test_size=0.33, random_state=19) randf = RandomForestRegressor(max_depth=5) randf.fit(X_train,y_train) randomforestscores.append(randf.score(X_test,y_test)) randomforestscores = pd.DataFrame(randomforestscores) randomforestscores = randomforestscores.rename(index={0: 'RandomForest with all features(29)'}) randomforestscores = randomforestscores.rename(index={1: 'RandomForest with Lasso features(18)'}) randomforestscores = randomforestscores.rename(index={2: 'RandomForest with ElasticNet features(22)'}) randomforestscores pd.DataFrame(np.transpose(randomforestscores)).to_csv("../results/RandomForestScores.csv", encoding='utf-8', index=False) ```
github_jupyter
# MARATONA BEHIND THE CODE 2020 ## DESAFIO 6 - LIT <hr> ## Installing Libs ``` !pip install scikit-learn --upgrade !pip install xgboost --upgrade !pip install imblearn --upgrade ``` <hr> ## Download dos conjuntos de dados em formato .csv ``` import pandas as pd !wget --no-check-certificate --content-disposition https://raw.githubusercontent.com/vanderlei-test/dataset-3/master/training_dataset.csv df_training_dataset = pd.read_csv(r'training_dataset.csv') df_training_dataset.tail() ``` Sobre o arquivo "training_dataset.csv", temos algumas informações gerais sobre os usuários da plataforma: **id** **graduacao** **universidade** **profissao** **organizacao** **pretende_fazer_cursos_lit** **interesse_mba_lit** **importante_ter_certificado** **horas_semanais_estudo** **como_conheceu_lit** **total_modulos** **modulos_iniciados** **modulos_finalizados** **certificados** **categoria** ``` df_training_dataset.info() df_training_dataset.nunique() ``` <hr> ## Detalhamento do desafio: classificação multiclasse Este é um desafio cujo objetivo de negócio é a segmentação dos usuários de uma plataforma de ensino. Para tal, podemos utilizar duas abordagens: aprendizado de máquina supervisionado (classificação) ou não-supervisionado (clustering). Neste desafio será aplicada a classificação, pois é disponível um dataset já com "labels", ou em outras palavras, já com exemplos de dados juntamente com a variável alvo. Na biblioteca scikit-learn temos diversos algoritmos para classificação. O participante é livre para utilizar o framework que desejar para completar esse desafio. Neste notebook será mostrado um exeplo de uso do algoritmo "Decision Tree" para classificar parte dos estudantes em seis diferentes perfís. # Atenção! A coluna-alvo neste desafio é a coluna ``categoria`` <hr> ``` for column in ['horas_semanais_estudo','total_modulos','modulos_iniciados','modulos_finalizados','certificados']: df_training_dataset[column] = df_training_dataset[column].fillna(df_training_dataset.groupby('categoria')[column].transform('mean')) most_common = df_training_dataset[[ 'categoria', 'graduacao','universidade','profissao','organizacao','pretende_fazer_cursos_lit', 'interesse_mba_lit', 'importante_ter_certificado','como_conheceu_lit' ]].groupby(['categoria']).agg(lambda x:x.value_counts().index[0]) for column in ['graduacao','universidade','profissao','organizacao','pretende_fazer_cursos_lit', 'interesse_mba_lit', 'importante_ter_certificado','como_conheceu_lit']: df_training_dataset[column] = df_training_dataset.apply( lambda row: most_common.loc[row['categoria']][column] if pd.isna(row[column]) else row[column], axis=1 ) ``` ## Pre-processando o dataset antes do treinamento ### Removendo todas as linhas que possuem algum valor nulos em determinadas colunas Usando o método Pandas **DataFrame.dropna()** você pode remover todas as linhas nulas do dataset. Docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html ``` # Exibindo os dados ausentes do conjunto de dados antes da primeira transformação (df) print("Valores nulos no df_training_dataset antes da transformação DropNA: \n\n{}\n".format(df_training_dataset.isnull().sum(axis = 0))) # Aplicando a função para deletar todas as linhas com valor NaN na coluna ``certificados'' e ``total_modulos'': df_training_dataset = df_training_dataset.dropna(axis='index', how='any', subset=['certificados', 'total_modulos']) # Exibindo os dados ausentes do conjunto de dados após a primeira transformação (df) print("Valores nulos no df_training_dataset após a transformação DropNA: \n\n{}\n".format(df_training_dataset.isnull().sum(axis = 0))) ``` ### Processando valores NaN com o SimpleImputer do sklearn Para os valores NaN, usaremos a substituição pela constante 0 como **exemplo**. Você pode escolher a estratégia que achar melhor para tratar os valores nulos :) Docs: https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html?highlight=simpleimputer#sklearn.impute.SimpleImputer ``` from sklearn.impute import SimpleImputer import numpy as np impute_zeros = SimpleImputer( missing_values=np.nan, strategy='constant', fill_value=0, verbose=0, copy=True ) # Exibindo os dados ausentes do conjunto de dados antes da primeira transformação (df) print("Valores nulos no df_training_dataset antes da transformação SimpleImputer: \n\n{}\n".format(df_training_dataset.isnull().sum(axis = 0))) # Aplicando a transformação ``SimpleImputer`` no conjunto de dados base impute_zeros.fit(X=df_training_dataset) # Reconstruindo um Pandas DataFrame com os resultados df_training_dataset_imputed = pd.DataFrame.from_records( data=impute_zeros.transform( X=df_training_dataset ), columns=df_training_dataset.columns ) # Exibindo os dados ausentes do conjunto de dados após a primeira transformação (df) print("Valores nulos no df_training_dataset após a transformação SimpleImputer: \n\n{}\n".format(df_training_dataset_imputed.isnull().sum(axis = 0))) ``` ### Eliminando colunas indesejadas Vamos **demonstrar** abaixo como usar o método **DataFrame.drop()**. Docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html ``` df_training_dataset_imputed.tail() df_training_dataset_rmcolumns = df_training_dataset_imputed.drop(columns=['id'], inplace=False) df_training_dataset_rmcolumns.tail() ``` # Atenção! As colunas removidas acima são apenas para fim de exemplo, você pode usar as colunas que quiser e inclusive criar novas colunas com dados que achar importantes! ### Tratamento de de variáveis categóricas Como mencionado antes, os computadores não são bons com variáveis "categóricas" (ou strings). Dado uma coluna com variável categórica, o que podemos realizar é a codificação dessa coluna em múltiplas colunas contendo variáveis binárias. Esse processo é chamado de "one-hot-encoding" ou "dummy encoding". Se você não é familiarizado com esses termos, você pode pesquisar mais sobre isso na internet :) ``` # Tratando variáveis categóricas com o método Pandas ``get_dummies()'' df_training = pd.get_dummies(df_training_dataset_rmcolumns, columns=['graduacao','universidade','profissao','organizacao','como_conheceu_lit']) df_training.tail() ``` # Atenção! A coluna **categoria** deve ser mantida como uma string. Você não precisa processar/codificar a variável-alvo. <hr> ## Treinando um classificador com base em uma árvore de decisão ### Selecionando FEATURES e definindo a variável TARGET ``` df_training.columns features = df_training[ [ 'pretende_fazer_cursos_lit', 'interesse_mba_lit', 'importante_ter_certificado', 'horas_semanais_estudo', 'total_modulos', 'modulos_iniciados', 'modulos_finalizados', 'certificados', 'graduacao_Bacharelado', 'graduacao_Especialização', 'graduacao_Licenciatura', 'graduacao_MBA', 'graduacao_SEM FORMAÇÃO', 'graduacao_Tecnólogo', 'universidade_CENTRO UNIVERSITÁRIO ESTÁCIO DA SÁ', 'universidade_Escola Paulista de Direito', 'universidade_FACULDADE ANHANGUERA', 'universidade_FATEC', 'universidade_FGV-RJ', 'universidade_INSPER INSTITUTO DE ENSINO E PESQUISA', 'universidade_UEPB', 'universidade_UFF', 'universidade_UFPE', 'universidade_UFRJ', 'universidade_UFRN', 'universidade_UFSCar', 'universidade_UNICAMP', 'universidade_UNIP', 'universidade_UNIVERSIDADE CRUZEIRO DO SUL', 'universidade_UNIVERSIDADE ESTADUAL DE PONTA GROSSA', 'universidade_UNIVERSIDADE NOVE DE JULHO', 'universidade_UNIVERSIDADE PRESBITERIANA MACKENZIE', 'universidade_USP', 'universidade_Unesp', 'universidade_Universidade Metodista de Sao Paulo', 'profissao_Advogado', 'profissao_Analista', 'profissao_Analista Senior', 'profissao_Assessor', 'profissao_Coordenador', 'profissao_Diretor', 'profissao_Engenheiro', 'profissao_Gerente', 'profissao_Outros', 'profissao_SEM EXPERIÊNCIA', 'profissao_Supervisor', 'profissao_Sócio/Dono/Proprietário', 'organizacao_Borracha', 'organizacao_Eletrodomesticos', 'organizacao_Eletroeletronicos', 'organizacao_Entretenimento', 'organizacao_Estado', 'organizacao_Laminados', 'organizacao_Montadora', 'organizacao_Oleo e Gas', 'organizacao_Siderurgica', 'organizacao_e-commerce', 'organizacao_servicos', 'como_conheceu_lit_Facebook', 'como_conheceu_lit_Google', 'como_conheceu_lit_Instagram', 'como_conheceu_lit_Linkedin', 'como_conheceu_lit_Minha empresa - benefício LITpass', 'como_conheceu_lit_Mídia (revista/jornal/web)', 'como_conheceu_lit_Outros', 'como_conheceu_lit_Saint Paul', 'como_conheceu_lit_YouTube' ] ] target = df_training['categoria'] ## NÃO TROQUE O NOME DA VARIÁVEL TARGET. ``` ### Dividindo nosso conjunto de dados em conjuntos de treinamento e teste ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.00001, random_state=133) from imblearn.over_sampling import SMOTE smt = SMOTE(random_state=0) X_train_SMOTE, y_train_SMOTE = smt.fit_sample(X_train, y_train) ``` ### Treinando uma árvore de decisão ``` # Método para creacion de modelos basados en arbol de desición from sklearn.tree import DecisionTreeClassifier import xgboost as xgb dtc = xgb.XGBClassifier(learning_rate=0.005, n_estimators=1000, max_depth=50, gamma=10).fit(X_train_SMOTE, y_train_SMOTE) ``` ### Fazendo previsões na amostra de teste ``` y_pred = dtc.predict(X_test) print(y_pred) ``` ### Analisando a qualidade do modelo através da matriz de confusão ``` import matplotlib.pyplot as plt import numpy as np import itertools def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=None, normalize=True): accuracy = np.trace(cm) / float(np.sum(cm)) misclass = 1 - accuracy if cmap is None: cmap = plt.get_cmap('Blues') plt.figure(figsize=(8, 6)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() if target_names is not None: tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 1.5 if normalize else cm.max() / 2 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): if normalize: plt.text(j, i, "{:0.4f}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") else: plt.text(j, i, "{:,}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass)) plt.show() from sklearn.metrics import confusion_matrix plot_confusion_matrix(confusion_matrix(y_test, y_pred), ['parfil1', 'perfil2', 'perfil3', 'perfil4', 'perfil5', 'perfil6']) ``` <hr> ``` from sklearn.metrics import classification_report target_names = ['perfil1', 'perfil2','perfil3','perfil4','perfil5','perfil6'] print(classification_report(y_test, y_pred, target_names=target_names)) ``` ## Scoring dos dados necessários para entregar a solução Como entrega da sua solução, esperamos os resultados classificados no seguinte dataset chamado "to_be_scored.csv": ### Download da "folha de respostas" ``` !wget --no-check-certificate --content-disposition https://raw.githubusercontent.com/vanderlei-test/dataset-3/master/to_be_scored.csv df_to_be_scored = pd.read_csv(r'to_be_scored.csv') df_to_be_scored.tail() ``` # Atenção! O dataframe ``to_be_scored`` é a sua "folha de respostas". Note que a coluna "categoria" não existe nessa amostra, que não pode ser então utilizada para treino de modelos de aprendizado supervisionado. ``` df_to_be_scored.info() ``` <hr> # Atenção! # Para poder aplicar seu modelo e classificar a folha de respostas, você precisa primeiro aplicar as mesmas transformações com colunas que você aplicou no dataset de treino. # Não remova ou adicione linhas na folha de respostas. # Não altere a ordem das linhas na folha de respostas. # Ao final, as 1000 entradas devem estar classificadas, com os valores previstos em uma coluna chamada "target" <hr> Na célula abaixo, repetimos rapidamente os mesmos passos de pré-processamento usados no exemplo dado com árvore de decisão ``` # 1 - Removendo linhas com valores NaN em "certificados" e "total_modulos" df_to_be_scored_1 = df_to_be_scored.dropna(axis='index', how='any', subset=['certificados', 'total_modulos']) # 2 - Inputando zeros nos valores faltantes impute_zeros.fit(X=df_to_be_scored_1) df_to_be_scored_2 = pd.DataFrame.from_records( data=impute_zeros.transform( X=df_to_be_scored_1 ), columns=df_to_be_scored_1.columns ) # 3 - Remoção de colunas df_to_be_scored_3 = df_to_be_scored_2.drop(columns=['id'], inplace=False) # 4 - Encoding com "dummy variables" df_to_be_scored_4 = pd.get_dummies(df_to_be_scored_3, columns=['graduacao','universidade','profissao','organizacao','como_conheceu_lit']) df_to_be_scored_4.tail() ``` <hr> Pode ser verificado abaixo que as colunas da folha de resposta agora são idênticas às que foram usadas para treinar o modelo: ``` df_training[ [ 'pretende_fazer_cursos_lit', 'interesse_mba_lit', 'importante_ter_certificado', 'horas_semanais_estudo', 'total_modulos', 'modulos_iniciados', 'modulos_finalizados', 'certificados', 'graduacao_Bacharelado', 'graduacao_Especialização', 'graduacao_Licenciatura', 'graduacao_MBA', 'graduacao_SEM FORMAÇÃO', 'graduacao_Tecnólogo', 'universidade_CENTRO UNIVERSITÁRIO ESTÁCIO DA SÁ', 'universidade_Escola Paulista de Direito', 'universidade_FACULDADE ANHANGUERA', 'universidade_FATEC', 'universidade_FGV-RJ', 'universidade_INSPER INSTITUTO DE ENSINO E PESQUISA', 'universidade_UEPB', 'universidade_UFF', 'universidade_UFPE', 'universidade_UFRJ', 'universidade_UFRN', 'universidade_UFSCar', 'universidade_UNICAMP', 'universidade_UNIP', 'universidade_UNIVERSIDADE CRUZEIRO DO SUL', 'universidade_UNIVERSIDADE ESTADUAL DE PONTA GROSSA', 'universidade_UNIVERSIDADE NOVE DE JULHO', 'universidade_UNIVERSIDADE PRESBITERIANA MACKENZIE', 'universidade_USP', 'universidade_Unesp', 'universidade_Universidade Metodista de Sao Paulo', 'profissao_Advogado', 'profissao_Analista', 'profissao_Analista Senior', 'profissao_Assessor', 'profissao_Coordenador', 'profissao_Diretor', 'profissao_Engenheiro', 'profissao_Gerente', 'profissao_Outros', 'profissao_SEM EXPERIÊNCIA', 'profissao_Supervisor', 'profissao_Sócio/Dono/Proprietário', 'organizacao_Borracha', 'organizacao_Eletrodomesticos', 'organizacao_Eletroeletronicos', 'organizacao_Entretenimento', 'organizacao_Estado', 'organizacao_Laminados', 'organizacao_Montadora', 'organizacao_Oleo e Gas', 'organizacao_Siderurgica', 'organizacao_e-commerce', 'organizacao_servicos', 'como_conheceu_lit_Facebook', 'como_conheceu_lit_Google', 'como_conheceu_lit_Instagram', 'como_conheceu_lit_Linkedin', 'como_conheceu_lit_Minha empresa - benefício LITpass', 'como_conheceu_lit_Mídia (revista/jornal/web)', 'como_conheceu_lit_Outros', 'como_conheceu_lit_Saint Paul', 'como_conheceu_lit_YouTube' ] ].columns df_to_be_scored_4.columns ``` # Atenção Para todas colunas que não existirem no "df_to_be_scored", você pode usar a técnica abaixo para adicioná-las: ``` y_pred = dtc.predict(df_to_be_scored_4) df_to_be_scored_4['target'] = y_pred df_to_be_scored_4.tail() ``` ### Salvando a folha de respostas como um arquivo .csv para ser submetido ``` df_to_be_scored_4.to_csv("results1.csv") ``` # Atenção # A execução da célula acima irá criar um novo "data asset" no seu projeto no Watson Studio. Você precisará realizar o download deste arquivo juntamente com este notebook e criar um arquivo zip com os arquivos **results.csv** e **notebook.ipynb** para submissão. (os arquivos devem estar nomeados desta forma) <hr> ## Parabéns! Se você já está satisfeito com a sua solução, vá até a página abaixo e envie os arquivos necessários para submissão. # https://lit.maratona.dev
github_jupyter
## Michael DiGregorio - Homework 1 - CPE/EE 695 Applied Machine Learning ## Imports ``` import numpy as np import matplotlib.pyplot as pt from typing import List, Tuple ``` ## Function Definitions ``` def get_polynomial(x): return 5*x + 20*x**2 + 1*x**3 def get_dataset(number_of_samples, noise_scale) -> Tuple[np.ndarray]: x_rand = np.sort(25*(np.random.rand(number_of_samples, 1) - 0.8), -1).reshape((number_of_samples,)) noise = (noise_scale*np.random.randn(number_of_samples, 1)).reshape((number_of_samples,)) x = np.sort(x_rand) y = np.add(get_polynomial(x), noise) x_plot = np.linspace(x[0], x[-1], 100) y_plot = get_polynomial(x_plot) return (x, y, x_plot, y_plot, noise) def plot_arbitrary_polynomial(x, coef, title: str = f"Polynomial"): x_plot = np.linspace(x[0], x[-1], 100) y_seq = np.zeros(len(x_plot)) for i in range(len(coef)): y_seq = np.add(y_seq, coef[i]*x_plot**i) pt.plot(x_plot, y_seq) pt.title(title) pt.show() def polyfit(x: np.array, y: np.array, order: int, title: str = None) -> Tuple[np.ndarray]: poly = np.polyfit(x, y, order, full=True) coefficients = poly[0] residuals = poly[1] pt.plot(x, y, 'ro') if title is not None: plot_arbitrary_polynomial(x, coefficients[::-1], title=title) else: plot_arbitrary_polynomial(x, coefficients[::-1], titlet=title) return (coefficients, residuals) ``` ## Assignment Main Logic Starts Here ``` pt.style.use('seaborn-whitegrid') (x, y, x_plot, y_plot, noise) = get_dataset(100, 50) pt.plot(x_plot, y_plot, 'b') pt.plot(x, y, 'ro') ``` ### Question 1 1) Please plot the noisy data and the polynomial you found (in the same figure). You can use any value of m selected from 2, 3, 4, 5, 6. ``` mse: List[float] = [] order: List[int] = [1, 2, 3, 4, 5, 6, 7, 8] for m in order: (coef, res) = polyfit(x, y, m, title=f"Polynomial of order: {m}") function_string = "" for i in range(len(coef)): function_string += f" {coef[i]}*x^{len(coef)-i-1} " if i != len(coef)-1: function_string += '+' print(f"Function: {function_string}\n") print(f"Coefficients: {coef}") print(f"Residuals: {res}") mse += res.tolist() ``` ### Question 2 2) Plot MSE versus order m, for m = 1, 2, 3, 4, 5, 6, 7, 8 respectively. Identify the best choice of m. ``` pt.plot(order, mse) best_order = order[mse.index(min(mse))] print(f"The best order for our function was {best_order}, however, we can see that the leading coefficients for all polynomials of orders higher than 3 are close to 0. This means that they are essentially order 3 polynomials. Additionally, the mse shows next to no improvement past order 3. Because of this, I will be using 3 as my 'best order'") ``` ### Question 3 3) Change variable noise_scale to 150, 200, 400, 600, 1000 respectively, re-run the algorithm and plot the polynomials with the m found in 2). Discuss the impact of noise scale to the accuracy of the returned parameters. [You need to plot a figure like in 1) for each choice of noise_scale.] ``` noise_scales: List[int] = [150, 200, 400, 600, 1000] for i in range(len(noise_scales)): (x, y, x_plot, y_plot, noise) = get_dataset(50, noise_scales[i]) (coef, res) = polyfit(x, y, 3, title=f"Order = 3, noise_scale = {noise_scales[i]}") function_string = "" for i in range(len(coef)): function_string += f" {coef[i]}*x^{len(coef)-i-1} " if i != len(coef)-1: function_string += '+' print(f"Function: {function_string}\n") print(f"Coefficients: {coef}") print(f"Residuals: {res}") ``` ### Question 4 4) Change variable number_of_samples to 40, 30, 20, 10 respectively, re-ran the algorithm and plot the polynomials with the m found in 2). Discuss the impact of the number of samples to the accuracy of the returned parameters. [You need to plot a figure like in 1) for each choice of number_of_samples.] ``` samples: List[int] = [40, 30, 20, 10] for i in range(len(samples)): (x, y, x_plot, y_plot, noise) = get_dataset(samples[i], 100) (coef, res) = polyfit(x, y, 3, title=f"Order = 3, num_samples = {samples[i]}") function_string = "" for i in range(len(coef)): function_string += f" {coef[i]}*x^{len(coef)-i-1} " if i != len(coef)-1: function_string += '+' print(f"Function: {function_string}\n") print(f"Coefficients: {coef}") print(f"Residuals: {res}") ```
github_jupyter
# TensorBoard ``` import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('/tmp/tensorflow/alex/mnist/input_data', one_hot=True) def variable_summaries(var): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var) ``` ### Graph ``` run_id = 'initial' log_dir = '/home/jovyan/work/logs/alex/' + run_id with tf.name_scope('input'): x = tf.placeholder(tf.float32, [None, 784], name='x-input') y_ = tf.placeholder(tf.float32, [None, 10], name='y-input') with tf.name_scope('input_reshape'): image_shaped_input = tf.reshape(x, [-1, 28, 28, 1]) tf.summary.image('input', image_shaped_input, max_outputs=10) with tf.name_scope('weights'): W = tf.Variable(initial_value=tf.zeros([784, 10], dtype=tf.float32), name='weights', trainable=True) variable_summaries(W) with tf.name_scope('biases'): b = tf.Variable(initial_value=tf.zeros([10]), dtype=tf.float32, name='bias', trainable=True) variable_summaries(b) with tf.name_scope('Wx_plus_b'): y = tf.matmul(x, W) + b tf.summary.histogram('predictions', y) with tf.name_scope('cross_entropy'): diff = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y) with tf.name_scope('total'): cross_entropy = tf.reduce_mean(diff) tf.summary.scalar('cross_entropy', cross_entropy) with tf.name_scope('train'): train_step = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(cross_entropy) with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) with tf.name_scope('accuracy'): accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', accuracy) merged = tf.summary.merge_all() ``` ### Initialize ``` sess = tf.Session() sess.run(tf.global_variables_initializer()) train_writer = tf.summary.FileWriter(log_dir + '/train', sess.graph) test_writer = tf.summary.FileWriter(log_dir + '/test') print(log_dir) ``` ### Train ``` for i in range(1000): if i % 10 == 0: # Record summaries and test-set accuracy summary, acc = sess.run([merged, accuracy], feed_dict={x: mnist.test.images, y_: mnist.test.labels}) test_writer.add_summary(summary, i) print('Accuracy at step %s: %s' % (i, acc)) else: # Record train set summaries, and train xs, ys = mnist.train.next_batch(100) if i % 100 == 99: # Record execution stats run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() summary, _ = sess.run([merged, train_step], feed_dict={x: xs, y_: ys}, options=run_options, run_metadata=run_metadata) train_writer.add_run_metadata(run_metadata, 'step%03d' % i) train_writer.add_summary(summary, i) print('Adding run metadata for', i) else: # Record a summary summary, _ = sess.run([merged, train_step], feed_dict={x: xs, y_: ys}) train_writer.add_summary(summary, i) train_writer.close() test_writer.close() sess.close() print('tensorboard --logdir=' + log_dir) ```
github_jupyter
``` from types import SimpleNamespace from functools import lru_cache import os import time from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score import pandas as pd import numpy as np import scipy.io.wavfile import scipy.fftpack import scipy.linalg import torch import torch.utils.data as data import torch.nn as nn import torch.optim as optim import math @lru_cache(maxsize=10) def get_window(n, type='hamming'): coefs = np.arange(n) window = 0.54 - 0.46 * np.cos(2 * np.pi * coefs / (n - 1)) return window def apply_preemphasis(y, preemCoef=0.97): y[1:] = y[1:] - preemCoef*y[:-1] y[0] *= (1 - preemCoef) return y def freq_to_mel(freq): return 2595.0 * np.log10(1.0 + freq / 700.0) def mel_to_freq(mels): return 700.0 * (np.power(10.0, mels / 2595.0) - 1.0) @lru_cache(maxsize=10) def get_filterbank(numfilters, filterLen, lowFreq, highFreq, samplingFreq): minwarpfreq = freq_to_mel(lowFreq) maxwarpfreq = freq_to_mel(highFreq) dwarp = (maxwarpfreq - minwarpfreq) / (numfilters + 1) f = mel_to_freq(np.arange(numfilters + 2) * dwarp + minwarpfreq) * (filterLen - 1) * 2.0 / samplingFreq i = np.arange(filterLen)[None, :] f = f[:, None] hislope = (i - f[:numfilters]) / (f[1:numfilters+1] - f[:numfilters]) loslope = (f[2:numfilters+2] - i) / (f[2:numfilters+2] - f[1:numfilters+1]) H = np.maximum(0, np.minimum(hislope, loslope)) return H def normalized(y, threshold=0): y -= y.mean() stddev = y.std() if stddev > threshold: y /= stddev return y def mfsc(y, sfr, window_size=0.025, window_stride=0.010, window='hamming', normalize=True, log=True, n_mels=80, preemCoef=0.97, melfloor=1.0): win_length = int(sfr * window_size) hop_length = int(sfr * window_stride) n_fft = 2048 lowfreq = 0 highfreq = sfr/2 # get window window = get_window(win_length) padded_window = np.pad(window, (0, n_fft - win_length), mode='constant')[:, None] # preemphasis y = apply_preemphasis(y, preemCoef) # scale wave signal y *= 32768 # get frames and scale input num_frames = 1 + (len(y) - win_length) // hop_length pad_after = num_frames*hop_length + (n_fft - hop_length) - len(y) if pad_after > 0: y = np.pad(y, (0, pad_after), mode='constant') frames = np.lib.stride_tricks.as_strided(y, shape=(n_fft, num_frames), strides=(y.itemsize, hop_length * y.itemsize), writeable=False) windowed_frames = padded_window * frames D = np.abs(np.fft.rfft(windowed_frames, axis=0)) # mel filterbank filterbank = get_filterbank(n_mels, n_fft/2 + 1, lowfreq, highfreq, sfr) mf = np.dot(filterbank, D) mf = np.maximum(melfloor, mf) if log: mf = np.log(mf) if normalize: mf = normalized(mf) return mf def make_dataset(kaldi_path, class_to_id): text_path = os.path.join(kaldi_path, 'text') wav_path = os.path.join(kaldi_path, 'wav.scp') key_to_word = dict() key_to_wav = dict() with open(wav_path, 'rt') as wav_scp: for line in wav_scp: key, wav = line.strip().split(' ', 1) key_to_wav[key] = wav key_to_word[key] = None # default if os.path.isfile(text_path): with open(text_path, 'rt') as text: for line in text: key, word = line.strip().split(' ', 1) key_to_word[key] = word wavs = [] for key, wav_command in key_to_wav.items(): word = key_to_word[key] word_id = class_to_id[word] if word is not None else -1 # default for test wav_item = [key, wav_command, word_id] wavs.append(wav_item) return wavs def wav_read(path): sr, y = scipy.io.wavfile.read(path) y = y/32768 # Normalize to -1..1 y -= y.mean() return y, sr def param_loader(path, window_size, window_stride, window, normalize, max_len): y, sfr = wav_read(path) param = mfsc(y, sfr, window_size=window_size, window_stride=window_stride, window=window, normalize=normalize, log=False, n_mels=60, preemCoef=0, melfloor=1.0) # Add zero padding to make all param with the same dims if param.shape[1] < max_len: pad = np.zeros((param.shape[0], max_len - param.shape[1])) param = np.hstack((pad, param)) # If exceeds max_len keep last samples elif param.shape[1] > max_len: param = param[:, -max_len:] param = torch.FloatTensor(param) return param def get_classes(): classes = ['neg', 'pos'] weight = None class_to_id = {label: i for i, label in enumerate(classes)} return classes, weight, class_to_id class Loader(data.Dataset): """Data set loader:: Args: root (string): Kaldi directory path. transform (callable, optional): A function/transform that takes in a spectrogram and returns a transformed version. E.g, ``transforms.RandomCrop`` target_transform (callable, optional): A function/transform that takes in the target and transforms it. window_size: window size for the stft, default value is .02 window_stride: window stride for the stft, default value is .01 window_type: typye of window to extract the stft, default value is 'hamming' normalize: boolean, whether or not to normalize the param to have zero mean and one std max_len: the maximum length of frames to use Attributes: classes (list): List of the class names. class_to_id (dict): Dict with items (class_name, class_index). wavs (list): List of (wavs path, class_index) tuples STFT parameters: window_size, window_stride, window_type, normalize """ def __init__(self, root, transform=None, target_transform=None, window_size=.02, window_stride=.01, window_type='hamming', normalize=True, max_len=1000): classes, weight, class_to_id = get_classes() self.root = root self.wavs = make_dataset(root, class_to_id) self.classes = classes self.weight = weight self.class_to_id = class_to_id self.transform = transform self.target_transform = target_transform self.loader = param_loader self.window_size = window_size self.window_stride = window_stride self.window_type = window_type self.normalize = normalize self.max_len = max_len def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (key, params, target) where target is class_index of the target class. """ key, path, target = self.wavs[index] path = '../input/covid/wavs16k/' + path params = self.loader(path, self.window_size, self.window_stride, self.window_type, self.normalize, self.max_len) # pylint: disable=line-too-long if self.transform is not None: params = self.transform(params) if self.target_transform is not None: target = self.target_transform(target) return key, params, target def __len__(self): return len(self.wavs) class VGG(nn.Module): def __init__(self, vgg_name, hidden=64, dropout=0.4): super(VGG, self).__init__() self.features = make_layers(cfg[vgg_name]) self.classifier = nn.Sequential( nn.Dropout(dropout), nn.Linear(2*512, hidden), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden, hidden), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden, 1), ) self._initialize_weights() def forward(self, x): x.unsqueeze_(1) x = self.features(x) x1, _ = x.max(dim=-1) x2 = x.mean(dim=-1) x = torch.cat((x1, x2), dim=-1) # print(x.shape) x = x.view(x.size(0), -1) x = self.classifier(x) return x.squeeze(-1) def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) m.bias.data.zero_() def make_layers(cfg, batch_norm=True): layers = [] in_channels = 1 for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) if batch_norm: layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v return nn.Sequential(*layers) cfg = { 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], } def train(loader, model, criterion, optimizer, epoch, cuda, log_interval, weight=None, verbose=True): model.train() global_epoch_loss = 0 samples = 0 for batch_idx, (_, data, target) in enumerate(loader): if cuda: data, target = data.cuda(), target.cuda() optimizer.zero_grad() output = model(data) loss = criterion(output, target.float()) loss.backward() optimizer.step() global_epoch_loss += loss.data.item() * len(target) samples += len(target) if verbose: if batch_idx % log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, samples, len(loader.dataset), 100 * samples / len(loader.dataset), global_epoch_loss / samples)) return global_epoch_loss / samples def test(loader, model, criterion, cuda, verbose=True, data_set='Test', save=None): model.eval() test_loss = 0 tpred = [] ttarget = [] if save is not None: csv = open(save, 'wt') print('index,prob', file=csv) with torch.no_grad(): for keys, data, target in loader: if cuda: data, target = data.cuda(), target.cuda() output = model(data) pred = output.sigmoid() tpred.append(pred.cpu().numpy()) if target[0] != -1: loss = criterion(output, target.float()).data.item() test_loss += loss * len(target) # sum up batch loss ttarget.append(target.cpu().numpy()) if save is not None: for i, key in enumerate(keys): print(f'{key},{pred[i]}', file=csv) if len(ttarget) > 0: test_loss /= len(loader.dataset) auc = roc_auc_score(np.concatenate(ttarget), np.concatenate(tpred)) if verbose: print('\n{} set: Average loss: {:.4f}, AUC: ({:.1f}%)\n'.format(data_set, test_loss, 100 * auc)) return test_loss, auc args = SimpleNamespace( # general options train_path = '../input/covid/train', # train data folder valid_path = '../input/covid/valid', # valid data folder test_path = '../input/covid/test', # test data folder batch_size = 32, # training and valid batch size test_batch_size = 32, # batch size for testing arc = 'VGG13', # VGG11, VGG13, VGG16, VGG19 epochs = 100, # maximum number of epochs to train lr = 0.0001, # learning rate momentum = 0.9, # SGD momentum, for SGD only optimizer = 'adam', # optimization method: sgd | adam seed = 1234, # random seed log_interval = 5, # how many batches to wait before logging training status patience = 5, # how many epochs of no loss improvement should we wait before stop training checkpoint = '.', # checkpoints directory train = True, # train before testing cuda = True, # use gpu # feature extraction options window_size = .04, # window size for the stft window_stride = .02, # window stride for the stft window_type = 'hamming', # window type for the stft normalize = True, # use spect normalization num_workers = 2, # how many subprocesses to use for data loading ) args.cuda = args.cuda and torch.cuda.is_available() torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) print('Using CUDA with {0} GPUs'.format(torch.cuda.device_count())) # build model model = VGG(args.arc) if args.cuda: model.cuda() # Define criterion criterion = nn.BCEWithLogitsLoss(reduction='mean') # This loss combines a Sigmoid layer and the BCELoss in one single class. ``` ## Train model ``` # loading data if args.train: train_dataset = Loader(args.train_path, window_size=args.window_size, window_stride=args.window_stride, window_type=args.window_type, normalize=args.normalize) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=args.cuda, sampler=None) valid_dataset = Loader(args.valid_path, window_size=args.window_size, window_stride=args.window_stride, window_type=args.window_type, normalize=args.normalize) valid_loader = torch.utils.data.DataLoader( valid_dataset, batch_size=args.batch_size, shuffle=None, num_workers=args.num_workers, pin_memory=args.cuda, sampler=None) # define optimizer if args.optimizer.lower() == 'adam': optimizer = optim.Adam(model.parameters(), lr=args.lr) else: optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum) best_valid_auc = 0 iteration = 0 epoch = 1 # trainint with early stopping t0 = time.time() while (epoch < args.epochs + 1) and (iteration < args.patience): train(train_loader, model, criterion, optimizer, epoch, args.cuda, args.log_interval, weight=train_dataset.weight) valid_loss, valid_auc = test(valid_loader, model, criterion, args.cuda, data_set='Validation') if not os.path.isdir(args.checkpoint): os.mkdir(args.checkpoint) torch.save(model.state_dict(), './{}/model{:03d}.pt'.format(args.checkpoint, epoch)) if valid_auc <= best_valid_auc: iteration += 1 print('AUC was not improved, iteration {0}'.format(str(iteration))) else: print('Saving state') iteration = 0 best_valid_auc = valid_auc state = { 'valid_auc': valid_auc, 'valid_loss': valid_loss, 'epoch': epoch, } if not os.path.isdir(args.checkpoint): os.mkdir(args.checkpoint) torch.save(state, './{}/ckpt.pt'.format(args.checkpoint)) epoch += 1 print(f'Elapsed seconds: ({time.time() - t0:.0f}s)') ``` ## Test Model ``` test_dataset = Loader(args.test_path, window_size=args.window_size, window_stride=args.window_stride, window_type=args.window_type, normalize=args.normalize) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=args.test_batch_size, shuffle=None, num_workers=args.num_workers, pin_memory=args.cuda, sampler=None) # get best epoch state = torch.load('./{}/ckpt.pt'.format(args.checkpoint)) epoch = state['epoch'] print("Testing model (epoch {})".format(epoch)) model.load_state_dict(torch.load('./{}/model{:03d}.pt'.format(args.checkpoint, epoch))) if args.cuda: model.cuda() results = 'submission.csv' print("Saving results in {}".format(results)) test(test_loader, model, criterion, args.cuda, save=results) ```
github_jupyter
``` import mglearn import pandas as pd import matplotlib.pyplot as plt import numpy as np import IPython import sklearn from sklearn.datasets import load_iris iris=load_iris() print (iris['target']) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test=train_test_split(iris['data'], iris['target'], random_state=0) from sklearn.neighbors import KNeighborsClassifier knn=KNeighborsClassifier(n_neighbors=1) print (knn.fit(X_train, y_train)) X_new=np.array([[4.9,2.9,1,0.2]]) X_new.shape X_new2=np.array([[5,3,2,0.5]]) X_new2.shape prediction=knn.predict(X_new2) prediction2=knn.predict(X_new) print ("Iris 1 is a " +str(iris['target_names'][prediction])) print ("Iris 2 is a " +str(iris['target_names'][prediction2])) y_pred=knn.predict(X_test) np.mean(y_pred==y_test) print("-----------------LASSO---------------------") from sklearn.linear_model import Lasso lasso = Lasso().fit(X_train, y_train) print("training set score: %f" % lasso.score(X_train, y_train)) print("test set score: %f" % lasso.score(X_test, y_test)) print("number of features used: %d" % np.sum(lasso.coef_ != 3)) print ("---------------SVC AND LOGISTIC REGRESSION-----------") from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC X, y=mglearn.datasets.make_forge() fig, axes= plt.subplots(1,2,figsize=(10,3)) for model, ax in zip([LinearSVC(), LogisticRegression()], axes): clf = model.fit(X, y) mglearn.plots.plot_2d_separator(clf, X, fill=False, eps=0.5, ax=ax, alpha=.7) ax.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap=mglearn.cm2) ax.set_title("%s" % clf.__class__.__name__) plt.show() print ("----------Multi-Class Uncertainty-------") from sklearn.ensemble import GradientBoostingClassifier gbrt = GradientBoostingClassifier(learning_rate=0.01, random_state=0) gbrt.fit(X_train, y_train) GradientBoostingClassifier(init=None, learning_rate=0.01, loss='deviance', max_depth=3, max_features=None, max_leaf_nodes=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, presort='auto', random_state=0, subsample=1.0, verbose=0, warm_start=False) print(gbrt.decision_function(X_test).shape) # plot the first few entries of the decision function print(gbrt.decision_function(X_test)[:6, :]) print(np.argmax(gbrt.decision_function(X_test), axis=1)) print(gbrt.predict(X_test)) # show the first few entries of predict_proba print(gbrt.predict_proba(X_test)[:6]) ```
github_jupyter
# Machine Learning Engineer Nanodegree ## Model Evaluation & Validation ## Project: Predicting Boston Housing Prices Welcome to the first project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully! In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode. ## Getting Started In this project, you will evaluate the performance and predictive power of a model that has been trained and tested on data collected from homes in suburbs of Boston, Massachusetts. A model trained on this data that is seen as a *good fit* could then be used to make certain predictions about a home — in particular, its monetary value. This model would prove to be invaluable for someone like a real estate agent who could make use of such information on a daily basis. The dataset for this project originates from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Housing). The Boston housing data was collected in 1978 and each of the 506 entries represent aggregated data about 14 features for homes from various suburbs in Boston, Massachusetts. For the purposes of this project, the following preprocessing steps have been made to the dataset: - 16 data points have an `'MEDV'` value of 50.0. These data points likely contain **missing or censored values** and have been removed. - 1 data point has an `'RM'` value of 8.78. This data point can be considered an **outlier** and has been removed. - The features `'RM'`, `'LSTAT'`, `'PTRATIO'`, and `'MEDV'` are essential. The remaining **non-relevant features** have been excluded. - The feature `'MEDV'` has been **multiplicatively scaled** to account for 35 years of market inflation. Run the code cell below to load the Boston housing dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported. ``` # Import libraries necessary for this project import numpy as np import pandas as pd from sklearn.cross_validation import ShuffleSplit # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the Boston housing dataset data = pd.read_csv('housing.csv') prices = data['MEDV'] features = data.drop('MEDV', axis = 1) # Success print "Boston housing dataset has {} data points with {} variables each.".format(*data.shape) ``` ## Data Exploration In this first section of this project, you will make a cursory investigation about the Boston housing data and provide your observations. Familiarizing yourself with the data through an explorative process is a fundamental practice to help you better understand and justify your results. Since the main goal of this project is to construct a working model which has the capability of predicting the value of houses, we will need to separate the dataset into **features** and the **target variable**. The **features**, `'RM'`, `'LSTAT'`, and `'PTRATIO'`, give us quantitative information about each data point. The **target variable**, `'MEDV'`, will be the variable we seek to predict. These are stored in `features` and `prices`, respectively. ### Implementation: Calculate Statistics For your very first coding implementation, you will calculate descriptive statistics about the Boston housing prices. Since `numpy` has already been imported for you, use this library to perform the necessary calculations. These statistics will be extremely important later on to analyze various prediction results from the constructed model. In the code cell below, you will need to implement the following: - Calculate the minimum, maximum, mean, median, and standard deviation of `'MEDV'`, which is stored in `prices`. - Store each calculation in their respective variable. ``` # TODO: Minimum price of the data minimum_price = np.min(prices) # TODO: Maximum price of the data maximum_price = np.max(prices) # TODO: Mean price of the data mean_price = np.mean(prices) # TODO: Median price of the data median_price = np.median(prices) # TODO: Standard deviation of prices of the data std_price = np.std(prices) # Show the calculated statistics print "Statistics for Boston housing dataset:\n" print "Minimum price: ${:,.2f}".format(minimum_price) print "Maximum price: ${:,.2f}".format(maximum_price) print "Mean price: ${:,.2f}".format(mean_price) print "Median price ${:,.2f}".format(median_price) print "Standard deviation of prices: ${:,.2f}".format(std_price) ``` ### Question 1 - Feature Observation As a reminder, we are using three features from the Boston housing dataset: `'RM'`, `'LSTAT'`, and `'PTRATIO'`. For each data point (neighborhood): - `'RM'` is the average number of rooms among homes in the neighborhood. - `'LSTAT'` is the percentage of homeowners in the neighborhood considered "lower class" (working poor). - `'PTRATIO'` is the ratio of students to teachers in primary and secondary schools in the neighborhood. ** Using your intuition, for each of the three features above, do you think that an increase in the value of that feature would lead to an **increase** in the value of `'MEDV'` or a **decrease** in the value of `'MEDV'`? Justify your answer for each.** **Hint:** This problem can phrased using examples like below. * Would you expect a home that has an `'RM'` value(number of rooms) of 6 be worth more or less than a home that has an `'RM'` value of 7? * Would you expect a neighborhood that has an `'LSTAT'` value(percent of lower class workers) of 15 have home prices be worth more or less than a neighborhood that has an `'LSTAT'` value of 20? * Would you expect a neighborhood that has an `'PTRATIO'` value(ratio of students to teachers) of 10 have home prices be worth more or less than a neighborhood that has an `'PTRATIO'` value of 15? **Answer: ** The values of these features will effect the value of MEDV as follows: * RM: According to me, as the number of rooms increase, it means a larger house. As a result, it will have a greater price. * LSTAT: I expect that greater the percentage of home owners of "lower class", lesser the price of the houses in the neighbourhood. * PTRATIO: High ratios of students/teachers mean that there are only few schools compared to the number of people living in the neighborhood. Therefore, this educational situation indicates an underdeveloped and less expensive neighborhood. ---- ## Developing a Model In this second section of the project, you will develop the tools and techniques necessary for a model to make a prediction. Being able to make accurate evaluations of each model's performance through the use of these tools and techniques helps to greatly reinforce the confidence in your predictions. ### Implementation: Define a Performance Metric It is difficult to measure the quality of a given model without quantifying its performance over training and testing. This is typically done using some type of performance metric, whether it is through calculating some type of error, the goodness of fit, or some other useful measurement. For this project, you will be calculating the [*coefficient of determination*](http://stattrek.com/statistics/dictionary.aspx?definition=coefficient_of_determination), R<sup>2</sup>, to quantify your model's performance. The coefficient of determination for a model is a useful statistic in regression analysis, as it often describes how "good" that model is at making predictions. The values for R<sup>2</sup> range from 0 to 1, which captures the percentage of squared correlation between the predicted and actual values of the **target variable**. A model with an R<sup>2</sup> of 0 is no better than a model that always predicts the *mean* of the target variable, whereas a model with an R<sup>2</sup> of 1 perfectly predicts the target variable. Any value between 0 and 1 indicates what percentage of the target variable, using this model, can be explained by the **features**. _A model can be given a negative R<sup>2</sup> as well, which indicates that the model is **arbitrarily worse** than one that always predicts the mean of the target variable._ For the `performance_metric` function in the code cell below, you will need to implement the following: - Use `r2_score` from `sklearn.metrics` to perform a performance calculation between `y_true` and `y_predict`. - Assign the performance score to the `score` variable. ``` # TODO: Import 'r2_score' from sklearn.metrics import r2_score def performance_metric(y_true, y_predict): """ Calculates and returns the performance score between true and predicted values based on the metric chosen. """ # TODO: Calculate the performance score between 'y_true' and 'y_predict' score = r2_score(y_true, y_predict) # Return the score return score ``` ### Question 2 - Goodness of Fit Assume that a dataset contains five data points and a model made the following predictions for the target variable: | True Value | Prediction | | :-------------: | :--------: | | 3.0 | 2.5 | | -0.5 | 0.0 | | 2.0 | 2.1 | | 7.0 | 7.8 | | 4.2 | 5.3 | Run the code cell below to use the `performance_metric` function and calculate this model's coefficient of determination. ``` # Calculate the performance of this model score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3]) print "Model has a coefficient of determination, R^2, of {:.3f}.".format(score) ``` * Would you consider this model to have successfully captured the variation of the target variable? * Why or why not? ** Hint: ** The R2 score is the proportion of the variance in the dependent variable that is predictable from the independent variable. In other words: * R2 score of 0 means that the dependent variable cannot be predicted from the independent variable. * R2 score of 1 means the dependent variable can be predicted from the independent variable. * R2 score between 0 and 1 indicates the extent to which the dependent variable is predictable. * R2 score of 0.40 means that 40 percent of the variance in Y is predictable from X. **Answer:** The model has a coefficient of determination, R^2, of 0.923. Therefore, I would consider the model to have successfully captured the variation of the target variable. With that score, 92.3% of the variance in Y is predictable from X. ### Implementation: Shuffle and Split Data Your next implementation requires that you take the Boston housing dataset and split the data into training and testing subsets. Typically, the data is also shuffled into a random order when creating the training and testing subsets to remove any bias in the ordering of the dataset. For the code cell below, you will need to implement the following: - Use `train_test_split` from `sklearn.cross_validation` to shuffle and split the `features` and `prices` data into training and testing sets. - Split the data into 80% training and 20% testing. - Set the `random_state` for `train_test_split` to a value of your choice. This ensures results are consistent. - Assign the train and testing splits to `X_train`, `X_test`, `y_train`, and `y_test`. ``` # TODO: Import 'train_test_split' from sklearn.cross_validation import train_test_split # TODO: Shuffle and split the data into training and testing subsets X = features y = prices X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 1) # Success print "Training and testing split was successful." ``` ### Question 3 - Training and Testing * What is the benefit to splitting a dataset into some ratio of training and testing subsets for a learning algorithm? **Hint:** Think about how overfitting or underfitting is contingent upon how splits on data is done. **Answer: ** The benefit of splitting of data into training and testing sets is that we can measure the accuracy of our model i.e how well it performs on unseen data. The testing data set works as a set of unseen data. The objective is to have the model perform on any data with the highest accuracy. Only when the model has been trained well and tested thoroughly, it is used for actual prediction applications. We should not use the same data for testing and training because that would make the model biased towards the test set. It wouldn't then show if overfitting occurred or not and how well generalized our model is. ---- ## Analyzing Model Performance In this third section of the project, you'll take a look at several models' learning and testing performances on various subsets of training data. Additionally, you'll investigate one particular algorithm with an increasing `'max_depth'` parameter on the full training set to observe how model complexity affects performance. Graphing your model's performance based on varying criteria can be beneficial in the analysis process, such as visualizing behavior that may not have been apparent from the results alone. ### Learning Curves The following code cell produces four graphs for a decision tree model with different maximum depths. Each graph visualizes the learning curves of the model for both training and testing as the size of the training set is increased. Note that the shaded region of a learning curve denotes the uncertainty of that curve (measured as the standard deviation). The model is scored on both the training and testing sets using R<sup>2</sup>, the coefficient of determination. Run the code cell below and use these graphs to answer the following question. ``` # Produce learning curves for varying training set sizes and maximum depths vs.ModelLearning(features, prices) ``` ### Question 4 - Learning the Data * Choose one of the graphs above and state the maximum depth for the model. * What happens to the score of the training curve as more training points are added? What about the testing curve? * Would having more training points benefit the model? **Hint:** Are the learning curves converging to particular scores? Generally speaking, the more data you have, the better. But if your training and testing curves are converging with a score above your benchmark threshold, would this be necessary? Think about the pros and cons of adding more training points based on if the training and testing curves are converging. **Answer: ** I have chosen the first graph, with a max_depth = 1. - The training score decreases significantly between 0 and 50 training points, then gradually continues to decrease by small increments until about 300, where it levels off. - The testing score increases significantly between 0 and 50 training points, then gradually continues to increase (with a couple small increase points). It levels off around 300 points as well, which is the closest point to the training score. - More training points do not appear to benefit the model after 300. Adding more points shows stabilization of the data with slight fluctuations around 0.42. ### Complexity Curves The following code cell produces a graph for a decision tree model that has been trained and validated on the training data using different maximum depths. The graph produces two complexity curves — one for training and one for validation. Similar to the **learning curves**, the shaded regions of both the complexity curves denote the uncertainty in those curves, and the model is scored on both the training and validation sets using the `performance_metric` function. ** Run the code cell below and use this graph to answer the following two questions Q5 and Q6. ** ``` vs.ModelComplexity(X_train, y_train) ``` ### Question 5 - Bias-Variance Tradeoff * When the model is trained with a maximum depth of 1, does the model suffer from high bias or from high variance? * How about when the model is trained with a maximum depth of 10? What visual cues in the graph justify your conclusions? **Hint:** High bias is a sign of underfitting(model is not complex enough to pick up the nuances in the data) and high variance is a sign of overfitting(model is by-hearting the data and cannot generalize well). Think about which model(depth 1 or 10) aligns with which part of the tradeoff. **Answer: ** When the model is trained with a maximum depth of 1, it suffers from high bias. Both training and validation scores are low, and the model is not complex enough. When the model is trained with a maximum depth of 10, it suffers from high variance. There is a significant gap between the training score and valudation score. ### Question 6 - Best-Guess Optimal Model * Which maximum depth do you think results in a model that best generalizes to unseen data? * What intuition lead you to this answer? ** Hint: ** Look at the graph above Question 5 and see where the validation scores lie for the various depths that have been assigned to the model. Does it get better with increased depth? At what point do we get our best validation score without overcomplicating our model? And remember, Occams Razor states "Among competing hypotheses, the one with the fewest assumptions should be selected." **Answer: ** The model that best generalizes to unseen data appears to be one with max_depth = 4, since the training and validation scores are both high and close together. After this point, they diverge significantly and validation score goes down. ----- ## Evaluating Model Performance In this final section of the project, you will construct a model and make a prediction on the client's feature set using an optimized model from `fit_model`. ### Question 7 - Grid Search * What is the grid search technique? * How it can be applied to optimize a learning algorithm? ** Hint: ** When explaining the Grid Search technique, be sure to touch upon why it is used, what the 'grid' entails and what the end goal of this method is. To solidify your answer, you can also give an example of a parameter in a model that can be optimized using this approach. **Answer: ** Grid search is a hyperparameter optimization technique that is scored against a performance metric. It is an algorithm with the help of which we can find the best hyper-parameter combinations of a ML model. The grid consists of the hyper-parameters to tune along one axis and the values for those hyper-parameters along the opposite axis. Grid Search will exhaustively search for all the possible parameter combinations and weigh them against a specified performance metric. It can be used to better classify parameters which will yield a better score and eleminate the parameters which have less or no effect thus, reducing the time taken for guessing the good parameters. ### Question 8 - Cross-Validation * What is the k-fold cross-validation training technique? * What benefit does this technique provide for grid search when optimizing a model? **Hint:** When explaining the k-fold cross validation technique, be sure to touch upon what 'k' is, how the dataset is split into different parts for training and testing and the number of times it is run based on the 'k' value. When thinking about how k-fold cross validation helps grid search, think about the main drawbacks of grid search which are hinged upon **using a particular subset of data for training or testing** and how k-fold cv could help alleviate that. You can refer to the [docs](http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation) for your answer. **Answer: ** K-fold cross-validation helps prevent overfitting and helps maximize data usage if the dataset is small. It splits the training set into k smaller subsets of data, then trains a model (this is the training data) using k-1 of the folds, or subsets.The process eliminates the need for a validation set of data, since the training set it also used for validation. Then, the result can be validated against the remaining data, which is used as a test set. ### Implementation: Fitting a Model Your final implementation requires that you bring everything together and train a model using the **decision tree algorithm**. To ensure that you are producing an optimized model, you will train the model using the grid search technique to optimize the `'max_depth'` parameter for the decision tree. The `'max_depth'` parameter can be thought of as how many questions the decision tree algorithm is allowed to ask about the data before making a prediction. Decision trees are part of a class of algorithms called *supervised learning algorithms*. In addition, you will find your implementation is using `ShuffleSplit()` for an alternative form of cross-validation (see the `'cv_sets'` variable). While it is not the K-Fold cross-validation technique you describe in **Question 8**, this type of cross-validation technique is just as useful!. The `ShuffleSplit()` implementation below will create 10 (`'n_splits'`) shuffled sets, and for each shuffle, 20% (`'test_size'`) of the data will be used as the *validation set*. While you're working on your implementation, think about the contrasts and similarities it has to the K-fold cross-validation technique. Please note that ShuffleSplit has different parameters in scikit-learn versions 0.17 and 0.18. For the `fit_model` function in the code cell below, you will need to implement the following: - Use [`DecisionTreeRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html) from `sklearn.tree` to create a decision tree regressor object. - Assign this object to the `'regressor'` variable. - Create a dictionary for `'max_depth'` with the values from 1 to 10, and assign this to the `'params'` variable. - Use [`make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html) from `sklearn.metrics` to create a scoring function object. - Pass the `performance_metric` function as a parameter to the object. - Assign this scoring function to the `'scoring_fnc'` variable. - Use [`GridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) from `sklearn.grid_search` to create a grid search object. - Pass the variables `'regressor'`, `'params'`, `'scoring_fnc'`, and `'cv_sets'` as parameters to the object. - Assign the `GridSearchCV` object to the `'grid'` variable. ``` # TODO: Import 'make_scorer', 'DecisionTreeRegressor', and 'GridSearchCV' from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import make_scorer from sklearn.grid_search import GridSearchCV def fit_model(X, y): """ Performs grid search over the 'max_depth' parameter for a decision tree regressor trained on the input data [X, y]. """ # Create cross-validation sets from the training data # sklearn version 0.18: ShuffleSplit(n_splits=10, test_size=0.1, train_size=None, random_state=None) # sklearn versiin 0.17: ShuffleSplit(n, n_iter=10, test_size=0.1, train_size=None, random_state=None) cv_sets = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.20, random_state = 0) # TODO: Create a decision tree regressor object regressor = DecisionTreeRegressor() # TODO: Create a dictionary for the parameter 'max_depth' with a range from 1 to 10 params = {'max_depth': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} # TODO: Transform 'performance_metric' into a scoring function using 'make_scorer' scoring_fnc = make_scorer(performance_metric) # TODO: Create the grid search cv object --> GridSearchCV() # Make sure to include the right parameters in the object: # (estimator, param_grid, scoring, cv) which have values 'regressor', 'params', 'scoring_fnc', and 'cv_sets' respectively. grid = GridSearchCV(estimator = regressor, param_grid = params, scoring = scoring_fnc, cv = cv_sets) # Fit the grid search object to the data to compute the optimal model grid = grid.fit(X, y) # Return the optimal model after fitting the data return grid.best_estimator_ ``` ### Making Predictions Once a model has been trained on a given set of data, it can now be used to make predictions on new sets of input data. In the case of a *decision tree regressor*, the model has learned *what the best questions to ask about the input data are*, and can respond with a prediction for the **target variable**. You can use these predictions to gain information about data where the value of the target variable is unknown — such as data the model was not trained on. ### Question 9 - Optimal Model * What maximum depth does the optimal model have? How does this result compare to your guess in **Question 6**? Run the code block below to fit the decision tree regressor to the training data and produce an optimal model. ``` # Fit the training data to the model using grid search reg = fit_model(X_train, y_train) # Produce the value for 'max_depth' print "Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth']) ``` ** Hint: ** The answer comes from the output of the code snipped above. **Answer: ** The optimal model has a maximum depth of 5. In question 6, I guessed a max_depth of 4 where as the optimal value comes out to be 5. This is completely okay as according to the graph in question 6, considering the value as 5, we get a good score and the training & testing scores tend to converge there too. ### Question 10 - Predicting Selling Prices Imagine that you were a real estate agent in the Boston area looking to use this model to help price homes owned by your clients that they wish to sell. You have collected the following information from three of your clients: | Feature | Client 1 | Client 2 | Client 3 | | :---: | :---: | :---: | :---: | | Total number of rooms in home | 5 rooms | 4 rooms | 8 rooms | | Neighborhood poverty level (as %) | 17% | 32% | 3% | | Student-teacher ratio of nearby schools | 15-to-1 | 22-to-1 | 12-to-1 | * What price would you recommend each client sell his/her home at? * Do these prices seem reasonable given the values for the respective features? **Hint:** Use the statistics you calculated in the **Data Exploration** section to help justify your response. Of the three clients, client 3 has has the biggest house, in the best public school neighborhood with the lowest poverty level; while client 2 has the smallest house, in a neighborhood with a relatively high poverty rate and not the best public schools. Run the code block below to have your optimized model make predictions for each client's home. ``` # Produce a matrix for client data client_data = [[5, 17, 15], # Client 1 [4, 32, 22], # Client 2 [8, 3, 12]] # Client 3 # Show predictions for i, price in enumerate(reg.predict(client_data)): print "Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price) ``` **Answer: ** The recommended price for Client 1 is $419,700. It has the middle number of rooms (5), neighborhood poverty level of 17%, and student-teacher ratio of 15-to-1. It has average parameters in all categories, so it makes sense for it to be of average price. The recommended price for Client 2 is $287,100. This is reasonable considering they have high poverty (32%) and student-to-teacher ratios (22-to-1), and the least number of rooms (4). The recommended price for Client 3 is $927,500. This is reasonable since it has the greatest number of rooms (8), a very low poverty level (3%), and the lowest student-teacher ratio (12-to-1). ### Sensitivity An optimal model is not necessarily a robust model. Sometimes, a model is either too complex or too simple to sufficiently generalize to new data. Sometimes, a model could use a learning algorithm that is not appropriate for the structure of the data given. Other times, the data itself could be too noisy or contain too few samples to allow a model to adequately capture the target variable — i.e., the model is underfitted. **Run the code cell below to run the `fit_model` function ten times with different training and testing sets to see how the prediction for a specific client changes with respect to the data it's trained on.** ``` vs.PredictTrials(features, prices, fit_model, client_data) ``` ### Question 11 - Applicability * In a few sentences, discuss whether the constructed model should or should not be used in a real-world setting. **Hint:** Take a look at the range in prices as calculated in the code snippet above. Some questions to answering: - How relevant today is data that was collected from 1978? How important is inflation? - Are the features present in the data sufficient to describe a home? Do you think factors like quality of apppliances in the home, square feet of the plot area, presence of pool or not etc should factor in? - Is the model robust enough to make consistent predictions? - Would data collected in an urban city like Boston be applicable in a rural city? - Is it fair to judge the price of an individual home based on the characteristics of the entire neighborhood? **Answer: ** The range in prices is $69,044.61. The constructed model should not be used in a real-world setting because it is 2018 now and the data we have worked upon is from 1978. The data collected from 1978 is still somewhat relevant, but doesn't account for several other factors that should be considered in today's time. The model is not robust enough to make consistent predictions, but it can be used to generalize. For example, if we know that most homes in the target area are approximately 2,000 square feet and were built in 1950, we can rely more heavily on the model. Data collected in an urban city like Boston would not be applicable in a rural city. Homes in rural cities often cost less due to their distance from jobs and city resources like shopping centers, and they also are often larger than city homes in general. It is not fair to judge the price of an individual home based on the characteristics of the entire neighborhood. A home could have been renovated or could have extra amenities that the typical neighborhood house does not have. > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.
github_jupyter
``` %matplotlib inline ``` # Early stopping of Gradient Boosting Gradient boosting is an ensembling technique where several weak learners (regression trees) are combined to yield a powerful single model, in an iterative fashion. Early stopping support in Gradient Boosting enables us to find the least number of iterations which is sufficient to build a model that generalizes well to unseen data. The concept of early stopping is simple. We specify a ``validation_fraction`` which denotes the fraction of the whole dataset that will be kept aside from training to assess the validation loss of the model. The gradient boosting model is trained using the training set and evaluated using the validation set. When each additional stage of regression tree is added, the validation set is used to score the model. This is continued until the scores of the model in the last ``n_iter_no_change`` stages do not improve by atleast `tol`. After that the model is considered to have converged and further addition of stages is "stopped early". The number of stages of the final model is available at the attribute ``n_estimators_``. This example illustrates how the early stopping can used in the :class:`sklearn.ensemble.GradientBoostingClassifier` model to achieve almost the same accuracy as compared to a model built without early stopping using many fewer estimators. This can significantly reduce training time, memory usage and prediction latency. ``` # Authors: Vighnesh Birodkar <vighneshbirodkar@nyu.edu> # Raghav RV <rvraghav93@gmail.com> # License: BSD 3 clause import time import numpy as np import matplotlib.pyplot as plt from sklearn import ensemble from sklearn import datasets from sklearn.model_selection import train_test_split print(__doc__) data_list = [datasets.load_iris(), datasets.load_digits()] data_list = [(d.data, d.target) for d in data_list] data_list += [datasets.make_hastie_10_2()] names = ['Iris Data', 'Digits Data', 'Hastie Data'] n_gb = [] score_gb = [] time_gb = [] n_gbes = [] score_gbes = [] time_gbes = [] n_estimators = 500 for X, y in data_list: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # We specify that if the scores don't improve by atleast 0.01 for the last # 10 stages, stop fitting additional stages gbes = ensemble.GradientBoostingClassifier(n_estimators=n_estimators, validation_fraction=0.2, n_iter_no_change=5, tol=0.01, random_state=0) gb = ensemble.GradientBoostingClassifier(n_estimators=n_estimators, random_state=0) start = time.time() gb.fit(X_train, y_train) time_gb.append(time.time() - start) start = time.time() gbes.fit(X_train, y_train) time_gbes.append(time.time() - start) score_gb.append(gb.score(X_test, y_test)) score_gbes.append(gbes.score(X_test, y_test)) n_gb.append(gb.n_estimators_) n_gbes.append(gbes.n_estimators_) bar_width = 0.2 n = len(data_list) index = np.arange(0, n * bar_width, bar_width) * 2.5 index = index[0:n] ``` Compare scores with and without early stopping ---------------------------------------------- ``` plt.figure(figsize=(9, 5)) bar1 = plt.bar(index, score_gb, bar_width, label='Without early stopping', color='crimson') bar2 = plt.bar(index + bar_width, score_gbes, bar_width, label='With early stopping', color='coral') plt.xticks(index + bar_width, names) plt.yticks(np.arange(0, 1.3, 0.1)) def autolabel(rects, n_estimators): """ Attach a text label above each bar displaying n_estimators of each model """ for i, rect in enumerate(rects): plt.text(rect.get_x() + rect.get_width() / 2., 1.05 * rect.get_height(), 'n_est=%d' % n_estimators[i], ha='center', va='bottom') autolabel(bar1, n_gb) autolabel(bar2, n_gbes) plt.ylim([0, 1.3]) plt.legend(loc='best') plt.grid(True) plt.xlabel('Datasets') plt.ylabel('Test score') plt.show() ``` Compare fit times with and without early stopping ------------------------------------------------- ``` plt.figure(figsize=(9, 5)) bar1 = plt.bar(index, time_gb, bar_width, label='Without early stopping', color='crimson') bar2 = plt.bar(index + bar_width, time_gbes, bar_width, label='With early stopping', color='coral') max_y = np.amax(np.maximum(time_gb, time_gbes)) plt.xticks(index + bar_width, names) plt.yticks(np.linspace(0, 1.3 * max_y, 13)) autolabel(bar1, n_gb) autolabel(bar2, n_gbes) plt.ylim([0, 1.3 * max_y]) plt.legend(loc='best') plt.grid(True) plt.xlabel('Datasets') plt.ylabel('Fit Time') plt.show() ```
github_jupyter
``` import numpy as np import matplotlib as mpl #mpl.use('pdf') import matplotlib.pyplot as plt import numpy as np plt.rc('font', family='serif', serif='Times') plt.rc('text', usetex=True) plt.rc('xtick', labelsize=6) plt.rc('ytick', labelsize=6) plt.rc('axes', labelsize=6) #axes.linewidth : 0.5 plt.rc('axes', linewidth=0.5) #ytick.major.width : 0.5 plt.rc('ytick.major', width=0.5) plt.rcParams['xtick.direction'] = 'in' plt.rcParams['ytick.direction'] = 'in' plt.rc('ytick.minor', visible=True) #plt.style.use(r"..\..\styles\infocom.mplstyle") # Insert your save location here # width as measured in inkscape fig_width = 3.487 #height = width / 1.618 / 2 fig_height = fig_width / 1.3 / 2 cc_folder_list = ["SF_new_results/", "capacity_results/", "BF_new_results/"] nc_folder_list = ["SF_new_results_NC/", "capacity_resultsNC/", "BF_new_results_NC/"] cc_folder_list = ["failure20stages-new-rounding/" + e for e in cc_folder_list] nc_folder_list = ["failure20stages-new-rounding/" + e for e in nc_folder_list] file_list = ["no-reconfig120.csv", "Link-reconfig120.csv", "LimitedReconfig120.csv", "Any-reconfig120.csv"] print(cc_folder_list) print(nc_folder_list) nc_objective_data = np.full((5, 3), 0) max_stage = 20 selected_stage = 10 for i in range(3): for j in range(4): with open(nc_folder_list[i]+file_list[j], "r") as f: if j != 2: f1 = f.readlines() start_line = 0 for line in f1: if line.find("%Stage") >= 0: break else: start_line = start_line + 1 #print(start_line) #print(len(f1)) line = f1[selected_stage+start_line] line = line.split(",") if j == 0: nc_objective_data[0, i] = float(line[2]) if j == 1: nc_objective_data[1, i] = float(line[2]) if j == 3: nc_objective_data[4, i] = float(line[2]) else: f1 = f.readlines() start_line = 0 start_line1 = 0 for line in f1: if line.find("%Stage") >= 0: break else: start_line = start_line + 1 for index in range(start_line+max_stage+1, len(f1)): start_line1 = index if f1[index].find("%Stage") >= 0: break else: start_line1 = start_line1 + 1 line = f1[selected_stage+start_line] line = line.split(",") nc_objective_data[2, i] = float(line[2]) #mesh3data[2, index] = int(line[1]) line = f1[selected_stage+start_line1] line = line.split(",") nc_objective_data[3, i] = float(line[2]) print(nc_objective_data) cc_objective_data = np.full((5, 3), 0) max_stage = 10 selected_stage = 10 for i in range(1): for j in range(4): with open(cc_folder_list[i]+file_list[j], "r") as f: if j != 2: f1 = f.readlines() start_line = 0 for line in f1: if line.find("%Stage") >= 0: break else: start_line = start_line + 1 #print(start_line) #print(len(f1)) line = f1[selected_stage+start_line] line = line.split(",") if j == 0: cc_objective_data[0, i] = float(line[2]) if j == 1: cc_objective_data[1, i] = float(line[2]) if j == 3: cc_objective_data[4, i] = float(line[2]) else: f1 = f.readlines() start_line = 0 start_line1 = 0 for line in f1: if line.find("%Stage") >= 0: break else: start_line = start_line + 1 for index in range(start_line+max_stage+1, len(f1)): if f1[index].find("%Stage") >= 0: start_line1 = index break else: start_line1 = start_line1 + 1 line = f1[selected_stage+start_line] line = line.split(",") cc_objective_data[2, i] = float(line[2]) #mesh3data[2, index] = int(line[1]) line = f1[selected_stage+start_line1] line = line.split(",") cc_objective_data[3, i] = float(line[2]) print(cc_objective_data) max_stage = 20 selected_stage = 10 for i in range(1, 3): for j in range(4): with open(cc_folder_list[i]+file_list[j], "r") as f: if j != 2: f1 = f.readlines() start_line = 0 for line in f1: if line.find("%Stage") >= 0: break else: start_line = start_line + 1 #print(start_line) #print(len(f1)) line = f1[selected_stage+start_line] line = line.split(",") if j == 0: cc_objective_data[0, i] = float(line[2]) if j == 1: cc_objective_data[1, i] = float(line[2]) if j == 3: cc_objective_data[4, i] = float(line[2]) else: f1 = f.readlines() start_line = 0 start_line1 = 0 for line in f1: if line.find("%Stage") >= 0: break else: start_line = start_line + 1 for index in range(start_line+max_stage+1, len(f1)): if f1[index].find("%Stage") >= 0: start_line1 = index break else: start_line1 = start_line1 + 1 line = f1[selected_stage+start_line] line = line.split(",") cc_objective_data[2, i] = float(line[2]) #mesh3data[2, index] = int(line[1]) line = f1[selected_stage+start_line1] line = line.split(",") cc_objective_data[3, i] = float(line[2]) print(cc_objective_data) (cc_objective_data - nc_objective_data) / nc_objective_data import numpy as np N = 3 ind = np.arange(N) width = 1 / 6 x = [0, '20', '30', '40'] x_tick_label_list = ['20', '30', '40'] fig, (ax1, ax2) = plt.subplots(1, 2) #ax1.bar(x, objective) #ax1.bar(x, objective[0]) label_list = ['No-rec', 'Link-rec', 'Lim-rec(3, 0)', 'Lim-rec(3, 1)', 'Any-rec'] patterns = ('//////','\\\\\\','---', 'ooo', 'xxx', '\\', '\\\\','++', '*', 'O', '.') plt.rcParams['hatch.linewidth'] = 0.25 # previous pdf hatch linewidth #plt.rcParams['hatch.linewidth'] = 1.0 # previous svg hatch linewidth #plt.rcParams['hatch.color'] = 'r' for i in range(5): ax1.bar(ind + width * (i-2), nc_objective_data[i], width, label=label_list[i], #alpha=0.7) hatch=patterns[i], alpha=0.7) #yerr=error[i], ecolor='black', capsize=1) ax1.grid(lw = 0.25) ax2.grid(lw = 0.25) ax1.set_xticklabels(x) ax1.set_ylabel('Objective value for NC') ax1.set_xlabel('Percentage of substrate failures (\%)') #ax1.set_ylabel('Objective value') #ax1.set_xlabel('Recovery Scenarios') ax1.xaxis.set_label_coords(0.5,-0.17) ax1.yaxis.set_label_coords(-0.17,0.5) #ax1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), # ncol=3, fancybox=True, shadow=True, fontsize='small') for i in range(5): ax2.bar(ind + width * (i-2), cc_objective_data[i], width, label=label_list[i], #alpha=0.7) hatch=patterns[i], alpha=0.7) ax2.set_xticklabels(x) ax2.set_ylabel('Objective value for CC') ax2.set_xlabel('Percentage of substrate failures (\%)') ax2.xaxis.set_label_coords(0.5,-0.17) ax2.yaxis.set_label_coords(-0.17,0.5) ax1.legend(loc='upper center', bbox_to_anchor=(1.16, 1.2), ncol=5, prop={'size': 5}) fig.set_size_inches(fig_width, fig_height) mpl.pyplot.subplots_adjust(wspace = 0.3) fig.subplots_adjust(left=.10, bottom=.20, right=.97, top=.85) #ax1.grid(color='b', ls = '-.', lw = 0.25) plt.show() fig.savefig('test-heuristic-failure-cc-nc.pdf') ```
github_jupyter
# Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will: * Write a function to take an SArray and a degree and return an SFrame where each column is the SArray to a polynomial value up to the total degree e.g. degree = 3 then column 1 is the SArray column 2 is the SArray squared and column 3 is the SArray cubed * Use matplotlib to visualize polynomial regressions * Use matplotlib to visualize the same polynomial degree on different subsets of the data * Use a validation set to select a polynomial degree * Assess the final fit using test data We will continue to use the House data from previous notebooks. # Fire up graphlab create ``` import graphlab ``` Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers up to the maximal degree. The easiest way to apply a power to an SArray is to use the .apply() and lambda x: functions. For example to take the example array and compute the third power we can do as follows: (note running this cell the first time may take longer than expected since it loads graphlab) ``` tmp = graphlab.SArray([1., 2., 3.]) tmp_cubed = tmp.apply(lambda x: x**3) print tmp print tmp_cubed ``` We can create an empty SFrame using graphlab.SFrame() and then add any columns to it with ex_sframe['column_name'] = value. For example we create an empty SFrame and make the column 'power_1' to be the first power of tmp (i.e. tmp itself). ``` ex_sframe = graphlab.SFrame() ex_sframe['power_1'] = tmp print ex_sframe ``` # Polynomial_sframe function Using the hints above complete the following function to create an SFrame consisting of the powers of an SArray up to a specific degree: ``` def polynomial_sframe(feature, degree): # assume that degree >= 1 # initialize the SFrame: poly_sframe = graphlab.SFrame() # and set poly_sframe['power_1'] equal to the passed feature # first check if degree > 1 if degree > 1: # then loop over the remaining degrees: # range usually starts at 0 and stops at the endpoint-1. We want it to start at 2 and stop at degree for power in range(2, degree+1): # first we'll give the column a name: name = 'power_' + str(power) # then assign poly_sframe[name] to the appropriate power of feature return poly_sframe ``` To test your function consider the smaller tmp variable and what you would expect the outcome of the following call: ``` print polynomial_sframe(tmp, 3) ``` # Visualizing polynomial regression Let's use matplotlib to visualize what a polynomial regression looks like on some real data. ``` sales = graphlab.SFrame('kc_house_data.gl/') ``` As in Week 3, we will use the sqft_living variable. For plotting purposes (connecting the dots), you'll need to sort by the values of sqft_living. For houses with identical square footage, we break the tie by their prices. ``` sales = sales.sort(['sqft_living', 'price']) ``` Let's start with a degree 1 polynomial using 'sqft_living' (i.e. a line) to predict 'price' and plot what it looks like. ``` poly1_data = polynomial_sframe(sales['sqft_living'], 1) poly1_data['price'] = sales['price'] # add price to the data since it's the target ``` NOTE: for all the models in this notebook use validation_set = None to ensure that all results are consistent across users. ``` model1 = graphlab.linear_regression.create(poly1_data, target = 'price', features = ['power_1'], validation_set = None) #let's take a look at the weights before we plot model1.get("coefficients") import matplotlib.pyplot as plt %matplotlib inline plt.plot(poly1_data['power_1'],poly1_data['price'],'.', poly1_data['power_1'], model1.predict(poly1_data),'-') ``` Let's unpack that plt.plot() command. The first pair of SArrays we passed are the 1st power of sqft and the actual price we then ask it to print these as dots '.'. The next pair we pass is the 1st power of sqft and the predicted values from the linear model. We ask these to be plotted as a line '-'. We can see, not surprisingly, that the predicted values all fall on a line, specifically the one with slope 280 and intercept -43579. What if we wanted to plot a second degree polynomial? ``` poly2_data = polynomial_sframe(sales['sqft_living'], 2) my_features = poly2_data.column_names() # get the name of the features poly2_data['price'] = sales['price'] # add price to the data since it's the target model2 = graphlab.linear_regression.create(poly2_data, target = 'price', features = my_features, validation_set = None) model2.get("coefficients") plt.plot(poly2_data['power_1'],poly2_data['price'],'.', poly2_data['power_1'], model2.predict(poly2_data),'-') ``` The resulting model looks like half a parabola. Try on your own to see what the cubic looks like: Now try a 15th degree polynomial: What do you think of the 15th degree polynomial? Do you think this is appropriate? If we were to change the data do you think you'd get pretty much the same curve? Let's take a look. # Changing the data and re-learning We're going to split the sales data into four subsets of roughly equal size. Then you will estimate a 15th degree polynomial model on all four subsets of the data. Print the coefficients (you should use .print_rows(num_rows = 16) to view all of them) and plot the resulting fit (as we did above). The quiz will ask you some questions about these results. To split the sales data into four subsets, we perform the following steps: * First split sales into 2 subsets with `.random_split(0.5, seed=0)`. * Next split the resulting subsets into 2 more subsets each. Use `.random_split(0.5, seed=0)`. We set `seed=0` in these steps so that different users get consistent results. You should end up with 4 subsets (`set_1`, `set_2`, `set_3`, `set_4`) of approximately equal size. Fit a 15th degree polynomial on set_1, set_2, set_3, and set_4 using sqft_living to predict prices. Print the coefficients and make a plot of the resulting model. Some questions you will be asked on your quiz: **Quiz Question: Is the sign (positive or negative) for power_15 the same in all four models?** **Quiz Question: (True/False) the plotted fitted lines look the same in all four plots** # Selecting a Polynomial Degree Whenever we have a "magic" parameter like the degree of the polynomial there is one well-known way to select these parameters: validation set. (We will explore another approach in week 4). We split the sales dataset 3-way into training set, test set, and validation set as follows: * Split our sales data into 2 sets: `training_and_validation` and `testing`. Use `random_split(0.9, seed=1)`. * Further split our training data into two sets: `training` and `validation`. Use `random_split(0.5, seed=1)`. Again, we set `seed=1` to obtain consistent results for different users. Next you should write a loop that does the following: * For degree in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] (to get this in python type range(1, 15+1)) * Build an SFrame of polynomial data of train_data['sqft_living'] at the current degree * hint: my_features = poly_data.column_names() gives you a list e.g. ['power_1', 'power_2', 'power_3'] which you might find useful for graphlab.linear_regression.create( features = my_features) * Add train_data['price'] to the polynomial SFrame * Learn a polynomial regression model to sqft vs price with that degree on TRAIN data * Compute the RSS on VALIDATION data (here you will want to use .predict()) for that degree and you will need to make a polynmial SFrame using validation data. * Report which degree had the lowest RSS on validation data (remember python indexes from 0) (Note you can turn off the print out of linear_regression.create() with verbose = False) **Quiz Question: Which degree (1, 2, …, 15) had the lowest RSS on Validation data?** Now that you have chosen the degree of your polynomial using validation data, compute the RSS of this model on TEST data. Report the RSS on your quiz. **Quiz Question: what is the RSS on TEST data for the model with the degree selected from Validation data?**
github_jupyter
# Problems ``` import math import pandas as pd from sklearn import preprocessing from sklearn.neighbors import NearestNeighbors, KNeighborsClassifier, KNeighborsRegressor from sklearn.model_selection import train_test_split from sklearn.metrics.pairwise import euclidean_distances from sklearn.metrics import accuracy_score, mean_squared_error from dmutils import classification_summary from dmutils import regression_summary ``` **1. Calculating Distance with Categorical Predictors.** This exercise with a tiny dataset illustrates the calculation of Euclidean distance, and the creation of binary dummies. The online education company Statistics.com segments its customers and prospects into three main categories: IT professionals (IT), statisticians (Stat), and other (Other). It also tracks, for each customer, the number of years since first contact (years). Consider the following customers; information about whether they have taken a course or not (the outcome to be predicted) is included: Customer 1: Stat, 1 year, did not take course Customer 2: Other, 1.1 year, took course **a.** Consider now the following new prospect: Prospect 1: IT, 1 year Using the above information on the two customers and one prospect, create one dataset for all three with the categorical predictor variable transformed into 2 binaries, and a similar dataset with the categorical predictor variable transformed into 3 binaries. ``` # dataset for all three customers with the categorical predictor (category) # transformed into 2 binaries tiny_two_cat_dummies_df = pd.DataFrame({"IT": [0, 0, 1], "Stat": [1, 0, 0], "years_since_first_contact": [1, 1.1, 1], "course": [0, 1, None]}) tiny_two_cat_dummies_df # dataset for all three customers with the categorical predictor (category) # transformed into 3 binaries tiny_all_cat_dummies_df = pd.DataFrame({"IT": [0, 0, 1], "Stat": [1, 0, 0], "Other": [0, 1, 0], "years_since_first_contact": [1, 1.1, 1], "course": [0, 1, None]}) tiny_all_cat_dummies_df ``` **b.** For each derived dataset, calculate the Euclidean distance between the prospect and each of the other two customers. (Note: While it is typical to normalize data for k-NN, this is not an iron-clad rule and you may proceed here without normalization.) - Two categorical dummies (IT/Stat): ``` predictors = ["IT", "Stat", "years_since_first_contact"] pd.DataFrame(euclidean_distances(tiny_two_cat_dummies_df[predictors], tiny_two_cat_dummies_df[predictors]), columns=["customer_1", "customer_2", "customer_3"], index=["customer_1", "customer_2", "customer_3"]) ``` - Three categorical dummies (IT/Stat/Other): ``` predictors = ["IT", "Stat", "Other", "years_since_first_contact"] pd.DataFrame(euclidean_distances(tiny_all_cat_dummies_df[predictors], tiny_all_cat_dummies_df[predictors]), columns=["customer_1", "customer_2", "customer_3"], index=["customer_1", "customer_2", "customer_3"]) ``` We can already see the effect of using two/three dummy variables. For the two dummy variables dataset, the `customer_3` is nearer to `customer_2` than to `customer_1`. This happens because the variable `years_since_first_contact` are the same for the both customers. For the three dummy variables, we still see that the `customer_3` are nearer to `customer_1` than to `customer_2` though the distances are very close between all customers. This happens because the `Other` variable helps to discriminate each of the customers. In contrast to the situation with statistical models such as regression, all *m* binaries should be created and used with *k*-NN. While mathematically this is redundant, since *m* - 1 dummies contain the same information as *m* dummies, this redundant information does not create the multicollinearity problems that it does for linear models. Moreover, in *k*-NN the use of *m* - 1 dummies can yield different classifications than the use of *m* dummies, and lead to an imbalance in the contribution of the different categories to the model. **c.** Using k-NN with k = 1, classify the prospect as taking or not taking a course using each of the two derived datasets. Does it make a difference whether you use two or three dummies? - Two dummies variables (IT/Stat) ``` predictors = ["IT", "Stat", "years_since_first_contact"] # user NearestNeighbors from scikit-learn to compute knn knn = NearestNeighbors(n_neighbors=1) knn.fit(tiny_two_cat_dummies_df.loc[:1, predictors]) new_customer = pd.DataFrame({"IT": [1], "Stat": [0], "years_since_first_contact": [1]}) distances, indices = knn.kneighbors(new_customer) # indices is a list of lists, we are only interested in the first element tiny_two_cat_dummies_df.iloc[indices[0], :] ``` - Three dummies variable(IT/Stat/Other) ``` predictors = ["IT", "Stat", "Other", "years_since_first_contact"] # user NearestNeighbors from scikit-learn to compute knn knn = NearestNeighbors(n_neighbors=1) knn.fit(tiny_all_cat_dummies_df.loc[:1, predictors]) new_customer = pd.DataFrame({"IT": [1], "Stat": [0], "Other": [1], "years_since_first_contact": [1]}) distances, indices = knn.kneighbors(new_customer) # indices is a list of lists, we are only interested in the first element tiny_all_cat_dummies_df.iloc[indices[0], :] ``` If we use *k* = 1, the nearest customer is the one that took the course for both variables. Therefore, for this specific example there was no difference on using two or three categorical variable. Therefore, as indicated in the previous item (**b**), this redundant information does not create the multicollinearity problems that it does for linear models. Moreover, in *k*-NN the use of *m* - 1 dummies can yield different classifications than the use of *m* dummies, and lead to an imbalance in the contribution of the different categories to the model. **2. Personal Loan Acceptance.** Universal Bank is a relatively young bank growing rapidly in terms of overall customer acquisition. The majority of these customers are liability customers (depositors) with varying sizes of relationship with the bank. The customer base of asset customers (borrowers) is quite small, and the bank is interested in expanding this base rapidly to bring in more loan business. In particular, it wants to explore ways of converting its liability customers to personal loan customers (while retaining them as depositors). A campaign that the bank ran last year for liability customers showed a healthy conversion rate of over 9% success. This has encouraged the retail marketing department to devise smarter campaigns with better target marketing. The goal is to use *k*-NN to predict whether a new customer will accept a loan offer. This will serve as the basis for the design of a new campaign. The file `UniversalBank.csv` contains data on 5000 customers. The data include customer demographic information (age, income, etc.), the customer's relationship with the bank (mortgage, securities account, etc.), and the customer response to the last personal loan campaign (Personal Loan). Among these 5000 customers, only 480 (=9.6%) accepted the personal loan that was offered to them in the earlier campaign. Partition the data into training (60%) and validation (40%) sets. **a.** Consider the following customer: Age = 40, Experience = 10, Income = 84, Family = 2, CCAvg = 2, Education_1 = 0, Education_2 = 1, Education_3 = 0, Mortgage = 0, Securities Account = 0, CDAccount = 0, Online = 1, and Credit Card = 1. Perform a *k*-NN classification with all predictors except ID and ZIP code using k = 1. Remember to transform categorical predictors with more than two categories into dummy variables first. Specify the success class as 1 (loan acceptance), and use the default cutoff value of 0.5. How would this customer be classified? ``` customer_df = pd.read_csv("../datasets/UniversalBank.csv") customer_df.head() # define predictors and the outcome for this problem predictors = ["Age", "Experience", "Income", "Family", "CCAvg", "Education", "Mortgage", "Securities Account", "CD Account", "Online", "CreditCard"] outcome = "Personal Loan" # before k-NN, we will convert 'Education' to binary dummies. # 'Family' remains unchanged customer_df = pd.get_dummies(customer_df, columns=["Education"], prefix_sep="_") # update predictors to include the new dummy variables predictors = ["Age", "Experience", "Income", "Family", "CCAvg", "Education_1", "Education_2", "Education_3", "Mortgage", "Securities Account", "CD Account", "Online", "CreditCard"] # partition the data into training 60% and validation 40% sets train_data, valid_data = train_test_split(customer_df, test_size=0.4, random_state=26) # equalize the scales that the various predictors have(standardization) scaler = preprocessing.StandardScaler() scaler.fit(train_data[predictors]) # transform the full dataset customer_norm = pd.concat([pd.DataFrame(scaler.transform(customer_df[predictors]), columns=["z"+col for col in predictors]), customer_df[outcome]], axis=1) train_norm = customer_norm.iloc[train_data.index] valid_norm = customer_norm.iloc[valid_data.index] # new customer new_customer = pd.DataFrame({"Age": [40], "Experience": [10], "Income": [84], "Family": [2], "CCAvg": [2], "Education_1": [0], "Education_2": [1], "Education_3": [0], "Mortgage": [0], "Securities Account": [0], "CDAccount": [0], "Online": [1], "Credit Card": [1]}) new_customer_norm = pd.DataFrame(scaler.transform(new_customer), columns=["z"+col for col in predictors]) # use NearestNeighbors from scikit-learn to compute knn # using all the dataset (training + validation sets) here! knn = NearestNeighbors(n_neighbors=1) knn.fit(customer_norm.iloc[:, 0:-1]) distances, indices = knn.kneighbors(new_customer_norm) # indices is a list of lists, we are only interested in the first element customer_norm.iloc[indices[0], :] ``` Since the closest customer did not accepted the loan (=0), we can estimate for the new customer a probability of 1 of being an non-borrower (and 0 for being a borrower). Using a simple majority rule is equivalent to setting the cutoff value to 0.5. In the above results, we see that the software assigned class non-borrower to this record. **b.** What is a choice of *k* that balances between overfitting and ignoring the predictor information? First, we need to remember that a balanced choice greatly depends on the nature of the data. The more complex and irregular the structure of the data, the lower the optimum value of *k*. Typically, values of *k* fall in the range of 1-20. We will use odd numbers to avoid ties. If we choose *k* = 1, we will classify in a way that is very sensitive to the local characteristics of the training data. On the other hand, if we choose a large value of *k*, such as *k* = 14, we would simply predict the most frequent class in the dataset in all cases. To find a balance, we examine the accuracy (of predictions in the validation set) that results from different choices of *k* between 1 and 14. ``` train_X = train_norm[["z"+col for col in predictors]] train_y = train_norm[outcome] valid_X = valid_norm[["z"+col for col in predictors]] valid_y = valid_norm[outcome] # Train a classifier for different values of k results = [] for k in range(1, 15): knn = KNeighborsClassifier(n_neighbors=k).fit(train_X, train_y) results.append({"k": k, "accuracy": accuracy_score(valid_y, knn.predict(valid_X))}) # Convert results to a pandas data frame results = pd.DataFrame(results) results ``` Based on the above table, we would choose **k = 3** (though **k = 5** appears to be another option too), which maximizes our accuracy in the validation set. Note, however, that now the validation set is used as part of the training process (to set *k*) and does not reflect a true holdout set as before. Ideally, we would want a third test set to evaluate the performance of the method on data that it did not see. **c.** Show the confusion matrix for the validation data that results from using the best *k*. - k = 3 ``` knn = KNeighborsClassifier(n_neighbors=3).fit(train_X, train_y) classification_summary(y_true=valid_y, y_pred=knn.predict(valid_X)) ``` - k = 5 ``` knn = KNeighborsClassifier(n_neighbors=5).fit(train_X, train_y) classification_summary(y_true=valid_y, y_pred=knn.predict(valid_X)) ``` **d.** Consider the following customer: Age = 40, Experience = 10, Income = 84, Family = 2, CCAvg = 2, Education_1 = 0, Education_2 = 1, Education_3 = 0, Mortgage = 0, Securities Account = 0, CD Account = 0, Online = 1 and Credit Card = 1. Classify the customer using the best *k*. Note: once *k* is chosen, we rerun the algorithm on the combined training and testing sets in order to generate classifications of new records. ``` # using the same user created before :) knn = KNeighborsClassifier(n_neighbors=3).fit(customer_norm.iloc[:, 0:-1], customer_norm.loc[:, "Personal Loan"]) knn.predict(new_customer_norm), knn.predict_proba(new_customer_norm) knn = KNeighborsClassifier(n_neighbors=5).fit(customer_norm.iloc[:, 0:-1], customer_norm.loc[:, "Personal Loan"]) knn.predict(new_customer_norm), knn.predict_proba(new_customer_norm) ``` Using the best *k* (=3) the user was classified as a **non-borrower**. Also with *k* = 5 **e**. Repartition the data, this time into training, validation, and test sets (50%:30%:20%). Apply the *k*-NN method with the *k* chosen above. Compare the confusion matrix of the test set with that of the training and validation sets. Comment on the differences and their reason. ``` # using the customer_norm computed earlier # training: 50% # validation: 30% (0.5 * 0.6) # test: 20% (0.5 * 0.4) train_data, temp = train_test_split(customer_df, test_size=0.50, random_state=1) valid_data, test_data = train_test_split(temp, test_size=0.40, random_state=1) train_norm = customer_norm.iloc[train_data.index] valid_norm = customer_norm.iloc[valid_data.index] test_norm = customer_norm.iloc[test_data.index] train_X = train_norm[["z"+col for col in predictors]] train_y = train_norm[outcome] valid_X = valid_norm[["z"+col for col in predictors]] valid_y = valid_norm[outcome] test_X = test_norm[["z"+col for col in predictors]] test_y = test_norm[outcome] knn = KNeighborsClassifier(n_neighbors=3).fit(train_X, train_y) print("Training set\n" + "*" * 12) classification_summary(y_true=train_y, y_pred=knn.predict(train_X)) print("\nValidation set\n" + "*" * 14) classification_summary(y_true=valid_y, y_pred=knn.predict(valid_X)) print("\nTest set\n" + "*" * 8) classification_summary(y_true=test_y, y_pred=knn.predict(test_X)) ``` Based on the training, validation, and test matrices we can see a steady increase in the percentage error from training set and validation/test sets. As the model is being fit on the training data it would make intuitive sense that the classifications are most accurate on it rather than validation/test datasets. We can see also that there does not appear to be overfitting due to the minimal error discrepancies among all three matrices, and specially between validation and test sets. **3. Predicting Housing Median Prices.** The file `BostonHousing.csv` contains information on over 500 census tracts in Boston, where for each tract multiple variables are recorded. The last column (`CAT.MEDV`) was derived from `MEDV`, such that it obtains the value 1 if `MEDV` > 30 and 0 otherwise. Consider the goal of predicting the median value (`MEDV`) of a tract, given the information in the first 12 columns. Partition the data into training (60%) and validation (40%) sets. **a.** Perform a *k*-NN prediction with all 12 predictors (ignore the `CAT.MEDV` column), trying values of *k* from 1 to 5. Make sure to normalize the data. What is the best *k*? What does it mean? The idea of *k*-NN can readily be extended to predicting a continuous value (as is our aim with multiple linear regression models). The first step of determining neighbors by computing distances remains unchanged. The second step, where a majority vote of the neighbors is used to determine class, is modified such that we take the average outcome value of the *k*-nearest neighbors to determine the prediction. Often, this average is a weighted average, with the weight decreasing with increasing distance from the point at which the prediction is required. In `scikit-learn`, we can use `KNeighborsRegressor` to compute *k*-NN numerical predictions for the validation set. Another modification is in the error metric used for determining the "best k". Rather than the overall error rate used in classification, RMSE (root-mean-squared error) or another prediction error metric should be used in prediction. ``` housing_df = pd.read_csv("../datasets/BostonHousing.csv") housing_df.head() # define predictors and the outcome for this problem predictors = ["CRIM", "ZN", "INDUS", "CHAS", "NOX", "RM", "AGE", "DIS", "RAD", "TAX", "PTRATIO", "LSTAT"] outcome = "MEDV" # partition the data into training 60% and validation 40% sets train_data, valid_data = train_test_split(housing_df, test_size=0.4, random_state=26) # equalize the scales that the various predictors have(standardization) scaler = preprocessing.StandardScaler() scaler.fit(train_data[predictors]) # transform the full dataset housing_norm = pd.concat([pd.DataFrame(scaler.transform(housing_df[predictors]), columns=["z"+col for col in predictors]), housing_df[outcome]], axis=1) train_norm = housing_norm.iloc[train_data.index] valid_norm = housing_norm.iloc[valid_data.index] # Perform a k-NN prediction with all 12 predictors # trying values of k from 1 to 5 train_X = train_norm[["z"+col for col in predictors]] train_y = train_norm[outcome] valid_X = valid_norm[["z"+col for col in predictors]] valid_y = valid_norm[outcome] # Train a classifier for different values of k # Using weighted average results = [] for k in range(1, 6): knn = KNeighborsRegressor(n_neighbors=k, weights="distance").fit(train_X, train_y) y_pred = knn.predict(valid_X) y_res = valid_y - y_pred results.append({"k": k, "mean_error": sum(y_res) / len(y_res), "rmse": math.sqrt(mean_squared_error(valid_y, y_pred)), "mae": sum(abs(y_res)) / len(y_res)}) # Convert results to a pandas data frame results = pd.DataFrame(results) results ``` Using the RMSE (root mean squared errors) as the *k* decision driver, the best *k* is 4. We choose 4 as a way to minimize the errors found in the validation set. Note, however, that now the validation set is used as part of the training process (to set *k*) and does not reflect a true holdout set as before. Note also that performance on validation data may be overly optimistic when it comes to predicting performance on data that have not been exposed to the model at all. This is because when the validation data are used to select a final model among a set of model, we are selecting based on how well the model performs with those data and therefore may be incorporating some of the random idiosyncrasies (bias) of the validation data into the judgment about the best model. The model still may be the best for the validation data among those considered, but it will probably not do as well with the unseen data. Therefore, it is useful to evaluate the chosen model on a new test set to get a sense of how well it will perform on new data. In addition, one must consider practical issues such as costs of collecting variables, error-proneness, and model complexity in the selection of the final model. **b.** Predict the `MEDV` for a tract with the following information, using the best *k*: CRIM: 0.2 ZN: 0 INDUS: 7 CHAS: 0 NOX: 0.538 RM: 6 AGE: 62 DIS: 4.7 RAD: 4 TAX: 307 PTRATIO: 21 LSTAT: 10 Once *k* is chosen, we rerun the algorithm on the combined training and testing sets in order to generate classifications of new records. ``` # new house to be predicted. Before predicting the MEDV we normalize it new_house = pd.DataFrame({"CRIM": [0.2], "ZN": [0], "INDUS": [7], "CHAS": [0], "NOX": [0.538], "RM": [6], "AGE": [62], "DIS": [4.7], "RAD": [4], "TAX": [307], "PTRATIO": [21], "LSTAT": [10]}) new_house_norm = pd.DataFrame(scaler.transform(new_house), columns=["z"+col for col in predictors]) # retrain the knn using the best k and all data knn = KNeighborsRegressor(n_neighbors=4, weights="distance").fit(housing_norm[["z"+col for col in predictors]], housing_norm[outcome]) knn.predict(new_house_norm) ``` The new house has a predicted value of 19.6 (in \\$1000s) **c.** If we used the above *k*-NN algorithm to score the training data, what would be the error of the training set? It would be zero or near zero. This happens because the best *k* was selected from a model built using such dataset. Therefore, we have used the same data for fitting the classification functions and for estimating the error. ``` # Using the previous trained model (all data, k=5) y_pred = knn.predict(train_X) y_res = train_y - y_pred results = {"k": 4, "mean_error": sum(y_res) / len(y_res), "rmse": math.sqrt(mean_squared_error(train_y, y_pred)), "mae": sum(abs(y_res)) / len(y_res)} # Convert results to a pandas data frame results = pd.DataFrame(results, index=[0]) results ``` **d.** Why is the validation data error overly optimistic compared to the error rate when applying this *k*-NN predictor to new data? When we use the validation data to assess multiple models and then choose the model that performs best with the validation data, we again encounter another (lesser) facet of the overfitting problem - chance aspects of the validation data that happen to match the chosen model better than they match other models. In other words, by using the validation data to choose one of several models, the performance of the chosen model on the validation data will be overly optimistic. In other words, chances are that the training/validation sets can be biased, so cross-validation would give a better approximation in this scenario. **e.** If the purpose is to predict `MEDV` for several thousands of new tracts, what would be the disadvantage of using *k*-NN prediction? List the operations that the algorithm goes through in order to produce each prediction. The disadvantage of the *k*-NN in this case would be it's laziness characteristic meaning that it would take too much time to predict all the cases. Basically, the algorithm would need to perform the following operations repeatedly for each case to predict the `MEDV` value for them: - Normalize the data of each new variable for each case based on the mean and standard deviation in training data set; - Calculate the distance of this case from all the training data; - Sorting the new data based on the calculated distances; - Use the majority rule on the first *k* nearest neighbors to predict the new case; And as mentioned this process would be repeated for each of the thousands of new cases which would be computationally expensive and time consuming.
github_jupyter
``` %matplotlib inline import control from control.matlab import * import numpy as np import matplotlib.pyplot as plt def pole_plot(poles, title='Pole Map'): plt.title(title) plt.scatter(np.real(poles), np.imag(poles), s=50, marker='x') plt.axhline(y=0, color='black'); plt.axvline(x=0, color='black'); plt.xlabel('Re'); plt.ylabel('Im'); ``` # Tune Those Gains! State space control requires that you fill in up to three gain matrices (K, L & I), each potentially containing a number of elements. Given the heurism that goes into selecting PID gains (of which there are only three) tuning a state space controller can seem a bit daunting. Fortunately, the state space control framework includes a formal way to calculate gains to arrive at what is called a Linear Quadratic Regulator as well as a Linear Quadratic Estimator. The goal of this notebook will be to walk you through the steps necessary to formulate the gains for an LQR and LQE. Once we've arrived at some acceptable gains, you can cut and paste them directly into your arduino sketch and start controlling some cool, complex dynamic systems with hopefully less guesswork and gain tweaking than if you were use a PID controller. We'll be working from the model for the cart pole system from the examples folder. This system has multiple outputs and is inherently unstable so it's a nice way of showing the power of state space control. Having said that, **this analysis can apply to any state space model**, so to adapt it your system, just modify the system matricies ($A,B,C,D$) and the and cost function weighting matrices ($ Q_{ctrl}, R_{ctrl}, Q_{est}, R_{est} $ ) and rerun the notebook. ## Cart Pole You can find the details on the system modelling for the inverted pendulum [here](http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=SystemModeling) but by way of a quick introduction, the physical system consists of a pendulum mounted on top of a moving cart shown below. The cart is fitted with two sensors that measure the angle of the stick and the displacement of the cart. The cart also has an actuator to apply a horizontal force on the cart to drive it forwards and backwards. The aim of the controller is to manipulate the force on the cart in order to balance the stick upright. ![output](http://ctms.engin.umich.edu/CTMS/Content/InvertedPendulum/System/Modeling/figures/pendulum.png) The state for this system is defined as: \begin{equation} \mathbf{x} = [ cart \;displacement, \; cart \;velocity, \; stick \;angle, \; stick \;angular\; velocity ]^T \end{equation} and the state space model that describes this system is as follows: ``` A = [[0.0, 1.0, 0.0, 0.0 ], [0.0, -0.18, 2.68, 0.0 ], [0.00, 0.00, 0.00, 1.00], [0.00, -0.45, 31.21, 0.00]] B = [[0.00], [1.82], [0.00], [4.55]] C = [[1, 0, 0, 0],[0,0,1,0]] D = [[0],[0]] ``` ## Take a look at the Open Loop System Poles To get an idea of how this system behaves before we add any feedback control we can look at the poles of the open loop (uncontrolled) system. Poles are the roots of a characteristic equation derived from the system model. They're often complex numbers (having a real and an imaginary component) and are useful in understanding how the output of a system will respond to changes in its input. There's quite a bit of interesting information that can be gleaned from looking at system poles but for now we'll focus on stability; which is determined by the pole with the largest real component (the x-axis in the plot below). If a system has any poles with positive real components then that system will be inherently unstable (i.e some or all of the state will shoot off to infinity if the system is left to its own devices). The inverted pendulum has a pole at Re(+5.56) which makes sense when you consider that if the stick is stood up on its end and let go it'd fall over (obviously it'd stop short of infinity when it hits the side of the cart, but this isn't taken into account by the model). Using a feedback controller we'll move this pole over to the left of the imaginary axis in the plot below and in so doing, stabilise the system. ``` plant = ss(A, B, C, D) open_loop_poles = pole(plant) print '\nThe poles of the open loop system are:\n' print open_loop_poles pole_plot(open_loop_poles, 'Open Loop Poles') ``` # Design a Control Law With a model defined, we can get started on calculating the gain matrix K (the control law) which determines the control input necessary to regulate the system state to $ \boldsymbol{0} $ (all zeros, you might want to control it to other set points but to do so just requires offsetting the control law which can be calculated on the arduino). ## Check for Controllability For it to be possible to control a system defined by a given state space model, that model needs to be controllable. Being controllable simply means that the available set of control inputs are capable of driving the entire state to a desired set point. If there's a part of the system that is totally decoupled from the actuators that are manipulated by the controller then a system won't be controllable. A system is controllable if the rank of the controllability matrix is the same as the number of states in the system model. ``` controllability = ctrb(A, B) print 'The controllability matrix is:\n' print controllability if np.linalg.matrix_rank(controllability) == np.array(B).shape[0]: print '\nThe system is controllable!' else: print '\nThe system is not controllable, double-check your modelling and that you entered the system matrices correctly' ``` ## Fill out the Quadratic Cost Function Assuming the system is controllable, we can get started on calculating the control gains. The approach we take here is to calculate a Linear Quadratic Regulator. An LQR is basically a control law (K matrix) that minimises the quadratic cost function: \begin{equation} J = \int_0^\infty (\boldsymbol{x}' Q \boldsymbol{x} + \boldsymbol{u}' R \boldsymbol{u})\; dt \end{equation} The best way to think about this cost function is to realise that whenever we switch on the state space controller, it'll expend some amount of control effort to bring the state to $ \boldsymbol{0} $ (all zeros). Ideally it'll do that as quickly and with as little overshoot as possible. We can represent that with the expression $ \int_0^\infty \boldsymbol{x}' \;\boldsymbol{x} \; dt $. Similarly it's probably a good idea to keep the control effort to a minimum such that the controller is energy efficient and doesn't damage the system with overly aggressive control inputs. This total control effort can be represented with $ \int_0^\infty \boldsymbol{u}' \;\boldsymbol{u} \; dt $. Inevitably, there'll be some parts of the state and some control inputs that we care about minimising more than others. To reflect that in the cost function we specify two matrices; $ Q $ and $ R $ $ Q_{ctrl} \in \mathbf{R}^{X \;\times\; X} $ is the state weight matrix; the elements on its diagonal represent how important it is to tighly control the corresponding state element (as in Q[0,0] corresponds to x[0]). $ R_{ctrl} \in \mathbf{R}^{U \;\times\; U} $ is the input weight matrix; the elements on its diagonal represent how important it is to minimise the use of the corresponding control input (as in R[0,0] corresponds to u[0]). ``` Q_ctrl = [[5000, 0, 0, 0], [0, 0, 0, 0], [0, 0, 100, 0], [0, 0, 0, 0]] R_ctrl = [1] ``` ## Calculate the Gain Matrix for a Linear Quadratic Regulator With a cost function defined, the cell below will calculate the gain matrix K for an LQR. Bear in mind it usually takes a bit of tweaking of the cost function to arrive at a good K matrix. Also note that it's the relative value of each weight that's important, not their absolute values. You can multiply both $ Q_{ctrl} $ and $ R_{ctrl} $ by 1e20 and you'll still wind up with the same gains. To guide your tweaking it's helpful to see the effect that different weightings have on the closed loop system poles. Remember that the further the dominant pole (largest real component) is to the left of the Im axis, the more stable your system will be. That said, don't get carried away and set ridiculously high gains; your actual system might not behave in exactly the same way as the model and an overly aggressive controller might just end up destabilising the system under realistic conditions. ``` K, _, _ = lqr(A, B, Q_ctrl, R_ctrl) print 'The control gain is:\n' print 'K = ', K plant_w_full_state_feedback = ss(A, B, np.identity(plant.states), np.zeros([plant.states, plant.inputs])) controller = ss(np.zeros([plant.states, plant.states]), np.zeros([plant.states, plant.states]), np.zeros([plant.inputs, plant.states]), K) closed_loop_system = feedback(plant_w_full_state_feedback, controller) closed_loop_poles = pole(closed_loop_system) print '\nThe poles of the closed loop system are:\n' print closed_loop_poles pole_plot(closed_loop_poles, 'Closed Loop Poles') ``` # Design an Estimator If you're lucky enough to be able to directly observe the system's entire state (in which case the $ C $ matrix will be an identity matrix) then you're done! This obviously isn't the case for the cart pole since given our sensors we aren't able to directly observe the cart velocity or the stick angular velocity (we can differentiate the sensor readings ofcourse, but doing so is a bad idea if the sensors are even a little bit noisy). Because of this, we'll need to introduce an estimator into the feedback controller to reconstruct those parts of the state based on our sensor readings $ \mathbf{y} $. There's a nice duality between the estimator and the controller so the basic approach we take to calculate the estimator gain ($ L $ matrix) are very similar those for the control law above. ## Check for Observability Observability tells us whether the sensors we've attached to our system (as defined by the C matrix) are sufficient to derive an estimate of the state to feed into our control law. If for example, a part of the state was completely decoupled from all of the sensor measurements we take, then the system won't be observable and it'll be impossible to estimate and ultimately, to control. Similar to controllability, a system is observable if the rank of the observability matrix is the same as the number of states in the model. ``` observability = obsv(A, C) print 'The observability matrix is:\n' print observability if np.linalg.matrix_rank(observability) == plant.states: print '\nThe system is observable!' else: print '\nThe system is not observable, double-check your modelling and that you entered the matrices correctly' ``` ## Fill out the Noise Covariance Matrices To calculate the estimator gain L, we can use the same algorithm as that used to calculate the control law. Again we define two matrices, $ Q $ and $ R $ however in this case their interpretations are slightly different. $ Q_{est} \in \mathbf{R}^{X \;\times\; X} $ is referred to as the process noise covariance, it represents the accuracy of the state space model in being able to predict the next state based on the last state and the control input. It's assumed that the actual system is subject to some unknown noise which throws out the estimate of the state and in cases where that noise is very high, it's best to rely more heavily on the sensor readings. $ R_{est} \in \mathbf{R}^{Y \;\times\; Y} $ is referred to as the sensor noise covariance, it represents the accuracy of the sensor readings in being able to observe the state. Here again, it's assumed that the actual sensors are subject to some unknown noise which throws out their measurements. In cases where this noise is very high, it's best to be less reliant on sensor readings. ``` Q_est = [[100, 0, 0, 0 ], [0, 1000, 0, 0 ], [0, 0, 100, 0 ], [0, 0, 0, 10000]] R_est = [[1,0],[0,1]] ``` ## Calculate the Gain Matrix for a Linear Quadratic Estimator (aka Kalman Filter) Ideally, the estimator's covariance matrices can be calculated empirically using data collected from the system's actual sensors and its model. Doing so is a bit outside of the scope of this notebook, so instead we can just tweak the noise values to come up with an estimator that converges on the actual state with a reasonable settling time based on the closed loop poles. ``` L, _, _ = lqr(np.array(A).T, np.array(C).T, Q_est, R_est) L = L.T print 'The estimator gain is:\n' print 'L = ', L controller_w_estimator = ss(A - np.matmul(B , K) - np.matmul(L , C), L, K, np.zeros([plant.inputs, plant.outputs])) closed_loop_system_w_estimator = feedback(plant, controller_w_estimator) closed_loop_estimator_poles = pole(closed_loop_system_w_estimator) print '\nThe poles of the closed loop system are:\n' print closed_loop_estimator_poles pole_plot(closed_loop_estimator_poles, 'Closed Loop Poles with Estimation') ``` # And You're Done! Congratulations! You've tuned an LQR and an LQE to suit your system model and you can now cut and paste the gains into your arduino sketch. ## Coming soon, Integral Gain selection!
github_jupyter
``` import pymatgen.core print(pymatgen.core.__version__) print(pymatgen.core.__file__) import sys print(sys.version) from pymatgen.core import Molecule Molecule c_monox = Molecule(["C","O"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.2]]) print(c_monox) oh_minus = Molecule(["O", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], charge=-1) print(oh_minus) water = Molecule.from_file("water.xyz") print(water) methane = Molecule.from_file("methane.xyz") print(methane) furan = Molecule.from_file("furan.xyz") print(furan) benzene = Molecule.from_file("benzene.xyz") print(benzene) print(c_monox.cart_coords) print(c_monox.center_of_mass) c_monox.set_charge_and_spin(charge=1) print(c_monox) len(c_monox) print(c_monox[0]) c_monox[0] = "O" c_monox[1] = "C" print(c_monox) site0 = c_monox[0] site0.coords site0.specie from pymatgen.core import Element, Composition from pymatgen.core.periodic_table import Specie carbon = Element('C') carbon.average_ionic_radius o_ion = Specie('O', oxidation_state=-2) o_ion o_ion.oxi_state o_ion.atomic_mass Specie.from_string('O2-') comp = Composition({'Au': 0.5, 'Cu': 0.5}) print("formula", comp.alphabetical_formula) print("chemical system", comp.chemical_system) H_rad = Element('H').atomic_radius C_rad = Element('C').atomic_radius N_rad = Element('N').atomic_radius HC_bond_dist = H_rad + C_rad CN_bond_dist = C_rad + N_rad H_pos = 0 C_pos = H_pos + HC_bond_dist N_pos = C_pos + CN_bond_dist hcn = Molecule(['H','C','N'], [[H_pos, 0, 0], [C_pos, 0, 0],[N_pos, 0, 0]]) print(hcn) from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure my_lattice = Lattice([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) print(my_lattice) my_lattice_2 = Lattice.from_parameters(5, 5, 5, 90, 90, 90) print(my_lattice_2) my_lattice_3 = Lattice.cubic(5) print(my_lattice_3) my_lattice == my_lattice_2 == my_lattice_3 bcc_fe = Structure(Lattice.cubic(2.8), ["Fe", "Fe"], [[0, 0, 0], [0.5, 0.5, 0.5]]) print(bcc_fe) bcc_fe_from_cart = Structure(Lattice.cubic(2.8), ["Fe", "Fe"], [[0, 0, 0], [1.4, 1.4, 1.4]], coords_are_cartesian=True) print(bcc_fe_from_cart) bcc_fe == bcc_fe_from_cart bcc_fe.volume bcc_fe = Structure.from_spacegroup("Im-3m", Lattice.cubic(2.8), ["Fe"], [[0, 0, 0]]) print(bcc_fe) nacl = Structure.from_spacegroup("Fm-3m", Lattice.cubic(5.692), ["Na+", "Cl-"], [[0, 0, 0], [0.5, 0.5, 0.5]]) print(nacl) nacl.get_space_group_info() polonium = Structure(Lattice.cubic(3.4), ["Po"], [[0.0, 0.0, 0.0]]) print(polonium) supercell = polonium * (2, 2, 2) print(supercell) BaTiO3=Structure.from_file("BaTiO3.cif") print(BaTiO3.get_space_group_info()) BaTiO3.replace(0,'Mg') BaTiO3=BaTiO3*(1,1,4) print(BaTiO3) print(BaTiO3.get_space_group_info()) ```
github_jupyter
### - load data ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd import math dataset = pd.read_csv('data-kmeans.csv') data = dataset.values ``` ### - init labels ``` label = [] for i in range(len(data)): label.append([i % 5 + 1]) label = np.array(label) data = np.concatenate((data, label), axis=1) init_data = data.copy() ``` ### - Compute init Centroids ``` init_Centroids = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] for i in range(data.shape[0]): if data[i][2] == 1: init_Centroids[0][0] += data[i][0] / 40 init_Centroids[0][1] += data[i][1] / 40 elif data[i][2] == 2: init_Centroids[1][0] += data[i][0] / 40 init_Centroids[1][1] += data[i][1] / 40 elif data[i][2] == 3: init_Centroids[2][0] += data[i][0] / 40 init_Centroids[2][1] += data[i][1] / 40 elif data[i][2] == 4: init_Centroids[3][0] += data[i][0] / 40 init_Centroids[3][1] += data[i][1] / 40 elif data[i][2] == 5: init_Centroids[4][0] += data[i][0] / 40 init_Centroids[4][1] += data[i][1] / 40 ``` ### - Define functions ``` def compute_distance(a, b): # distance between a and b dist = math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) return dist def compute_centroid(Z): center = [[0, 0] for i in range(5)] cluster_n = [0 for i in range(5)] for i in range(data.shape[0]): if Z[i][2] == 1: center[0][0] += data[i][0] center[0][1] += data[i][1] cluster_n[0] +=1 elif Z[i][2] == 2: center[1][0] += data[i][0] center[1][1] += data[i][1] cluster_n[1] +=1 elif Z[i][2] == 3: center[2][0] += data[i][0] center[2][1] += data[i][1] cluster_n[2] +=1 elif Z[i][2] == 4: center[3][0] += data[i][0] center[3][1] += data[i][1] cluster_n[3] +=1 elif Z[i][2] == 5: center[4][0] += data[i][0] center[4][1] += data[i][1] cluster_n[4] +=1 for i in range(len(center)): center[i][0] = center[i][0] / cluster_n[i] center[i][1] = center[i][1] / cluster_n[i] return center def compute_label(z, M): distance_list = [compute_distance(z, M[i]) for i in range(len(M))] label = distance_list.index(min(distance_list)) + 1 return label def compute_loss(C, M): loss = 0 for i in range(C.shape[0]): loss += compute_distance(C[i], M[C[i][2] - 1]) return loss / C.shape[0] ``` ### - main code ``` loss_curve = [] centroid_curv = [[] for i in range(5)] ephochs = 100 for run in range(ephochs): Centroids = compute_centroid(data) for i in range(data.shape[0]): data[i][2] = compute_label(data[i], Centroids) loss_curve.append(compute_loss(data, Centroids)) for j in range(len(centroid_curv)): centroid_curv[j].append(compute_distance([0, 0], Centroids[j])) ``` ### - Define color and label ``` color_list = ["green", "blue", "brown", "skyblue", "violet"] name_list = ["Cluster 1", "Cluster 2", "Cluster 3", "Cluster 4", "Cluster 5"] ``` ### - Compute clusters ``` init_Cluster1 = [] init_Cluster2 = [] init_Cluster3 = [] init_Cluster4 = [] init_Cluster5 = [] for i in range(init_data.shape[0]): if init_data[i][2] == 1: init_Cluster1.append(init_data[i]) elif init_data[i][2] == 2: init_Cluster2.append(init_data[i]) elif init_data[i][2] == 3: init_Cluster3.append(init_data[i]) elif init_data[i][2] == 4: init_Cluster4.append(init_data[i]) elif init_data[i][2] == 5: init_Cluster5.append(init_data[i]) Cluster1 = [] Cluster2 = [] Cluster3 = [] Cluster4 = [] Cluster5 = [] for i in range(init_data.shape[0]): if data[i][2] == 1: Cluster1.append(data[i]) elif data[i][2] == 2: Cluster2.append(data[i]) elif data[i][2] == 3: Cluster3.append(data[i]) elif data[i][2] == 4: Cluster4.append(data[i]) elif data[i][2] == 5: Cluster5.append(data[i]) ``` ## 1. Plot the data points [1pt] ``` fig = plt.figure(figsize=(12,10)) plt.scatter(data[:,0], data[:,1], s =70, c = 'black', label='data') plt.title("data point") plt.legend(loc = 'upper right') plt.show() ``` ## 2. Visualise the initial condition of the point labels [1pt] ``` fig = plt.figure(figsize=(12,10)) plt.scatter(np.array(init_Cluster1)[:,0], np.array(init_Cluster1)[:,1], s = 70, c = color_list[0], label = name_list[0]) plt.scatter(np.array(init_Cluster2)[:,0], np.array(init_Cluster2)[:,1], s = 70, c = color_list[1], label = name_list[1]) plt.scatter(np.array(init_Cluster3)[:,0], np.array(init_Cluster3)[:,1], s = 70, c = color_list[2], label = name_list[2]) plt.scatter(np.array(init_Cluster4)[:,0], np.array(init_Cluster4)[:,1], s = 70, c = color_list[3], label = name_list[3]) plt.scatter(np.array(init_Cluster5)[:,0], np.array(init_Cluster5)[:,1], s = 70, c = color_list[4], label = name_list[4]) plt.scatter(np.array(init_Centroids)[:,0], np.array(init_Centroids)[:,1], s = 200, c = 'black', marker = '+', label = "Centroids") plt.title("Initial cluster") plt.legend(loc = 'upper right') plt.show() ``` ## 3. Plot the loss curve [5pt] ``` fig = plt.figure(figsize=(8,6)) plt.plot([i for i in range(len(loss_curve))], loss_curve, c = 'b') plt.title('loss') plt.show() ``` ## 4. Plot the centroid of each clsuter [5pt] ``` fig = plt.figure(figsize=(8,6)) for i in range(len(centroid_curv)): plt.plot([i for i in range(len(centroid_curv[i]))], centroid_curv[i], c = color_list[i], label = name_list[i]) plt.title('centroid of cluster') plt.legend(loc = 'upper right') plt.show() ``` ## 5. Plot the final clustering result [5pt] ``` fig = plt.figure(figsize=(12,10)) plt.scatter(np.array(Cluster1)[:,0], np.array(Cluster1)[:,1], s = 70, c = color_list[0], label = name_list[0]) plt.scatter(np.array(Cluster2)[:,0], np.array(Cluster2)[:,1], s = 70, c = color_list[1], label = name_list[1]) plt.scatter(np.array(Cluster3)[:,0], np.array(Cluster3)[:,1], s = 70, c = color_list[2], label = name_list[2]) plt.scatter(np.array(Cluster4)[:,0], np.array(Cluster4)[:,1], s = 70, c = color_list[3], label = name_list[3]) plt.scatter(np.array(Cluster5)[:,0], np.array(Cluster5)[:,1], s = 70, c = color_list[4], label = name_list[4]) plt.scatter(np.array(Centroids)[:,0], np.array(Centroids)[:,1], s = 200, c = 'black', marker = '+', label = "Centroids") plt.title("Initial cluster") plt.legend(loc = 'upper right') plt.show() ```
github_jupyter
``` import pandas as pd import numpy as np import TrialPathfinder as tp ``` # Trial PathFinder ## Load Data Tables TrialPathfinder reads tables in Pandas dataframe structure (pd.dataframe) as default. The date information should be read as datetime (use function pd.to_datetime to convert if not). **1. Features**: - <font color=darkblue>*Patient ID*</font> - Treatment Information - <font color=darkblue>*Drug name*</font>. - <font color=darkblue>*Start date*</font>. - <font color=darkblue>*Date of outcome*</font>. For example, if overall survival (OS) is used as metric, the date of outcome is the date of death. If progression-free survival (PFS) is used as metric, the date of outcome is the date of progression. - <font color=darkblue>*Date of last visit*</font>. The patient's last record date of visit, used for censoring. - <font color=darkblue>*Covariates (optional)*</font>: adjusted to emulate the blind assignment, used by Inverse probability of treatment weighting (IPTW) or propensity score matching (PSM). Some examples: age, gender, composite race/ethnicity, histology, smoking status, staging, ECOG, and biomarkers status. **2. Tables used by eligibility criteria.** - Use the same Patient ID as the features table. We provide a synthetic example data in directory [tutorial/data](https://github.com/RuishanLiu/TrialPathfinder/tree/master/tutorial/data). The features (*'features.csv'*) contain the required treatment information and three covariates (gender, race, ecog). Two tables (*'demographics.csv'* and *'lab.csv'*) are used by its eligibility criteria (*'criteria.csv'*). [tutorial.ipynb](https://github.com/RuishanLiu/TrialPathfinder/blob/master/tutorial/tutorial.ipynb) provides a detailed tutorial and example to use the library TrialPathFinder. We provide a synthetic example data in directory [tutorial/data](https://github.com/RuishanLiu/TrialPathfinder/tree/master/tutorial/data). - Eligibility criteria (*'criteria.csv'*) have five rules: Age, Histology_Squamous, ECOG, Platelets, Bilirubin. - The features (*'features.csv'*) contain the required treatment information and three covariates (gender, race, ecog). - Two tables (*'demographics.csv'* and *'lab.csv'*) are used. ``` features = pd.read_csv('data/features.csv') demographics = pd.read_csv('data/demographics.csv') lab = pd.read_csv('data/lab.csv') indicator_miss = 'Missing' # Process date information to be datetime format and explicitly define annotation for missing values for table in [lab, features, demographics]: for col in table.columns: if 'Date' in col: table[col] = pd.to_datetime(table[col]) table.loc[table[col].isna(), col] = indicator_miss features.head() demographics.head() lab.head() ``` ## Stadards of encoding eligibility criteria We built a computational workflow to encode the description of eligibility criteria in the protocols into standardized instructions which can be parsed by Trial Pathfinder for cohort selection use. **1. Basic logic.** - Name of the criteria is written in the first row. - A new statement starts with “#inclusion” or “#exclusion” to indicate the criterion’s type. Whether to include patients who have missing entries in the criteria: “(missing include)” or “(missing exclude)”. The default choice is including patients with missing entries. - Data name format: “Table[‘featurename’]”. For example, “demographics[‘birthdate’]” denotes column date of birth in table demographics. - Equation: ==, !=, <, <=, >, >=. - Logic: AND, OR. - Other operations: MIN, MAX, ABS. - Time is encoded as “DAYS(80)”: 80 days; “MONTHS(4)”: 4 months; “YEARS(3)”: 3 years. --- *Example: criteria "Age" - include patients more than 18 years old when they received the treatment.* > Age \ \#Inclusion \ features['StartDate'] >= demographics['BirthDate'] + @YEARS(18) --- **2. Complex rule with hierachy.** - Each row is operated in sequential order - The tables are prepared before the last row. - The patients are selected at the last row. --- *Example: criteria "Platelets" - include patients whose platelet count ≥ 100 x 10^3/μL*. \ To encode this criterion, we follow the procedure: 1. Prepare the lab table: 1. Pick the lab tests for platelet count 2. The lab test date should be within a -28 to +0 window around the treatment start date 3. Use the record closest to the treatment start date to do selection. 2. Select patients: lab value larger than 100 x 10^3/μL. > Platelets \ \#Inclusion \ (lab['LabName'] == 'Platelet count') \ (lab['TestDate'] >= features['StartDate'] - @DAYS(28) ) AND (lab['TestDate'] <= features['StartDate']) \ MIN(ABS(lab['TestDate'] - features['StartDate'])) \ (lab['LabValue'] >= 100) --- Here we load the example criteria 'criteria.csv' under directory [tutorial/data](https://github.com/RuishanLiu/TrialPathfinder/tree/master/tutorial/data). ``` criteria = pd.read_csv('data/criteria.csv', header=None).values.reshape(-1) print(*criteria, sep='\n\n') ``` ## Preparation Before simulating real trials, we first encode all the eligibility criteria --- load pseudo-code, input to the algorithm and figure out which patient is excluded by each rule. 1. Create an empty cohort object - tp.cohort_selection() requires all the patients ids used in the study. Here we analyze all the patients in the dataset, people can also use a subset of patients based on their needs. ``` patientids = features['PatientID'] cohort = tp.cohort_selection(patientids, name_PatientID='PatientID') ``` 2. Add the tables needed in the eligibility criterion. ``` cohort.add_table('demographics', demographics) cohort.add_table('lab', lab) cohort.add_table('features', features) ``` 3. Add individual eligibility criterion ``` # Option 1: add rules individually for rule in criteria[:]: name_rule, select, missing = cohort.add_rule(rule) print('Rule %s: exclude patients %d/%d' % (name_rule, select.shape[0]-np.sum(select), select.shape[0])) # # Option 2: add the list of criteria # cohort.add_rules(criteria) ``` # Analysis - Treatment drug: B - Control drug: A - Criteria used: Age, ECOG, Histology_Squamous, Platelets, Bilirubin ``` drug_treatment = ['drug B'] drug_control = ['drug A'] name_rules = ['Age', 'Histology_Squamous', 'ECOG', 'Platelets', 'Bilirubin'] covariates_cat = ['Gender', 'Race', 'ECOG'] # categorical covariates covariates_cont = [] # continuous covariates ``` 1. Original trial crieria - Criteria includes Age, ECOG, Histology_Squamous, Platelets, Bilirubin. ``` HR, CI, data_cox = tp.emulate_trials(cohort, features, drug_treatment, drug_control, name_rules, covariates_cat=covariates_cat, covariates_cont=covariates_cont, name_DrugName='DrugName', name_StartDate='StartDate', name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate', indicator_miss=indicator_miss) print('Hazard Ratio: %.2f (%.2f-%.2f)' % (HR, CI[0], CI[1])) print('Number of Patients: %d' % (data_cox.shape[0])) ``` 2. Fully-relaxed criteria - No rule applied (name_rules=[]). ``` HR, CI, data_cox = tp.emulate_trials(cohort, features, drug_treatment, drug_control, [], covariates_cat=covariates_cat, covariates_cont=covariates_cont, name_DrugName='DrugName', name_StartDate='StartDate', name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate', indicator_miss=indicator_miss) print('Hazard Ratio: %.2f (%.2f-%.2f)' % (HR, CI[0], CI[1])) print('Number of Patients: %d' % (data_cox.shape[0])) ``` 3. Compute shapley values ``` shapley_values = tp.shapley_computation(cohort, features, drug_treatment, drug_control, name_rules, tolerance=0.01, iter_max=1000, covariates_cat=covariates_cat, covariates_cont=covariates_cont, name_DrugName='DrugName', name_StartDate='StartDate', name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate', indicator_miss=indicator_miss, random_seed=1001, verbose=1) pd.DataFrame([shapley_values], columns=name_rules, index=['Shapley Value']) ``` 4. Data-driven criteria ``` name_rules_relax = np.array(name_rules)[shapley_values < 0] HR, CI, data_cox = tp.emulate_trials(cohort, features, drug_treatment, drug_control, name_rules_relax, covariates_cat=covariates_cat, covariates_cont=covariates_cont, name_DrugName='DrugName', name_StartDate='StartDate', name_OutcomeDate='OutcomeDate', name_LastVisitDate='LastVisitDate', indicator_miss=indicator_miss) print('Hazard Ratio: %.2f (%.2f-%.2f)' % (HR, CI[0], CI[1])) print('Number of Patients: %d' % (data_cox.shape[0])) ```
github_jupyter
# Team Surface Velocity ### **Members**: Grace Barcheck, Canyon Breyer, Rodrigo Gómez-Fell, Trevor Hillebrand, Ben Hills, Lynn Kaluzienski, Joseph Martin, David Polashenski ### **Science Advisor**: Daniel Shapero ### **Special Thanks**: Ben Smith, David Shean ### Motivation **Speaker: Canyon Breyer** Previous work by Marsh and Rack (2012), and Lee and others (2012), have demonstrated the value of using satellite altimetry as a method of calculating ice surface velocity utilizing the Geoscience Laser Altimeter System (GLAS) on board ICESat. This altimetry method has several advantages over more traditional techniques due to high pointing accuracy for geo-location and an ability to measure velocity in regions that lack visible surface features (Marsh and Rack, 2012). The method also has the added benefit of dealing with tidal fluctuations without the need for a tidal correction model. The motivation for this project was to expand the methodology outlined in Marsh and Rack (2012) to the ICE-Sat2 dataset. The smaller footprint of the ICE-Sat2 mission will likely improve the overall accuracy of velocity measurements and the nature of its precise repeat passes would provide an avenue for studying temporal variations of glacier velocities. ### Project Objective: **Speaker: Rodrigo Gómez-Fell** Extract surface ice velocity on polar regions from ICESat-2 along track measurements ##### Goals: - Compare the capabilities of ICESat-2 to extract surface ice velocity from ice shelves and ice streams - Compare ICESat GLAS methodology (along track) to ICESat-2 across track - Use crossovers for calculating velocities and determine how the measurements compare with simple along track and across track. -Does this resolve different directions of ice flow? - Can a surface velocity product be extracted from ATL06, or is ATL03 the more suitable product. ### Study Area: When looking for a study region to test our ICESat-2 velocity derivation method, we prioritized regions that **1)** included both grounded and floating ice and **2)** had a good alignment between satellite track position and overall flow direction. We found Foundation Ice Stream, a large ice stream draining into the Filchner-Ronne Ice Shelf, to meet both of these criteria. ![FIS](FISimage.PNG) ### Data Selection We used the ICESat-2 Land Ice Height ATL06 product and then used the MEaSUREs Antarctic Velocity Map V2 (Rignot, 2017) for validation of our derived velocities ### Method **Speaker: Ben Hills** Following Marsh and Rack (2012) we used the slope of elevation for analysis, this helped amplify differences in the ice profile between repeat measurements and also removed the influence of tidal effects. This is portrayed in the figure below. ![Beardmore](beardmore.PNG) ![Marsh_method](marsh2.PNG) Fig.2: From Marsh and Rack 2012. Schematic of the method used to reduce the effect of oblique surface features and ice flow which is non-parallel to ICESat tracks. Black lines indicate satellite tracks, grey ticks indicate the orientation of surface features, and ⍺ is the feature-track angle. Bottom right profile illustrates that after adjustment there is no relative feature displacement due to cross-track separation, therefore all displacement is due to ice movement in the track direction. ### Our Methods: **Cross-correlation background** **Speaker: Grace Barcheck** ##### Test.scipy.signal.correlate on some ATL06 data from Foundation Ice Stream (FIS) ``` import numpy as np import scipy, sys, os, pyproj, glob, re, h5py import matplotlib.pyplot as plt from scipy.signal import correlate from astropy.time import Time %matplotlib widget %load_ext autoreload %autoreload 2 ``` ##### Test scipy.signal.correlate Generate test data ``` dx = 0.1 x = np.arange(0,10,dx) y = np.zeros(np.shape(x)) ix0 = 30 ix1 = 30 + 15 y[ix0:ix1] = 1 fig,axs = plt.subplots(1,2) axs[0].plot(x,y,'k') axs[0].set_xlabel('distance (m)') axs[0].set_ylabel('value') axs[1].plot(np.arange(len(x)), y,'k') axs[1].set_xlabel('index') ``` Next, we generate a signal to correlate the test data with ``` imposed_offset = int(14/dx) # 14 meters, in units of samples x_noise = np.arange(0,50,dx) # make the vector we're comparing with much longer y_noise = np.zeros(np.shape(x_noise)) y_noise[ix0 + imposed_offset : ix1 + imposed_offset] = 1 # uncomment the line below to add noise # y_noise = y_noise * np.random.random(np.shape(y_noise)) fig,axs = plt.subplots(1,2) axs[0].plot(x,y,'k') axs[0].set_xlabel('distance (m)') axs[0].set_ylabel('value') axs[1].plot(np.arange(len(x)), y, 'k') axs[1].set_xlabel('index') axs[0].plot(x_noise,y_noise, 'b') axs[0].set_xlabel('distance (m)') axs[0].set_ylabel('value') axs[1].plot(np.arange(len(x_noise)), y_noise,'b') axs[1].set_xlabel('index') fig.suptitle('black = original, blue = shifted') ``` ##### Try scipy.signal.correlate: mode ='full' returns the entire cross correlation; could be 'valid' to return only non- zero-padded part method = direct (not fft) ``` corr = correlate(y_noise,y, mode = 'full', method = 'direct') norm_val = np.sqrt(np.sum(y_noise**2)*np.sum(y**2)) corr = corr / norm_val ``` Let's look at the dimensions of corr ``` print('corr: ', np.shape(corr)) print('x: ', np.shape(x)) print('x: ', np.shape(x_noise)) ``` ##### Look at the correlation visualized in the plots below ``` # lagvec = np.arange(0,len(x_noise) - len(x) + 1) lagvec = np.arange( -(len(x) - 1), len(x_noise), 1) shift_vec = lagvec * dx ix_peak = np.arange(len(corr))[corr == np.nanmax(corr)][0] best_lag = lagvec[ix_peak] best_shift = shift_vec[ix_peak] fig,axs = plt.subplots(3,1) axs[0].plot(lagvec,corr) axs[0].plot(lagvec[ix_peak],corr[ix_peak], 'r*') axs[0].set_xlabel('lag (samples)') axs[0].set_ylabel('correlation coefficient') axs[1].plot(shift_vec,corr) axs[1].plot(shift_vec[ix_peak],corr[ix_peak], 'r*') axs[1].set_xlabel('shift (m)') axs[1].set_ylabel('correlation coefficient') axs[2].plot(x + best_shift, y,'k') axs[2].plot(x_noise, y_noise, 'b--') axs[2].set_xlabel('shift (m)') fig.suptitle(' '.join(['Shift ', str(best_lag), ' samples, or ', str(best_shift), ' m to line up signals'])) ``` ### A little Background on cross-correlation... ![Correlation](Corr_Coeff.gif) ### Applying our method to ATL06 data **Speaker: Ben Hills** Load repeat data: Import readers, etc. ``` # ! cd ..; [ -d pointCollection ] || git clone https://www.github.com/smithB/pointCollection.git # sys.path.append(os.path.join(os.getcwd(), '..')) #!python3 -m pip install --user git+https://github.com/tsutterley/pointCollection.git@pip import pointCollection as pc moa_datapath = '/srv/tutorial-data/land_ice_applications/' datapath = '/home/jovyan/shared/surface_velocity/FIS_ATL06/' ``` #### **Geographic setting: Foundation Ice Stream** ``` print(pc.__file__) spatial_extent = np.array([-65, -86, -55, -81]) lat=spatial_extent[[1, 3, 3, 1, 1]] lon=spatial_extent[[2, 2, 0, 0, 2]] print(lat) print(lon) # project the coordinates to Antarctic polar stereographic xy=np.array(pyproj.Proj(3031)(lon, lat)) # get the bounds of the projected coordinates XR=[np.nanmin(xy[0,:]), np.nanmax(xy[0,:])] YR=[np.nanmin(xy[1,:]), np.nanmax(xy[1,:])] MOA=pc.grid.data().from_geotif(os.path.join(moa_datapath, 'MOA','moa_2009_1km.tif'), bounds=[XR, YR]) # show the mosaic: plt.figure() MOA.show(cmap='gray', clim=[14000, 17000]) plt.plot(xy[0,:], xy[1,:]) plt.title('Mosaic of Antarctica for Foundation Ice Stream') ``` ##### Load the repeat track data ATL06 reader ``` def atl06_to_dict(filename, beam, field_dict=None, index=None, epsg=None): """ Read selected datasets from an ATL06 file Input arguments: filename: ATl06 file to read beam: a string specifying which beam is to be read (ex: gt1l, gt1r, gt2l, etc) field_dict: A dictinary describing the fields to be read keys give the group names to be read, entries are lists of datasets within the groups index: which entries in each field to read epsg: an EPSG code specifying a projection (see www.epsg.org). Good choices are: for Greenland, 3413 (polar stereographic projection, with Greenland along the Y axis) for Antarctica, 3031 (polar stereographic projection, centered on the Pouth Pole) Output argument: D6: dictionary containing ATL06 data. Each dataset in dataset_dict has its own entry in D6. Each dataset in D6 contains a numpy array containing the data """ if field_dict is None: field_dict={None:['latitude','longitude','h_li', 'atl06_quality_summary'],\ 'ground_track':['x_atc','y_atc'],\ 'fit_statistics':['dh_fit_dx', 'dh_fit_dy']} D={} # below: file_re = regular expression, it will pull apart the regular expression to get the information from the filename file_re=re.compile('ATL06_(?P<date>\d+)_(?P<rgt>\d\d\d\d)(?P<cycle>\d\d)(?P<region>\d\d)_(?P<release>\d\d\d)_(?P<version>\d\d).h5') with h5py.File(filename,'r') as h5f: for key in field_dict: for ds in field_dict[key]: if key is not None: ds_name=beam+'/land_ice_segments/'+key+'/'+ds else: ds_name=beam+'/land_ice_segments/'+ds if index is not None: D[ds]=np.array(h5f[ds_name][index]) else: D[ds]=np.array(h5f[ds_name]) if '_FillValue' in h5f[ds_name].attrs: bad_vals=D[ds]==h5f[ds_name].attrs['_FillValue'] D[ds]=D[ds].astype(float) D[ds][bad_vals]=np.NaN D['data_start_utc'] = h5f['/ancillary_data/data_start_utc'][:] D['delta_time'] = h5f['/' + beam + '/land_ice_segments/delta_time'][:] D['segment_id'] = h5f['/' + beam + '/land_ice_segments/segment_id'][:] if epsg is not None: xy=np.array(pyproj.proj.Proj(epsg)(D['longitude'], D['latitude'])) D['x']=xy[0,:].reshape(D['latitude'].shape) D['y']=xy[1,:].reshape(D['latitude'].shape) temp=file_re.search(filename) D['rgt']=int(temp['rgt']) D['cycle']=int(temp['cycle']) D['beam']=beam return D ``` ##### Next we will read in the files ``` # find all the files in the directory: # ATL06_files=glob.glob(os.path.join(datapath, 'PIG_ATL06', '*.h5')) rgt = '0848' ATL06_files=glob.glob(os.path.join(datapath, '*' + rgt + '*.h5')) D_dict={} error_count=0 for file in ATL06_files[:10]: try: D_dict[file]=atl06_to_dict(file, '/gt2l', index=slice(0, -1, 25), epsg=3031) except KeyError as e: print(f'file {file} encountered error {e}') error_count += 1 print(f"read {len(D_dict)} data files of which {error_count} gave errors") # find all the files in the directory: # ATL06_files=glob.glob(os.path.join(datapath, 'PIG_ATL06', '*.h5')) rgt = '0537' ATL06_files=glob.glob(os.path.join(datapath, '*' + rgt + '*.h5')) #D_dict={} error_count=0 for file in ATL06_files[:10]: try: D_dict[file]=atl06_to_dict(file, '/gt2l', index=slice(0, -1, 25), epsg=3031) except KeyError as e: print(f'file {file} encountered error {e}') error_count += 1 print(f"read {len(D_dict)} data files of which {error_count} gave errors") ``` ##### Then, we will plot the ground tracks ``` plt.figure(figsize=[8,8]) hax0=plt.gcf().add_subplot(211, aspect='equal') MOA.show(ax=hax0, cmap='gray', clim=[14000, 17000]); hax1=plt.gcf().add_subplot(212, aspect='equal', sharex=hax0, sharey=hax0) MOA.show(ax=hax1, cmap='gray', clim=[14000, 17000]); for fname, Di in D_dict.items(): cycle=Di['cycle'] if cycle <= 2: ax=hax0 else: ax=hax1 #print(fname) #print(f'\t{rgt}, {cycle}, {region}') ax.plot(Di['x'], Di['y']) if True: try: if cycle < 3: ax.text(Di['x'][0], Di['y'][0], f"rgt={Di['rgt']}, cyc={cycle}", clip_on=True) elif cycle==3: ax.text(Di['x'][0], Di['y'][0], f"rgt={Di['rgt']}, cyc={cycle}+", clip_on=True) except IndexError: pass hax0.set_title('cycles 1 and 2'); hax1.set_title('cycle 3+'); # find all the files in the directory: # ATL06_files=glob.glob(os.path.join(datapath, 'PIG_ATL06', '*.h5')) rgt = '0848' ATL06_files=glob.glob(os.path.join(datapath, '*' + rgt + '*.h5')) D_dict={} error_count=0 for file in ATL06_files[:10]: try: D_dict[file]=atl06_to_dict(file, '/gt2l', index=slice(0, -1, 25), epsg=3031) except KeyError as e: print(f'file {file} encountered error {e}') error_count += 1 print(f"read {len(D_dict)} data files of which {error_count} gave errors") ``` ##### Repeat track elevation profile ``` # A revised code to plot the elevations of segment midpoints (h_li): def plot_elevation(D6, ind=None, **kwargs): """ Plot midpoint elevation for each ATL06 segment """ if ind is None: ind=np.ones_like(D6['h_li'], dtype=bool) # pull out heights of segment midpoints h_li = D6['h_li'][ind] # pull out along track x coordinates of segment midpoints x_atc = D6['x_atc'][ind] plt.plot(x_atc, h_li, **kwargs) ``` **Data Visualization** ``` D_2l={} D_2r={} # specify the rgt here: rgt="0027" rgt="0848" #Ben's suggestion # iterate over the repeat cycles for cycle in ['03','04','05','06','07']: for filename in glob.glob(os.path.join(datapath, f'*ATL06_*_{rgt}{cycle}*_003*.h5')): try: # read the left-beam data D_2l[filename]=atl06_to_dict(filename,'/gt2l', index=None, epsg=3031) # read the right-beam data D_2r[filename]=atl06_to_dict(filename,'/gt2r', index=None, epsg=3031) # plot the locations in the previous plot map_ax.plot(D_2r[filename]['x'], D_2r[filename]['y'],'k'); map_ax.plot(D_2l[filename]['x'], D_2l[filename]['y'],'k'); except Exception as e: print(f'filename={filename}, exception={e}') plt.figure(); for filename, Di in D_2l.items(): #Plot only points that have ATL06_quality_summary==0 (good points) hl=plot_elevation(Di, ind=Di['atl06_quality_summary']==0, label=f"cycle={Di['cycle']}") #hl=plt.plot(Di['x_atc'][Di['atl06_quality_summary']==0], Di['h_li'][Di['atl06_quality_summary']==0], '.', label=f"cycle={Di['cycle']}") plt.legend() plt.xlabel('x_atc') plt.ylabel('elevation'); ``` ##### Now, we need to pull out a segment and cross correlate: Let's try 2.93e7 through x_atc=2.935e7 ``` cycles = [] # names of cycles with data for filename, Di in D_2l.items(): cycles += [str(Di['cycle']).zfill(2)] cycles.sort() # x1 = 2.93e7 # x2 = 2.935e7 beams = ['gt1l','gt1r','gt2l','gt2r','gt3l','gt3r'] # try and smooth without filling nans smoothing_window_size = int(np.round(60 / dx)) # meters / dx; odd multiples of 20 only! it will break filt = np.ones(smoothing_window_size) smoothed = True ### extract and plot data from all available cycles fig, axs = plt.subplots(4,1) x_atc = {} h_li_raw = {} h_li = {} h_li_diff = {} times = {} for cycle in cycles: # find Di that matches cycle: Di = {} x_atc[cycle] = {} h_li_raw[cycle] = {} h_li[cycle] = {} h_li_diff[cycle] = {} times[cycle] = {} filenames = glob.glob(os.path.join(datapath, f'*ATL06_*_{rgt}{cycle}*_003*.h5')) for filename in filenames: try: for beam in beams: Di[filename]=atl06_to_dict(filename,'/'+ beam, index=None, epsg=3031) times[cycle][beam] = Di[filename]['data_start_utc'] # extract h_li and x_atc for that section x_atc_tmp = Di[filename]['x_atc'] h_li_tmp = Di[filename]['h_li']#[ixs] # segment ids: seg_ids = Di[filename]['segment_id'] # print(len(seg_ids), len(x_atc_tmp)) # make a monotonically increasing x vector # assumes dx = 20 exactly, so be carefull referencing back ind = seg_ids - np.nanmin(seg_ids) # indices starting at zero, using the segment_id field, so any skipped segment will be kept in correct location x_full = np.arange(np.max(ind)+1) * 20 + x_atc_tmp[0] h_full = np.zeros(np.max(ind)+1) + np.NaN h_full[ind] = h_li_tmp x_atc[cycle][beam] = x_full h_li_raw[cycle][beam] = h_full # running average smoother /filter if smoothed == True: h_smoothed = (1/smoothing_window_size) * np.convolve(filt, h_full, mode="same") #h_smoothed = h_smoothed[int(np.floor(smoothing_window_size/2)):int(-np.floor(smoothing_window_size/2))] # cut off ends h_li[cycle][beam] = h_smoothed # # differentiate that section of data h_diff = (h_smoothed[1:] - h_smoothed[0:-1]) / (x_full[1:] - x_full[0:-1]) else: h_li[cycle][beam] = h_full h_diff = (h_full[1:] - h_full[0:-1]) / (x_full[1:] - x_full[0:-1]) h_li_diff[cycle][beam] = h_diff # plot axs[0].plot(x_full, h_full) axs[1].plot(x_full[1:], h_diff) # axs[2].plot(x_atc_tmp[1:] - x_atc_tmp[:-1]) axs[2].plot(np.isnan(h_full)) axs[3].plot(seg_ids[1:]- seg_ids[:-1]) except: print(f'filename={filename}, exception={e}') ``` **Speaker: Grace Barcheck** ``` n_veloc = len(cycles) - 1 segment_length = 3000 # m x1 = 2.935e7# 2.925e7#x_atc[cycles[0]][beams[0]][1000] <-- the very first x value in a file; doesn't work, I think b/c nans # 2.93e7 #x1=2.917e7 search_width = 800 # m dx = 20 # meters between x_atc points for veloc_number in range(n_veloc): cycle1 = cycles[veloc_number] cycle2 = cycles[veloc_number+1] t1_string = times[cycle1]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok t1 = Time(t1_string) t2_string = times[cycle2]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok t2 = Time(t2_string) dt = (t2 - t1).jd # difference in julian days velocities = {} for beam in beams: fig1, axs = plt.subplots(4,1) # cut out small chunk of data at time t1 (first cycle) x_full_t1 = x_atc[cycle1][beam] ix_x1 = np.arange(len(x_full_t1))[x_full_t1 >= x1][0] ix_x2 = ix_x1 + int(np.round(segment_length/dx)) x_t1 = x_full_t1[ix_x1:ix_x2] h_li1 = h_li_diff[cycle1][beam][ix_x1-1:ix_x2-1] # start 1 index earlier because the data are differentiated # cut out a wider chunk of data at time t2 (second cycle) x_full_t2 = x_atc[cycle2][beam] ix_x3 = ix_x1 - int(np.round(search_width/dx)) # offset on earlier end by # indices in search_width ix_x4 = ix_x2 + int(np.round(search_width/dx)) # offset on later end by # indices in search_width x_t2 = x_full_t2[ix_x3:ix_x4] h_li2 = h_li_diff[cycle2][beam][ix_x3:ix_x4] # plot data axs[0].plot(x_t2, h_li2, 'r') axs[0].plot(x_t1, h_li1, 'k') axs[0].set_xlabel('x_atc (m)') # correlate old with newer data corr = correlate(h_li1, h_li2, mode = 'valid', method = 'direct') norm_val = np.sqrt(np.sum(h_li1**2)*np.sum(h_li2**2)) # normalize so values range between 0 and 1 corr = corr / norm_val # lagvec = np.arange( -(len(h_li1) - 1), len(h_li2), 1)# for mode = 'full' # lagvec = np.arange( -int(search_width/dx) - 1, int(search_width/dx) +1, 1) # for mode = 'valid' lagvec = np.arange(- int(np.round(search_width/dx)), int(search_width/dx) +1,1)# for mode = 'valid' shift_vec = lagvec * dx ix_peak = np.arange(len(corr))[corr == np.nanmax(corr)][0] best_lag = lagvec[ix_peak] best_shift = shift_vec[ix_peak] velocities[beam] = best_shift/(dt/365) axs[1].plot(lagvec,corr) axs[1].plot(lagvec[ix_peak],corr[ix_peak], 'r*') axs[1].set_xlabel('lag (samples)') axs[2].plot(shift_vec,corr) axs[2].plot(shift_vec[ix_peak],corr[ix_peak], 'r*') axs[2].set_xlabel('shift (m)') # plot shifted data axs[3].plot(x_t2, h_li2, 'r') axs[3].plot(x_t1 - best_shift, h_li1, 'k') axs[3].set_xlabel('x_atc (m)') axs[0].text(x_t2[100], 0.6*np.nanmax(h_li2), beam) axs[1].text(lagvec[5], 0.6*np.nanmax(corr), 'best lag: ' + str(best_lag) + '; corr val: ' + str(np.round(corr[ix_peak],3))) axs[2].text(shift_vec[5], 0.6*np.nanmax(corr), 'best shift: ' + str(best_shift) + ' m'+ '; corr val: ' + str(np.round(corr[ix_peak],3))) axs[2].text(shift_vec[5], 0.3*np.nanmax(corr), 'veloc of ' + str(np.round(best_shift/(dt/365),1)) + ' m/yr') plt.tight_layout() fig1.suptitle('black = older cycle data, red = newer cycle data to search across') n_veloc = len(cycles) - 1 segment_length = 2000 # m search_width = 800 # m dx = 20 # meters between x_atc points correlation_threshold = 0.65 x1 = 2.915e7#x_atc[cycles[0]][beams[0]][1000] <-- the very first x value in a file; doesn't work, I think b/c nans # 2.93e7 x1s = x_atc[cycles[veloc_number]][beams[0]][search_width:-segment_length-2*search_width:10] velocities = {} correlations = {} for beam in beams: velocities[beam] = np.empty_like(x1s) correlations[beam] = np.empty_like(x1s) for xi,x1 in enumerate(x1s): for veloc_number in range(n_veloc): cycle1 = cycles[veloc_number] cycle2 = cycles[veloc_number+1] t1_string = times[cycle1]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok t1 = Time(t1_string) t2_string = times[cycle2]['gt1l'][0].astype(str) #figure out later if just picking hte first one it ok t2 = Time(t2_string) dt = (t2 - t1).jd # difference in julian days for beam in beams: # cut out small chunk of data at time t1 (first cycle) x_full_t1 = x_atc[cycle1][beam] ix_x1 = np.arange(len(x_full_t1))[x_full_t1 >= x1][0] ix_x2 = ix_x1 + int(np.round(segment_length/dx)) x_t1 = x_full_t1[ix_x1:ix_x2] h_li1 = h_li_diff[cycle1][beam][ix_x1-1:ix_x2-1] # start 1 index earlier because the data are differentiated # cut out a wider chunk of data at time t2 (second cycle) x_full_t2 = x_atc[cycle2][beam] ix_x3 = ix_x1 - int(np.round(search_width/dx)) # offset on earlier end by # indices in search_width ix_x4 = ix_x2 + int(np.round(search_width/dx)) # offset on later end by # indices in search_width x_t2 = x_full_t2[ix_x3:ix_x4] h_li2 = h_li_diff[cycle2][beam][ix_x3:ix_x4] # correlate old with newer data corr = correlate(h_li1, h_li2, mode = 'valid', method = 'direct') norm_val = np.sqrt(np.sum(h_li1**2)*np.sum(h_li2**2)) # normalize so values range between 0 and 1 corr = corr / norm_val # lagvec = np.arange( -(len(h_li1) - 1), len(h_li2), 1)# for mode = 'full' # lagvec = np.arange( -int(search_width/dx) - 1, int(search_width/dx) +1, 1) # for mode = 'valid' lagvec = np.arange(- int(np.round(search_width/dx)), int(search_width/dx) +1,1)# for mode = 'valid' shift_vec = lagvec * dx if all(np.isnan(corr)): velocities[beam][xi] = np.nan correlations[beam][xi] = np.nan else: correlation_value = np.nanmax(corr) if correlation_value >= correlation_threshold: ix_peak = np.arange(len(corr))[corr == correlation_value][0] best_lag = lagvec[ix_peak] best_shift = shift_vec[ix_peak] velocities[beam][xi] = best_shift/(dt/365) correlations[beam][xi] = correlation_value else: velocities[beam][xi] = np.nan correlations[beam][xi] = correlation_value plt.figure() ax1 = plt.subplot(211) for filename, Di in D_2l.items(): #Plot only points that have ATL06_quality_summary==0 (good points) hl=plot_elevation(Di, ind=Di['atl06_quality_summary']==0, label=f"cycle={Di['cycle']}") #hl=plt.plot(Di['x_atc'][Di['atl06_quality_summary']==0], Di['h_li'][Di['atl06_quality_summary']==0], '.', label=f"cycle={Di['cycle']}") plt.legend() plt.ylabel('elevation'); ax2 = plt.subplot(212,sharex=ax1) for beam in beams: plt.plot(x1s+dx*(segment_length/2),velocities[beam],'.',alpha=0.2,ms=3,label=beam) plt.ylabel('velocity (m/yr)') plt.xlabel('x_atc') plt.ylim(0,1500) plt.legend() plt.suptitle('Along track velocity: all beams') ``` #### **Median velocity for all 6 beams:** **Above a cross-correlation threshold of 0.65** ``` plt.figure() ax1 = plt.subplot(211) for filename, Di in D_2l.items(): #Plot only points that have ATL06_quality_summary==0 (good points) hl=plot_elevation(Di, ind=Di['atl06_quality_summary']==0, label=f"cycle={Di['cycle']}") #hl=plt.plot(Di['x_atc'][Di['atl06_quality_summary']==0], Di['h_li'][Di['atl06_quality_summary']==0], '.', label=f"cycle={Di['cycle']}") plt.legend() plt.ylabel('elevation'); ax2 = plt.subplot(212,sharex=ax1) medians = np.empty(len(x1s)) stds = np.empty(len(x1s)) for xi, x1 in enumerate(x1s): corr_vals = [] velocs = [] for beam in beams: corr_vals += [correlations[beam][xi]] velocs += [velocities[beam][xi]] n_obs = len(velocs) if n_obs >0: corr_mask = np.array(corr_vals) >= correlation_threshold veloc_mask = np.abs(np.array(velocs)) < 0.67*segment_length # get rid of segments that are nailed against one edge for some reason mask = corr_mask * veloc_mask median_veloc = np.nanmedian(np.array(velocs)[mask]) std_veloc = np.nanstd(np.array(velocs)[mask]) medians[xi] = median_veloc stds[xi] = std_veloc ax2.plot([x1,x1], [median_veloc - std_veloc, median_veloc +std_veloc], '-', color= [0.7, 0.7, 0.7]) ax2.plot(x1s, medians, 'k.', markersize=2) # for beam in beams: # plt.plot(x1s+dx*(segment_length/2),velocities[beam],'.',alpha=0.2,ms=3,label=beam) plt.ylabel('velocity (m/yr)') plt.xlabel('x_atc') plt.ylim(0,1500) plt.legend() plt.suptitle('Median along track velocity') plt.figure() ax1 = plt.subplot(211) for beam in beams: xvals = x1s+dx*(segment_length/2) corrs = correlations[beam] ixs = corrs >= correlation_threshold ax1.plot(xvals[ixs], corrs[ixs],'.',alpha=0.2,ms=3,label=beam) plt.ylabel('correlation values, 0->1') plt.xlabel('x_atc') plt.legend() plt.suptitle('Correlation values > threshold, all beams') ax1 = plt.subplot(212) for beam in beams: ax1.plot(x1s+dx*(segment_length/2),correlations[beam],'.',alpha=0.2,ms=3,label=beam) plt.ylabel('correlation values, 0->1') plt.xlabel('x_atc') plt.legend() plt.suptitle('Correlation values, all beams') ``` Comparison between measures ### Results: **848** **Speaker: Lynn Kaluzienski** ![LynnFig](Figure_96.png) ![comparison1](median_along_track1.png) **537** **Speaker: Joseph Martin** ![537_velocity](0537_measures.png) ![comparison](median_along_track2.png) ![537_veloc](537_velocity.png) ### Future Work for the Surface Velocity Team: **Speaker: David Polashenski** - Calculating correlation uncertainty - Considering larger, more complex areas - Pending objectives - Develop methodology to extract Across Track velocities and test efficacy - Compare ICESat GLAS methodology (Along Track) to ICESat-2 methodology (Across Track) - Compare the capabilites of ICESat-2 to extract surface ice velocity from ice shelves and ice streams
github_jupyter
# aitextgen Training Hello World _Last Updated: Feb 21, 2021 (v.0.4.0)_ by Max Woolf A "Hello World" Tutorial to show how training works with aitextgen, even on a CPU! ``` from aitextgen.TokenDataset import TokenDataset from aitextgen.tokenizers import train_tokenizer from aitextgen.utils import GPT2ConfigCPU from aitextgen import aitextgen ``` First, download this [text file of Shakespeare's plays](https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt), to the folder with this notebook, then put the name of the downloaded Shakespeare text for training into the cell below. ``` file_name = "input.txt" ``` You can now train a custom Byte Pair Encoding Tokenizer on the downloaded text! This will save one file: `aitextgen.tokenizer.json`, which contains the information needed to rebuild the tokenizer. ``` train_tokenizer(file_name) tokenizer_file = "aitextgen.tokenizer.json" ``` `GPT2ConfigCPU()` is a mini variant of GPT-2 optimized for CPU-training. e.g. the # of input tokens here is 64 vs. 1024 for base GPT-2. This dramatically speeds training up. ``` config = GPT2ConfigCPU() ``` Instantiate aitextgen using the created tokenizer and config ``` ai = aitextgen(tokenizer_file=tokenizer_file, config=config) ``` You can build datasets for training by creating TokenDatasets, which automatically processes the dataset with the appropriate size. ``` data = TokenDataset(file_name, tokenizer_file=tokenizer_file, block_size=64) data ``` Train the model! It will save pytorch_model.bin periodically and after completion to the `trained_model` folder. On a 2020 8-core iMac, this took ~25 minutes to run. The configuration below processes 400,000 subsets of tokens (8 * 50000), which is about just one pass through all the data (1 epoch). Ideally you'll want multiple passes through the data and a training loss less than `2.0` for coherent output; when training a model from scratch, that's more difficult, but with long enough training you can get there! ``` ai.train(data, batch_size=8, num_steps=50000, generate_every=5000, save_every=5000) ``` Generate text from your trained model! ``` ai.generate(10, prompt="ROMEO:") ``` With your trained model, you can reload the model at any time by providing the `pytorch_model.bin` model weights, the `config`, and the `tokenizer`. ``` ai2 = aitextgen(model_folder="trained_model", tokenizer_file="aitextgen.tokenizer.json") ai2.generate(10, prompt="ROMEO:") ``` # MIT License Copyright (c) 2021 Max Woolf Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
github_jupyter
``` """ Simple distributed implementation of the K-Means algorithm using Tensorflow. """ import tensorflow as tf import tensorframes as tfs from pyspark.mllib.random import RandomRDDs import numpy as np num_features = 4 k = 2 # TODO: does not work with 1 data = RandomRDDs.normalVectorRDD( sc, numCols=num_features, numRows=100, seed=1).map(lambda v: [v.tolist()]) df = sqlContext.createDataFrame(data).toDF("features") # For now, analysis is still required. df0 = tfs.analyze(df) init_centers = np.random.randn(k, num_features) # For debugging block = np.array(data.take(10))[::,0,::] # Find the distances first with tf.Graph().as_default() as g: points = tf.placeholder(tf.double, shape=[None, num_features], name='points') num_points = tf.shape(points)[0] #centers = tf.placeholder(tf.double, shape=[k, num_features], name='centers') centers = tf.constant(init_centers) squares = tf.reduce_sum(tf.square(points), reduction_indices=1) center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1) prods = tf.matmul(points, centers, transpose_b = True) t1a = tf.expand_dims(center_squares, 0) t1b = tf.pack([num_points, 1]) t1 = tf.tile(t1a, t1b) t2a = tf.expand_dims(squares, 1) t2b = tf.pack([1, k]) t2 = tf.tile(t2a, t2b) distances = t1 + t2 - 2 * prods indexes = tf.argmin(distances, 1) sess = tf.Session() print sess.run([distances, indexes], feed_dict={points:block, centers:init_centers}) with tf.Graph().as_default() as g: points = tf.placeholder(tf.double, shape=[None, num_features], name='features') num_points = tf.shape(points)[0] centers = tf.constant(init_centers) squares = tf.reduce_sum(tf.square(points), reduction_indices=1) center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1) prods = tf.matmul(points, centers, transpose_b = True) t1a = tf.expand_dims(center_squares, 0) t1b = tf.pack([num_points, 1]) t1 = tf.tile(t1a, t1b) t2a = tf.expand_dims(squares, 1) t2b = tf.pack([1, k]) t2 = tf.tile(t2a, t2b) distances = t1 + t2 - 2 * prods # TODO cast indexes = tf.argmin(distances, 1, name='indexes') min_distances = tf.reduce_min(distances, 1, name='min_distances') counts = tf.tile(tf.constant([1]), tf.pack([num_points]), name='count') df2 = tfs.map_blocks([indexes, counts, min_distances], df0) # Perform the reduction gb = df2.groupBy("indexes") with tf.Graph().as_default() as g: # Look at the documentation of tfs.aggregate for the naming conventions of the placeholders. x_input = tfs.block(df2, "features", tf_name="features_input") count_input = tfs.block(df2, "count", tf_name="count_input") md_input = tfs.block(df2, "min_distances", tf_name="min_distances_input") x = tf.reduce_sum(x_input, [0], name='features') count = tf.reduce_sum(count_input, [0], name='count') min_distances = tf.reduce_sum(md_input, [0], name='min_distances') df3 = tfs.aggregate([x, count, min_distances], gb) # Get the new centroids df3_c = df3.collect() new_centers = np.array([np.array(row.features) / row['count'] for row in df3_c]) total_distances = np.sum([row['min_distances'] for row in df3_c]) def run_one_step(dataframe, start_centers): """ Performs one iteration of K-Means. This function takes a dataframe with dense feature vectors, a set of centroids, and returns a new set of centroids along with the total distance of points to centroids. This function calculates for each point the closest centroid and then aggregates the newly formed clusters to find the new centroids. :param dataframe: a dataframe containing a column of features (an array of doubles) :param start_centers: a k x m matrix with k the number of centroids and m the number of features :return: a k x m matrix, and a positive double """ # The dimensions in the problem (num_centroids, num_features) = np.shape(start_centers) # For each feature vector, compute the nearest centroid and the distance to that centroid. # The index of the nearest centroid is stored in the 'indexes' column. # We also add a column of 1's that will be reduced later to count the number of elements in # each cluster. with tf.Graph().as_default() as g: # The placeholder for the input: we use the block format points = tf.placeholder(tf.double, shape=[None, num_features], name='features') # The shape of the block is extracted as a TF variable. num_points = tf.shape(points)[0] # The centers are embedded in the TF program. centers = tf.constant(start_centers) # Computation of the minimum distance. This is a standard implementation that follows # what MLlib does. squares = tf.reduce_sum(tf.square(points), reduction_indices=1) center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1) prods = tf.matmul(points, centers, transpose_b = True) t1a = tf.expand_dims(center_squares, 0) t1b = tf.pack([num_points, 1]) t1 = tf.tile(t1a, t1b) t2a = tf.expand_dims(squares, 1) t2b = tf.pack([1, num_centroids]) t2 = tf.tile(t2a, t2b) distances = t1 + t2 - 2 * prods # The outputs of the program. # The closest centroids are extracted. indexes = tf.argmin(distances, 1, name='indexes') # This could be done based on the indexes as well. min_distances = tf.reduce_min(distances, 1, name='min_distances') counts = tf.tile(tf.constant([1]), tf.pack([num_points]), name='count') df2 = tfs.map_blocks([indexes, counts, min_distances], dataframe) # Perform the reduction: we regroup the point by their centroid indexes. gb = df2.groupBy("indexes") with tf.Graph().as_default() as g: # Look at the documentation of tfs.aggregate for the naming conventions of the placeholders. x_input = tfs.block(df2, "features", tf_name="features_input") count_input = tfs.block(df2, "count", tf_name="count_input") md_input = tfs.block(df2, "min_distances", tf_name="min_distances_input") # Each operation is just the sum. x = tf.reduce_sum(x_input, [0], name='features') count = tf.reduce_sum(count_input, [0], name='count') min_distances = tf.reduce_sum(md_input, [0], name='min_distances') df3 = tfs.aggregate([x, count, min_distances], gb) # Get the new centroids df3_c = df3.collect() # The new centroids. new_centers = np.array([np.array(row.features) / row['count'] for row in df3_c]) total_distances = np.sum([row['min_distances'] for row in df3_c]) return (new_centers, total_distances) def kmeans(dataframe, init_centers, num_iters = 50): c = init_centers d = np.Inf ds = [] for i in range(num_iters): (c1, d1) = run_one_step(dataframe, c) print "Step =", i, ", overall distance = ", d1 c = c1 if d == d1: break d = d1 ds.append(d1) return c, ds c, ds = kmeans(df0, init_centers) ```
github_jupyter
## Example deTiN run using data from invitro mixing validation experiment Loading data and deTiN modules: ``` import deTiN.deTiN import deTiN.deTiN_SSNV_based_estimate as dssnv import deTiN.deTiN_aSCNA_based_estimate as dascna import deTiN.deTiN_utilities as du import numpy as np import matplotlib import matplotlib.pyplot as plt %matplotlib inline import optparse args = optparse.Values() args.mutation_data_path ='example_data/HCC_10_90.call_stats.pon_removed.txt' args.cn_data_path = 'example_data/HCC-1143_100_T-sim-final.acs.seg' args.tumor_het_data_path ='example_data/HCC_10_90.tumor.hets.tsv' args.normal_het_data_path = 'example_data/HCC_10_90.normal.hets.tsv' args.exac_data_path = 'example_data/exac.pickle_high_af' args.indel_data_path = 'example_data/MuTect2.call_stats.txt' args.indel_data_type = 'MuTect2' args.output_dir = 'example_data/' args.aSCNA_threshold = 0.1 args.output_name = 'HCC_10_90' args.use_outlier_removal = True args.mutation_prior = 0.1 args.TiN_prior = 1 args.resolution = 101 args.weighted_classification = False di = deTiN.input(args) di.read_and_preprocess_data() ``` Estimate tumor in normal based on SSNVs : ``` reload(dssnv) # identify SSNV candidates based on MuTect and panel of normal flags di.candidates = du.select_candidate_mutations(di.call_stats_table,di.exac_db_file) # generate SSNV based model using candidate sites ssnv_based_model = dssnv.model(di.candidates, di.mutation_prior,di.resolution) ssnv_based_model.perform_inference() ``` Estimate tumor in normal based on aSCNAs ``` # filter input SNPs based to maintain symmetry di.aSCNA_hets = du.ensure_balanced_hets(di.seg_table,di.het_table) # recalculate minor allele fraction and detect allelic imbalance di.aSCNA_segs,convergent_segs = du.identify_aSCNAs(di.seg_table,di.aSCNA_hets,di.aSCNA_thresh) reload(dascna) # generate aSCNA based model ascna_based_model = dascna.model(di.aSCNA_segs, di.aSCNA_hets,di.resolution) # MAP estimate of TiN for each segment and then K-means clustering procedure ascna_based_model.perform_inference() # calculate joint estimate and recover mutations do = deTiN.output(di,ssnv_based_model,ascna_based_model) do.calculate_joint_estimate() # reclassify somatic events based on TiN estimate do.reclassify_mutations() # write out SSNVs with deTiN annotations (rescued SSNVs are marked KEEP) do.SSNVs.to_csv(path_or_buf=do.input.output_path + '/' + do.input.output_name + '_deTiN_SSNVs.txt',sep='\t') # plot TiN posteriors from each model and the joint estimate du.plot_TiN_models(do) # plot recovered SSNVs based on TiN du.plot_SSNVs(do) # plot K-means clustering results and RSS information du.plot_kmeans_info(ascna_based_model,do.input.output_path,do.input.output_name) # plot K-means clustering results and RSS information du.plot_aSCNA_het_data(do) do.SSNVs.to_csv(path_or_buf=do.input.output_path + '/' + do.input.output_name + '_deTiN_SSNVs.txt', sep='\t',index=None) file = open(do.input.output_path + '/' + do.input.output_name + 'TiN_estimate_CI.txt', 'w') file.write('%s - %s' % (str(do.CI_tin_low),str(do.CI_tin_high))) file.close() file = open(do.input.output_path +'/' + do.input.output_name + 'TiN_estimate.txt', 'w') file.write('%d' % (do.TiN)) file.close() ```
github_jupyter
# Acquisition Models for MR, PET and CT This demonstration shows how to set-up and use SIRF/CIL acquisition models for different modalities. You should have tried the `introduction` notebook first. The current notebook briefly repeats some items without explanation. This demo is a jupyter notebook, i.e. intended to be run step by step. You could export it as a Python file and run it one go, but that might make little sense as the figures are not labelled. Authors: Christoph Kolbitsch, Edoardo Pasca, Kris Thielemans First version: 23rd of April 2021 CCP SyneRBI Synergistic Image Reconstruction Framework (SIRF). Copyright 2015 - 2017 Rutherford Appleton Laboratory STFC. Copyright 2015 - 2019, 2021 University College London. Copyright 2021 Physikalisch-Technische Bundesanstalt. This is software developed for the Collaborative Computational Project in Synergistic Reconstruction for Biomedical Imaging (http://www.ccpsynerbi.ac.uk/). 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. # Initial set-up ``` # Make sure figures appears inline and animations works %matplotlib notebook # Initial imports etc import numpy import matplotlib.pyplot as plt import os import sys import shutil import brainweb from tqdm.auto import tqdm # Import MR, PET and CT functionality import sirf.Gadgetron as mr import sirf.STIR as pet import cil.framework as ct from sirf.Utilities import examples_data_path from cil.plugins.astra.operators import ProjectionOperator as ap ``` If the above failed with a message like `No module named 'cil.plugins.astra'`, Astra has not been installed. Most CIL lines will therefore fail. We recommend that you comment them out (or install the Astra plugin for CIL of course). # Utilities First define some handy function definitions to make subsequent code cleaner. You can ignore them when you first see this demo. They have (minimal) documentation using Python docstrings such that you can do for instance `help(plot_2d_image)` ``` def plot_2d_image(idx,vol,title,clims=None,cmap="viridis"): """Customized version of subplot to plot 2D image""" plt.subplot(*idx) plt.imshow(vol,cmap=cmap) if not clims is None: plt.clim(clims) plt.colorbar() plt.title(title) plt.axis("off") def crop_and_fill(templ_im, vol): """Crop volumetric image data and replace image content in template image object""" # Get size of template image and crop idim_orig = templ_im.as_array().shape idim = (1,)*(3-len(idim_orig)) + idim_orig offset = (numpy.array(vol.shape) - numpy.array(idim)) // 2 vol = vol[offset[0]:offset[0]+idim[0], offset[1]:offset[1]+idim[1], offset[2]:offset[2]+idim[2]] # Make a copy of the template to ensure we do not overwrite it templ_im_out = templ_im.copy() # Fill image content templ_im_out.fill(numpy.reshape(vol, idim_orig)) return(templ_im_out) ``` # Get brainweb data We will download and use data from the brainweb. We will use a FDG image for PET and the PET uMAP for CT. MR usually provides qualitative images with an image contrast proportional to difference in T1, T2 or T2* depending on the sequence parameters. Nevertheless, we will make our life easy, by directly using the T1 map provided by the brainweb for MR. ``` fname, url= sorted(brainweb.utils.LINKS.items())[0] files = brainweb.get_file(fname, url, ".") data = brainweb.load_file(fname) brainweb.seed(1337) for f in tqdm([fname], desc="mMR ground truths", unit="subject"): vol = brainweb.get_mmr_fromfile(f, petNoise=1, t1Noise=0.75, t2Noise=0.75, petSigma=1, t1Sigma=1, t2Sigma=1) FDG_arr = vol['PET'] T1_arr = vol['T1'] uMap_arr = vol['uMap'] # Display it plt.figure(); slice_show = FDG_arr.shape[0]//2 plot_2d_image([1,3,1], FDG_arr[slice_show, 100:-100, 100:-100], 'FDG', cmap="hot") plot_2d_image([1,3,2], T1_arr[slice_show, 100:-100, 100:-100], 'T1', cmap="Greys_r") plot_2d_image([1,3,3], uMap_arr[slice_show, 100:-100, 100:-100], 'uMap', cmap="bone") ``` # Acquisition Models In SIRF and CIL, an `AcquisitionModel` basically contains everything we need to know in order to describe what happens when we go from the imaged object to the acquired raw data (`AcquisitionData`) and then to the reconstructed image (`ImageData`). What we actually need to know depends strongly on the modality we are looking at. Here are some examples of modality specific information: * __PET__: scanner geometry, detector efficiency, attenuation, randoms/scatter background... * __CT__: scanner geometry * __MR__: k-space sampling pattern, coil sensitivity information,... and then there is information which is independent of the modality such as field-of-view or image discretisation (e.g. voxel sizes). For __PET__ and __MR__ a lot of this information is already in the raw data. Because it would be quite a lot of work to enter all the necessary information by hand and then checking it is consistent, we create `AcquisitionModel` objects from `AcquisitionData` objects. The `AcquisitionData` only serves as a template and both its actual image and raw data content can be (and in this exercise will be) replaced. For __CT__ we will create an acquisition model from scratch, i.e. we will define the scanner geometry, image dimensions and image voxels sizes and so by hand. So let's get started with __MR__ . ## MR For MR we basically need the following: 1. create an MR `AcquisitionData` object from a raw data file 2. calculate the coil sensitivity maps (csm, for more information on that please see the notebook `MR/c_coil_combination.ipynb`). 3. then we will carry out a simple image reconstruction to get a `ImageData` object which we can use as a template for our `AcquisitionModel` 4. then we will set up the MR `AcquisitionModel` ``` # 1. create MR AcquisitionData mr_acq = mr.AcquisitionData(os.path.join(examples_data_path('MR'),'grappa2_1rep.h5')) # 2. calculate CSM preprocessed_data = mr.preprocess_acquisition_data(mr_acq) csm = mr.CoilSensitivityData() csm.smoothness = 50 csm.calculate(preprocessed_data) # 3. calculate image template recon = mr.FullySampledReconstructor() recon.set_input(preprocessed_data) recon.process() im_mr = recon.get_output() # 4. create AcquisitionModel acq_mod_mr = mr.AcquisitionModel(preprocessed_data, im_mr) # Supply csm to the acquisition model acq_mod_mr.set_coil_sensitivity_maps(csm) ``` ## PET For PET we need to: 1. create a PET `AcquisitionData` object from a raw data file 2. create a PET `ImageData` object from the PET `AcquisitionData` 3. then we will set up the PET `AcquisitionModel` ``` # 1. create PET AcquisitionData templ_sino = pet.AcquisitionData(os.path.join(examples_data_path('PET'),"thorax_single_slice","template_sinogram.hs")) # 2. create a template PET ImageData im_pet = pet.ImageData(templ_sino) # 3. create AcquisitionModel # create PET acquisition model acq_mod_pet = pet.AcquisitionModelUsingRayTracingMatrix() acq_mod_pet.set_up(templ_sino, im_pet) ``` ## CT For CT we need to: 1. create a CT `AcquisitionGeometry` object 2. obtain CT `ImageGeometry` from `AcquisitionGeometry` 3. create a CT `ImageData` object 4. then we will set up the CT `AcquisitionModel` ``` # 1. define AcquisitionGeometry angles = numpy.linspace(0, 360, 50, True, dtype=numpy.float32) ag2d = ct.AcquisitionGeometry.create_Cone2D((0,-1000), (0, 500))\ .set_panel(128,pixel_size=3.104)\ .set_angles(angles) # 2. get ImageGeometry ct_ig = ag2d.get_ImageGeometry() # 3. create ImageData im_ct = ct_ig.allocate(None) # 4. create AcquisitionModel acq_mod_ct = ap(ct_ig, ag2d, device='cpu') ``` # Apply acquisition models ## ImageData In order to be able to apply our acquisition models in order to create raw data, we first need some image data. Because this image data has to fit to the `ImageData` and `AcquisitionData` objects of the different modalities, we will use them to create our image data. For more information on that please have a look at the notebook _introductory/introduction.ipynb_. Let's create an `ImageData` object for each modality and display the slice in the centre of each data set: ``` # MR im_mr = crop_and_fill(im_mr, T1_arr) # PET im_pet = crop_and_fill(im_pet, FDG_arr) # CT im_ct = crop_and_fill(im_ct, uMap_arr) plt.figure(); plot_2d_image([1,3,1], im_pet.as_array()[im_pet.dimensions()[0]//2, :, :], 'PET', cmap="hot") plot_2d_image([1,3,2], numpy.abs(im_mr.as_array())[im_mr.dimensions()[0]//2, :, :], 'MR', cmap="Greys_r") plot_2d_image([1,3,3], numpy.abs(im_ct.as_array()), 'CT', cmap="bone") ``` ## Forward and Backward ### Fun fact The methods `forward` and `backward` for __MR__ and __PET__ describe to forward acquisition model (i.e. going from the object to the raw data) and backward acquisition model (i.e. going from the raw data to the object). For the __CT__ acquisition model we utilise functionality from __CIL__ . Here, these two operations are defined by `direct` (corresponding to `forward`) and `adjoint` (corresponding to `backward`). In order to make sure that the __MR__ and __PET__ acquisition models are fully compatible with all the __CIL__ functionality, both acquisition models also have the methods `direct` and `adjoint` which are simple aliases of `forward` and `backward`. Now back to our three acquisition models and let's create some raw data ``` # PET raw_pet = acq_mod_pet.forward(im_pet) # MR raw_mr = acq_mod_mr.forward(im_mr) # CT raw_ct = acq_mod_ct.direct(im_ct) ``` and we can apply the backward/adjoint operation to do a simply image reconstruction. ``` # PET bwd_pet = acq_mod_pet.backward(raw_pet) # MR bwd_mr = acq_mod_mr.backward(raw_mr) # CT bwd_ct = acq_mod_ct.adjoint(raw_ct) plt.figure(); # Raw data plot_2d_image([2,3,1], raw_pet.as_array()[0, raw_pet.dimensions()[1]//2, :, :], 'PET raw', cmap="viridis") plot_2d_image([2,3,2], numpy.log(numpy.abs(raw_mr.as_array()[:, raw_mr.dimensions()[1]//2, :])), 'MR raw', cmap="viridis") plot_2d_image([2,3,3], raw_ct.as_array(), 'CT raw', cmap="viridis") # Rec data plot_2d_image([2,3,4], bwd_pet.as_array()[bwd_pet.dimensions()[0]//2, :, :], 'PET', cmap="magma") plot_2d_image([2,3,5], numpy.abs(bwd_mr.as_array()[bwd_mr.dimensions()[0]//2, :, :]), 'MR', cmap="Greys_r") plot_2d_image([2,3,6], bwd_ct.as_array(), 'CT', cmap="bone") ``` These images don't look too great. This is due to many things, e.g. for MR the raw data is missing a lot of k-space information and hence we get undersampling artefacts.In general, the adjoint operation is not equal to the inverse operation. Therefore SIRF offers a range of more sophisticated image reconstruction techniques which strongly improve the image quality, but this is another notebook...
github_jupyter
# Train-Eval --- ## Import Libraries ``` import os import sys from pathlib import Path import torch import torch.nn as nn import torch.optim as optim from torchtext.data import BucketIterator sys.path.append("../") from meta_infomax.datasets.fudan_reviews import prepare_data, get_data ``` ## Global Constants ``` BSIZE = 16 ENCODER_DIM = 100 CLASSIFIER_DIM = 100 NUM_TASKS = 14 EPOCHS = 1 DATASETS = ['apparel', 'baby', 'books', 'camera_photo', 'electronics', 'health_personal_care', 'imdb', 'kitchen_housewares', 'magazines', 'music', 'software', 'sports_outdoors', 'toys_games', 'video'] ``` # Load Data ``` from torchtext.vocab import GloVe # prepare_data() train_set, dev_set, test_set, vocab = get_data() train_iter, dev_iter, test_iter = BucketIterator.splits((train_set, dev_set, test_set), batch_sizes=(BSIZE, BSIZE*2, BSIZE*2), sort_within_batch=False, sort_key=lambda x: len(x.text)) batch = next(iter(train_iter)) batch batch.text[0].shape, batch.label.shape, batch.task.shape vocab.stoi["<pad>"] ``` # Baseline Model ``` class Encoder(nn.Module): def __init__(self,emb_dim, hidden_dim, num_layers): super().__init__() self.lstm = nn.LSTM(emb_dim, hidden_dim, num_layers, batch_first=True, bidirectional=True) def forward(self, x): self.h0 = self.h0.to(x.device) self.c0 = self.c0.to(x.device) out, _ = self.lstm(x, (self.h0, self.c0)) return out class Classifier(nn.Module): def __init__(self, in_dim, hidden_dim, out_dim): super().__init__() self.layers = nn.Sequential( nn.Linear(in_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, out_dim) ) def forward(self, x): return self.layers(x) class MultiTaskInfoMax(nn.Module): def __init__(self, shared_encoder, embeddings, vocab, encoder_dim, encoder_layers, classifier_dim, out_dim): super().__init__() self.emb = nn.Embedding.from_pretrained(embeddings, freeze=True, padding_idx=vocab.stoi["<pad>"]) self.shared_encoder = shared_encoder self.private_encoder = Encoder(embeddings.shape[-1], encoder_dim, encoder_layers) self.classifier = Classifier(encoder_dim*4, classifier_dim, out_dim) def forward(self, sentences, lengths): sent_embed = self.emb(sentences) shared_out = self.shared_encoder(sent_embed) private_out = self.private_encoder(sent_embed) h = torch.cat((shared_out, private_out), dim=1) out = self.classifier(h) return out, shared_out, private_out ``` # Train ## Overfit Batch ``` vocab.vectors.shape shared_encoder = Encoder(vocab.vectors.shape[1], ENCODER_DIM, 1) shared_encoder multitask_models = [MultiTaskInfoMax(shared_encoder=shared_encoder, embeddings=vocab.vectors, vocab=vocab, encoder_dim=ENCODER_DIM,encoder_layers=1, classifier_dim=CLASSIFIER_DIM, out_dim=2) for i in range(len(DATASETS))] multitask_models[1] multitask_models[batch] ```
github_jupyter
# Introduction to Jupyter Notebooks Today we are going to learn about [Jupyter Notebooks](https://jupyter.org/)! The advantage of notebooks is that they can include explanatory text, code, and plots in the same document. **This makes notebooks an ideal playground for explaining and learning new things without having to jump between several documents.** You will use notebooks a LOT during your studies, and this is why I decided to teach you how they work very early in your programming journey. This document itself is a notebook. It is a simple text file with a `.ipynb` file path ending. Notebooks are best opened in "JupyterLab", the development environment that you learned about last week. **Note: learning about notebooks is less urgent than learning how to write correct code. If you are feeling overwhelmed by coding, you should focus on the coding exercises for now and learn about notebooks a bit later. They will only become mandatory in about 2 to 3 weeks.** Let's start with a short video introduction, which will invite you to download this notebook to try it yourself: ``` from IPython.display import VimeoVideo VimeoVideo(691294249, width=900) ``` ## First steps Have you downloaded and opened the notebook as explained in the video? If not, do that first and continue this lesson on your own latpop. At first sight the notebook looks like a text editor. Below this line, you can see a **cell**. The default purpose of a cell is to write code: ``` # Click on this cell, so that its frame gets highlighted m = 'Hello' print(m) ``` You can write one or more lines of code in a cell. You can **run** this code by clicking on the "Run" button from the toolbar above when the cell's frame is highlighted. Try it now! Clicking "play" through a notebook is possible, but it is much faster to use the keybord shortcut instead: `[Shift+Enter]`. Once you have executed a cell, the next cell is selected. You can **insert** cells in a notebook with the `+` button in the toolbar. Again, it is much faster to learn the keybord shortcut for this: `[Ctrl+m]` or `[ESC]` to enter in command mode (blue frame) then press `[a]` to insert a cell "above" the active cell or `[b]` for "below". Create a few empty cells above and below the current one and try to create some variables. Instead of clicking on a cell to enter in edit mode press `[Enter]`. You can **delete** a cell by clicking "Delete" in the "Edit" menu, or you can use the shortcut: `[Ctrl+m]` to enter in command mode then press `[d]` two times! ## More cell editing When you have a look into the "Edit" menu, you will see that there are more possibilities to edit cells, like: - **copy** / **cut** and **paste** - **splitting** and **merging** cells and more. ``` a = 'This cell needs to be splitted.' b = 'Put the cursor in the row between the variables a and b, then choose [split cell] in the "Edit" menu!' ``` Another helpful command is "Undo delete cell', which is sometimes needed when the key `[d]` was pressed too fast. ## Writing and executing code The variables created in one cell can be used (or overwritten) in subsequent cells: ``` s = 'Hello' print(s) s = s + ' Python!' # Lines which start with # are not executed. These are for comments. s ``` Note that we ommited the `print` commmand above (this is OK if you want to print something at the end of the cell only). In jupyter notebooks, **code autocompletion** is supported. This is very useful when writing code. Variable names, functions and methods can be completed by pressing `[TAB]`. ``` # Let's define a random sentence as string. sentence = 'How Are You?' # Now try autocompletion! Type 'se' in the next row and press [TAB]. ``` An advantage of notebooks is that each single cell can be executed separately. That provides an easy way to execute code step by step, one cell after another. **It is important to notice that the order in which you execute the cells is the order with which the jupyter notebook calculates and saves variables - the execution order therefore depends on you, NOT on the order of the cells in the document**. That means that it makes a difference, whether you execute the cells top down one after another, or you mix them (cell 1, then cell 5, then cell 2 etc.). The numbers on the left of each cell show you your order of execution. When a calculation is running longer, you will see an asterisk in the place of the number. That leads us to the next topic: ## Restart or interrupt the kernel Sometimes calculations last too long and you want to **interrupt** them. You can do this by clicking the "Stop button" in the toolbar. The "**kernel**" of a notebook is the actual python interpreter which runs your code. There is one kernel per opened notebook (i.e. the notebooks cannot share data or variables between each other). In certain situations (for example, if you got confused about the order of your cells and variables and want a fresh state), you might want to **retart the kernel**. You can do so (as well as other options such as **clearing the output** of a notebook) in the "Kernel" menu in the top jupyterlab bar. ## Errors in a cell Sometimes, a piece of code in a cell won't run properly. This happens to everyone! Here is an example: ``` # This will produce a "NameError" test = 1 + 3 print(tesT) ``` When a cell ends with an error, don't panic! Nothing we cannot recover from. First of all, the other cells will still run (unless they depend on the output of the failing cell): i.e., your kernel is still active. If you want to recover from the error, adress the problem (here a capsize issue) and re-run the cell. ## Formatting your notebook with text, titles and formulas The default role of a cell is to run code, but you can tell the notebook to format a cell as "text" by clicking in the menu bar on "Cell", choose "Cell Type" $\rightarrow$ "Markdown". The current cell will now be transformed to a normal text. Again, there is a keyboard shortcut for this: press `[Ctrl+m]` to enter in command mode and then `[m]` to convert the active cell to text. The opposite (converting a text cell to code) can be done with `[Ctrl+m]` to enter in command mode and then `[y]`. As we have seen, the notebook editor has two simple modes: the "command mode" to navigate between cells and activate them, and the "edit mode" to edit their content. To edit a cell you have two choices: - press `[enter]` on a selected (highlighted) cell - double click on a cell (any cell) Now, try to edit the cell below! A text cell is formatted with the [Markdown](https://en.wikipedia.org/wiki/Markdown) format, e.g. it is possible to write lists: - item 1 - item 2 Numbered lists: 1. part a 2. part b Titles with the `#` syntax (the number of `#` indicating the level of the title: ### This is a level 3 title (with 3 `#` symbols) Mathematical formulas can be written down with the familiar Latex notation: $$ E = m c^2$$ You can also write text in **bold** or *cursive*. ## Download a notebook Jupyter notebooks can be downloaded in various formats: - Standard notebook (`*.ipynb`): a text file only useful within the Jupyter framework - Python (`*.py`): a python script that can be executed separately. - HTML (`*.html`): an html text file that can be opened in any web browser (doens't require python or jupyter!) - ... and a number of other formats that may or may not work depending on your installation **To download a jupyter notebook in the notebook format** (`.ipynb`), select the file on the left-hand side bar, right-click and select "Download". Try it now! **For all other formats**, go to the "File" menu, then "Export notebook as..." ## Take home points - jupyter notebooks consist of cells, which can be either code or text (not both) - one can navigate between cells in "control mode" (`[ctrl+m]`) and edit them in "edit mode" (`[enter]` or double click) - to exectute a cell, do: `[shift+enter]` - the order of execution of cells *does* matter - a text cell is written in markdown format, which allows lots of fancy formatting These were the most important features of jupyter-notebook. In the notebook's menu bar the tab "Help" provides links to the documentation. Keyboard shortcuts are listed in the "Palette" icon on the left-hand side toolbar. Furthermore, there are more tutorials [on the Jupyter website](https://jupyter.org/try). But with the few commands you learned today, you are already well prepared for the rest of the class!
github_jupyter
# Navigation --- In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). ### 1. Start the Environment We begin by importing some necessary packages. If the code cell below returns an error, please revisit the project instructions to double-check that you have installed [Unity ML-Agents](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md) and [NumPy](http://www.numpy.org/). ``` from unityagents import UnityEnvironment import numpy as np ``` Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded. - **Mac**: `"path/to/Banana.app"` - **Windows** (x86): `"path/to/Banana_Windows_x86/Banana.exe"` - **Windows** (x86_64): `"path/to/Banana_Windows_x86_64/Banana.exe"` - **Linux** (x86): `"path/to/Banana_Linux/Banana.x86"` - **Linux** (x86_64): `"path/to/Banana_Linux/Banana.x86_64"` - **Linux** (x86, headless): `"path/to/Banana_Linux_NoVis/Banana.x86"` - **Linux** (x86_64, headless): `"path/to/Banana_Linux_NoVis/Banana.x86_64"` For instance, if you are using a Mac, then you downloaded `Banana.app`. If this file is in the same folder as the notebook, then the line below should appear as follows: ``` env = UnityEnvironment(file_name="Banana.app") ``` ``` env = UnityEnvironment(file_name="Banana.app", no_graphics=True) ``` ### 1. Define imports python 3, numpy, matplotlib, torch ``` # General imports import numpy as np import random from collections import namedtuple, deque import matplotlib.pyplot as plt %matplotlib inline # torch imports import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # Constants Defin itions BUFFER_SIZE = int(1e5) # replay buffer size BATCH_SIZE = 64 # minibatch size GAMMA = 0.99 # discount factor TAU = 1e-3 # for soft update of target parameters LR = 5e-4 # learning rate UPDATE_EVERY = 4 # how often to update the network # Number of neurons in the layers of the q Network FC1_UNITS = 32 # 16 # 32 # 64 FC2_UNITS = 16 # 8 # 16 # 64 FC3_UNITS = 8 # Work area to quickly test utility functions import time from datetime import datetime, timedelta start_time = time.time() time.sleep(10) print('Elapsed : {}'.format(timedelta(seconds=time.time() - start_time))) ``` Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. ``` from unityagents import UnityEnvironment env = UnityEnvironment(file_name="Banana.app", no_graphics=True) # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] ``` ### 2. Examine the State and Action Spaces The simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal: - `0` - walk forward - `1` - walk backward - `2` - turn left - `3` - turn right The state space has `37` dimensions and contains the agent's velocity, along with ray-based perception of objects around agent's forward direction. A reward of `+1` is provided for collecting a yellow banana, and a reward of `-1` is provided for collecting a blue banana. The cell below tests to make sure the environment is up and running by printing some information about the environment. ``` # reset the environment for training agents via external python API 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) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class QNetwork(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, fc1_units = FC1_UNITS, fc2_units = FC2_UNITS, fc3_units = FC3_UNITS): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed """ super(QNetwork, self).__init__() self.seed = torch.manual_seed(seed) self.fc1 = nn.Linear(state_size,fc1_units) self.fc2 = nn.Linear(fc1_units,fc2_units) self.fc3 = nn.Linear(fc2_units,fc3_units) self.fc4 = nn.Linear(fc3_units,action_size) def forward(self, state): """Build a network that maps state -> action values.""" x = F.relu(self.fc1(state)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = self.fc4(x) return x class ReplayBuffer: """Fixed-size buffer to store experience tuples.""" def __init__(self, action_size, buffer_size, batch_size, seed): """Initialize a ReplayBuffer object. Params ====== action_size (int): dimension of each action buffer_size (int): maximum size of buffer batch_size (int): size of each training batch seed (int): random seed """ self.action_size = action_size self.memory = deque(maxlen=buffer_size) self.batch_size = batch_size self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"]) self.seed = random.seed(seed) def add(self, state, action, reward, next_state, done): """Add a new experience to memory.""" e = self.experience(state, action, reward, next_state, done) self.memory.append(e) def sample(self): """Randomly sample a batch of experiences from memory.""" experiences = random.sample(self.memory, k=self.batch_size) states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device) actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device) rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device) next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device) dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device) return (states, actions, rewards, next_states, dones) def __len__(self): """Return the current size of internal memory.""" return len(self.memory) class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(seed) # Q-Network self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device) self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device) self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR) # Replay memory self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 def step(self, state, action, reward, next_state, done): # Save experience in replay memory self.memory.add(state, action, reward, next_state, done) # Learn every UPDATE_EVERY time steps. self.t_step = (self.t_step + 1) % UPDATE_EVERY if self.t_step == 0: # If enough samples are available in memory, get random subset and learn if len(self.memory) > BATCH_SIZE: experiences = self.memory.sample() self.learn(experiences, GAMMA) def act(self, state, eps=0.): """Returns actions for given state as per current policy. Params ====== state (array_like): current state eps (float): epsilon, for epsilon-greedy action selection """ state = torch.from_numpy(state).float().unsqueeze(0).to(device) self.qnetwork_local.eval() with torch.no_grad(): action_values = self.qnetwork_local(state) self.qnetwork_local.train() # Epsilon-greedy action selection if random.random() > eps: return np.argmax(action_values.cpu().data.numpy()) else: return random.choice(np.arange(self.action_size)) def learn(self, experiences, gamma): """Update value parameters using given batch of experience tuples. Params ====== experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones = experiences # compute and minimize the loss # Get max predicted Q values (for next states) from target model Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1) # Compute Q targets for current states Q_targets = rewards + gamma * Q_targets_next * (1 - dones) # Get expected Q values from local model Q_expected = self.qnetwork_local(states).gather(1,actions) # Compute Loss loss = F.mse_loss(Q_expected,Q_targets) #Minimize Loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() # ------------------- update target network ------------------- # self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) def soft_update(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data) agent = Agent(state_size=state_size, action_size=action_size, seed=42) print(agent.qnetwork_local) def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of timesteps per episode eps_start (float): starting value of epsilon, for epsilon-greedy action selection eps_end (float): minimum value of epsilon eps_decay (float): multiplicative factor (per episode) for decreasing epsilon """ scores = [] # list containing scores from each episode scores_window = deque(maxlen=100) # last 100 scores eps = eps_start # initialize epsilon has_seen_13 = False max_score = 0 for i_episode in range(1, n_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 max_steps = 0 for t in range(max_t): action = agent.act(state, eps) # next_state, reward, done, _ = env.step(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] agent.step(state, action, reward, next_state, done) state = next_state score += reward max_steps += 1 if done: break scores_window.append(score) # save most recent score scores.append(score) # save most recent score eps = max(eps_end, eps_decay*eps) # decrease epsilon print('\rEpisode : {}\tAverage Score : {:.2f}\tMax_steps : {}'.format(i_episode, np.mean(scores_window),max_steps), end="") if i_episode % 100 == 0: print('\rEpisode : {}\tAverage Score : {:.2f}\tMax_steps : {}'.format(i_episode, np.mean(scores_window),max_steps)) if (np.mean(scores_window)>=13.0) and (not has_seen_13): print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window))) torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth') has_seen_13 = True # break # To see how far it can go # Store the best model if np.mean(scores_window) > max_score: max_score = np.mean(scores_window) torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth') return scores start_time = time.time() scores = dqn() # The env ends at 300 steps. Tried max_t > 1K. Didn't see any complex adaptive temporal behavior env.close() # Close the environment print('Elapsed : {}'.format(timedelta(seconds=time.time() - start_time))) # plot the scores fig = plt.figure() ax = fig.add_subplot(111) plt.plot(np.arange(len(scores)), scores) plt.ylabel('Score') plt.xlabel('Episode #') plt.show() agent.qnetwork_local print('Max Score {:2f} at {}'.format(np.max(scores), np.argmax(scores))) print('Percentile [25,50,75] : {}'.format(np.percentile(scores,[25,50,75]))) print('Variance : {:.3f}'.format(np.var(scores))) # Run Logs ''' Max = 2000 episodes, GAMMA = 0.99 # discount factor TAU = 1e-3 # for soft update of target parameters LR = 5e-4 # learning rate UPDATE_EVERY = 4 # how often to update the network fc1:64-fc2:64-fc3:4 -> 510 episodes/13.04, Max 26 @ 1183 episodes, Runnimg 100 mean 16.25 @1200, @1800 Elapsed : 1:19:28.997291 fc1:32-fc2:16-fc3:4 -> 449 episodes/13.01, Max 28 @ 1991 episodes, Runnimg 100 mean 16.41 @1300, 16.66 @1600, 17.65 @2000 Elapsed : 1:20:27.390989 Less Variance ? Overall learns better & steady; keeps high scores onc it learned them - match impedence percentile[25,50,75] = [11. 15. 18.]; var = 30.469993749999997 fc1:16-fc2:8-fc3:4 -> 502 episodes/13.01, Max 28 @ 1568 episodes, Runnimg 100 mean 16.41 @1400, 16.23 @1500, 16.32 @1600 Elapsed : 1:18:33.396898 percentile[25,50,75] = [10. 14. 17.]; var = 30.15840975 Very calm CPU ! Embed in TX2 or raspberry Pi environment - definitely this network Doesn't reach the highs of a larger network fc1:32-fc2:16-fc3:8-fc4:4 -> 405 episodes/13.03, Max 28 @ 1281 episodes, Runnimg 100 mean 17.05 @1500, 16.69 @1700 Elapsed : 1:24:07.507518 percentile[25,50,75] = [11. 15. 18.]; var = 34.83351975 Back to heavy CPU usage. Reaches solution faster, so definitely more fidelity. Depth gives early advantage fc1:64-fc2:32-fc3:16-fc4:8-fc5:4 -> 510 episodes, max score : 15.50 @ 700 episodes Monstrous atrocity ! fc1:32-fc2:4-> 510 episodes, max score : 15.50 @ 700 episodes Minimalist ''' print(np.percentile(scores,[25,50,75])) print(np.var(scores)) print(agent.qnetwork_local) print('Max Score {:2f} at {}'.format(np.max(scores), np.argmax(scores))) len(scores) np.median(scores) # Run best model ```
github_jupyter
``` import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler df = pd.read_csv('train_FD001.txt', sep=' ', header=None) # dropping NAN values df = df.dropna(axis=1, how='all') # Naming the columns df.columns = ["unit", "cycles", "Op1", "Op2", "Op3", "S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "S11", "S12", "S13", "S14", "S15", "S16", "S17", "S18", "S19", "S20", "S21"] # # show dataframe # df.head() # data preprocessing; removing unnecessary data df.drop(['Op3','S1', 'S5', 'S6', 'S16', 'S10', 'S18', 'S19'], axis=1, inplace=True) df.head() # MinMaxScaler scaler = MinMaxScaler() df.iloc[:,2:18] = scaler.fit_transform(df.iloc[:,2:18]) # finding the max cycles of a unit which is used to find the Time to Failure (TTF) df = pd.merge(df, df.groupby('unit', as_index=False)['cycles'].max(), how='left', on='unit') df.rename(columns={"cycles_x": "cycles", "cycles_y": "maxcycles"}, inplace=True) df['TTF'] = df['maxcycles'] - df['cycles'] # defining Fraction of Time to Failure (fTTF), where value of 1 denotes healthy engine and 0 denotes failure def fractionTTF(dat,q): return(dat.TTF[q]-dat.TTF.min()) / (dat.TTF.max()-dat.TTF.min()) fTTFz = [] fTTF = [] for i in range(df['unit'].min(),df['unit'].max()+1): dat=df[df.unit==i] dat = dat.reset_index(drop=True) for q in range(len(dat)): fTTFz = fractionTTF(dat, q) fTTF.append(fTTFz) df['fTTF'] = fTTF df cycles = df.groupby('unit', as_index=False)['cycles'].max() mx = cycles.iloc[0:4,1].sum() plt.plot(df.fTTF[0:mx]) plt.legend(['Time to failure (fraction)'], bbox_to_anchor=(0., 1.02, 1., .102), loc=3, mode="expand", borderaxespad=0) plt.ylabel('Scaled unit') plt.show() # splitting train and test data, test size 20% # train set df_train = df[(df.unit <= 80)] X_train = df_train[['cycles', 'Op1', 'Op2', 'S2', 'S3', 'S4', 'S7', 'S8', 'S9', 'S11', 'S12', 'S13', 'S14', 'S15', 'S17', 'S20', 'S21']].values y_train = df_train[['fTTF']].values.ravel() # test set df_test = df[(df.unit > 80)] X_test = df_test[['cycles', 'Op1', 'Op2', 'S2', 'S3', 'S4', 'S7', 'S8', 'S9', 'S11', 'S12', 'S13', 'S14', 'S15', 'S17', 'S20', 'S21']].values y_test = df_test[['fTTF']].values.ravel() from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.wrappers.scikit_learn import KerasRegressor model = Sequential() model.add(Dense(50, input_dim=17, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal')) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X_train, y_train, epochs = 50) score = model.predict(X_test) df_test['predicted'] = score plt.figure(figsize = (16, 8)) plt.plot(df_test.fTTF) plt.plot(df_test.predicted) # RMSE from sklearn.metrics import mean_squared_error, r2_score from math import sqrt nn_rmse = sqrt(mean_squared_error(y_test, score)) print("RMSE: ", nn_rmse) # r2 score nn_r2 = r2_score(y_test, score) print("r2 score: ", nn_r2) df_test def totcycles(data): return(data['cycles'] / (1-data['predicted'])) df_test['maxpredcycles'] = totcycles(df_test) df_test from google.colab import drive drive.mount('/drive') df_test.to_csv('/drive/My Drive/test_dataframe.csv') # export dataframe to google drive as as csv file to analyse the findings # upon observation it is noticed that the prediction gets more accurate the further the cycle is in the time series # df_test.groupby('unit', as_index=False)['maxpredcycles'].quantile(.10) // pd.groupby().quantile() to get the quantile result # df_test.groupby('unit', as_index=False)['cycles'].max() dff = pd.merge(df_test.groupby('unit', as_index=False)['maxpredcycles'].quantile(.72), df.groupby('unit', as_index=False)['maxcycles'].max(), how='left', on='unit') dff # display the preliminary results for obervation MAXPRED = dff.maxpredcycles MAXI = dff.maxcycles dff_rmse = sqrt(mean_squared_error(MAXPRED, MAXI)) print("RMSE: ", dff_rmse) ```
github_jupyter
# ML Pipeline Preparation Follow the instructions below to help you create your ML pipeline. ### 1. Import libraries and load data from database. - Import Python libraries - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html) - Define feature and target variables X and Y ``` # import libraries import pandas as pd import numpy as np from sqlalchemy import create_engine from nltk.tokenize import word_tokenize , RegexpTokenizer from nltk.stem import WordNetLemmatizer from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.model_selection import GridSearchCV from sklearn.decomposition import TruncatedSVD import pickle import sqlite3 import nltk import re import string from sklearn.metrics import precision_recall_fscore_support %matplotlib inline import matplotlib.pyplot as plt from nltk.corpus import wordnet as wn import nltk nltk.download('wordnet') nltk.download('punkt') nltk.download('wordent') nltk.download('stopwords') # load data from database engine = create_engine('sqlite:///InsertDatabaseName.db') df = pd.read_sql_table('InsertTableName', engine) X = df.filter(items=['id', 'message', 'original', 'genre']) y = df.drop(['id', 'message', 'original', 'genre', 'child_alone'], axis=1)#'child_alone' has no responses y['related']=y['related'].map(lambda x: 1 if x == 2 else x) df.head() ``` ### 2. Write a tokenization function to process your text data ``` from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem.porter import PorterStemmer def tokenize(text): tokens = nltk.word_tokenize(text) lemmatizer = nltk.WordNetLemmatizer() return [lemmatizer.lemmatize(w).lower().strip() for w in tokens] #stop_words = nltk.corpus.stopwords.words("english") #lemmatizer = nltk.stem.wordnet.WordNetLemmatizer() #remove_punc_table = str.maketrans('', '', string.punctuation) ``` ### 3. Build a machine learning pipeline This machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) helpful for predicting multiple target variables. ``` from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multioutput import MultiOutputClassifier from sklearn.pipeline import Pipeline pipeline = Pipeline([('cvect', CountVectorizer(tokenizer = tokenize)), ('tfidf', TfidfTransformer()), ('clf', RandomForestClassifier()) ]) ``` ### 4. Train pipeline - Split data into train and test sets - Train pipeline ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y) pipeline.fit(X_train['message'], y_train) ``` ### 5. Test your model Report the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each. ``` from sklearn.metrics import classification_report from sklearn.metrics import accuracy_score from sklearn.multioutput import MultiOutputClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, make_scorer from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC y_pred_test = pipeline.predict(X_test['message']) y_pred_train = pipeline.predict(X_train['message']) print(classification_report(y_test.values, y_pred_test, target_names=y.columns.values)) print('-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-') print('\n',classification_report(y_train.values, y_pred_train, target_names=y.columns.values)) parameters = {'clf__max_depth': [10, 20, None], 'clf__min_samples_leaf': [1, 2, 4], 'clf__min_samples_split': [2, 5, 10], 'clf__n_estimators': [10, 20, 40]} cv = GridSearchCV(pipeline, param_grid=parameters, scoring='f1_micro', verbose=1, n_jobs=-1) cv.fit(X_train['message'], y_train) ``` ### 7. Test your model Show the accuracy, precision, and recall of the tuned model. Since this project focuses on code quality, process, and pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - especially for your portfolio! ``` y_pred_test = cv.predict(X_test['message']) y_pred_train = cv.predict(X_train['message']) print(classification_report(y_test.values, y_pred_test, target_names=y.columns.values)) print('-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-\|/-') print('\n',classification_report(y_train.values, y_pred_train, target_names=y.columns.values)) ``` ### 8. Try improving your model further. Here are a few ideas: * try other machine learning algorithms * add other features besides the TF-IDF ``` cv.best_params_ ``` ### 9. Export your model as a pickle file ``` m = pickle.dumps('clf') with open('disaster_model.pkl', 'wb') as f: pickle.dump(cv, f) ``` ### 10. Use this notebook to complete `train.py` Use the template file attached in the Resources folder to write a script that runs the steps above to create a database and export a model based on a new dataset specified by the user.
github_jupyter
# Data Augumentation on Animals dataset using MiniVGG net In this example, We explore the Data Augmentation. This method of regularization can aid us to improve our results during the training process. In addition, we consider the Aspect Ratio when resizing the images. Maintaining the aspect ratio help the CNN to extract considerable features from each image, unlike the simple resizing that distort the images, causing the loss of information contained on the images. We perform two experiments. The fist, we just consider the resizing process maintaining the aspect ratio. For the second experiment, we consider the Data Augmentation and the aspect ration for the resizing. For the both models, We consider the Learning Rate Scheduler, defining a piecewise function. ## Importing libraries ``` from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report import tensorflow as tf #compvis modeule from compvis.preprocessing import ImageToArrayPreprocessor from compvis.preprocessing import ResizeAR from compvis.datasets import SimpleDatasetLoader from compvis.ann.cnns import MiniVGG from tensorflow.keras.optimizers import SGD from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.callbacks import LearningRateScheduler from imutils import paths import matplotlib.pyplot as plt import numpy as np ``` ## Loading and preprocessing the dataset ``` dataset = "/home/igor/Documents/Artificial_Inteligence/Datasets/Animals" #path imagePaths = list(paths.list_images(dataset)) # list of all images ar = ResizeAR(32, 32) # simple image preprocessor iap = ImageToArrayPreprocessor() # to convert image into arraey sdl = SimpleDatasetLoader(preprocessors=[ar, iap]) # to load images from disk and process them (data, labels) = sdl.load(imagePaths, verbose = 500) # return images and labels data = data.astype("float") / 255. # Normalize into 0 and 1 ``` ### Splitting the dataset into train and test set ``` (X_train, X_test, y_train, y_test) = train_test_split(data, labels, test_size = 0.25, random_state = 42) ``` ### Transforming the labels ``` y_train = LabelBinarizer().fit_transform(y_train) y_test = LabelBinarizer().fit_transform(y_test) ``` ### Defining the Image Generator function from Keras The Data Augmentations consists in transform an image, rotating, shearing, zooming and flipping horizontally it. In this way, a simple image generates others six. ``` aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode="nearest") ``` ## Building the model Model **Defining the step decay function** ``` def step_decay(epoch, lr): init_alpha = 0.01 # initial learning rate factor = 0.25 dropEvery = 5 # step size if epoch == 1: lr = init_alpha elif epoch%5 == 0: lr = init_alpha * (factor ** np.floor((1 + epoch) / dropEvery)) else: lr = lr return lr ``` **Defining the Callbacks** ``` callbacks = [LearningRateScheduler(step_decay)] ``` ### Defining the first model ``` opt = SGD(momentum=0.9, nesterov=True) # regularization model = MiniVGG.build(32, 32, 3, 3) #model model.compile(loss = "categorical_crossentropy", optimizer = opt, metrics = ["accuracy"]) # compiling the model ``` ### Training the first model We choose the batch size of $32$ and $100$ epochs. ``` ne = 100 bs = 32 H = model.fit(X_train, y_train, validation_data = (X_test, y_test), batch_size = bs, epochs = ne, callbacks=callbacks, verbose = 1) ``` ### Predicting on the first trained model ``` predictions = model.predict(X_test, batch_size = bs) ``` ### Evaluating the first model ``` cr = classification_report(y_test.argmax(axis = 1), predictions.argmax(axis = 1), target_names = ["cat", "dog", "panda"]) print(cr) ``` ### Visualizing the metrics results ``` plt.style.use("ggplot") plt.figure(figsize=(20,20)) plt.plot(np.arange(0, ne), H.history["loss"], label="train_loss") plt.plot(np.arange(0, ne), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, ne), H.history["accuracy"], label="train_acc") plt.plot(np.arange(0, ne), H.history["val_accuracy"], label="val_acc") plt.axis((0, ne, 0.25, 1)) plt.title("Training Loss and Accuracy") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend() plt.show() ``` ### Defining the second model with Data Augmentation ``` model1 = MiniVGG.build(32, 32, 3, 3) model1.compile(loss = "categorical_crossentropy", optimizer = opt, metrics = ["accuracy"]) ``` ### Training the second model In the fit, We have add the aug.flow() that accepts as argument, the training and the batch size. ``` H = model1.fit(aug.flow(X_train, y_train, batch_size=bs), validation_data=(X_test, y_test), steps_per_epoch=len(X_train) // 32, epochs=ne, callbacks=callbacks, verbose=1) ``` ### Predicting on the second model ``` predictions = model.predict(X_test, batch_size = bs) ``` ### Evaluating the second model ``` cr = classification_report(y_test.argmax(axis = 1), predictions.argmax(axis = 1), target_names = ["cat", "dog", "panda"]) print(cr) ``` ### Visualizing the metrics results ``` plt.style.use("ggplot") plt.figure(figsize=(20,20)) plt.plot(np.arange(0, ne), H.history["loss"], label="train_loss") plt.plot(np.arange(0, ne), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, ne), H.history["accuracy"], label="train_acc") plt.plot(np.arange(0, ne), H.history["val_accuracy"], label="val_acc") #plt.axis('on') plt.axis((0, ne, 0.25, 1)) plt.title("Training Loss and Accuracy") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend() plt.savefig("1off") plt.show() ``` ## Conclusions First of all, We can note that all results for the Animal dataset increased, in comparison with the last implemented model. The primary accuracy was of $70\%$ considering the [ShallowNet architecture](https://github.com/IgorMeloS/Computer-Vision-Training/blob/main/Practical%20Examples/3%20-%20Simple%20CNN/Animals_shallownet.ipynb). Here, the accuracy for the two model was $74\%$, a gain of $4\%$, that can represent a significant gain. The result from the first model shows an interesting fact, resize the images considering the aspect ratio, enable us to improve our results. On the other hand, the model still in over-fitting situation, the gap between the train and validation loss is enough considerable, despite the gain on the accuracy. The second model shows in your results, the power of Data Augmentation. This regularization allowed us to obtain a gain for the accuracy, but the remarkable aspect is, the loss for the training set and validation do not show a gap, this indicates there is no overt-fit. The fact that the model didn’t reach a higher accuracy is due to the depth of the network.
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Multi-dimensional-Particle-in-a-Box" data-toc-modified-id="Multi-dimensional-Particle-in-a-Box-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Multi-dimensional Particle-in-a-Box</a></span><ul class="toc-item"><li><span><a href="#🥅-Learning-Objectives" data-toc-modified-id="🥅-Learning-Objectives-4.1"><span class="toc-item-num">4.1&nbsp;&nbsp;</span>🥅 Learning Objectives</a></span></li><li><span><a href="#The-2-Dimensional-Particle-in-a-Box" data-toc-modified-id="The-2-Dimensional-Particle-in-a-Box-4.2"><span class="toc-item-num">4.2&nbsp;&nbsp;</span>The 2-Dimensional Particle-in-a-Box</a></span></li><li><span><a href="#📝-Exercise:-Verify-the-above-equation-for-the-energy-eigenvalues-of-a-particle-confined-to-a-rectangular-box." data-toc-modified-id="📝-Exercise:-Verify-the-above-equation-for-the-energy-eigenvalues-of-a-particle-confined-to-a-rectangular-box.-4.3"><span class="toc-item-num">4.3&nbsp;&nbsp;</span>📝 Exercise: Verify the above equation for the energy eigenvalues of a particle confined to a rectangular box.</a></span></li><li><span><a href="#Separation-of-Variables" data-toc-modified-id="Separation-of-Variables-4.4"><span class="toc-item-num">4.4&nbsp;&nbsp;</span>Separation of Variables</a></span></li><li><span><a href="#📝-Exercise:-By-direct-substitution,-verify-that-the-above-expressions-for-the-eigenvalues-and-eigenvectors-of-a-Hamiltonian-sum-are-correct." data-toc-modified-id="📝-Exercise:-By-direct-substitution,-verify-that-the-above-expressions-for-the-eigenvalues-and-eigenvectors-of-a-Hamiltonian-sum-are-correct.-4.5"><span class="toc-item-num">4.5&nbsp;&nbsp;</span>📝 Exercise: By direct substitution, verify that the above expressions for the eigenvalues and eigenvectors of a Hamiltonian-sum are correct.</a></span></li><li><span><a href="#Degenerate-States" data-toc-modified-id="Degenerate-States-4.6"><span class="toc-item-num">4.6&nbsp;&nbsp;</span>Degenerate States</a></span></li><li><span><a href="#Electrons-in-a-3-dimensional-box-(cuboid)" data-toc-modified-id="Electrons-in-a-3-dimensional-box-(cuboid)-4.7"><span class="toc-item-num">4.7&nbsp;&nbsp;</span>Electrons in a 3-dimensional box (cuboid)</a></span></li><li><span><a href="#📝-Exercise:-Verify-the-expressions-for-the-eigenvalues-and-eigenvectors-of-a-particle-in-a-cuboid." data-toc-modified-id="📝-Exercise:-Verify-the-expressions-for-the-eigenvalues-and-eigenvectors-of-a-particle-in-a-cuboid.-4.8"><span class="toc-item-num">4.8&nbsp;&nbsp;</span>📝 Exercise: Verify the expressions for the eigenvalues and eigenvectors of a particle in a cuboid.</a></span></li><li><span><a href="#📝-Exercise:-Construct-an-accidentally-degenerate-state-for-the-particle-in-a-cuboid." data-toc-modified-id="📝-Exercise:-Construct-an-accidentally-degenerate-state-for-the-particle-in-a-cuboid.-4.9"><span class="toc-item-num">4.9&nbsp;&nbsp;</span>📝 Exercise: Construct an accidentally degenerate state for the particle-in-a-cuboid.</a></span></li><li><span><a href="#Particle-in-a-circle" data-toc-modified-id="Particle-in-a-circle-4.10"><span class="toc-item-num">4.10&nbsp;&nbsp;</span>Particle-in-a-circle</a></span><ul class="toc-item"><li><span><a href="#The-Schrödinger-equation-for-a-particle-confined-to-a-circular-disk." data-toc-modified-id="The-Schrödinger-equation-for-a-particle-confined-to-a-circular-disk.-4.10.1"><span class="toc-item-num">4.10.1&nbsp;&nbsp;</span>The Schrödinger equation for a particle confined to a circular disk.</a></span></li><li><span><a href="#The-Schrödinger-Equation-in-Polar-Coordinates" data-toc-modified-id="The-Schrödinger-Equation-in-Polar-Coordinates-4.10.2"><span class="toc-item-num">4.10.2&nbsp;&nbsp;</span>The Schrödinger Equation in Polar Coordinates</a></span></li><li><span><a href="#The-Angular-Schrödinger-equation-in-Polar-Coordinates" data-toc-modified-id="The-Angular-Schrödinger-equation-in-Polar-Coordinates-4.10.3"><span class="toc-item-num">4.10.3&nbsp;&nbsp;</span>The Angular Schrödinger equation in Polar Coordinates</a></span></li><li><span><a href="#The-Radial-Schrödinger-equation-in-Polar-Coordinates" data-toc-modified-id="The-Radial-Schrödinger-equation-in-Polar-Coordinates-4.10.4"><span class="toc-item-num">4.10.4&nbsp;&nbsp;</span>The Radial Schrödinger equation in Polar Coordinates</a></span></li><li><span><a href="#The-Radial-Schrödinger-Equation-for-a-Particle-Confined-to-a-Circular-Disk" data-toc-modified-id="The-Radial-Schrödinger-Equation-for-a-Particle-Confined-to-a-Circular-Disk-4.10.5"><span class="toc-item-num">4.10.5&nbsp;&nbsp;</span>The Radial Schrödinger Equation for a Particle Confined to a Circular Disk</a></span></li><li><span><a href="#Eigenvalues-and-Eigenfunctions-for-a-Particle-Confined-to-a-Circular-Disk" data-toc-modified-id="Eigenvalues-and-Eigenfunctions-for-a-Particle-Confined-to-a-Circular-Disk-4.10.6"><span class="toc-item-num">4.10.6&nbsp;&nbsp;</span>Eigenvalues and Eigenfunctions for a Particle Confined to a Circular Disk</a></span></li></ul></li><li><span><a href="#Particle-in-a-Spherical-Ball" data-toc-modified-id="Particle-in-a-Spherical-Ball-4.11"><span class="toc-item-num">4.11&nbsp;&nbsp;</span>Particle-in-a-Spherical Ball</a></span><ul class="toc-item"><li><span><a href="#The-Schrödinger-equation-for-a-particle-confined-to-a-spherical-ball" data-toc-modified-id="The-Schrödinger-equation-for-a-particle-confined-to-a-spherical-ball-4.11.1"><span class="toc-item-num">4.11.1&nbsp;&nbsp;</span>The Schrödinger equation for a particle confined to a spherical ball</a></span></li><li><span><a href="#The-Schrödinger-Equation-in-Spherical-Coordinates" data-toc-modified-id="The-Schrödinger-Equation-in-Spherical-Coordinates-4.11.2"><span class="toc-item-num">4.11.2&nbsp;&nbsp;</span>The Schrödinger Equation in Spherical Coordinates</a></span></li><li><span><a href="#The-Angular-Wavefunction-in-Spherical-Coordinates" data-toc-modified-id="The-Angular-Wavefunction-in-Spherical-Coordinates-4.11.3"><span class="toc-item-num">4.11.3&nbsp;&nbsp;</span>The Angular Wavefunction in Spherical Coordinates</a></span></li><li><span><a href="#The-Radial-Schrödinger-equation-in-Spherical-Coordinates" data-toc-modified-id="The-Radial-Schrödinger-equation-in-Spherical-Coordinates-4.11.4"><span class="toc-item-num">4.11.4&nbsp;&nbsp;</span>The Radial Schrödinger equation in Spherical Coordinates</a></span></li></ul></li><li><span><a href="#📝-Exercise:-Use-the-equation-for-the-zeros-of-$\sin-x$-to-write-the-wavefunction-and-energy-for-the-one-dimensional-particle-in-a-box-in-a-form-similar-to-the-expressions-for-the-particle-in-a-disk-and-the-particle-in-a-sphere." data-toc-modified-id="📝-Exercise:-Use-the-equation-for-the-zeros-of-$\sin-x$-to-write-the-wavefunction-and-energy-for-the-one-dimensional-particle-in-a-box-in-a-form-similar-to-the-expressions-for-the-particle-in-a-disk-and-the-particle-in-a-sphere.-4.12"><span class="toc-item-num">4.12&nbsp;&nbsp;</span>📝 Exercise: Use the equation for the zeros of $\sin x$ to write the wavefunction and energy for the one-dimensional particle-in-a-box in a form similar to the expressions for the particle-in-a-disk and the particle-in-a-sphere.</a></span><ul class="toc-item"><li><span><a href="#Solutions-to-the-Schrödinger-Equation-for-a-Particle-Confined-to-a-Spherical-Ball" data-toc-modified-id="Solutions-to-the-Schrödinger-Equation-for-a-Particle-Confined-to-a-Spherical-Ball-4.12.1"><span class="toc-item-num">4.12.1&nbsp;&nbsp;</span>Solutions to the Schrödinger Equation for a Particle Confined to a Spherical Ball</a></span></li></ul></li><li><span><a href="#📝-Exercise:-For-the-hydrogen-atom,-the-2s-orbital-($n=2$,-$l=0$)-and-2p-orbitals-($n=2$,$l=1$,$m_l=-1,0,1$)-have-the-same-energy.-Is-this-true-for-the-particle-in-a-ball?" data-toc-modified-id="📝-Exercise:-For-the-hydrogen-atom,-the-2s-orbital-($n=2$,-$l=0$)-and-2p-orbitals-($n=2$,$l=1$,$m_l=-1,0,1$)-have-the-same-energy.-Is-this-true-for-the-particle-in-a-ball?-4.13"><span class="toc-item-num">4.13&nbsp;&nbsp;</span>📝 Exercise: For the hydrogen atom, the 2s orbital ($n=2$, $l=0$) and 2p orbitals ($n=2$,$l=1$,$m_l=-1,0,1$) have the same energy. Is this true for the particle-in-a-ball?</a></span></li><li><span><a href="#🪞-Self-Reflection" data-toc-modified-id="🪞-Self-Reflection-4.14"><span class="toc-item-num">4.14&nbsp;&nbsp;</span>🪞 Self-Reflection</a></span></li><li><span><a href="#🤔-Thought-Provoking-Questions" data-toc-modified-id="🤔-Thought-Provoking-Questions-4.15"><span class="toc-item-num">4.15&nbsp;&nbsp;</span>🤔 Thought-Provoking Questions</a></span></li><li><span><a href="#🔁-Recapitulation" data-toc-modified-id="🔁-Recapitulation-4.16"><span class="toc-item-num">4.16&nbsp;&nbsp;</span>🔁 Recapitulation</a></span></li><li><span><a href="#🔮-Next-Up..." data-toc-modified-id="🔮-Next-Up...-4.17"><span class="toc-item-num">4.17&nbsp;&nbsp;</span>🔮 Next Up...</a></span></li><li><span><a href="#📚-References" data-toc-modified-id="📚-References-4.18"><span class="toc-item-num">4.18&nbsp;&nbsp;</span>📚 References</a></span></li></ul></li></ul></div> # Multi-dimensional Particle-in-a-Box ![Particles in 2D confinement](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/MVZL4.jpg?raw=true "Particles in various types of 2-dimensional confinement") ## 🥅 Learning Objectives - Hamiltonian for a two-dimensional particle-in-a-box - Hamiltonian for a three-dimensional particle-in-a-box - Hamiltonian for a 3-dimensional spherical box - Separation of variables - Solutions for the 2- and 3- dimensional particle-in-a-box (rectangular) - Solutions for the 3-dimensional particle in a box (spherical) - Expectation values ## The 2-Dimensional Particle-in-a-Box ![Particles in a 2-dimensional box](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/1024px-Particle2D.svg.png?raw=true "Particles in 2-dimensional box with nx=ny=2; image from wikipedia courtesy of Keenan Pepper") We have treated the particle in a one-dimensional box, where the (time-independent) Schr&ouml;dinger equation was: $$ \left(-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} + V(x) \right)\psi_n(x) = E_n \psi_n(x) $$ where $$ V(x) = \begin{cases} +\infty & x\leq 0\\ 0 & 0\lt x \lt a\\ +\infty & a \leq x \end{cases} $$ However, electrons really move in three dimensions. However, just as sometimes electrons are (essentially) confined to one dimension, sometimes they are effectively confined to two dimensions. If the confinement is to a rectangle with side-widths $a_x$ and $a_y$, then the Schr&ouml;dinger equation is: $$ \left(-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} -\frac{\hbar^2}{2m} \frac{d^2}{dy^2} + V(x,y) \right)\psi_{n_x,n_y}(x,y) = E_{n_x,n_y} \psi_{n_x,n_y}(x,y) $$ where $$ V(x,y) = \begin{cases} +\infty & x\leq 0 \text{ or }y\leq 0 \\ 0 & 0\lt x \lt a_x \text{ and } 0 \lt y \lt a_y \\ +\infty & a_x \leq x \text{ or } a_y \leq y \end{cases} $$ The first thing to notice is that there are now two quantum numbers, $n_x$ and $n_y$. > The number of quantum numbers that are needed to label the state of a system is equal to its dimensionality. The second thing to notice is that the Hamiltonian in this Schr&ouml;dinger equation can be written as the sum of two Hamiltonians, $$ \left[\left(-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} + V_x(x) \right) +\left(-\frac{\hbar^2}{2m} \frac{d^2}{dy^2} + V_y(y) \right) \right]\psi_{n_x,n_y}(x,y) = E_{n_x,n_y} \psi_{n_x,n_y}(x,y) $$ where $$ V_x(x) = \begin{cases} +\infty & x\leq 0\\ 0 & 0\lt x \lt a_x\\ +\infty & a_x \leq x \end{cases} \\ V_y(y) = \begin{cases} +\infty & y\leq 0\\ 0 & 0\lt y \lt a_y\\ +\infty & a_y \leq y \end{cases} $$ By the same logic as we used for the 1-dimensional particle in a box, we can deduce that the ground-state wavefunction for an electron in a rectangular box is: $$ \psi_{n_x n_y}(x,y) = \frac{2}{\sqrt{a_x a_y}} \sin\left(\tfrac{n_x \pi x}{a_x}\right) \sin\left(\tfrac{n_y \pi y}{a_y}\right) \qquad \qquad n_x=1,2,3,\ldots;n_y=1,2,3,\ldots $$ The corresponding energy is thus: $$ E_{n_x n_y} = \frac{h^2}{8m}\left(\frac{n_x^2}{a_x^2}+\frac{n_y^2}{a_y^2}\right)\qquad \qquad n_x,n_y=1,2,3,\ldots $$ ## &#x1f4dd; Exercise: Verify the above equation for the energy eigenvalues of a particle confined to a rectangular box. ## Separation of Variables The preceding solution is a very special case of a general approach called separation of variables. > Given a $D$-dimensional Hamiltonian that is a sum of independent terms, $$ \hat{H}(x_1,x_2,\ldots,x_D) = \sum_{d=1}^D\hat{H}_d(x_d) $$ where the solutions to the individual Schr&ouml;dinger equations are known: $$ \hat{H}_d \psi_{d;n_d}(x_d) = E_{d;n_d} \psi_{d;n_d}(x_d) $$ the solution to the $D$-dimensional Schr&ouml;dinger equation is $$ \hat{H}(x_1,x_2,\ldots,x_D) \Psi_{n_1,n_2,\ldots,n_D}(x_1,x_2,\ldots,x_D) = E_{n_1,n_2,\ldots,n_D}\Psi_{n_1,n_2,\ldots,n_D}(x_1,x_2,\ldots,x_D) $$ where the $D$-dimensional eigenfunctions are products of the Schr&ouml;dinger equations of the individual terms $$ \Psi_{n_1,n_2,\ldots,n_D}(x_1,x_2,\ldots,x_D) = \prod_{d=1}^D\psi_{d;n_d}(x_d) $$ and the $D$-dimensional eigenvalues are sums of the eigenvalues of the individual terms, $$ E_{n_1,n_2,\ldots,n_D} = \sum_{d=1}^D E_{d;n_d} $$ This expression can be verified by direct substitution. Interpretatively, in a Hamiltonian with the form $$ \hat{H}(x_1,x_2,\ldots,x_D) = \sum_{d=1}^D\hat{H}_d(x_d) $$ the coordinates $x_1,x_2,\ldots,x_D$ are all independent, because there are no terms that couple them together in the Hamiltonian. This means that the probability of observing a particle with values $x_1,x_2,\ldots,x_D$ are all independent. Recall that when probabilities are independent, they are multiplied together. E.g., if the probability that your impoverished professor will be paid today is independent of the probability that will rain today, then $$ p_{\text{paycheck + rain}} = p_{\text{paycheck}} p_{\text{rain}} $$ Similarly, because $x_1,x_2,\ldots,x_D$ are all independent, $$ p(x_1,x_2,\ldots,x_D) = p_1(x_1) p_2(x_2) \ldots p_D(x_D) $$ Owing to the Born postulate, the probability distribution function for observing a particle at $x_1,x_2,\ldots,x_D$ is the wavefunction squared, so $$ \left| \Psi_{n_1,n_2,\ldots,n_D}(x_1,x_2,\ldots,x_D)\right|^2 = \prod_{d=1}^D \left| \psi_{d;n_d}(x_d) \right|^2 $$ It is reassuring that the separation-of-independent-variables solution to the $D$-dimensional Schr&ouml;dinger equation reproduces this intuitive conclusion. ## &#x1f4dd; Exercise: By direct substitution, verify that the above expressions for the eigenvalues and eigenvectors of a Hamiltonian-sum are correct. ## Degenerate States When two quantum states have the same energy, they are said to be degenerate. For example, for a square box, where $a_x = a_y = a$, the states with $n_x=1; n_y=2$ and $n_x=2;n_y=1$ are degenerate because: $$ E_{1,2} = \frac{h^2}{8ma^2}\left(1+4\right) = \frac{h^2}{8ma^2}\left(4+1\right) = E_{2,1} $$ This symmetry reflects physical symmetry, whereby the $x$ and $y$ coordinates are equivalent. The state with energy $E=\frac{5h^2}{8ma^2}$ is said to be two-fold degenerate, or to have degeneracy of two. For the particle in a square box, degeneracies of all levels exist. An example of a three-fold degeneracy is: $$ E_{1,7} = E_{7,1} = E_{5,5} = \frac{50h^2}{8ma^2} $$ and an example of a four-fold degeneracy is: $$ E_{1,8} = E_{8,1} = E_{7,4} = E_{4,7} = \frac{65h^2}{8ma^2} $$ It isn't trivial to show that degeneracies of all orders are possible (it's tied up in the theory of [Diophantine equations](https://en.wikipedia.org/wiki/Diophantine_equation)), but perhaps it becomes plausible by giving an example with an eight-fold degeneracy: $$ E_{8,49} = E_{49,8} = E_{16,47} = E_{47,16} = E_{23,44} = E_{44,23} = E_{28,41} = E_{41,28} = \frac{2465 h^2}{8ma^2} $$ Notice that all of these degeneracies are removed if the symmetry of the box is broken. For example, if a slight change of the box changes it from square to rectangulary, $a_x \rightarrow a_x + \delta x$, then the aforementioned states have different energies. This doesn't mean, however, that rectangular boxes do not have degeneracies. If $\tfrac{a_x}{a_y}$ is a rational number, $\tfrac{p}{q}$, then there will be an *accidental* degeneracies when $n_x$ is divisible by $p$ and $n_y$ is divisible by $q$. For example, if $a_x = 2a$ and $a_y = 3a$ (so $p=2$ and $q=3$), there is a degeneracy associated with $$ E_{4,3} = \frac{h^2}{8m}\left(\frac{4^2}{(2a)^2}+\frac{3^2}{(3a)^2}\right) = \frac{h^2}{8m}\left(\frac{2^2}{(2a)^2}+\frac{6^2}{(3a)^2}\right) = \frac{5h^2}{8ma^2}= E_{2,6} $$ This is called an *accidental* degeneracy because it is not related to a symmetry of the system, like the $x \sim y$ symmetry that induces the degeneracy in the case of particles in a square box. ## Electrons in a 3-dimensional box (cuboid) ![Particles in a 3-dimensional box](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/Particle3Dbox.png?raw=true "Particles in 3-dimensional box; image from Gary Drobny's online notes at Univ. of Washington") Suppose that particles are confined to a [cuboid](https://en.wikipedia.org/wiki/Cuboid) (or rectangular prism) with side-lengths $a_x$, $a_y$, and $a_z$. Then the Schr&ouml;dinger equation is: $$ \left[-\frac{\hbar^2}{2m}\left( \frac{d^2}{dx^2} + \frac{d^2}{dy^2} + \frac{d^2}{dz^2} \right) + V(x,y,z) \right]\psi_{n_x,n_y,n_z}(x,y,z) = E_{n_x,n_y,n_z} \psi_{n_x,n_y,n_z}(x,y,z) $$ where $$ V(x,y,z) = \begin{cases} +\infty & x\leq 0 \text{ or }y\leq 0 \text{ or }z\leq 0 \\ 0 & 0\lt x \lt a_x \text{ and } 0 \lt y \lt a_y \text{ and } 0 \lt z \lt a_z \\ +\infty & a_x \leq x \text{ or } a_y \leq y \text{ or } a_z \leq z \end{cases} $$ There are three quantum numbers because the system is three-dimensional. The three-dimensional second derivative is called the Laplacian, and is denoted $$ \nabla^2 = \frac{d^2}{dx^2} + \frac{d^2}{dy^2} + \frac{d^2}{dz^2} = \nabla \cdot \nabla $$ where $$ \nabla = \left[ \frac{d}{dx}, \frac{d}{dy}, \frac{d}{dz} \right]^T $$ is the operator that defines the gradient vector. The 3-dimensional momentum operator is $$ \hat{\mathbf{p}} = i \hbar \nabla $$ which explains why the kinetic energy is given by $$ \hat{T} = \frac{\hat{\mathbf{p}} \cdot \hat{\mathbf{p}}}{2m} = \frac{\hbar^2}{2m} \nabla^2 $$ As with the 2-dimensional particle-in-a-rectangle, the 3-dimensional particle-in-a-cuboid can be solved by separation of variables. Rewriting the Schr&ouml;dinger equation as: $$ \left[\left(-\frac{\hbar^2}{2m} \frac{d^2}{dx^2} + V_x(x) \right) +\left(-\frac{\hbar^2}{2m} \frac{d^2}{dy^2} + V_y(y) \right) +\left(-\frac{\hbar^2}{2m} \frac{d^2}{dz^2} + V_z(z) \right) \right]\psi_{n_x,n_y,n_z}(x,y,z) = E_{n_x,n_y,n_z} \psi_{n_x,n_y,n_z}(x,y,z) $$ where $$ V_x(x) = \begin{cases} +\infty & x\leq 0\\ 0 & 0\lt x \lt a_x\\ +\infty & a_x \leq x \end{cases} \\ V_y(y) = \begin{cases} +\infty & y\leq 0\\ 0 & 0\lt y \lt a_y\\ +\infty & a_y \leq y \end{cases} \\ V_z(z) = \begin{cases} +\infty & z\leq 0\\ 0 & 0\lt z \lt a_z\\ +\infty & a_z \leq z \end{cases} $$ By the same logic as we used for the 1-dimensional particle in a box, we can deduce that the ground-state wavefunction for an electron in a cuboid is: $$ \psi_{n_x n_y n_z}(x,y,z) = \frac{2\sqrt{2}}{\sqrt{a_x a_y z_z}} \ \sin\left(\tfrac{n_x \pi x}{a_x}\right) \sin\left(\tfrac{n_y \pi y}{a_y}\right)\sin\left(\tfrac{n_z \pi z}{a_z}\right) \qquad \qquad n_x=1,2,3,\ldots;n_y=1,2,3,\ldots;n_z=1,2,3,\ldots $$ The corresponding energy is thus: $$ E_{n_x n_y n_z} = \frac{h^2}{8m}\left(\frac{n_x^2}{a_x^2}+\frac{n_y^2}{a_y^2}+\frac{n_z^2}{a_z^2}\right)\qquad \qquad n_x,n_y,n_z=1,2,3,\ldots $$ As before, especially when there is symmetry, there are many degenerate states. For example, for a particle-in-a-cube, where $a_x = a_y = a_z = a$, the first excited state is three-fold degenerate since: $$ E_{2,1,1} = E_{1,2,1} = E_{1,1,2} = \frac{6h^2}{8ma^2} $$ There are other states of even higher degeneracy. For example, there is a twelve-fold degenerate state: $$ E_{5,8,15} = E_{5,15,8} = E_{8,5,15} = E_{8,15,5} = E_{15,5,8} = E_{15,8,5} = E_{3,4,17} = E_{3,17,4} = E_{4,3,17} = E_{4,17,3} = E_{17,3,4} = E_{17,4,3} = \frac{314 h^2}{8ma^2} $$ ## &#x1f4dd; Exercise: Verify the expressions for the eigenvalues and eigenvectors of a particle in a cuboid. ## &#x1f4dd; Exercise: Construct an accidentally degenerate state for the particle-in-a-cuboid. (Hint: this is a lot easier than you may think.) ## Particle-in-a-circle ### The Schr&ouml;dinger equation for a particle confined to a circular disk. ![Particle in a Ring](https://github.com/PaulWAyers/IntroQChem/blob/main/linkedFiles/The_Well_(Quantum_Corral).jpg?raw=true "The states of particle confined by a ring of atoms (a quantum corral) is similar to a particle-in-acircle. Image licensed CC-SA by Julian Voss-Andreae") What happens if instead of being confined to a rectangle or a cuboid, the electrons were confined to some other shape? For example, it is not uncommon to have electrons confined in a circular disk ([quantum corral](https://en.wikipedia.org/wiki/Quantum_mirage)) or a sphere ([quantum dot](https://en.wikipedia.org/wiki/Quantum_dot)). It is relatively easy to write the Hamiltonian in these cases, but less easy to solve it because Cartesian (i.e., $x,y,z$) coordinates are less natural for these geometries. The Schr&ouml;dinger equation for a particle confined to a circular disk of radius $a$ is: $$ \left(-\frac{\hbar^2}{2m} \nabla^2 + V(x,y) \right)\psi(x,y) = E \psi(x,y) $$ where $$ V(x,y) = \begin{cases} 0 & \sqrt{x^2 + y^2} \lt a\\ +\infty & a \leq \sqrt{x^2 + y^2} \end{cases} $$ However, it is more useful to write this in polar coordinates (i.e., $r,\theta$): \begin{align} x &= r \cos \theta \\ y &= r \sin \theta \\ \\ r &= \sqrt{x^2 + y^2} \\ \theta &= \arctan{\tfrac{y}{x}} \end{align} because the potential depends only on the distance from the center of the system, $$ \left(-\frac{\hbar^2}{2m} \nabla^2 + V(r) \right)\psi(r,\theta) = E \psi(r,\theta) $$ where $$ V(r) = \begin{cases} 0 & r \lt a\\ +\infty & a \leq r \end{cases} $$ ### The Schr&ouml;dinger Equation in Polar Coordinates In order to solve this Schr&ouml;dinger equation, we need to rewrite the Laplacian, $\nabla^2 = \frac{d^2}{dx^2} + \frac{d^2}{dy^2}$ in polar coordinates. Deriving the Laplacian in alternative coordinate systems is a standard (and tedious) exercise that you hopefully saw in your calculus class. (If not, cf. [wikipedia](https://en.wikipedia.org/wiki/Laplace_operator) or this [meticulous derivation](https://www.math.ucdavis.edu/~saito/courses/21C.w11/polar-lap.pdf).) The result is that: $$ \nabla^2 = \frac{d^2}{dr^2} + \frac{1}{r} \frac{d}{dr} + \frac{1}{r^2}\frac{d^2}{d\theta^2} $$ The resulting Schr&ouml;dinger equation is, $$ \left[-\frac{\hbar^2}{2m} \left(\frac{d^2}{dr^2} + \frac{1}{r} \frac{d}{dr} + \frac{1}{r^2}\frac{d^2}{d\theta^2} \right)+ V(r) \right] \psi(r,\theta) = E \psi(r,\theta) $$ This looks like it might be amenable to solution by separation of variables insofar as the potential doesn't compute the radial and angular positions of the particles, and the kinetic energy doesn't couple the particles angular and radial momenta (i.e., the derivatives). So we propose the solution $\psi(r,\theta) = R(r) \Theta(\theta)$. Substituting this into the Schr&ouml;dinger equation, we obtain: \begin{align} \left[-\frac{\hbar^2}{2m} \left(\frac{d^2}{dr^2} + \frac{1}{r} \frac{d}{dr} + \frac{1}{r^2}\frac{d^2}{d\theta^2} \right)+ V(r) \right] R(r) \Theta(\theta) &= E R(r) \Theta(\theta) \\ \left[-\Theta(\theta)\frac{\hbar^2}{2m} \left(\frac{d^2 R(r)}{dr^2} + \frac{1}{r} \frac{d R(r)}{dr} \right) -\frac{\hbar^2}{2m} \frac{R(r)}{r^2}\left(\frac{d^2 \Theta(\theta)}{d \theta^2} \right) + V(r) R(r) \Theta(\theta) \right] &= E R(r)\Theta(\theta) \end{align} Dividing both sides by $R(r) \Theta(\theta)$ and multiplying both sides by $r^2$ we obtain: $$ E r^2 +\frac{\hbar^2}{2m}\frac{r^2}{R(r)} \left(\frac{d^2 R(r)}{dr^2} + \frac{1}{r} \frac{d R(r)}{dr} \right) - r^2 V(r)=-\frac{\hbar^2}{2m} \frac{1}{\Theta(\theta)}\left(\frac{d^2 \Theta(\theta)}{d \theta^2} \right) $$ The right-hand-side depends only on $r$ and the left-hand-side depends only on $\theta$; this can only be true for all $r$ and all $\theta$ if both sides are equal to the same constant. This problem can therefore be solved by separation of variables, though it is a slightly different form from the one we considered previously. ### The Angular Schr&ouml;dinger equation in Polar Coordinates To find the solution, we first solve the set the left-hand-side equal to a constant, which gives a 1-dimensional Schr&ouml;dinger equations for the angular motion of the particle around the circle, $$ -\frac{\hbar^2}{2m} \frac{d^2 \Theta_l(\theta)}{d \theta^2} = E_{\theta;l} \Theta_l(\theta) $$ This equation is identical to the particle-in-a-box, and has (unnormalized) solutions $$ \Theta_l(\theta) = e^{i l \theta} \qquad \qquad l = 0, \pm 1, \pm 2, \ldots $$ where $l$ must be an integer because otherwise the fact the periodicity of the wavefunction (i.e., that $\Theta_l(\theta) = \Theta_l(\theta + 2 k \pi)$ for any integer $k$) is not achieved. Using the expression for $\Theta_l(\theta)$, the angular kinetic energy of the particle in a circle is seen to be: $$ E_{\theta,l} = \tfrac{\hbar^2 l^2}{2m} $$ ### The Radial Schr&ouml;dinger equation in Polar Coordinates Inserting the results for the angular wavefunction into the Schr&ouml;dinger equation, we obtain $$ E r^2 +\frac{\hbar^2}{2m}\frac{r^2}{R(r)} \left(\frac{d^2 R(r)}{dr^2} + \frac{1}{r} \frac{d R(r)}{dr} \right) - r^2 V(r)=-\frac{\hbar^2}{2m} \frac{1}{\Theta_l(\theta)}\left(\frac{d^2 \Theta_l(\theta)}{d \theta^2} \right) = \frac{\hbar^2 l^2}{2m} $$ which can be rearranged into the radial Schr&ouml;dinger equation, $$ -\frac{\hbar^2}{2m} \left(\frac{1}{r^2} \frac{d^2}{dr^2} + \frac{1}{r} \frac{d}{dr} - \frac{l^2}{r^2} \right)R_{n,l}(r) + V(r) R_{n,l}(r) = E_{n,l} R_{n,l}(r) $$ Notice that the radial eigenfunctions, $R_{n,l}(r)$, and the energy eigenvalues, $E_{n,l}$, depend on the angular motion of the particle, as quantized by $l$. The term $\frac{\hbar^2 l^2}{2mr^2}$ is exactly the centrifugal potential, indicating that it takes energy to hold a rotating particle in an orbit with radius $r$, and that the potential energy that is required grows with $r^{-2}$. Notice also that no assumptions have been made about the nature of the circular potential, $V(r)$. The preceding analysis holds for *any* circular-symmetric potential. ### The Radial Schr&ouml;dinger Equation for a Particle Confined to a Circular Disk For the circular disk, where $$ V(r) = \begin{cases} 0 & r \lt a\\ +\infty & a \leq r \end{cases} $$ it is somewhat more convenient to rewrite the radial Schr&ouml;dinger equation as a [homogeneous linear differential equation](https://en.wikipedia.org/wiki/Homogeneous_differential_equation) $$ -\frac{\hbar^2}{2m} \left(r^2 \frac{d^2 R_{n,l}(r)}{dr^2} + r \frac{d R_{n,l}(r)}{dr} + \left[\left(\frac{2m E_{n,l}}{\hbar^2} \right) r^2 - l^2\right]R_{n,l}(r) \right) + r^2 V(r) R_{n,l}(r) = 0 $$ Using the specific form of the equation, we have that, for $0 \lt r \lt a$, $$ -\frac{\hbar^2}{2m} \left(r^2 \frac{d^2 R_{n,l}(r)}{dr^2} + r \frac{d R_{n,l}(r)}{dr} + \left[\left(\frac{2m E_{n,l}}{\hbar^2} \right) r^2 - l^2\right]R_{n,l}(r) \right) = 0 $$ While this equation can be solved by the usual methods, that is [beyond the scope of this course](https://opencommons.uconn.edu/cgi/viewcontent.cgi?article=1013&context=chem_educ). However, we recognize that this equation is strongly resembles [Bessel's differential equation](https://en.wikipedia.org/wiki/Bessel_function), $$ x^2 \frac{d^2 f}{dx^2} + x \frac{df}{dx} + \left(x^2 - \alpha^2 \right) f(x) = 0 $$ The solutions to Bessel's equation are called the *Bessel functions of the first kind* and denoted, $J_{\alpha}(r)$. However, the radial wavefunction must vanish at the edge of the disk, $R_{n,l}(a) = 0$, and the Bessel functions generally do not satisfy this requirement. Recall that the boundary condition in the 1-dimensional particle in a box was satisfied by moving from the generic solution, $\psi(x) \propto \sin(x)$ to the scaled solution, $\psi(x) \propto \sin(k x)$, where $k=\tfrac{2 \pi}{a}$ was chosen to satisfy the boundary condition. Similarly, we write the solutions as $R_{n,l}(r) \propto J_l(kr)$. Substituting this form into the Schr&ouml;dinger equation and using the fact that: $$ (kr)^n \frac{d^n}{d(kr)^n} = r^n \frac{d^n}{dr^n} \qquad \qquad n=1,2,\ldots $$ we have $$ -\frac{\hbar^2}{2m} \left((kr)^2 \frac{d^2 J_{l}(kr)}{d(kr)^2} + (kr) \frac{d J_{l}(kr)}{d(kr)} + \left[\left(\frac{2m E_{n,l}}{k^2 \hbar^2} \right) (kr)^2 - l^2\right]J_{l}(kr) \right) = 0 $$ Referring back to the Bessel equation, it is clear that this equation is satisfied when $$ \frac{2m E_{n,l}}{k^2 \hbar^2} = 1 $$ or, equivalently, $$ E_{n,l} = \frac{\hbar^2 k^2}{2m} $$ where $k$ is chosen so that $J_l(ka) = 0$. If we label the zeros of the Bessel functions, $$ J_l(x_{n,l}) = 0 \qquad \qquad n=1,2,3,\ldots \\ x_{1,l} \lt x_{2,l} \lt x_{3,l} \lt \cdots $$ then $$ k_{n,l} = \frac{x_{n,l}}{a} $$ and the energies of the particle-in-a-disk are $$ E_{n,l} = \frac{\hbar^2 x_{n,l}^2}{2ma^2} = \frac{h^2 x_{n,l}^2}{8 m \pi^2 a^2} $$ and the eigenfunctions of the particle-in-a-disk are: $$ \psi_{n,l}(r,\theta) \propto J_{l}\left(\frac{x_{n,l}r}{a} \right) e^{i l \theta} $$ ### Eigenvalues and Eigenfunctions for a Particle Confined to a Circular Disk ![Vibrations of a Circular Drum-Head](https://upload.wikimedia.org/wikipedia/commons/b/bc/Vibrating_drum_Bessel_function.gif "An eigenfunction of the Particle-in-a-Circle. CC-SA4 license by Sławomir Biały at English Wikipedia") The energies of a particle confined to a circular disk of radius $a$ are: $$ E_{n,l} = \frac{\hbar^2 x_{n,l}^2}{2ma^2} = \frac{h^2 x_{n,l}^2}{8 m \pi^2 a^2} \qquad \qquad n=1,2,\ldots; \quad l=0,\pm 1,\pm 2, \ldots $$ and its eigenfunctions are: $$ \psi_{n,l}(r,\theta) \propto J_{l}\left(\frac{x_{n,l}r}{a} \right) e^{i l \theta} $$ where $x_{n,l}$ are the zeros of the Bessel function, $J_l(x_{n,l}) = 0$. The first zero is $x_{1,0} = 2.4048$. These solutions are exactly the resonant energies and modes that are associated with the vibration of a circular drum whose membrane has uniform thickness/density. You can find elegant video animations of the eigenvectors of the particle-in-a-circle at the following links: - [Interactive Demonstration of the States of a Particle-in-a-Circular-Disk](https://demonstrations.wolfram.com/ParticleInAnInfiniteCircularWell/) - [Movie animation of the quantum states of a particle-in-a-circular-disk](https://www.reddit.com/r/dataisbeautiful/comments/mfx5og/first_70_states_of_a_particle_trapped_in_a/?utm_source=share&utm_medium=web2x&context=3) A subtle result, [originally proposed by Bourget](https://en.wikipedia.org/wiki/Bessel_function#Bourget's_hypothesis), is that no two Bessel functions ever have the same zeros, which means that the values of $\{x_{n,l} \}$ are all distinct. A corollary of this is that eigenvalues of the particle confined to a circular disk are either nondegenerate ($l=0$) or doubly degenerate ($|l| /ge 1$). There are no accidental degeneracies for a particle in a circular disk. The energies of an electron confined to a circular disk with radius $a$ Bohr are: $$ E_{n,l} = \tfrac{x_{n,l}^2}{2a^2} $$ The following code block computes these energies. ``` from scipy import constants from scipy import special import ipywidgets as widgets import mpmath #The next few lines just set up the sliders for setting parameters. #Principle quantum number slider: n = widgets.IntSlider( value=1, min=1, max=10, step=1, description='n (princ. #):', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='d') #Angular quantum number slider: l = widgets.IntSlider( value=0, min=-10, max=10, step=1, description='l (ang. #):', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='d') #Box length slider: a = widgets.FloatSlider( value=1, min=.01, max=10.0, step=0.01, description='a (length):', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='.2f', ) # Define a function for the energy (in a.u.) of a particle in a circular disk # with length a, principle quantum number n, and angular quantum number l # The length is input in Bohr (atomic units). def compute_energy_disk(n, l, a): "Compute 1-dimensional particle-in-a-spherical-ball energy." #Compute the first n zeros of the Bessel function zeros = special.jn_zeros(l,n) #Compute the energy from the n-th zero. return (zeros[-1])**2/ (2 * a**2) #This next bit of code just prints out the energy in atomic units def print_energy_disk(a, n, l): print(f'The energy of an electron confined to a disk with radius {a:.2f} a.u.,' f' principle quantum number {n}, and angular quantum number {l}' f' is {compute_energy_disk(n, l, a):.3f} a.u..') out = widgets.interactive_output(print_energy_disk, {'a': a, 'n': n, 'l': l}) widgets.VBox([widgets.VBox([a, n, l]),out]) ``` ## Particle-in-a-Spherical Ball ### The Schr&ouml;dinger equation for a particle confined to a spherical ball ![Quantum Dot](https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Colloidal_nanoparticle_of_lead_sulfide_%28selenide%29_with_complete_passivation.png/842px-Colloidal_nanoparticle_of_lead_sulfide_%28selenide%29_with_complete_passivation.png "A quantum dot is a model for a particle spherically confined. CC-SA3 licensed by Zherebetskyy") The final model we will consider for now is a particle confined to a spherical ball with radius $a$, $$ \left(-\frac{\hbar^2}{2m} \nabla^2 + V(x,y,z) \right)\psi(x,y,z) = E \psi(x,y,z) $$ where $$ V(x,y,z) = \begin{cases} 0 & \sqrt{x^2 + y^2 + z^2} \lt a\\ +\infty & a \leq \sqrt{x^2 + y^2 + z^2} \end{cases} $$ However, it is more useful to write this in spherical polar coordinates (i.e., $r,\theta, \phi$): \begin{align} x &= r \sin \theta \cos \phi\\ y &= r \sin \theta \sin \phi\\ z &= r cos \theta \\ \\ r &= \sqrt{x^2 + y^2 + z^2} \\ \theta &= \arccos{\tfrac{z}{r}} \\ \phi &= \arctan{\tfrac{y}{x}} \end{align} because the potential depends only on the distance from the center of the system, $$ \left(-\frac{\hbar^2}{2m} \nabla^2 + V(r) \right)\psi(r,\theta, \phi) = E \psi(r,\theta, \phi) $$ where $$ V(r) = \begin{cases} 0 & r \lt a\\ +\infty & a \leq r \end{cases} $$ ### The Schr&ouml;dinger Equation in Spherical Coordinates In order to solve the Schr&ouml;dinger equation for a particle in a spherical ball, we need to rewrite the Laplacian, $\nabla^2 = \frac{d^2}{dx^2} + \frac{d^2}{dy^2} + \frac{d^2}{dz^2}$ in polar coordinates. A meticulous derivation of the [Laplacian](https://en.wikipedia.org/wiki/Laplace_operator) and its [eigenfunctions](http://galileo.phys.virginia.edu/classes/252/Classical_Waves/Classical_Waves.html) The result is that: $$ \nabla^2 = \frac{1}{r^2}\frac{d}{dr}r^2\frac{d}{dr} + \frac{1}{r^2 \sin \theta}\frac{d}{d\theta}\sin\theta\frac{d}{d\theta} + \frac{1}{r^2 \sin^2 \theta} \frac{d^2}{d\phi^2} $$ which can be rewritten in a more familiar form as: $$ \nabla^2 = \frac{d^2}{dr^2}+ \frac{2}{r}\frac{d}{dr} + \frac{1}{r^2}\left[\frac{1}{\sin \theta}\frac{d}{d\theta}\sin\theta\frac{d}{d\theta} + \frac{1}{\sin^2 \theta} \frac{d^2}{d\phi^2}\right] $$ Inserting this into the Schr&ouml;dinger equation for a particle confined to a spherical potential, $V(r)$, one has: $$ \left({} -\frac{\hbar^2}{2m} \left( \frac{d^2}{dr^2} + \frac{2}{r} \frac{d}{dr}\right) - \frac{\hbar^2}{2mr^2}\left[\frac{1}{\sin \theta}\frac{d}{d\theta}\sin\theta\frac{d}{d\theta} + \frac{1}{\sin^2 \theta} \frac{d^2}{d\phi^2}\right] \\ + V(r) \right)\psi_{n,l,m_l}(r,\theta,\phi) = E_{n,l,m_l}\psi_{n,l,m_l}(r,\theta,\phi) $$ The solutions of the Schr&ouml;dinger equation are characterized by three quantum numbers because this equation is 3-dimensional. Recall that the classical equation for the kinetic energy of a set of points rotating around the origin, in spherical coordinates, is: $$ T = \sum_{i=1}^{N_{\text{particles}}} \frac{p_{r;i}^2}{2m_i} + \frac{\mathbf{L}_i \cdot \mathbf{L}_i}{2m_i r_i^2} $$ where $p_{r,i}$ and $\mathbf{L}_i$ are the radial and [angular momenta](https://en.wikipedia.org/wiki/Angular_momentum#In_Hamiltonian_formalism) of the $i^{\text{th}}$ particle, respectively. It's apparent, then, that the quantum-mechanical operator for the square of the angular momentum is: $$ \hat{L}^2 = - \hbar^2 \left[\frac{1}{\sin \theta}\frac{d}{d\theta}\sin\theta\frac{d}{d\theta} + \frac{1}{\sin^2 \theta} \frac{d^2}{d\phi^2}\right] $$ The Schr&ouml;dinger equation for a spherically-symmetric system is thus, $$ \left(-\frac{\hbar^2}{2m} \left( \frac{d^2}{dr^2} + \frac{2}{r} \frac{d}{dr}\right) + \frac{\hat{L}^2}{2mr^2} + V(r) \right) \psi_{n,l,m_l}(r,\theta,\phi) = E_{n,l,m_l}\psi_{n,l,m_l}(r,\theta,\phi) $$ ### The Angular Wavefunction in Spherical Coordinates ![Spherical Harmonics](https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Spherical_Harmonics.png/1024px-Spherical_Harmonics.png "Representation of the real spherical harmonics, licensed CC-SA3 by Inigo.quilez") The Schr&ouml;dinger equation for a spherically-symmetric system can be solved by separation of variables. If one compares to the result in polar coordinates, it is already clear that the angular wavefunction has the form $\Theta{\theta,\phi} = P(\theta)e^{im_l\phi}$. From this starting point we could deduce the eigenfunctions of $\hat{L}^2$, but instead we will just present the eigenfunctions and eigenvalues, $$ \hat{L}^2 Y_l^{m_l} (\theta, \phi) = \hbar^2 l(l+1)Y_l^{m_l} (\theta, \phi) \qquad l=0,1,2,\ldots m_l=0, \pm 1, \ldots, \pm l $$ The functions [$Y_l^{m_l} (\theta, \phi)$](https://en.wikipedia.org/wiki/Spherical_harmonics) are called [spherical harmonics](https://mathworld.wolfram.com/SphericalHarmonic.html), and they are the fundamental vibrational modes of the surface of a spherical membrane. Note that these functions resemble s-orbitals ($l=0$), p-orbitals ($l=1$), d-orbitals ($l=2$), etc., and that the number of choices for $m_l$, $2l+1$, is equal to the number of $l$-type orbitals. ### The Radial Schr&ouml;dinger equation in Spherical Coordinates Using separation of variables, we write the wavefunction as: $$ \psi_{n,l,m_l}(r,\theta,\phi) = R_{n,l}(r) Y_l^{m_l}(\theta,\phi) $$ Inserting this expression into the Schr&ouml;dinger equation, and exploiting the fact that the spherical harmonics are eigenfunctions of $\hat{L}^2$, one obtains the radial Schr&ouml;dinger equation: $$ \left(-\frac{\hbar^2}{2m} \left( \frac{d^2}{dr^2} + \frac{2}{r} \frac{d}{dr}\right) + \frac{\hbar^2 l(l+1)}{2mr^2} + V(r) \right) R_{n,l}(r) = E_{n,l}R_{n,l}(r) $$ Inside the sphere, $V(r) = 0$. Rearranging the radial Schr&ouml;dinger equation for the interior of the sphere as a homogeneous linear differential equation, $$ r^2 \frac{d^2R_{n,l}}{dr^2} + 2r \frac{dR_{n,l}}{dr} + \left( \frac{2mr^2E_{n,l}}{\hbar^2} - l(l+1) \right) R_{n,l}(r) = 0 $$ This equation strongly resembles the differential equations satisfied by the [spherical Bessel functions](https://en.wikipedia.org/wiki/Bessel_function#Spherical_Bessel_functions:_jn,_yn), $j_l(x)$ $$ x^2 \frac{d^2 j_l}{dx^2} + 2x \frac{dj_l}{dx} + \left(x^2 - l(l+1) \right)j_l(x) = 0 $$ The spherical Bessel functions are eigenfunctions for the particle-in-a-spherical-ball, but do not satisfy the boundary condition that the wavefunction be zero on the sphere, $R_{n,l}(a) = 0$. To satisfy this constraint, we propose $$ R_{n,l}(r) = j_l(k r) $$ Using this form in the radial Schr&ouml;dinger equation, we have $$ (kr)^2 \frac{d^2 j_l(kr)}{d(kr)^2} + 2kr \frac{d j_l(kr)}{d(kr)} + \left( \frac{2m(kr)^2E_{n,l}}{\hbar^2k^2} - l(l+1) \right) j_l(kr) = 0 $$ Referring back to the differential equation satisfied by the spherical Bessel functions, it is clear that this equation is satisfied when $$ \frac{2m E_{n,l}}{k^2 \hbar^2} = 1 $$ or, equivalently, $$ E_{n,l} = \frac{\hbar^2 k^2}{2m} $$ where $k$ is chosen so that $j_l(ka) = 0$. If we label the zeros of the spherical Bessel functions, $$ j_l(y_{n,l}) = 0 \qquad \qquad n=1,2,3,\ldots \\ y_{1,l} \lt y_{2,l} \lt y_{3,l} \lt \cdots $$ then $$ k_{n,l} = \frac{y_{n,l}}{a} $$ and the energies of the particle-in-a-ball are $$ E_{n,l} = \frac{\hbar^2 y_{n,l}^2}{2ma^2} = \frac{h^2 y_{n,l}^2}{8 m \pi^2 a^2} $$ and the eigenfunctions of the particle-in-a-ball are: $$ \psi_{n,l,m}(r,\theta,\phi) \propto j_l\left(\frac{y_{n,l}r}{a} \right) Y_l^{m_l}(\theta, \phi) $$ Notice that the eigenenergies have the same form as those in the particle-in-a-disk and even the same as those for a particle-in-a-one-dimensional-box; the only difference is the identity of the function whose zeros we are considering. ## &#x1f4dd; Exercise: Use the equation for the zeros of $\sin x$ to write the wavefunction and energy for the one-dimensional particle-in-a-box in a form similar to the expressions for the particle-in-a-disk and the particle-in-a-sphere. ### Solutions to the Schr&ouml;dinger Equation for a Particle Confined to a Spherical Ball ![Eigenfunction Animation](https://upload.wikimedia.org/wikipedia/commons/8/86/Hydrogen_Wave.gif "Schematic of an eigenfunction of a spherically-confined particle, with the n, l, and m quantum numbers specified") The energies of a particle confined to a spherical ball of radius $a$ are: $$ E_{n,l} = \frac{\hbar^2 y_{n,l}^2}{2ma^2} \qquad n=1,2,\ldots; \quad l=0,1,\ldots; \quad m=0, \pm1, \ldots, \pm l $$ and its eigenfunctions are: $$ \psi_{n,l,m}(r,\theta,\phi) \propto j_l\left(\frac{y_{n,l}r}{a} \right) Y_l^{m_l}(\theta, \phi) $$ where $y_{n,l}$ are the zeros of the spherical Bessel function, $j_l(y_{n,l}) = 0$. The first spherical Bessel function, which corresponds to s-like solutions ($l=0$), is $$ j_l(y) = \frac{\sin y}{y} $$ and so $$ y_{n,0} = n \pi $$ This gives explicit and useful expressions for the $l=0$ wavefunctions and energies, $$ E_{n,0} = \frac{h^2 n^2}{8 m a^2} $$ and its eigenfunctions are: $$ \psi_{n,0,0}(r,\theta,\phi) \propto \frac{a}{n \pi r} \sin \left( \frac{n \pi r}{a} \right) $$ Notice that the $l=0$ energies are the same as in the one-dimensional particle-in-a-box and the eigenfunctions are very similar. In atomic units, the energies of an electron confined to a spherical ball with radius $a$ Bohr are: $$ E_{n,l} = \tfrac{y_{n,l}^2}{2a^2} $$ The following code block computes these energies. It uses the relationship between the spherical Bessel functions and the ordinary Bessel functions, $$ j_l(x) = \sqrt{\frac{\pi}{2x}} J_{l+\tfrac{1}{2}}(x) $$ which indicates that the zeros of $j_l(x)$ and $J_{l+\tfrac{1}{2}}(x)$ occur the same places. ``` #The next few lines just set up the sliders for setting parameters. #Principle quantum number slider: n = widgets.IntSlider( value=1, min=1, max=10, step=1, description='n (princ. #):', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='d') #Angular quantum number slider: l = widgets.IntSlider( value=0, min=-10, max=10, step=1, description='l (ang. #):', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='d') #Box length slider: a = widgets.FloatSlider( value=1, min=.01, max=10.0, step=0.01, description='a (length):', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='.2f', ) # Define a function for the energy (in a.u.) of a particle in a spherical ball # with length a, principle quantum number n, and angular quantum number l # The length is input in Bohr (atomic units). def compute_energy_ball(n, l, a): "Compute 1-dimensional particle-in-a-spherical-ball energy." #Compute the energy from the n-th zero. return float((mpmath.besseljzero(l+0.5,n))**2/ (2 * a**2)) #This next bit of code just prints out the energy in atomic units def print_energy_ball(a, n, l): print(f'The energy of an electron confined to a ball with radius {a:.2f} a.u.,' f' principle quantum number {n}, and angular quantum number {l}' f' is {compute_energy_ball(n, l, a):5.2f} a.u..') out = widgets.interactive_output(print_energy_ball, {'a': a, 'n': n, 'l': l}) widgets.VBox([widgets.VBox([a, n, l]),out]) ``` ## &#x1f4dd; Exercise: For the hydrogen atom, the 2s orbital ($n=2$, $l=0$) and 2p orbitals ($n=2$,$l=1$,$m_l=-1,0,1$) have the same energy. Is this true for the particle-in-a-ball? ## &#x1fa9e; Self-Reflection - Can you think of other physical or chemical systems where a multi-dimensional particle-in-a-box Hamiltonian would be appropriate? What shape would the box be? - Can you think of another chemical system where separation of variables would be useful? - Explain why separation of variables is consistent with the Born Postulate that the square-magnitude of a particle's wavefunction is the probability distribution function for the particle. - What is the expression for the zero-point energy and ground-state wavefunction of an electron in a 4-dimensional box? Can you identify some states of the 4-dimensional box with especially high degeneracy? - What is the degeneracy of the k-th excited state of a particle confined to a circular disk? What is the degeneracy of the k-th excited state of a particle confined in a spherical ball? - Write a Python function that computes the normalization constant for the particle-in-a-disk and the particle-in-a-sphere. ## &#x1f914; Thought-Provoking Questions - How would you write the Hamiltonian for two electrons confined to a box? Could you solve this system with separation of variables? Why or why not? - Write the time-independent Schr&ouml;dinger equation for an electron in an cylindrical box. What are its eigenfunctions and eigenvalues? - What would the time-independent Schr&ouml;dinger equation for electrons in an elliptical box look like? (You may find it useful to reference [elliptical](https://en.wikipedia.org/wiki/Elliptic_coordinate_system) and [ellipsoidal](https://en.wikipedia.org/wiki/Ellipsoidal_coordinates) coordinates. - Construct an example of a four-fold *accidental* degeneracy for a particle in a 2-dimensional rectangular (not square!) box. - If there is any degenerate state (either accidental or due to symmetry) for the multi-dimensional particle-in-a-box, then there are always an infinite number of other degenerate states. Why? - Consider an electron confined to a circular harmonic well, $V(r) = k r^2$. What is the angular kinetic energy and angular wavefunction for this system? ## &#x1f501; Recapitulation - Write the Hamiltonian, time-independent Schr&ouml;dinger equation, eigenfunctions, and eigenvalues for two-dimensional and three-dimensional particles in a box. - What is the definition of degeneracy? How does an "accidental" degeneracy differ from an ordinary degeneracy? - What is the zero-point energy for an electron in a circle and an electron in a sphere? - What are the spherical harmonics? - Describe the technique of separation of variables? When can it be applied? - What is the Laplacian operator in Cartesian coordinates? In spherical coordinates? - What are *boundary conditions* and how are they important in quantum mechanics? ## &#x1f52e; Next Up... - 1-electron atoms - Approximate methods for quantum mechanics - Multielectron particle-in-a-box - Postulates of Quantum Mechanics ## &#x1f4da; References My favorite sources for this material are: - [Randy's book](https://github.com/PaulWAyers/IntroQChem/blob/main/documents/DumontBook.pdf?raw=true) (See Chapter 3) - Also see my (pdf) class [notes] (https://github.com/PaulWAyers/IntroQChem/blob/main/documents/PinBox.pdf?raw=true). - [McQuarrie and Simon summary](https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Map%3A_Physical_Chemistry_(McQuarrie_and_Simon)/03%3A_The_Schrodinger_Equation_and_a_Particle_in_a_Box) - [Wolfram solutions for particle in a circle](https://demonstrations.wolfram.com/ParticleInAnInfiniteCircularWell/) - [Meticulous solution for a particle confined to a circular disk](https://opencommons.uconn.edu/cgi/viewcontent.cgi?article=1013&context=chem_educ) - [General discussion of the particle-in-a-region, which is the same as the classical wave equation](http://galileo.phys.virginia.edu/classes/252/Classical_Waves/Classical_Waves.html) - [More on the radial Schr&ouml;dinger equation](https://quantummechanics.ucsd.edu/ph130a/130_notes/node222.html) - Python tutorial ([part 1](https://physicspython.wordpress.com/2020/05/28/the-problem-of-the-hydrogen-atom-part-1/) and [part 2](https://physicspython.wordpress.com/2020/06/04/the-problem-of-the-hydrogen-atom-part-2/)) on the Hydrogen atom. There are also some excellent wikipedia articles: - [Particle in a Sphere](https://en.wikipedia.org/wiki/Particle_in_a_spherically_symmetric_potential) - [Other exactly solvable models](https://en.wikipedia.org/wiki/List_of_quantum-mechanical_systems_with_analytical_solutions)
github_jupyter
# Challenge In this challenge, we will practice on dimensionality reduction with PCA and selection of variables with RFE. We will use the _data set_ [Fifa 2019](https://www.kaggle.com/karangadiya/fifa19), originally containing 89 variables from over 18 thousand players of _game_ FIFA 2019. ## _Setup_ ``` from math import sqrt import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as sct import seaborn as sns import statsmodels.api as sm import statsmodels.stats as st from sklearn.decomposition import PCA from loguru import logger from IPython import get_ipython %matplotlib inline from IPython.core.pylabtools import figsize figsize(12, 8) sns.set() fifa = pd.read_csv("fifa.csv") columns_to_drop = ["Unnamed: 0", "ID", "Name", "Photo", "Nationality", "Flag", "Club", "Club Logo", "Value", "Wage", "Special", "Preferred Foot", "International Reputation", "Weak Foot", "Skill Moves", "Work Rate", "Body Type", "Real Face", "Position", "Jersey Number", "Joined", "Loaned From", "Contract Valid Until", "Height", "Weight", "LS", "ST", "RS", "LW", "LF", "CF", "RF", "RW", "LAM", "CAM", "RAM", "LM", "LCM", "CM", "RCM", "RM", "LWB", "LDM", "CDM", "RDM", "RWB", "LB", "LCB", "CB", "RCB", "RB", "Release Clause" ] try: fifa.drop(columns_to_drop, axis=1, inplace=True) except KeyError: logger.warning(f"Columns already dropped") ``` ## Starts analysis ``` fifa.head() fifa.shape fifa.info() fifa.isna().sum() fifa = fifa.dropna() fifa.isna().sum() ``` ## Question 1 Which fraction of the variance can be explained by the first main component of `fifa`? Respond as a single float (between 0 and 1) rounded to three decimal places. ``` def q1(): pca = PCA(n_components = 1).fit(fifa) return round(float(pca.explained_variance_ratio_), 3) q1() ``` ## Question 2 How many major components do we need to explain 95% of the total variance? Answer as a single integer scalar. ``` def q2(): pca_095 = PCA(n_components=0.95) X_reduced = pca_095.fit_transform(fifa) return X_reduced.shape[1] q2() ``` ## Question 3 What are the coordinates (first and second main components) of the `x` point below? The vector below is already centered. Be careful to __not__ center the vector again (for example, by invoking `PCA.transform ()` on it). Respond as a float tuple rounded to three decimal places. ``` x = [0.87747123, -1.24990363, -1.3191255, -36.7341814, -35.55091139, -37.29814417, -28.68671182, -30.90902583, -42.37100061, -32.17082438, -28.86315326, -22.71193348, -38.36945867, -20.61407566, -22.72696734, -25.50360703, 2.16339005, -27.96657305, -33.46004736, -5.08943224, -30.21994603, 3.68803348, -36.10997302, -30.86899058, -22.69827634, -37.95847789, -22.40090313, -30.54859849, -26.64827358, -19.28162344, -34.69783578, -34.6614351, 48.38377664, 47.60840355, 45.76793876, 44.61110193, 49.28911284 ] def q3(): pca_q3 = PCA(n_components = 2) pca_q3.fit(fifa) return tuple(np.round(pca_q3.components_.dot(x),3)) q3() ``` ## Question 4 Performs RFE with linear regression estimator to select five variables, eliminating them one by one. What are the selected variables? Respond as a list of variable names. ``` from sklearn.linear_model import LinearRegression from sklearn.feature_selection import RFE def q4(): x = fifa.drop('Overall', axis=1) y = fifa['Overall'] reg = LinearRegression().fit(x,y) rfe = RFE(reg, n_features_to_select=5).fit(x, y) nom_var = x.loc[:,rfe.get_support()].columns return list(nom_var) q4() ```
github_jupyter
``` from nbdev import * %nbdev_default_export cli ``` # Command line functions > Console commands added by the nbdev library ``` %nbdev_export from nbdev.imports import * from nbdev.export import * from nbdev.sync import * from nbdev.merge import * from nbdev.export2html import * from nbdev.test import * from fastscript import call_parse,Param,bool_arg ``` `nbdev` comes with the following commands. To use any of them, you must be in one of the subfolders of your project: they will search for the `settings.ini` recursively in the parent directory but need to access it to be able to work. Their names all begin with nbdev so you can easily get a list with tab completion. - `nbdev_build_docs` builds the documentation from the notebooks - `nbdev_build_lib` builds the library from the notebooks - `nbdev_bump_version` increments version in `settings.py` by one - `nbdev_clean_nbs` removes all superfluous metadata form the notebooks, to avoid merge conflicts - `nbdev_detach` exports cell attachments to `dest` and updates references - `nbdev_diff_nbs` gives you the diff between the notebooks and the exported library - `nbdev_fix_merge` will fix merge conflicts in a notebook file - `nbdev_install_git_hooks` installs the git hooks that use the last two command automatically on each commit/merge - `nbdev_nb2md` converts a notebook to a markdown file - `nbdev_new` creates a new nbdev project - `nbdev_read_nbs` reads all notebooks to make sure none are broken - `nbdev_test_nbs` runs tests in notebooks - `nbdev_trust_nbs` trusts all notebooks (so that the HTML content is shown) - `nbdev_update_lib` propagates any change in the library back to the notebooks - `nbdev_upgrade` updates an existing nbdev project to use the latest features ## Migrate from comment flags to magic flags ``` %nbdev_export import re,nbformat from nbdev.export import _mk_flag_re, _re_all_def from nbdev.flags import parse_line ``` ### Migrating notebooks Run `nbdev_upgrade` from the command line to update code cells in notebooks that use comment flags like ```python #export special.module ``` to use magic flags ```python %nbdev_export special.module ``` To make the magic flags work, `nbdev_upgrade` might need to add a new code cell to the top of the notebook ```python from nbdev import * ``` ### Hiding the `from nbdev import *` cell nbdev does not treat `from nbdev import *` as special, but this cell can be hidden from the docs by combining it with `%nbdev_default_export`. e.g. ```python from nbdev import * %nbdev_default_export my_module ``` this works because nbdev will hide any code cell containing the `%nbdev_default_export` flag. If you don't need `%nbdev_default_export` in your notebook you can: use the hide input [jupyter extension](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) or edit cell metadata to include `"hide_input": true` ``` %nbdev_export_internal def _code_patterns_and_replace_fns(): "Return a list of pattern/function tuples that can migrate flags used in code cells" patterns_and_replace_fns = [] def _replace_fn(magic, m): "Return a magic flag for a comment flag matched in `m`" if not m.groups() or not m.group(1): return f'%{magic}' return f'%{magic}' if m.group(1) is None else f'%{magic} {m.group(1)}' def _add_pattern_and_replace_fn(comment_flag, magic_flag, n_params=(0,1)): "Add a pattern/function tuple to go from comment to magic flag" pattern = _mk_flag_re(False, comment_flag, n_params, "") # note: fn has to be single arg so we can use it in `pattern.sub` calls later patterns_and_replace_fns.append((pattern, partial(_replace_fn, magic_flag))) _add_pattern_and_replace_fn('default_exp', 'nbdev_default_export', 1) _add_pattern_and_replace_fn('exports', 'nbdev_export_and_show') _add_pattern_and_replace_fn('exporti', 'nbdev_export_internal') _add_pattern_and_replace_fn('export', 'nbdev_export') _add_pattern_and_replace_fn('hide_input', 'nbdev_hide_input', 0) _add_pattern_and_replace_fn('hide_output', 'nbdev_hide_output', 0) _add_pattern_and_replace_fn('hide', 'nbdev_hide', 0) # keep at index 6 - see _migrate2magic _add_pattern_and_replace_fn('default_cls_lvl', 'nbdev_default_class_level', 1) _add_pattern_and_replace_fn('collapse[_-]output', 'nbdev_collapse_output', 0) _add_pattern_and_replace_fn('collapse[_-]show', 'nbdev_collapse_input open', 0) _add_pattern_and_replace_fn('collapse[_-]hide', 'nbdev_collapse_input', 0) _add_pattern_and_replace_fn('collapse', 'nbdev_collapse_input', 0) for flag in Config().get('tst_flags', '').split('|'): if flag.strip(): _add_pattern_and_replace_fn(f'all_{flag}', f'nbdev_{flag}_test all', 0) _add_pattern_and_replace_fn(flag, f'nbdev_{flag}_test', 0) patterns_and_replace_fns.append( (_re_all_def, lambda m: '%nbdev_add2all ' + ','.join(parse_line(m.group(1))))) return patterns_and_replace_fns %nbdev_export_internal class CellMigrator(): "Can migrate a cell using `patterns_and_replace_fns`" def __init__(self, patterns_and_replace_fns): self.patterns_and_replace_fns,self.upd_count,self.first_cell=patterns_and_replace_fns,0,None def __call__(self, cell): if self.first_cell is None: self.first_cell = cell for pattern, replace_fn in self.patterns_and_replace_fns: source=cell.source cell.source=pattern.sub(replace_fn, source) if source!=cell.source: self.upd_count+=1 %nbdev_export_internal def _migrate2magic(nb): "Migrate a single notebook" # migrate #hide in markdown m=CellMigrator(_code_patterns_and_replace_fns()[6:7]) [m(cell) for cell in nb.cells if cell.cell_type=='markdown'] # migrate everything in code_patterns_and_replace_fns in code cells m=CellMigrator(_code_patterns_and_replace_fns()) [m(cell) for cell in nb.cells if cell.cell_type=='code'] imp,fc='from nbdev import *',m.first_cell if m.upd_count!=0 and fc is not None and imp not in fc.get('source', ''): nb.cells.insert(0, nbformat.v4.new_code_cell(imp, metadata={'hide_input': True})) NotebookNotary().sign(nb) return nb %nbdev_hide def remove_line(starting_with, from_string): result=[] for line in from_string.split('\n'): if not line.strip().startswith(starting_with): result.append(line) return '\n'.join(result) test_lines = 'line1\n%magic\n#comment\n123\n %magic\n # comment' test_eq('line1\n%magic\n123\n %magic', remove_line('#', test_lines)) test_eq('line1\n123', remove_line('%', 'line1\n%magic\n123\n %magic')) %nbdev_hide def remove_comments_and_magics(string): return remove_line('#', remove_line('%', string)) test_eq('line1\n123', remove_comments_and_magics(test_lines)) %nbdev_hide def test_migrate2magic(fname): "Check that nothing other that comments and magics in code cells have been changed" nb=read_nb(fname) nb_migrated=_migrate2magic(read_nb(fname)) test_eq(len(nb.cells)+1, len(nb_migrated.cells)) test_eq('from nbdev import *', nb_migrated.cells[0].source) for i in range(len(nb.cells)): cell, cell_migrated=nb.cells[i], nb_migrated.cells[i+1] if cell.cell_type=='code': cell.source=remove_comments_and_magics(cell.source) cell_migrated.source=remove_comments_and_magics(cell_migrated.source) test_eq(cell, cell_migrated) test_migrate2magic('../test/00_export.ipynb') test_migrate2magic('../test/07_clean.ipynb') def test_migrate2magic_noop(fname): "Check that nothing is changed if there are no comment flags in a notebook" nb=read_nb(fname) nb_migrated=_migrate2magic(read_nb(fname)) test_eq(nb, nb_migrated) test_migrate2magic_noop('99_search.ipynb') %nbdev_hide sources=['#export aaa\nimport io,sys,json,glob\n#collapse-OUTPUT\nfrom fastscript ...', '%nbdev_export aaa\nimport io,sys,json,glob\n%nbdev_collapse_output\nfrom fastscript ...', '#EXPORT\n # collapse\nimport io,sys,json,glob', '%nbdev_export\n%nbdev_collapse_input\nimport io,sys,json,glob', '#exportS\nimport io,sys,json,glob\n#colLApse_show', '%nbdev_export_and_show\nimport io,sys,json,glob\n%nbdev_collapse_input open', ' # collapse-show \n#exporti\nimport io,sys,json,glob', '%nbdev_collapse_input open\n%nbdev_export_internal\nimport io,sys,json,glob', '#export\t\tspecial.module \nimport io,sys,json,glob', '%nbdev_export special.module\nimport io,sys,json,glob', '#exports special.module\nimport io,sys,json,glob', '%nbdev_export_and_show special.module\nimport io,sys,json,glob', '#EXPORT special.module\nimport io,sys,json,glob', '%nbdev_export special.module\nimport io,sys,json,glob', '#exportI \t \tspecial.module\n# collapse_hide \nimport io,sys,json,glob', '%nbdev_export_internal special.module\n%nbdev_collapse_input\nimport io,sys,json,glob', '# export \nimport io,sys,json,glob', '%nbdev_export\nimport io,sys,json,glob', ' # export\nimport io,sys,json,glob', '%nbdev_export\nimport io,sys,json,glob', '#default_cls_lvl ', '#default_cls_lvl ', '#default_cls_lvl 3 another', '#default_cls_lvl 3 another', '#default_cls_lvl 3', '%nbdev_default_class_level 3', 'from nbdev import *\n # default_cls_lvl 3', 'from nbdev import *\n%nbdev_default_class_level 3', ' # Collapse-Hide \n # EXPORTS\nimport io,sys,json,glob', '%nbdev_collapse_input\n%nbdev_export_and_show\nimport io,sys,json,glob', ' # exporti\nimport io,sys,json,glob', '%nbdev_export_internal\nimport io,sys,json,glob', 'import io,sys,json,glob\n#export aaa\nfrom fastscript import call_pars...', 'import io,sys,json,glob\n%nbdev_export aaa\nfrom fastscript import call_pars...', '#fastai2\nsome test code', '%nbdev_fastai2_test\nsome test code', '#fastai2 extra_comment\nsome test code', # test flags with "parameters" won't get migrated '#fastai2 extra_comment\nsome test code', '# all_fastai2 \nsome test code', '%nbdev_fastai2_test all\nsome test code', '# all_fastai2 extra_comment \nsome test code', '# all_fastai2 extra_comment \nsome test code', '#COLLAPSE_OUTPUT\nprint("lotsofoutput")', '%nbdev_collapse_output\nprint("lotsofoutput")', ' # hide\n#fastai2\ndef some_test():\n...', '%nbdev_hide\n%nbdev_fastai2_test\ndef some_test():\n...', '#comment\n# export \n_all_ = ["a",bb, "CCC" , \'d\'] \nmore code', '#comment\n%nbdev_export\n%nbdev_add2all "a",bb,"CCC",\'d\' \nmore code'] nb=nbformat.v4.new_notebook() nb_expected=nbformat.v4.new_notebook() nb_expected.cells.append(nbformat.v4.new_code_cell('from nbdev import *', metadata={'hide_input': True})) for cells, source in zip([nb.cells,nb_expected.cells]*(len(sources)//2), sources): cells.append(nbformat.v4.new_code_cell(source)) nb_migrated=_migrate2magic(nb) for cell_expected, cell_migrated in zip(nb_expected.cells, nb_migrated.cells): test_eq(cell_expected, cell_migrated) %nbdev_hide # hide is the only flag that we migrate in markdown sources=['#export aaa\nimport io,sys,json,glob\n#collapse-OUTPUT\nfrom fastscript ...', '#export aaa\nimport io,sys,json,glob\n#collapse-OUTPUT\nfrom fastscript ...', '#exportI \t \tspecial.module\n# collapse_hide \nimport io,sys,json,glob', '#exportI \t \tspecial.module\n# collapse_hide \nimport io,sys,json,glob', 'some text\n#hide\nwill still be hidden', 'some text\n%nbdev_hide\nwill still be hidden', ' # Collapse-Hide \n # EXPORTS\nimport io,sys,json,glob', ' # Collapse-Hide \n # EXPORTS\nimport io,sys,json,glob', ' # hide\n\n\n#fastai2\ndef some_test():\n...', '%nbdev_hide\n\n\n#fastai2\ndef some_test():\n...'] nb=nbformat.v4.new_notebook() nb_expected=nbformat.v4.new_notebook() for cells, source in zip([nb.cells,nb_expected.cells]*(len(sources)//2), sources): cells.append(nbformat.v4.new_markdown_cell(source)) nb_migrated=_migrate2magic(nb) for cell_expected, cell_migrated in zip(nb_expected.cells, nb_migrated.cells): test_eq(cell_expected, cell_migrated) ``` ## Add css for "collapse" components If you want to use collapsable cells in your HTML docs, you need to style the details tag in customstyles.css. `_add_collapse_css` will do this for you, if the details tag is not already styled. ``` %nbdev_export_internal _details_description_css = """\n /*Added by nbdev add_collapse_css*/ details.description[open] summary::after { content: attr(data-open); } details.description:not([open]) summary::after { content: attr(data-close); } details.description summary { text-align: right; font-size: 15px; color: #337ab7; cursor: pointer; } details + div.output_wrapper { /* show/hide code */ margin-top: 25px; } div.input + details { /* show/hide output */ margin-top: -25px; } /*End of section added by nbdev add_collapse_css*/""" def _add_collapse_css(doc_path=None): "Update customstyles.css so that collapse components can be used in HTML pages" fn = (Path(doc_path) if doc_path else Config().doc_path/'css')/'customstyles.css' with open(fn) as f: if 'details.description' in f.read(): print('details.description already styled in customstyles.css, no changes made') else: with open(fn, 'a') as f: f.write(_details_description_css) print('details.description styles added to customstyles.css') %nbdev_hide with open('/tmp/customstyles.css', 'w') as f: f.write('/*test file*/') _add_collapse_css('/tmp') # details.description styles added ... with open('/tmp/customstyles.css') as f: test_eq(''.join(['/*test file*/', _details_description_css]), f.read()) with open('/tmp/customstyles.css', 'a') as f: f.write('\nmore things added after') _add_collapse_css('/tmp') # details.description already styled ... with open('/tmp/customstyles.css') as f: test_eq(''.join(['/*test file*/', _details_description_css, '\nmore things added after']), f.read()) ``` ## Upgrading existing nbdev projects to use new features ``` %nbdev_export @call_parse def nbdev_upgrade(migrate2magic:Param("Migrate all notebooks in `nbs_path` to use magic flags", bool_arg)=True, add_collapse_css:Param("Add css for \"#collapse\" components", bool_arg)=True): "Update an existing nbdev project to use the latest features" if migrate2magic: for fname in Config().nbs_path.glob('*.ipynb'): print('Migrating', fname) nbformat.write(_migrate2magic(read_nb(fname)), str(fname), version=4) if add_collapse_css: _add_collapse_css() ``` - `migrate2magic` reads *all* notebooks in `nbs_path` and migrates them in-place - `add_collapse_css` updates `customstyles.css` so that "collapse" components can be used in HTML pages ## Navigating from notebooks to script and back ``` %nbdev_export @call_parse def nbdev_build_lib(fname:Param("A notebook name or glob to convert", str)=None): "Export notebooks matching `fname` to python modules" write_tmpls() notebook2script(fname=fname) ``` By default (`fname` left to `None`), the whole library is built from the notebooks in the `lib_folder` set in your `settings.ini`. ``` %nbdev_export @call_parse def nbdev_update_lib(fname:Param("A notebook name or glob to convert", str)=None): "Propagates any change in the modules matching `fname` to the notebooks that created them" script2notebook(fname=fname) ``` By default (`fname` left to `None`), the whole library is treated. Note that this tool is only designed for small changes such as typo or small bug fixes. You can't add new cells in notebook from the library. ``` %nbdev_export @call_parse def nbdev_diff_nbs(): "Prints the diff between an export of the library in notebooks and the actual modules" diff_nb_script() ``` ## Extracting tests ``` %nbdev_export def _test_one(fname, flags=None, verbose=True): print(f"testing: {fname}") start = time.time() try: test_nb(fname, flags=flags) return True,time.time()-start except Exception as e: if "Kernel died before replying to kernel_info" in str(e): time.sleep(random.random()) _test_one(fname, flags=flags) if verbose: print(f'Error in {fname}:\n{e}') return False,time.time()-start %nbdev_export @call_parse def nbdev_test_nbs(fname:Param("A notebook name or glob to convert", str)=None, flags:Param("Space separated list of flags", str)=None, n_workers:Param("Number of workers to use", int)=None, verbose:Param("Print errors along the way", bool)=True, timing:Param("Timing each notebook to see the ones are slow", bool)=False): "Test in parallel the notebooks matching `fname`, passing along `flags`" if flags is not None: flags = flags.split(' ') if fname is None: files = [f for f in Config().nbs_path.glob('*.ipynb') if not f.name.startswith('_')] else: files = glob.glob(fname) files = [Path(f).absolute() for f in sorted(files)] if len(files)==1 and n_workers is None: n_workers=0 # make sure we are inside the notebook folder of the project os.chdir(Config().nbs_path) results = parallel(_test_one, files, flags=flags, verbose=verbose, n_workers=n_workers) passed,times = [r[0] for r in results],[r[1] for r in results] if all(passed): print("All tests are passing!") else: msg = "The following notebooks failed:\n" raise Exception(msg + '\n'.join([f.name for p,f in zip(passed,files) if not p])) if timing: for i,t in sorted(enumerate(times), key=lambda o:o[1], reverse=True): print(f"Notebook {files[i].name} took {int(t)} seconds") ``` By default (`fname` left to `None`), the whole library is tested from the notebooks in the `lib_folder` set in your `settings.ini`. ## Building documentation The following functions complete the ones in `export2html` to fully build the documentation of your library. ``` %nbdev_export _re_index = re.compile(r'^(?:\d*_|)index\.ipynb$') %nbdev_export def make_readme(): "Convert the index notebook to README.md" index_fn = None for f in Config().nbs_path.glob('*.ipynb'): if _re_index.match(f.name): index_fn = f assert index_fn is not None, "Could not locate index notebook" print(f"converting {index_fn} to README.md") convert_md(index_fn, Config().config_file.parent, jekyll=False) n = Config().config_file.parent/index_fn.with_suffix('.md').name shutil.move(n, Config().config_file.parent/'README.md') if Path(Config().config_file.parent/'PRE_README.md').is_file(): with open(Config().config_file.parent/'README.md', 'r') as f: readme = f.read() with open(Config().config_file.parent/'PRE_README.md', 'r') as f: pre_readme = f.read() with open(Config().config_file.parent/'README.md', 'w') as f: f.write(f'{pre_readme}\n{readme}') %nbdev_export @call_parse def nbdev_build_docs(fname:Param("A notebook name or glob to convert", str)=None, force_all:Param("Rebuild even notebooks that haven't changed", bool)=False, mk_readme:Param("Also convert the index notebook to README", bool)=True, n_workers:Param("Number of workers to use", int)=None): "Build the documentation by converting notebooks mathing `fname` to html" notebook2html(fname=fname, force_all=force_all, n_workers=n_workers) if fname is None: make_sidebar() if mk_readme: make_readme() ``` By default (`fname` left to `None`), the whole documentation is build from the notebooks in the `lib_folder` set in your `settings.ini`, only converting the ones that have been modified since the their corresponding html was last touched unless you pass `force_all=True`. The index is also converted to make the README file, unless you pass along `mk_readme=False`. ``` %nbdev_export @call_parse def nbdev_nb2md(fname:Param("A notebook file name to convert", str), dest:Param("The destination folder", str)='.', img_path:Param("Folder to export images to")="", jekyll:Param("To use jekyll metadata for your markdown file or not", bool_arg)=False,): "Convert the notebook in `fname` to a markdown file" nb_detach_cells(fname, dest=img_path) convert_md(fname, dest, jekyll=jekyll, img_path=img_path) %nbdev_export @call_parse def nbdev_detach(path_nb:Param("Path to notebook"), dest:Param("Destination folder", str)="", use_img:Param("Convert markdown images to img tags", bool_arg)=False): "Export cell attachments to `dest` and update references" nb_detach_cells(path_nb, dest=dest, use_img=use_img) ``` ## Other utils ``` %nbdev_export @call_parse def nbdev_read_nbs(fname:Param("A notebook name or glob to convert", str)=None): "Check all notebooks matching `fname` can be opened" files = Config().nbs_path.glob('**/*.ipynb') if fname is None else glob.glob(fname) for nb in files: try: _ = read_nb(nb) except Exception as e: print(f"{nb} is corrupted and can't be opened.") raise e ``` By default (`fname` left to `None`), the all the notebooks in `lib_folder` are checked. ``` %nbdev_export @call_parse def nbdev_trust_nbs(fname:Param("A notebook name or glob to convert", str)=None, force_all:Param("Trust even notebooks that haven't changed", bool)=False): "Trust noteboks matching `fname`" check_fname = Config().nbs_path/".last_checked" last_checked = os.path.getmtime(check_fname) if check_fname.exists() else None files = Config().nbs_path.glob('**/*.ipynb') if fname is None else glob.glob(fname) for fn in files: if last_checked and not force_all: last_changed = os.path.getmtime(fn) if last_changed < last_checked: continue nb = read_nb(fn) if not NotebookNotary().check_signature(nb): NotebookNotary().sign(nb) check_fname.touch(exist_ok=True) ``` By default (`fname` left to `None`), the all the notebooks in `lib_folder` are trusted. To speed things up, only the ones touched since the last time this command was run are trusted unless you pass along `force_all=True`. ``` %nbdev_export @call_parse def nbdev_fix_merge(fname:Param("A notebook filename to fix", str), fast:Param("Fast fix: automatically fix the merge conflicts in outputs or metadata", bool)=True, trust_us:Param("Use local outputs/metadata when fast mergning", bool)=True): "Fix merge conflicts in notebook `fname`" fix_conflicts(fname, fast=fast, trust_us=trust_us) ``` When you have merge conflicts after a `git pull`, the notebook file will be broken and won't open in jupyter notebook anymore. This command fixes this by changing the notebook to a proper json file again and add markdown cells to signal the conflict, you just have to open that notebook again and look for `>>>>>>>` to see those conflicts and manually fix them. The old broken file is copied with a `.ipynb.bak` extension, so is still accessible in case the merge wasn't sucessful. Moreover, if `fast=True`, conflicts in outputs and metadata will automatically be fixed by using the local version if `trust_us=True`, the remote one if `trust_us=False`. With this option, it's very likely you won't have anything to do, unless there is a real conflict. ``` %nbdev_export def bump_version(version, part=2): version = version.split('.') version[part] = str(int(version[part]) + 1) for i in range(part+1, 3): version[i] = '0' return '.'.join(version) test_eq(bump_version('0.1.1' ), '0.1.2') test_eq(bump_version('0.1.1', 1), '0.2.0') %nbdev_export @call_parse def nbdev_bump_version(part:Param("Part of version to bump", int)=2): "Increment version in `settings.py` by one" cfg = Config() print(f'Old version: {cfg.version}') cfg.d['version'] = bump_version(Config().version, part) cfg.save() update_version() print(f'New version: {cfg.version}') ``` ## Git hooks ``` %nbdev_export import subprocess %nbdev_export @call_parse def nbdev_install_git_hooks(): "Install git hooks to clean/trust notebooks automatically" try: path = Config().config_file.parent except: path = Path.cwd() fn = path/'.git'/'hooks'/'post-merge' #Trust notebooks after merge with open(fn, 'w') as f: f.write("""#!/bin/bash echo "Trusting notebooks" nbdev_trust_nbs """ ) os.chmod(fn, os.stat(fn).st_mode | stat.S_IEXEC) #Clean notebooks on commit/diff with open(path/'.gitconfig', 'w') as f: f.write("""# Generated by nbdev_install_git_hooks # # If you need to disable this instrumentation do: # # git config --local --unset include.path # # To restore the filter # # git config --local include.path .gitconfig # # If you see notebooks not stripped, checked the filters are applied in .gitattributes # [filter "clean-nbs"] clean = nbdev_clean_nbs --read_input_stream True smudge = cat required = true [diff "ipynb"] textconv = nbdev_clean_nbs --disp True --fname """) cmd = "git config --local include.path ../.gitconfig" print(f"Executing: {cmd}") result = subprocess.run(cmd.split(), shell=False, check=False, stderr=subprocess.PIPE) if result.returncode == 0: print("Success: hooks are installed and repo's .gitconfig is now trusted") else: print("Failed to trust repo's .gitconfig") if result.stderr: print(f"Error: {result.stderr.decode('utf-8')}") try: nb_path = Config().nbs_path except: nb_path = Path.cwd() with open(nb_path/'.gitattributes', 'w') as f: f.write("""**/*.ipynb filter=clean-nbs **/*.ipynb diff=ipynb """ ) ``` This command installs git hooks to make sure notebooks are cleaned before you commit them to GitHub and automatically trusted at each merge. To be more specific, this creates: - an executable '.git/hooks/post-merge' file that contains the command `nbdev_trust_nbs` - a `.gitconfig` file that uses `nbev_clean_nbs` has a filter/diff on all notebook files inside `nbs_folder` and a `.gitattributes` file generated in this folder (copy this file in other folders where you might have notebooks you want cleaned as well) ## Starting a new project ``` %nbdev_export _template_git_repo = "https://github.com/fastai/nbdev_template.git" %nbdev_export @call_parse def nbdev_new(name: Param("A directory to create the project in", str), template_git_repo: Param("url to template repo", str)=_template_git_repo): "Create a new nbdev project with a given name." path = Path(f"./{name}").absolute() if path.is_dir(): print(f"Directory {path} already exists. Aborting.") return print(f"Creating a new nbdev project {name}.") def rmtree_onerror(func, path, exc_info): "Use with `shutil.rmtree` when you need to delete files/folders that might be read-only." os.chmod(path, stat.S_IWRITE) func(path) try: subprocess.run(['git', 'clone', f'{template_git_repo}', f'{path}'], check=True, timeout=5000) # Note: on windows, .git is created with a read-only flag shutil.rmtree(path/".git", onerror=rmtree_onerror) subprocess.run("git init".split(), cwd=path, check=True) subprocess.run("git add .".split(), cwd=path, check=True) subprocess.run("git commit -am \"Initial\"".split(), cwd=path, check=True) print(f"Created a new repo for project {name}. Please edit settings.ini and run nbdev_build_lib to get started.") except Exception as e: print("An error occured while copying nbdev project template:") print(e) if os.path.isdir(path): try: shutil.rmtree(path, onerror=rmtree_onerror) except Exception as e2: print(f"An error occured while cleaning up. Failed to delete {path}:") print(e2) ``` `nbdev_new` is a command line tool that creates a new nbdev project based on the [nbdev_template repo](https://github.com/fastai/nbdev_template). You can use a custom template by passing in `template_git_repo`. It'll initialize a new git repository and commit the new project. After you run `nbdev_new`, please edit `settings.ini` and run `nbdev_build_lib`. ## Export - ``` %nbdev_hide notebook2script() ```
github_jupyter
``` import json import pandas as pd import numpy as np import re file_dir = '/Users/sivaelango/desktop/Analysis Projects/Movies-ETL' with open(f'{file_dir}/wikipedia-movies.json', mode='r') as file: wiki_movies_raw = json.load(file) len(wiki_movies_raw) # First 5 records wiki_movies_raw[:5] # Last 5 records wiki_movies_raw[-5:] # Some records in the middle wiki_movies_raw[3600:3605] kaggle_metadata = pd.read_csv(f'{file_dir}/movies_metadata.csv', low_memory=False) ratings = pd.read_csv(f'{file_dir}/ratings.csv') kaggle_metadata.sample(n=5) ratings.sample(n=5) wiki_movies_df = pd.DataFrame(wiki_movies_raw) wiki_movies_df.head() wiki_movies_df.columns.tolist() wiki_movies = [movie for movie in wiki_movies_raw if ('Director' in movie or 'Directed by' in movie) and 'imdb_link' in movie] len(wiki_movies) wiki_movies_df = pd.DataFrame(wiki_movies) wiki_movies_df.head() wiki_movies = [movie for movie in wiki_movies_raw if ('Director' in movie or 'Directed by' in movie) and 'imdb_link' in movie and 'No. of episodes' not in movie] wiki_movies_df = pd.DataFrame(wiki_movies) wiki_movies_df.head() wiki_movies_df[wiki_movies_df['Arabic'].notnull()] wiki_movies_df[wiki_movies_df['Arabic'].notnull()]['url'] sorted(wiki_movies_df.columns.tolist()) def clean_movie(movie): movie = dict(movie) #create a non-destructive copy alt_titles = {} for key in ['Also known as','Arabic','Cantonese','Chinese','French', 'Hangul','Hebrew','Hepburn','Japanese','Literally', 'Mandarin','McCune–Reischauer','Original title','Polish', 'Revised Romanization','Romanized','Russian', 'Simplified','Traditional','Yiddish']: if key in movie: alt_titles[key] = movie[key] movie.pop(key) if len(alt_titles) > 0: movie['alt_titles'] = alt_titles # merge column names def change_column_name(old_name, new_name): if old_name in movie: movie[new_name] = movie.pop(old_name) change_column_name('Adaptation by', 'Writer(s)') change_column_name('Country of origin', 'Country') change_column_name('Directed by', 'Director') change_column_name('Distributed by', 'Distributor') change_column_name('Edited by', 'Editor(s)') change_column_name('Length', 'Running time') change_column_name('Original release', 'Release date') change_column_name('Music by', 'Composer(s)') change_column_name('Produced by', 'Producer(s)') change_column_name('Producer', 'Producer(s)') change_column_name('Productioncompanies ', 'Production company(s)') change_column_name('Productioncompany ', 'Production company(s)') change_column_name('Released', 'Release Date') change_column_name('Release Date', 'Release date') change_column_name('Screen story by', 'Writer(s)') change_column_name('Screenplay by', 'Writer(s)') change_column_name('Story by', 'Writer(s)') change_column_name('Theme music composer', 'Composer(s)') change_column_name('Written by', 'Writer(s)') return movie clean_movies = [clean_movie(movie) for movie in wiki_movies] wiki_movies_df = pd.DataFrame(clean_movies) sorted(wiki_movies_df.columns.tolist()) wiki_movies_df['imdb_id'] = wiki_movies_df['imdb_link'].str.extract(r'(tt\d{7})') wiki_movies_df['imdb_id'] wiki_movies_df.drop_duplicates(subset='imdb_id', inplace=True) print(len(wiki_movies_df)) wiki_movies_df.head() [[column,wiki_movies_df[column].isnull().sum()] for column in wiki_movies_df.columns] wiki_columns_to_keep = [column for column in wiki_movies_df.columns if wiki_movies_df[column].isnull().sum() < len(wiki_movies_df) * 0.9] wiki_movies_df = wiki_movies_df[wiki_columns_to_keep] wiki_movies_df.dtypes box_office = wiki_movies_df['Box office'].dropna() def is_not_a_string(x): return type(x) != str box_office[box_office.map(is_not_a_string)] lambda x: type(x) != str box_office[box_office.map(lambda x: type(x) != str)] box_office = box_office.apply(lambda x: ' '.join(x) if type(x) == list else x) form_one = r'\$\d+\.?\d*\s*[mb]illion' box_office.str.contains(form_one, flags=re.IGNORECASE, na=False).sum() form_two = r'\$\d{1,3}(?:,\d{3})+' box_office.str.contains(form_two, flags=re.IGNORECASE, na=False).sum() matches_form_one = box_office.str.contains(form_one, flags=re.IGNORECASE, na=False) matches_form_two = box_office.str.contains(form_two, flags=re.IGNORECASE, na=False) box_office[~matches_form_one & ~matches_form_two] form_one = r'\$\s*\d+\.?\d*\s*[mb]illion' form_two = r'\$\\s*d{1,3}(?:,\d{3})+(?!\s[mb]illion)' matches_form_one = box_office.str.contains(form_one, flags=re.IGNORECASE, na=False) matches_form_two = box_office.str.contains(form_two, flags=re.IGNORECASE, na=False) box_office[~matches_form_one & ~matches_form_two] box_office = box_office.str.replace(r'\$.*[-—–](?![a-z])', '$', regex=True) form_one = r'\$\s*\d+\.?\d*\s*[mb]illi?on' box_office.str.extract(f'({form_one}|{form_two})') def parse_dollars(s): # if s is not a string, return NaN if type(s) != str: return np.nan # if input is of the form $###.# million if re.match(r'\$\s*\d+\.?\d*\s*milli?on', s, flags=re.IGNORECASE): # remove dollar sign and " million" s = re.sub('\$|\s|[a-zA-Z]','', s) # convert to float and multiply by a million value = float(s) * 10**6 # return value return value # if input is of the form $###.# billion elif re.match(r'\$\s*\d+\.?\d*\s*billi?on', s, flags=re.IGNORECASE): # remove dollar sign and " billion" s = re.sub('\$|\s|[a-zA-Z]','', s) # convert to float and multiply by a billion value = float(s) * 10**9 # return value return value # if input is of the form $###,###,### elif re.match(r'\$\s*\d{1,3}(?:[,\.]\d{3})+(?!\s[mb]illion)', s, flags=re.IGNORECASE): # remove dollar sign and commas s = re.sub('\$|,','', s) # convert to float value = float(s) # return value return value # otherwise, return NaN else: return np.nan wiki_movies_df['box_office'] = box_office.str.extract(f'({form_one}|{form_two})', flags=re.IGNORECASE)[0].apply(parse_dollars) wiki_movies_df['box_office'] wiki_movies_df.drop('Box office', axis=1, inplace=True) budget = wiki_movies_df['Budget'].dropna() budget = budget.map(lambda x: ' '.join(x) if type(x) == list else x) budget = budget.str.replace(r'\$.*[-—–](?![a-z])', '$', regex=True) matches_form_one = budget.str.contains(form_one, flags=re.IGNORECASE, na=False) matches_form_two = budget.str.contains(form_two, flags=re.IGNORECASE, na=False) budget[~matches_form_one & ~matches_form_two] budget = budget.str.replace(r'\[\d+\]\s*', '') budget[~matches_form_one & ~matches_form_two] wiki_movies_df['budget'] = budget.str.extract(f'({form_one}|{form_two})', flags=re.IGNORECASE)[0].apply(parse_dollars) wiki_movies_df.drop('Budget', axis=1, inplace=True) release_date = wiki_movies_df['Release date'].dropna().apply(lambda x: ' '.join(x) if type(x) == list else x) date_form_one = r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\s[123]?\d,\s\d{4}' date_form_two = r'\d{4}.[01]\d.[0123]\d' date_form_three = r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}' date_form_four = r'\d{4}' release_date.str.extract(f'({date_form_one}|{date_form_two}|{date_form_three}|{date_form_four})', flags=re.IGNORECASE) wiki_movies_df['release_date'] = pd.to_datetime(release_date.str.extract(f'({date_form_one}|{date_form_two}|{date_form_three}|{date_form_four})')[0], infer_datetime_format=True) running_time = wiki_movies_df['Running time'].dropna().apply(lambda x: ' '.join(x) if type(x) == list else x) running_time.str.contains(r'^\d*\s*minutes$', flags=re.IGNORECASE, na=False).sum() running_time[running_time.str.contains(r'^\d*\s*minutes$', flags=re.IGNORECASE, na=False) != True] running_time.str.contains(r'^\d*\s*m', flags=re.IGNORECASE, na=False).sum() running_time[running_time.str.contains(r'^\d*\s*m', flags=re.IGNORECASE, na=False) != True] running_time_extract = running_time.str.extract(r'(\d+)\s*ho?u?r?s?\s*(\d*)|(\d+)\s*m') running_time_extract = running_time_extract.apply(lambda col: pd.to_numeric(col, errors='coerce')).fillna(0) wiki_movies_df['running_time'] = running_time_extract.apply(lambda row: row[0]*60 + row[1] if row[2] == 0 else row[2], axis=1) wiki_movies_df.drop('Running time', axis=1, inplace=True) kaggle_metadata.dtypes kaggle_metadata['adult'].value_counts() kaggle_metadata[~kaggle_metadata['adult'].isin(['True','False'])] kaggle_metadata = kaggle_metadata[kaggle_metadata['adult'] == 'False'].drop('adult',axis='columns') kaggle_metadata['video'].value_counts() kaggle_metadata['video'] == 'True' kaggle_metadata['video'] = kaggle_metadata['video'] == 'True' kaggle_metadata['budget'] = kaggle_metadata['budget'].astype(int) kaggle_metadata['id'] = pd.to_numeric(kaggle_metadata['id'], errors='raise') kaggle_metadata['popularity'] = pd.to_numeric(kaggle_metadata['popularity'], errors='raise') kaggle_metadata['release_date'] = pd.to_datetime(kaggle_metadata['release_date']) ratings.info(null_counts=True) pd.to_datetime(ratings['timestamp'], unit='s') ratings['timestamp'] = pd.to_datetime(ratings['timestamp'], unit='s') pd.options.display.float_format = '{:20,.2f}'.format ratings['rating'].plot(kind='hist') ratings['rating'].describe() movies_df = pd.merge(wiki_movies_df, kaggle_metadata, on='imdb_id', suffixes=['_wiki','_kaggle']) movies_df[['title_wiki','title_kaggle']] movies_df[movies_df['title_wiki'] != movies_df['title_kaggle']][['title_wiki','title_kaggle']] # Show any rows where title_kaggle is empty movies_df[(movies_df['title_kaggle'] == '') | (movies_df['title_kaggle'].isnull())] movies_df.fillna(0).plot(x='running_time', y='runtime', kind='scatter') movies_df.fillna(0).plot(x='budget_wiki',y='budget_kaggle', kind='scatter') movies_df.fillna(0).plot(x='box_office', y='revenue', kind='scatter') movies_df.fillna(0)[movies_df['box_office'] < 10**9].plot(x='box_office', y='revenue', kind='scatter') movies_df[['release_date_wiki','release_date_kaggle']].plot(x='release_date_wiki', y='release_date_kaggle', style='.') movies_df[(movies_df['release_date_wiki'] > '1996-01-01') & (movies_df['release_date_kaggle'] < '1965-01-01')] movies_df[(movies_df['release_date_wiki'] > '1996-01-01') & (movies_df['release_date_kaggle'] < '1965-01-01')].index movies_df = movies_df.drop(movies_df[(movies_df['release_date_wiki'] > '1996-01-01') & (movies_df['release_date_kaggle'] < '1965-01-01')].index) movies_df[movies_df['release_date_wiki'].isnull()] movies_df['Language'].value_counts() movies_df['Language'].apply(lambda x: tuple(x) if type(x) == list else x).value_counts(dropna=False) movies_df['original_language'].value_counts(dropna=False) movies_df[['Production company(s)','production_companies']] movies_df.drop(columns=['title_wiki','release_date_wiki','Language','Production company(s)'], inplace=True) def fill_missing_kaggle_data(df, kaggle_column, wiki_column): df[kaggle_column] = df.apply( lambda row: row[wiki_column] if row[kaggle_column] == 0 else row[kaggle_column] , axis=1) df.drop(columns=wiki_column, inplace=True) fill_missing_kaggle_data(movies_df, 'runtime', 'running_time') fill_missing_kaggle_data(movies_df, 'budget_kaggle', 'budget_wiki') fill_missing_kaggle_data(movies_df, 'revenue', 'box_office') movies_df for col in movies_df.columns: lists_to_tuples = lambda x: tuple(x) if type(x) == list else x value_counts = movies_df[col].apply(lists_to_tuples).value_counts(dropna=False) num_values = len(value_counts) if num_values == 1: print(col) movies_df['video'].value_counts(dropna=False) movies_df = movies_df.loc[:, ['imdb_id','id','title_kaggle','original_title','tagline','belongs_to_collection','url','imdb_link', 'runtime','budget_kaggle','revenue','release_date_kaggle','popularity','vote_average','vote_count', 'genres','original_language','overview','spoken_languages','Country', 'production_companies','production_countries','Distributor', 'Producer(s)','Director','Starring','Cinematography','Editor(s)','Writer(s)','Composer(s)','Based on' ]] movies_df.rename({'id':'kaggle_id', 'title_kaggle':'title', 'url':'wikipedia_url', 'budget_kaggle':'budget', 'release_date_kaggle':'release_date', 'Country':'country', 'Distributor':'distributor', 'Producer(s)':'producers', 'Director':'director', 'Starring':'starring', 'Cinematography':'cinematography', 'Editor(s)':'editors', 'Writer(s)':'writers', 'Composer(s)':'composers', 'Based on':'based_on' }, axis='columns', inplace=True) rating_counts = ratings.groupby(['movieId','rating'], as_index=False).count() rating_counts = ratings.groupby(['movieId','rating'], as_index=False).count() \ .rename({'userId':'count'}, axis=1) rating_counts = ratings.groupby(['movieId','rating'], as_index=False).count() \ .rename({'userId':'count'}, axis=1) \ .pivot(index='movieId',columns='rating', values='count') rating_counts.columns = ['rating_' + str(col) for col in rating_counts.columns] movies_with_ratings_df = pd.merge(movies_df, rating_counts, left_on='kaggle_id', right_index=True, how='left') movies_with_ratings_df[rating_counts.columns] = movies_with_ratings_df[rating_counts.columns].fillna(0) from sqlalchemy import create_engine #"postgres://[user]:[password]@[location]:[port]/[database]" from config import db_password db_string = f"postgresql://postgres:{db_password}@127.0.0.1:5432/movie_data" engine = create_engine(db_string) movies_df.to_sql(name='movies', con=engine) rows_imported = 0 for data in pd.read_csv(f'{file_dir}/ratings.csv', chunksize=1000000): print(f'importing rows {rows_imported} to {rows_imported + len(data)}...', end='') data.to_sql(name='ratings', con=engine, if_exists='append') rows_imported += len(data) print(f'Done.') ```
github_jupyter
``` import os if os.path.split(os.getcwd())[-1]=='notebooks': os.chdir("../") 'Your base path is at: '+os.path.split(os.getcwd())[-1] ``` # Update Data ``` # %load src/data/get_data.py import subprocess import os import pandas as pd import numpy as np from datetime import datetime import requests import json def get_johns_hopkins(): ''' Get data by a git pull request, the source code has to be pulled first Result is stored in the predifined csv structure ''' git_pull = subprocess.Popen( "/usr/bin/git pull" , cwd = os.path.dirname( 'data/raw/COVID-19/' ), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) (out, error) = git_pull.communicate() print("Error : " + str(error)) print("out : " + str(out)) def get_current_data_germany(): ''' Get current data from germany, attention API endpoint not too stable Result data frame is stored as pd.DataFrame ''' # 16 states #data=requests.get('https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Coronaf%C3%A4lle_in_den_Bundesl%C3%A4ndern/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json') # 400 regions / Landkreise data=requests.get('https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json') json_object=json.loads(data.content) full_list=[] for pos,each_dict in enumerate (json_object['features'][:]): full_list.append(each_dict['attributes']) pd_full_list=pd.DataFrame(full_list) pd_full_list.to_csv('data/processed/COVID_final_set.csv',sep=';') print(' Number of regions rows: '+str(pd_full_list.shape[0])) if __name__ == '__main__': get_johns_hopkins() get_current_data_germany() ``` # 2. Process pipeline ``` # %load src/data/process_JH_data.py import pandas as pd import numpy as np from datetime import datetime def store_relational_JH_data(): ''' Transformes the COVID data in a relational data set ''' data_path='data/raw/COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv' pd_raw=pd.read_csv(data_path) pd_data_base=pd_raw.rename(columns={'Country/Region':'country', 'Province/State':'state'}) pd_data_base['state']=pd_data_base['state'].fillna('no') pd_data_base=pd_data_base.drop(['Lat','Long'],axis=1) pd_relational_model=pd_data_base.set_index(['state','country']) \ .T \ .stack(level=[0,1]) \ .reset_index() \ .rename(columns={'level_0':'date', 0:'confirmed'}, ) pd_relational_model['date']=pd_relational_model.date.astype('datetime64[ns]') pd_relational_model.to_csv('data/processed/COVID_final_set.csv',sep=';',index=False) print(' Number of rows stored: '+str(pd_relational_model.shape[0])) if __name__ == '__main__': store_relational_JH_data() ``` # 3. Filter and Doubling rate Calculation ``` # %load src/features/build_features.py import numpy as np from sklearn import linear_model reg = linear_model.LinearRegression(fit_intercept=True) import pandas as pd from scipy import signal def get_doubling_time_via_regression(in_array): ''' Use a linear regression to approximate the doubling rate Parameters: ---------- in_array : pandas.series Returns: ---------- Doubling rate: double ''' y = np.array(in_array) X = np.arange(-1,2).reshape(-1, 1) assert len(in_array)==3 reg.fit(X,y) intercept=reg.intercept_ slope=reg.coef_ return intercept/slope def savgol_filter(df_input,column='confirmed',window=5): ''' Savgol Filter which can be used in groupby apply function (data structure kept) parameters: ---------- df_input : pandas.series column : str window : int used data points to calculate the filter result Returns: ---------- df_result: pd.DataFrame the index of the df_input has to be preserved in result ''' degree=1 df_result=df_input filter_in=df_input[column].fillna(0) # attention with the neutral element here result=signal.savgol_filter(np.array(filter_in), window, # window size used for filtering 1) df_result[str(column+'_filtered')]=result return df_result def rolling_reg(df_input,col='confirmed'): ''' Rolling Regression to approximate the doubling time' Parameters: ---------- df_input: pd.DataFrame col: str defines the used column Returns: ---------- result: pd.DataFrame ''' days_back=3 result=df_input[col].rolling( window=days_back, min_periods=days_back).apply(get_doubling_time_via_regression,raw=False) return result def calc_filtered_data(df_input,filter_on='confirmed'): ''' Calculate savgol filter and return merged data frame Parameters: ---------- df_input: pd.DataFrame filter_on: str defines the used column Returns: ---------- df_output: pd.DataFrame the result will be joined as a new column on the input data frame ''' must_contain=set(['state','country',filter_on]) assert must_contain.issubset(set(df_input.columns)), ' Erro in calc_filtered_data not all columns in data frame' df_output=df_input.copy() # we need a copy here otherwise the filter_on column will be overwritten pd_filtered_result=df_output[['state','country',filter_on]].groupby(['state','country']).apply(savgol_filter)#.reset_index() #print('--+++ after group by apply') #print(pd_filtered_result[pd_filtered_result['country']=='Germany'].tail()) #df_output=pd.merge(df_output,pd_filtered_result[['index',str(filter_on+'_filtered')]],on=['index'],how='left') df_output=pd.merge(df_output,pd_filtered_result[[str(filter_on+'_filtered')]],left_index=True,right_index=True,how='left') #print(df_output[df_output['country']=='Germany'].tail()) return df_output.copy() def calc_doubling_rate(df_input,filter_on='confirmed'): ''' Calculate approximated doubling rate and return merged data frame Parameters: ---------- df_input: pd.DataFrame filter_on: str defines the used column Returns: ---------- df_output: pd.DataFrame the result will be joined as a new column on the input data frame ''' must_contain=set(['state','country',filter_on]) assert must_contain.issubset(set(df_input.columns)), ' Erro in calc_filtered_data not all columns in data frame' pd_DR_result= df_input.groupby(['state','country']).apply(rolling_reg,filter_on).reset_index() pd_DR_result=pd_DR_result.rename(columns={filter_on:filter_on+'_DR', 'level_2':'index'}) #we do the merge on the index of our big table and on the index column after groupby df_output=pd.merge(df_input,pd_DR_result[['index',str(filter_on+'_DR')]],left_index=True,right_on=['index'],how='left') df_output=df_output.drop(columns=['index']) return df_output if __name__ == '__main__': test_data_reg=np.array([2,4,6]) result=get_doubling_time_via_regression(test_data_reg) print('the test slope is: '+str(result)) pd_JH_data=pd.read_csv('data/processed/COVID_relational_confirmed.csv',sep=';',parse_dates=[0]) pd_JH_data=pd_JH_data.sort_values('date',ascending=True).copy() #test_structure=pd_JH_data[((pd_JH_data['country']=='US')| # (pd_JH_data['country']=='Germany'))] pd_result_larg=calc_filtered_data(pd_JH_data) pd_result_larg=calc_doubling_rate(pd_result_larg) pd_result_larg=calc_doubling_rate(pd_result_larg,'confirmed_filtered') mask=pd_result_larg['confirmed']>100 pd_result_larg['confirmed_filtered_DR']=pd_result_larg['confirmed_filtered_DR'].where(mask, other=np.NaN) pd_result_larg.to_csv('data/processed/COVID_final_set.csv',sep=';',index=False) print(pd_result_larg.tail()) ``` # Visual Board ``` # %load src/visualization/visualize.py import pandas as pd import numpy as np import dash dash.__version__ import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output,State import plotly.graph_objects as go import os print(os.getcwd()) df_input_large=pd.read_csv('data/processed/COVID_final_set.csv',sep=';') fig = go.Figure() app = dash.Dash() app.layout = html.Div([ dcc.Markdown(''' # Applied Data Science on COVID-19 data Goal of the project is to teach data science by applying a cross industry standard process, it covers the full walkthrough of: automated data gathering, data transformations, filtering and machine learning to approximating the doubling time, and (static) deployment of responsive dashboard. '''), dcc.Markdown(''' ## Multi-Select Country for visualization '''), dcc.Dropdown( id='country_drop_down', options=[ {'label': each,'value':each} for each in df_input_large['country'].unique()], value=['US', 'Germany','Italy'], # which are pre-selected multi=True ), dcc.Markdown(''' ## Select Timeline of confirmed COVID-19 cases or the approximated doubling time '''), dcc.Dropdown( id='doubling_time', options=[ {'label': 'Timeline Confirmed ', 'value': 'confirmed'}, {'label': 'Timeline Confirmed Filtered', 'value': 'confirmed_filtered'}, {'label': 'Timeline Doubling Rate', 'value': 'confirmed_DR'}, {'label': 'Timeline Doubling Rate Filtered', 'value': 'confirmed_filtered_DR'}, ], value='confirmed', multi=False ), dcc.Graph(figure=fig, id='main_window_slope') ]) @app.callback( Output('main_window_slope', 'figure'), [Input('country_drop_down', 'value'), Input('doubling_time', 'value')]) def update_figure(country_list,show_doubling): if 'doubling_rate' in show_doubling: my_yaxis={'type':"log", 'title':'Approximated doubling rate over 3 days (larger numbers are better #stayathome)' } else: my_yaxis={'type':"log", 'title':'Confirmed infected people (source johns hopkins csse, log-scale)' } traces = [] for each in country_list: df_plot=df_input_large[df_input_large['country']==each] if show_doubling=='doubling_rate_filtered': df_plot=df_plot[['state','country','confirmed','confirmed_filtered','confirmed_DR','confirmed_filtered_DR','date']].groupby(['country','date']).agg(np.mean).reset_index() else: df_plot=df_plot[['state','country','confirmed','confirmed_filtered','confirmed_DR','confirmed_filtered_DR','date']].groupby(['country','date']).agg(np.sum).reset_index() #print(show_doubling) traces.append(dict(x=df_plot.date, y=df_plot[show_doubling], mode='markers+lines', opacity=0.9, name=each ) ) return { 'data': traces, 'layout': dict ( width=1280, height=720, xaxis={'title':'Timeline', 'tickangle':-45, 'nticks':20, 'tickfont':dict(size=14,color="#7f7f7f"), }, yaxis=my_yaxis ) } if __name__ == '__main__': app.run_server(debug=True, use_reloader=False) ```
github_jupyter
``` # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. ``` # Loading a pre-trained model in inference mode In this tutorial, we will show how to instantiate a model pre-trained with VISSL to use it in inference mode to extract features from its trunk. We will concentrate on loading a model pre-trained via SimCLR to use it in inference mode and extract features from an image, but this whole training is portable to any another pre-training methods (MoCo, SimSiam, SwAV, etc). Through it, we will show: 1. How to instantiate a model associated to a pre-training configuration 2. Load the weights of the pre-trained model (taking the weights from our Model Zoo) 3. Use it to extract features associated to the VISSL Logo **NOTE:** For a tutorial focused on how to use VISSL to schedule a feature extraction job, please refer to [the dedicated tutorial](https://colab.research.google.com/github/facebookresearch/vissl/blob/stable/tutorials/Feature_Extraction.ipynb) **NOTE:** Please ensure your Collab Notebook has GPU available: `Edit -> Notebook Settings -> select GPU`. **NOTE:** You can make a copy of this tutorial by `File -> Open in playground mode` and make changes there. DO NOT request access to this tutorial. ## Install VISSL We will start this tutorial by installing VISSL, following the instructions [here](https://github.com/facebookresearch/vissl/blob/master/INSTALL.md#install-vissl-pip-package). ``` # Install: PyTorch (we assume 1.5.1 but VISSL works with all PyTorch versions >=1.4) !pip install torch==1.5.1+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html # install opencv !pip install opencv-python # install apex by checking system settings: cuda version, pytorch version, python version import sys import torch version_str="".join([ f"py3{sys.version_info.minor}_cu", torch.version.cuda.replace(".",""), f"_pyt{torch.__version__[0:5:2]}" ]) print(version_str) # install apex (pre-compiled with optimizer C++ extensions and CUDA kernels) !pip install -f https://dl.fbaipublicfiles.com/vissl/packaging/apexwheels/{version_str}/download.html apex # install VISSL !pip install vissl ``` VISSL should be successfuly installed by now and all the dependencies should be available. ``` import vissl import tensorboard import apex import torch ``` ## Loading a VISSL SimCLR pre-trained model ## Download the configuration VISSL provides yaml configuration files for training a SimCLR model [here](https://github.com/facebookresearch/vissl/tree/master/configs/config/pretrain/simclr). We will start by fetching the configuration files we need. ``` !mkdir -p configs/config/simclr !mkdir -p vissl/config !wget -q -O configs/config/simclr/simclr_8node_resnet.yaml https://raw.githubusercontent.com/facebookresearch/vissl/master/configs/config/pretrain/simclr/simclr_8node_resnet.yaml !wget -q -O vissl/config/defaults.yaml https://raw.githubusercontent.com/facebookresearch/vissl/master/vissl/config/defaults.yaml ``` ``` # This is formatted as code ``` ## Download the ResNet-50 weights from the Model Zoo ``` !wget -q -O resnet_simclr.torch https://dl.fbaipublicfiles.com/vissl/model_zoo/simclr_rn101_1000ep_simclr_8node_resnet_16_07_20.35063cea/model_final_checkpoint_phase999.torch ``` ## Create the model associated to the configuration Load the configuration and merge it with the default configuration. ``` from omegaconf import OmegaConf from vissl.utils.hydra_config import AttrDict config = OmegaConf.load("configs/config/simclr/simclr_8node_resnet.yaml") default_config = OmegaConf.load("vissl/config/defaults.yaml") cfg = OmegaConf.merge(default_config, config) ``` Edit the configuration to freeze the trunk (inference mode) and ask for the extraction of the last layer feature. ``` cfg = AttrDict(cfg) cfg.config.MODEL.WEIGHTS_INIT.PARAMS_FILE = "resnet_simclr.torch" cfg.config.MODEL.FEATURE_EVAL_SETTINGS.EVAL_MODE_ON = True cfg.config.MODEL.FEATURE_EVAL_SETTINGS.FREEZE_TRUNK_ONLY = True cfg.config.MODEL.FEATURE_EVAL_SETTINGS.EXTRACT_TRUNK_FEATURES_ONLY = True cfg.config.MODEL.FEATURE_EVAL_SETTINGS.SHOULD_FLATTEN_FEATS = False cfg.config.MODEL.FEATURE_EVAL_SETTINGS.LINEAR_EVAL_FEAT_POOL_OPS_MAP = [["res5avg", ["Identity", []]]] ``` And then build the model: ``` from vissl.models import build_model model = build_model(cfg.config.MODEL, cfg.config.OPTIMIZER) ``` ## Loading the pre-trained weights ``` from classy_vision.generic.util import load_checkpoint from vissl.utils.checkpoint import init_model_from_weights weights = load_checkpoint(checkpoint_path=cfg.config.MODEL.WEIGHTS_INIT.PARAMS_FILE) init_model_from_weights( config=cfg.config, model=model, state_dict=weights, state_dict_key_name="classy_state_dict", skip_layers=[], # Use this if you do not want to load all layers ) print("Loaded...") ``` ## Trying the model on the VISSL Logo ``` !wget -q -O test_image.jpg https://raw.githubusercontent.com/facebookresearch/vissl/master/.github/logo/Logo_Color_Light_BG.png from PIL import Image import torchvision.transforms as transforms image = Image.open("test_image.jpg") image = image.convert("RGB") pipeline = transforms.Compose([ transforms.CenterCrop(224), transforms.ToTensor(), ]) x = pipeline(image) features = model(x.unsqueeze(0)) ``` The output is a list with as many representation layers as required in the configuration (in our case, `cfg.config.MODEL.FEATURE_EVAL_SETTINGS.LINEAR_EVAL_FEAT_POOL_OPS_MAP` asks for one representation layer, so we have just one output. ``` features[0].shape ```
github_jupyter
# Enterprise Time Series Forecasting and Decomposition Using LSTM This notebook is a tutorial on time series forecasting and decomposition using LSTM. * First, we generate a signal (time series) that includes several components that are commonly found in enterprise applications: trend, seasonality, covariates, and covariates with memory effects. * Second, we fit a basic LSTM model, produce the forecast, and introspect the evolution of the hidden state of the model. * Third, we fit the LSTM with attention model and visualize attention weights that provide some insights into the memory effects. ## Detailed Description Please see blog post [D006](https://github.com/ikatsov/tensor-house/blob/master/resources/descriptions.md) for more details. ## Data This notebook generates synthetic data internally, no external datset are used. --- # Step 1: Generate the Data We generate a time series that includes a trend, seasonality, covariates, and covariates. This signals mimics some of the effects usually found in sales data (cannibalization, halo, pull forward, and other effects). The covariates are just independent variables, but they can enter the signal in two modes: * Linear. The covariate series is directly added to the main signal with some coeffecient. E.g. the link function is indentity. * Memory. The covariate is transformed using a link function that include some delay and can be nonlinear. We use a simple smoothing filter as a link function. We observe the original covariate, but the link function is unknown. ``` import numpy as np import pandas as pd import datetime import collections from matplotlib import pylab as plt plt.style.use('ggplot') import seaborn as sns import matplotlib.dates as mdates from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() pd.options.mode.chained_assignment = None import tensorflow as tf from sklearn import preprocessing from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import LSTM, Dense, Input from tensorflow.keras.layers import Lambda, RepeatVector, Permute, Flatten, Activation, Multiply from tensorflow.keras.constraints import NonNeg from tensorflow.keras import backend as K from tensorflow.keras.regularizers import l1 from tensorflow.keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error def step_series(n, mean, scale, n_steps): s = np.zeros(n) step_idx = np.random.randint(0, n, n_steps) value = mean for t in range(n): s[t] = value if t in step_idx: value = mean + scale * np.random.randn() return s def linear_link(x): return x def mem_link(x, length = 50): mfilter = np.exp(np.linspace(-10, 0, length)) return np.convolve(x, mfilter/np.sum(mfilter), mode='same') def create_signal(links = [linear_link, linear_link]): days_year = 365 quaters_year = 4 days_week = 7 # three years of data, daily resolution idx = pd.date_range(start='2017-01-01', end='2020-01-01', freq='D') df = pd.DataFrame(index=idx, dtype=float) df = df.fillna(0.0) n = len(df.index) trend = np.zeros(n) seasonality = np.zeros(n) for t in range(n): trend[t] = 2.0 * t/n seasonality[t] = 4.0 * np.sin(np.pi * t/days_year*quaters_year) covariates = [step_series(n, 0, 1.0, 80), step_series(n, 0, 1.0, 80)] covariate_links = [ links[i](covariates[i]) for i in range(2) ] noise = 0.5 * np.random.randn(n) signal = trend + seasonality + np.sum(covariate_links, axis=0) + noise df['signal'], df['trend'], df['seasonality'], df['noise'] = signal, trend, seasonality, noise for i in range(2): df[f'covariate_0{i+1}'] = covariates[i] df[f'covariate_0{i+1}_link'] = covariate_links[i] return df df = create_signal() fig, ax = plt.subplots(len(df.columns), figsize=(20, 15)) for i, c in enumerate(df.columns): ax[i].plot(df.index, df[c]) ax[i].set_title(c) plt.tight_layout() plt.show() ``` # Step 2: Define and Fit the Basic LSTM Model We fit LSTM model that consumes patches of the observed signal and covariates, i.e. each input sample is a matrix where rows are time steps and columns are observed metrics (signal, covariate, and calendar features). ``` # # engineer features and create input tensors # def prepare_features_rnn(df): df_rnn = df[['signal', 'covariate_01', 'covariate_02']] df_rnn['year'] = df_rnn.index.year df_rnn['month'] = df_rnn.index.month df_rnn['day_of_year'] = df_rnn.index.dayofyear def normalize(df): x = df.values min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) return pd.DataFrame(x_scaled, index=df.index, columns=df.columns) return normalize(df_rnn) # # train-test split and adjustments # def train_test_split(df, train_ratio, forecast_days_ahead, n_time_steps, time_step_interval): # lenght of the input time window for each sample (the offset of the oldest sample in the input) input_window_size = n_time_steps*time_step_interval split_t = int(len(df)*train_ratio) x_train, y_train = [], [] x_test, y_test = [], [] y_col_idx = list(df.columns).index('signal') for i in range(input_window_size, len(df)): t_start = df.index[i - input_window_size] t_end = df.index[i] # we zero out last forecast_days_ahead signal observations, but covariates are assumed to be known x_t = df[t_start:t_end:time_step_interval].values.copy() if time_step_interval <= forecast_days_ahead: x_t[-int((forecast_days_ahead) / time_step_interval):, y_col_idx] = 0 y_t = df.iloc[i]['signal'] if i < split_t: x_train.append(x_t) y_train.append(y_t) else: x_test.append(x_t) y_test.append(y_t) return np.stack(x_train), np.hstack(y_train), np.stack(x_test), np.hstack(y_test) # # parameters # n_time_steps = 40 # lenght of LSTM input in samples time_step_interval = 2 # sampling interval, days hidden_units = 8 # LSTM state dimensionality forecast_days_ahead = 7 train_ratio = 0.8 # # generate data and fit the model # df = create_signal() df_rnn = prepare_features_rnn(df) x_train, y_train, x_test, y_test = train_test_split(df_rnn, train_ratio, forecast_days_ahead, n_time_steps, time_step_interval) print(f'Input tensor shape {x_train.shape}') n_samples = x_train.shape[0] n_features = x_train.shape[2] input_model = Input(shape=(n_time_steps, n_features)) lstm_state_seq, state_h, state_c = LSTM(hidden_units, return_sequences=True, return_state=True)(input_model) output_dense = Dense(1)(state_c) model_lstm = Model(inputs=input_model, outputs=output_dense) tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) model_lstm.compile(loss='mean_squared_error', metrics=['mean_absolute_percentage_error'], optimizer='RMSprop') model_lstm.summary() model_lstm.fit(x_train, y_train, epochs=20, batch_size=4, validation_data=(x_test, y_test), use_multiprocessing=True, verbose=1) score = model_lstm.evaluate(x_test, y_test, verbose=0) print('Test MSE:', score[0]) print('Test MAPE:', score[1]) ``` # Step 3: Visualize the Forecast and Evolution of the Hidden State We first plot the forecast to show that models fits well. Next, we visualize how individual components of the hidden state evolve over time: * We can see that some states actually extract seasonal and trend components, but this is not guaranteed. * We also overlay plots with covariates, to check if there are any correlation between states and covariates. We see that states do not correlate much with the covariate patterns. ``` input_window_size = n_time_steps*time_step_interval x = np.vstack([x_train, x_test]) y_hat = model_lstm.predict(x) forecast = np.append(np.zeros(input_window_size), y_hat) # # plot the forecast # fig, ax = plt.subplots(1, figsize=(20, 5)) ax.plot(df_rnn.index, forecast, label=f'Forecast ({forecast_days_ahead} days ahead)') ax.plot(df_rnn.index, df_rnn['signal'], label='Signal') ax.axvline(x=df.index[int(len(df) * train_ratio)], linestyle='--') ax.legend() plt.show() # # plot the evolution of the LSTM state # lstm_state_tap = Model(model_lstm.input, lstm_state_seq) lstm_state_trace = lstm_state_tap.predict(x) state_series = lstm_state_trace[:, -1, :].T fig, ax = plt.subplots(len(state_series), figsize=(20, 15)) for i, state in enumerate(state_series): ax[i].plot(df_rnn.index[:len(state)], state, label=f'State dimension {i}') for j in [1, 2]: ax[i].plot(df_rnn.index[:len(state)], df_rnn[f'covariate_0{j}'][:len(state)], color='#bbbbbb', label=f'Covariate 0{j}') ax[i].legend(loc='upper right') plt.show() ``` # Step 4: Define and Fit LSTM with Attention (LSTM-A) Model We fit the LSTM with attention model to analyze the contribution of individual time steps from input patches. It can help to reconstruct the (unknown) memory link function. ``` # # parameters # n_time_steps = 5 # lenght of LSTM input in samples time_step_interval = 10 # sampling interval, days hidden_units = 256 # LSTM state dimensionality forecast_days_ahead = 14 train_ratio = 0.8 def fit_lstm_a(df, train_verbose = 0, score_verbose = 0): df_rnn = prepare_features_rnn(df) x_train, y_train, x_test, y_test = train_test_split(df_rnn, train_ratio, forecast_days_ahead, n_time_steps, time_step_interval) n_steps = x_train.shape[0] n_features = x_train.shape[2] # # define the model: LSTM with attention # main_input = Input(shape=(n_steps, n_features)) activations = LSTM(hidden_units, recurrent_dropout=0.1, return_sequences=True)(main_input) attention = Dense(1, activation='tanh')(activations) attention = Flatten()(attention) attention = Activation('softmax', name = 'attention_weigths')(attention) attention = RepeatVector(hidden_units * 1)(attention) attention = Permute([2, 1])(attention) weighted_activations = Multiply()([activations, attention]) weighted_activations = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(hidden_units,))(weighted_activations) main_output = Dense(1, activation='sigmoid')(weighted_activations) model_attn = Model(inputs=main_input, outputs=main_output) # # fit the model # tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) model_attn.compile(optimizer='rmsprop', loss='mean_squared_error', metrics=['mean_absolute_percentage_error']) history = model_attn.fit(x_train, y_train, batch_size=4, epochs=30, verbose=train_verbose, validation_data=(x_test, y_test)) score = model_attn.evaluate(x_test, y_test, verbose=0) if score_verbose > 0: print(f'Test MSE [{score[0]}], MAPE [{score[1]}]') return model_attn, df_rnn, x_train, x_test df = create_signal(links = [linear_link, linear_link]) model_attn, df_rnn, x_train, x_test = fit_lstm_a(df, train_verbose = 1, score_verbose = 1) input_window_size = n_time_steps*time_step_interval x = np.vstack([x_train, x_test]) y_hat = model_attn.predict(x) forecast = np.append(np.zeros(input_window_size), y_hat) # # plot the forecast # fig, ax = plt.subplots(1, figsize=(20, 5)) ax.plot(df_rnn.index, forecast, label=f'Forecast ({forecast_days_ahead} days ahead)') ax.plot(df_rnn.index, df_rnn['signal'], label='Signal') ax.axvline(x=df.index[int(len(df) * train_ratio)], linestyle='--') ax.legend() plt.show() ``` # Step 5: Analyze LSTM-A Model The LSTM with attention model allows to extract the matrix of attention weights. For each time step, we have a vector of weights where each weight corresponds to one time step (lag) in the input patch. * For the linear link, only the contemporaneous covariates/features have high contribution weights. * For the memory link, the "LSTMogram" is more blurred becasue lagged samples have high contribution as well. ``` # # evaluate atention weights for each time step # attention_model = Model(inputs=model_attn.input, outputs=model_attn.get_layer('attention_weigths').output) a = attention_model.predict(x_train) print(f'Weight matrix shape {a.shape}') fig, ax = plt.subplots(1, figsize=(10, 2)) ax.imshow(a.T, cmap='viridis', interpolation='nearest', aspect='auto') ax.grid(None) # # generate multiple datasets and perform LSTM-A analysis for each of them # n_evaluations = 4 tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) fig, ax = plt.subplots(n_evaluations, 2, figsize=(16, n_evaluations * 2)) for j, link in enumerate([linear_link, mem_link]): for i in range(n_evaluations): print(f'Evaluating LSTMogram for link [{link.__name__}], trial [{i}]...') df = create_signal(links = [link, link]) model_attn, df_rnn, x_train, _ = fit_lstm_a(df, score_verbose = 0) attention_model = Model(inputs=model_attn.input, outputs=model_attn.get_layer('attention_weigths').output) a = attention_model.predict(x_train) ax[i, j].imshow(a.T, cmap='viridis', interpolation='nearest', aspect='auto') ax[i, j].grid(None) ```
github_jupyter
# OSM Data Exploration ## Extraction of districts from shape files For our experiments we consider two underdeveloped districts Araria, Bihar and Namsai, Arunachal Pradesh, the motivation of this comes from this [dna](https://www.dnaindia.com/india/report-out-of-niti-aayog-s-20-most-underdeveloped-districts-19-are-ruled-by-bjp-or-its-allies-2598984) news article, quoting a Niti Aayog Report. We also consider a developed city Bangalore in the south of India. ``` import os from dotenv import load_dotenv load_dotenv() # Read India shape file with level 2 (contains district level administrative boundaries) india_shape = os.environ.get("DATA_DIR") + "/gadm36_shp/gadm36_IND_2.shp" import geopandas as gpd india_gpd = gpd.read_file(india_shape) #inspect import matplotlib.pyplot as plt %matplotlib inline india_gpd.plot(); # Extract Araria district in Bihar state araria_gdf = india_gpd[india_gpd['NAME_2'] == 'Araria'] araria_gdf # Extract two main features of interest araria_gdf = araria_gdf[['NAME_2', 'geometry']] araria_gdf.plot() # Extract Namsai district in Arunachal Pradesh state. namsai_gdf = india_gpd[india_gpd['NAME_2'] == 'Namsai'] namsai_gdf # Extract the two main features namsai_gdf = namsai_gdf[['NAME_2', 'geometry']] namsai_gdf.plot() # Extract Bangalore district bangalore_gdf = india_gpd[india_gpd['NAME_2'] == 'Bangalore'] bangalore_gdf = bangalore_gdf[['NAME_2', 'geometry']] bangalore_gdf.plot() ``` ## Creating geographic extracts from OpenStreetMap Data Given a geopandas data frame representing a district boundary we find its bounding box ``` # Get the coordinate system for araria data frame araria_gdf.crs araria_bbox = araria_gdf.bounds print(araria_bbox) type(araria_gdf) ``` ## Fetch Open Street Map Data within Boundaries as Data Frame We use 'add_basemap' function of contextily to add a background map to our plot and make sure the added basemap has the same co-ordinate system (crs) as the boundary extracted from the shape file. ``` import contextily as ctx araria_ax = araria_gdf.plot(figsize=(20, 20), alpha=0.5, edgecolor='k') ctx.add_basemap(araria_ax, crs=araria_gdf.crs, zoom=12) #Using contextily to download basemaps and store them in standard raster files Store the base maps as tif w, s, e, n = (araria_bbox.minx.values[0], araria_bbox.miny.values[0], araria_bbox.maxx.values[0], araria_bbox.maxy.values[0]) _ = ctx.bounds2raster(w, s, e, n, ll=True, path = os.environ.get("OSM_DIR") + "araria.tif", source=ctx.providers.CartoDB.Positron) import rasterio from rasterio.plot import show r = rasterio.open(os.environ.get("OSM_DIR") + "araria.tif") plt.imshow(r.read(1)) #show(r, 2) plt.rcParams["figure.figsize"] = (20, 20) plt.rcParams["grid.color"] = 'k' plt.rcParams["grid.linestyle"] = ":" plt.rcParams["grid.linewidth"] = 0.5 plt.rcParams["grid.alpha"] = 0.5 plt.show() ``` Other than the raster image tiles of the map there is also the Knots and Edges Model associated with a map, which is the vector data in the geopandas data frame and visualized below ``` import osmnx as ox araria_graph = ox.graph_from_bbox(n, s, e, w) type(araria_graph) araria_fig, araria_ax = ox.plot_graph(araria_graph) plt.tight_layout() ``` The following section deals with creation of GeoDataFrame of OSM entities within a N, S, E, W bounding box and tags which is a dictionary of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. All Open Street Map tags can be found [here](https://wiki.openstreetmap.org/wiki/Map_features) ``` tags = {'amenity':True, 'building':True, 'emergency':True, 'highway':True, 'footway':True, 'landuse': True, 'water': True} araria_osmdf = ox.geometries.geometries_from_bbox(n, s, e, w, tags=tags) araria_osmdf.head() # Copy the dataframe as a csv araria_osmdf.to_csv(os.environ.get("OSM_DIR") + "araria_osmdf.csv") ```
github_jupyter
``` ''' Comparing single layer MLP with deep MLP (using TensorFlow) ''' import numpy as np from scipy.optimize import minimize from scipy.io import loadmat from scipy.stats import logistic from math import sqrt import time import pickle # Do not change this def initializeWeights(n_in,n_out): """ # initializeWeights return the random weights for Neural Network given the # number of node in the input layer and output layer # Input: # n_in: number of nodes of the input layer # n_out: number of nodes of the output layer # Output: # W: matrix of random initial weights with size (n_out x (n_in + 1))""" epsilon = sqrt(6) / sqrt(n_in + n_out + 1); W = (np.random.rand(n_out, n_in + 1)*2* epsilon) - epsilon; return W def sigmoid(z): return (1.0 / (1.0 + np.exp(-z))) def nnObjFunction(params, *args): n_input, n_hidden, n_class, training_data, training_label, lambdaval = args w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1))) w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1))) obj_val = 0 n = training_data.shape[0] ''' Step 01: Feedforward Propagation ''' '''Input Layer --> Hidden Layer ''' # Adding bias node to every training data. Here, the bias value is 1 for every training data # A training data is a feature vector X. # We have 717 features for every training data biases1 = np.full((n,1), 1) training_data_bias = np.concatenate((biases1, training_data),axis=1) # aj is the linear combination of input data and weight (w1) at jth hidden node. # Here, 1 <= j <= no_of_hidden_units aj = np.dot( training_data_bias, np.transpose(w1)) # zj is the output from the hidden unit j after applying sigmoid as an activation function zj = sigmoid(aj) '''Hidden Layer --> Output Layer ''' # Adding bias node to every zj. m = zj.shape[0] biases2 = np.full((m,1), 1) zj_bias = np.concatenate((biases2, zj), axis=1) # bl is the linear combination of hidden units output and weight(w2) at lth output node. # Here, l = 10 as we are classifying 10 digits bl = np.dot(zj_bias, np.transpose(w2)) ol = sigmoid(bl) ''' Step 2: Error Calculation by error function ''' # yl --> Ground truth for every training dataset yl = np.full((n, n_class), 0) for i in range(n): trueLabel = training_label[i] yl[i][trueLabel] = 1 yl_prime = (1.0-yl) ol_prime = (1.0-ol) lol = np.log(ol) lol_prime = np.log(ol_prime) # Our Error function is "negative log-likelihood" # We need elementwise multiplication between the matrices error = np.sum( np.multiply(yl,lol) + np.multiply(yl_prime,lol_prime) )/((-1)*n) # error = -np.sum( np.sum(yl*lol + yl_prime*lol_prime, 1))/ n ''' Step 03: Gradient Calculation for Backpropagation of error ''' delta = ol- yl gradient_w2 = np.dot(delta.T, zj_bias) temp = np.dot(delta,w2) * ( zj_bias * (1.0-zj_bias)) gradient_w1 = np.dot( np.transpose(temp), training_data_bias) gradient_w1 = gradient_w1[1:, :] ''' Step 04: Regularization ''' regularization = lambdaval * (np.sum(w1**2) + np.sum(w2**2)) / (2*n) obj_val = error + regularization gradient_w1_reg = (gradient_w1 + lambdaval * w1)/n gradient_w2_reg = (gradient_w2 + lambdaval * w2)/n obj_grad = np.concatenate((gradient_w1_reg.flatten(), gradient_w2_reg.flatten()), 0) return (obj_val, obj_grad) def nnPredict(w1, w2, training_data): n = training_data.shape[0] biases1 = np.full((n,1),1) training_data = np.concatenate((biases1, training_data), axis=1) aj = np.dot(training_data, w1.T) zj = sigmoid(aj) m = zj.shape[0] biases2 = np.full((m,1), 1) zj = np.concatenate((biases2, zj), axis=1) bl = np.dot(zj, w2.T) ol = sigmoid(bl) labels = np.argmax(ol, axis=1) return labels # Do not change this def preprocess(): pickle_obj = pickle.load(file=open('face_all.pickle', 'rb')) features = pickle_obj['Features'] labels = pickle_obj['Labels'] train_x = features[0:21100] / 255 valid_x = features[21100:23765] / 255 test_x = features[23765:] / 255 labels = labels[0] train_y = labels[0:21100] valid_y = labels[21100:23765] test_y = labels[23765:] return train_x, train_y, valid_x, valid_y, test_x, test_y """**************Neural Network Script Starts here********************************""" train_data, train_label, validation_data, validation_label, test_data, test_label = preprocess() # Train Neural Network trainingStart = time.time() # set the number of nodes in input unit (not including bias unit) n_input = train_data.shape[1] # set the number of nodes in hidden unit (not including bias unit) n_hidden = 256 # set the number of nodes in output unit n_class = 2 # initialize the weights into some random matrices initial_w1 = initializeWeights(n_input, n_hidden); initial_w2 = initializeWeights(n_hidden, n_class); # unroll 2 weight matrices into single column vector initialWeights = np.concatenate((initial_w1.flatten(), initial_w2.flatten()),0) # set the regularization hyper-parameter lambdaval = 10; args = (n_input, n_hidden, n_class, train_data, train_label, lambdaval) #Train Neural Network using fmin_cg or minimize from scipy,optimize module. Check documentation for a working example opts = {'maxiter' :50} # Preferred value. nn_params = minimize(nnObjFunction, initialWeights, jac=True, args=args,method='CG', options=opts) params = nn_params.get('x') #Reshape nnParams from 1D vector into w1 and w2 matrices w1 = params[0:n_hidden * (n_input + 1)].reshape( (n_hidden, (n_input + 1))) w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1))) #Test the computed parameters predicted_label = nnPredict(w1,w2,train_data) #find the accuracy on Training Dataset print('\n Training set Accuracy:' + str(100*np.mean((predicted_label == train_label).astype(float))) + '%') predicted_label = nnPredict(w1,w2,validation_data) #find the accuracy on Validation Dataset print('\n Validation set Accuracy:' + str(100*np.mean((predicted_label == validation_label).astype(float))) + '%') predicted_label = nnPredict(w1,w2,test_data) #find the accuracy on Validation Dataset print('\n Test set Accuracy:' + str(100*np.mean((predicted_label == test_label).astype(float))) + '%') trainingEnd = time.time() print('Training Time:',(trainingEnd-trainingStart)) ```
github_jupyter
##### Copyright 2020 The Cirq Developers ``` #@title 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 # # https://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. ``` # Cirq basics <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://quantumai.google/cirq/tutorials/basics"><img src="https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png" />View on QuantumAI</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/github_logo_1x.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/basics.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/download_icon_1x.png" />Download notebook</a> </td> </table> This tutorial will teach the basics of how to use Cirq. This tutorial will walk through how to use qubits, gates, and operations to create and simulate your first quantum circuit using Cirq. It will briefly introduce devices, unitary matrices, decompositions, and optimizers. This tutorial isn’t a quantum computing 101 tutorial, we assume familiarity of quantum computing at about the level of the textbook “Quantum Computation and Quantum Information” by Nielsen and Chuang. For more in-depth examples closer to those found in current work, check out our tutorials page. To begin, please follow the instructions for [installing Cirq](../install.md). ``` try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") ``` ## Qubits The first part of creating a quantum circuit is to define a set of qubits (also known as a quantum registers) to act on. Cirq has three main ways of defining qubits: * `cirq.NamedQubit`: used to label qubits by an abstract name * `cirq.LineQubit`: qubits labelled by number in a linear array * `cirq.GridQubit`: qubits labelled by two numbers in a rectangular lattice. Here are some examples of defining each type of qubit. ``` import cirq # Using named qubits can be useful for abstract algorithms # as well as algorithms not yet mapped onto hardware. q0 = cirq.NamedQubit('source') q1 = cirq.NamedQubit('target') # Line qubits can be created individually q3 = cirq.LineQubit(3) # Or created in a range # This will create LineQubit(0), LineQubit(1), LineQubit(2) q0, q1, q2 = cirq.LineQubit.range(3) # Grid Qubits can also be referenced individually q4_5 = cirq.GridQubit(4,5) # Or created in bulk in a square # This will create 16 qubits from (0,0) to (3,3) qubits = cirq.GridQubit.square(4) ``` There are also pre-packaged sets of qubits called [Devices](../devices.md). These are qubits along with a set of rules of how they can be used. A `cirq.Device` can be used to apply adjacency rules and other hardware constraints to a quantum circuit. For our example, we will use the `cirq.google.Foxtail` device that comes with cirq. It is a 2x11 grid that mimics early hardware released by Google. ``` print(cirq.google.Foxtail) ``` ## Gates and operations The next step is to use the qubits to create operations that can be used in our circuit. Cirq has two concepts that are important to understand here: * A `Gate` is an effect that can be applied to a set of qubits. * An `Operation` is a gate applied to a set of qubits. For instance, `cirq.H` is the quantum [Hadamard](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate) and is a `Gate` object. `cirq.H(cirq.LineQubit(1))` is an `Operation` object and is the Hadamard gate applied to a specific qubit (line qubit number 1). Many textbook gates are included within cirq. `cirq.X`, `cirq.Y`, and `cirq.Z` refer to the single-qubit Pauli gates. `cirq.CZ`, `cirq.CNOT`, `cirq.SWAP` are a few of the common two-qubit gates. `cirq.measure` is a macro to apply a `MeasurementGate` to a set of qubits. You can find more, as well as instructions on how to creats your own custom gates, on the [Gates documentation](../gates.ipynb) page. Many arithmetic operations can also be applied to gates. Here are some examples: ``` # Example gates not_gate = cirq.CNOT pauli_z = cirq.Z # Using exponentiation to get square root gates sqrt_x_gate = cirq.X**0.5 sqrt_iswap = cirq.ISWAP**0.5 # Some gates can also take parameters sqrt_sqrt_y = cirq.YPowGate(exponent=0.25) # Example operations q0, q1 = cirq.LineQubit.range(2) z_op = cirq.Z(q0) not_op = cirq.CNOT(q0, q1) sqrt_iswap_op = sqrt_iswap(q0, q1) ``` ## Circuits and moments We are now ready to construct a quantum circuit. A `Circuit` is a collection of `Moment`s. A `Moment` is a collection of `Operation`s that all act during the same abstract time slice. Each `Operation` must have a disjoint set of qubits from the other `Operation`s in the `Moment`. A `Moment` can be thought of as a vertical slice of a quantum circuit diagram. Circuits can be constructed in several different ways. By default, cirq will attempt to slide your operation into the earliest possible `Moment` when you insert it. ``` circuit = cirq.Circuit() # You can create a circuit by appending to it circuit.append(cirq.H(q) for q in cirq.LineQubit.range(3)) # All of the gates are put into the same Moment since none overlap print(circuit) # We can also create a circuit directly as well: print(cirq.Circuit(cirq.SWAP(q, q+1) for q in cirq.LineQubit.range(3))) ``` Sometimes, you may not want cirq to automatically shift operations all the way to the left. To construct a circuit without doing this, you can create the circuit moment-by-moment or use a different `InsertStrategy`, explained more in the [Circuit documentation](../circuits.ipynb). ``` # Creates each gate in a separate moment. print(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3))) ``` ### Circuits and devices One important consideration when using real quantum devices is that there are often hardware constraints on the circuit. Creating a circuit with a `Device` will allow you to capture some of these requirements. These `Device` objects will validate the operations you add to the circuit to make sure that no illegal operations are added. Let's look at an example using the Foxtail device. ``` q0 = cirq.GridQubit(0, 0) q1 = cirq.GridQubit(0, 1) q2 = cirq.GridQubit(0, 2) adjacent_op = cirq.CZ(q0, q1) nonadjacent_op = cirq.CZ(q0, q2) # This is an unconstrained circuit with no device free_circuit = cirq.Circuit() # Both operations are allowed: free_circuit.append(adjacent_op) free_circuit.append(nonadjacent_op) print('Unconstrained device:') print(free_circuit) print() # This is a circuit on the Foxtail device # only adjacent operations are allowed. print('Foxtail device:') foxtail_circuit = cirq.Circuit(device=cirq.google.Foxtail) foxtail_circuit.append(adjacent_op) try: # Not allowed, will throw exception foxtail_circuit.append(nonadjacent_op) except ValueError as e: print('Not allowed. %s' % e) ``` ## Simulation The results of the application of a quantum circuit can be calculated by a `Simulator`. Cirq comes bundled with a simulator that can calculate the results of circuits up to about a limit of 20 qubits. It can be initialized with `cirq.Simulator()`. There are two different approaches to using a simulator: * `simulate()`: Since we are classically simulating a circuit, a simulator can directly access and view the resulting wave function. This is useful for debugging, learning, and understanding how circuits will function. * `run()`: When using actual quantum devices, we can only access the end result of a computation and must sample the results to get a distribution of results. Running the simulator as a sampler mimics this behavior and only returns bit strings as output. Let's try to simulate a 2-qubit "Bell State": ``` # Create a circuit to generate a Bell State: # sqrt(2) * ( |00> + |11> ) bell_circuit = cirq.Circuit() q0, q1 = cirq.LineQubit.range(2) bell_circuit.append(cirq.H(q0)) bell_circuit.append(cirq.CNOT(q0,q1)) # Initialize Simulator s=cirq.Simulator() print('Simulate the circuit:') results=s.simulate(bell_circuit) print(results) print() # For sampling, we need to add a measurement at the end bell_circuit.append(cirq.measure(q0, q1, key='result')) print('Sample the circuit:') samples=s.run(bell_circuit, repetitions=1000) # Print a histogram of results print(samples.histogram(key='result')) ``` ### Using parameter sweeps Cirq circuits allow for gates to have symbols as free parameters within the circuit. This is especially useful for variational algorithms, which vary parameters within the circuit in order to optimize a cost function, but it can be useful in a variety of circumstances. For parameters, cirq uses the library `sympy` to add `sympy.Symbol` as parameters to gates and operations. Once the circuit is complete, you can fill in the possible values of each of these parameters with a `Sweep`. There are several possibilities that can be used as a sweep: * `cirq.Points`: A list of manually specified values for one specific symbol as a sequence of floats * `cirq.Linspace`: A linear sweep from a starting value to an ending value. * `cirq.ListSweep`: A list of manually specified values for several different symbols, specified as a list of dictionaries. * `cirq.Zip` and `cirq.Product`: Sweeps can be combined list-wise by zipping them together or through their Cartesian product. A parameterized circuit and sweep together can be run using the simulator or other sampler by changing `run()` to `run_sweep()` and adding the sweep as a parameter. Here is an example of sweeping an exponent of a X gate: ``` import matplotlib.pyplot as plt import sympy # Perform an X gate with variable exponent q = cirq.GridQubit(1,1) circuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'), cirq.measure(q, key='m')) # Sweep exponent from zero (off) to one (on) and back to two (off) param_sweep = cirq.Linspace('t', start=0, stop=2, length=200) # Simulate the sweep s = cirq.Simulator() trials = s.run_sweep(circuit, param_sweep, repetitions=1000) # Plot all the results x_data = [trial.params['t'] for trial in trials] y_data = [trial.histogram(key='m')[1] / 1000.0 for trial in trials] plt.scatter('t','p', data={'t': x_data, 'p': y_data}) ``` ## Unitary matrices and decompositions Most quantum operations have a unitary matrix representation. This matrix can be accessed by applying `cirq.unitary()`. This can be applied to gates, operations, and circuits that support this protocol and will return the unitary matrix that represents the object. ``` print('Unitary of the X gate') print(cirq.unitary(cirq.X)) print('Unitary of SWAP operator on two qubits.') q0, q1 = cirq.LineQubit.range(2) print(cirq.unitary(cirq.SWAP(q0, q1))) print('Unitary of a sample circuit') print(cirq.unitary(cirq.Circuit(cirq.X(q0), cirq.SWAP(q0, q1)))) ``` ### Decompositions Many gates can be decomposed into an equivalent circuit with simpler operations and gates. This is called decomposition and can be accomplished with the `cirq.decompose` protocol. For instance, a Hadamard H gate can be decomposed into X and Y gates: ``` print(cirq.decompose(cirq.H(cirq.LineQubit(0)))) ``` Another example is the 3-qubit Toffoli gate, which is equivalent to a controlled-controlled-X gate. Many devices do not support a three qubit gate, so it is important ``` q0, q1, q2 = cirq.LineQubit.range(3) print(cirq.Circuit(cirq.decompose(cirq.TOFFOLI(q0, q1, q2)))) ``` The above decomposes the Toffoli into a simpler set of one-qubit gates and CZ gates at the cost of lengthening the circuit considerably. Some devices will automatically decompose gates that they do not support. For instance, if we use the `Foxtail` device from above, we can see this in action by adding an unsupported SWAP gate: ``` swap = cirq.SWAP(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)) print(cirq.Circuit(swap, device=cirq.google.Foxtail)) ``` ### Optimizers The last concept in this tutorial is the optimizer. An optimizer can take a circuit and modify it. Usually, this will entail combining or modifying operations to make it more efficient and shorter, though an optimizer can, in theory, do any sort of circuit manipulation. For example, the `MergeSingleQubitGates` optimizer will take consecutive single-qubit operations and merge them into a single `PhasedXZ` operation. ``` q=cirq.GridQubit(1, 1) optimizer=cirq.MergeSingleQubitGates() c=cirq.Circuit(cirq.X(q) ** 0.25, cirq.Y(q) ** 0.25, cirq.Z(q) ** 0.25) print(c) optimizer.optimize_circuit(c) print(c) ``` Other optimizers can assist in transforming a circuit into operations that are native operations on specific hardware devices. You can find more about optimizers and how to create your own elsewhere in the documentation. ## Next steps After completing this tutorial, you should be able to use gates and operations to construct your own quantum circuits, simulate them, and to use sweeps. It should give you a brief idea of the commonly used There is much more to learn and try out for those who are interested: * Learn about the variety of [Gates](../gates.ipynb) available in cirq and more about the different ways to construct [Circuits](../circuits.ipynb) * Learn more about [Simulations](../simulation.ipynb) and how it works. * Learn about [Noise](../noise.ipynb) and how to utilize multi-level systems using [Qudits](../qudits.ipynb) * Dive into some [Examples](_index.yaml) and some in-depth tutorials of how to use cirq. Also, join our [cirq-announce mailing list](https://groups.google.com/forum/#!forum/cirq-announce) to hear about changes and releases or go to the [cirq github](https://github.com/quantumlib/Cirq/) to file issues.
github_jupyter
``` from fake_useragent import UserAgent import requests ua = UserAgent() from newspaper import Article from queue import Queue from urllib.parse import quote from unidecode import unidecode def get_date(load): try: date = re.findall( '[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?', load ) return '%s-%s-%s' % (date[2], date[0], date[1]) except Exce: return False def run_parallel_in_threads(target, args_list): globalparas = [] result = Queue() def task_wrapper(*args): result.put(target(*args)) threads = [ threading.Thread(target = task_wrapper, args = args) for args in args_list ] for t in threads: t.start() for t in threads: t.join() while not result.empty(): globalparas.append(result.get()) globalparas = list(filter(None, globalparas)) return globalparas def get_article(link, news, date): article = Article(link) article.download() article.parse() article.nlp() lang = 'ENGLISH' if len(article.title) < 5 or len(article.text) < 5: lang = 'INDONESIA' print('found BM/ID article') article = Article(link, language = 'id') article.download() article.parse() article.nlp() return { 'title': article.title, 'url': link, 'authors': article.authors, 'top-image': article.top_image, 'text': article.text, 'keyword': article.keywords, 'summary': article.summary, 'news': news, 'date': date, 'language': lang, } NUMBER_OF_CALLS_TO_GOOGLE_NEWS_ENDPOINT = 0 GOOGLE_NEWS_URL = 'https://www.google.com.my/search?q={}&source=lnt&tbs=cdr%3A1%2Ccd_min%3A{}%2Ccd_max%3A{}&tbm=nws&start={}' def forge_url(q, start, year_start, year_end): global NUMBER_OF_CALLS_TO_GOOGLE_NEWS_ENDPOINT NUMBER_OF_CALLS_TO_GOOGLE_NEWS_ENDPOINT += 1 return GOOGLE_NEWS_URL.format( q.replace(' ', '+'), str(year_start), str(year_end), start ) num_articles_index = 0 url = forge_url('america', num_articles_index, '2005', '2021') url headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'} headers response = requests.get(url, headers = headers, timeout = 60) soup = BeautifulSoup(response.content, 'html.parser') style="text-decoration:none;display:block" soup.find_all('div', {'class': 'XTjFC WF4CUc'})[0] [dateparser.parse(v.text) for v in soup.find_all('span', {'class': 'WG9SHc'})] import dateparser str(dateparser.parse('2 weeks ago')) from bs4 import BeautifulSoup from datetime import datetime, timedelta from dateutil import parser import dateparser def extract_links(content): soup = BeautifulSoup(content, 'html.parser') # return soup today = datetime.now().strftime('%m/%d/%Y') links_list = [v.attrs['href'] for v in soup.find_all('a', {'style': 'text-decoration:none;display:block'})] dates_list = [v.text for v in soup.find_all('span', {'class': 'WG9SHc'})] sources_list = [v.text for v in soup.find_all('div', {'class': 'XTjFC WF4CUc'})] output = [] for (link, date, source) in zip(links_list, dates_list, sources_list): try: date = str(dateparser.parse(date)) except: pass output.append((link, date, source)) return output r = extract_links(response.content) r ```
github_jupyter
# Building your Deep Neural Network: Step by Step Welcome to your week 4 assignment (part 1 of 2)! Previously you trained a 2-layer Neural Network with a single hidden layer. This week, you will build a deep neural network with as many layers as you want! - In this notebook, you'll implement all the functions required to build a deep neural network. - For the next assignment, you'll use these functions to build a deep neural network for image classification. **By the end of this assignment, you'll be able to:** - Use non-linear units like ReLU to improve your model - Build a deeper neural network (with more than 1 hidden layer) - Implement an easy-to-use neural network class **Notation**: - Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters. - Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example. - Lowerscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations). Let's get started! ## Table of Contents - [1 - Packages](#1) - [2 - Outline](#2) - [3 - Initialization](#3) - [3.1 - 2-layer Neural Network](#3-1) - [Exercise 1 - initialize_parameters](#ex-1) - [3.2 - L-layer Neural Network](#3-2) - [Exercise 2 - initialize_parameters_deep](#ex-2) - [4 - Forward Propagation Module](#4) - [4.1 - Linear Forward](#4-1) - [Exercise 3 - linear_forward](#ex-3) - [4.2 - Linear-Activation Forward](#4-2) - [Exercise 4 - linear_activation_forward](#ex-4) - [4.3 - L-Layer Model](#4-3) - [Exercise 5 - L_model_forward](#ex-5) - [5 - Cost Function](#5) - [Exercise 6 - compute_cost](#ex-6) - [6 - Backward Propagation Module](#6) - [6.1 - Linear Backward](#6-1) - [Exercise 7 - linear_backward](#ex-7) - [6.2 - Linear-Activation Backward](#6-2) - [Exercise 8 - linear_activation_backward](#ex-8) - [6.3 - L-Model Backward](#6-3) - [Exercise 9 - L_model_backward](#ex-9) - [6.4 - Update Parameters](#6-4) - [Exercise 10 - update_parameters](#ex-10) <a name='1'></a> ## 1 - Packages First, import all the packages you'll need during this assignment. - [numpy](www.numpy.org) is the main package for scientific computing with Python. - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python. - dnn_utils provides some necessary functions for this notebook. - testCases provides some test cases to assess the correctness of your functions - np.random.seed(1) is used to keep all the random function calls consistent. It helps grade your work. Please don't change the seed! ``` import numpy as np import h5py import matplotlib.pyplot as plt from testCases import * from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward from public_tests import * %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) ``` <a name='2'></a> ## 2 - Outline To build your neural network, you'll be implementing several "helper functions." These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function will have detailed instructions to walk you through the necessary steps. Here's an outline of the steps in this assignment: - Initialize the parameters for a two-layer network and for an $L$-layer neural network - Implement the forward propagation module (shown in purple in the figure below) - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$). - The ACTIVATION function is provided for you (relu/sigmoid) - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function. - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function. - Compute the loss - Implement the backward propagation module (denoted in red in the figure below) - Complete the LINEAR part of a layer's backward propagation step - The gradient of the ACTIVATE function is provided for you(relu_backward/sigmoid_backward) - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function - Finally, update the parameters <img src="images/final outline.png" style="width:800px;height:500px;"> <caption><center><b>Figure 1</b></center></caption><br> **Note**: For every forward function, there is a corresponding backward function. This is why at every step of your forward module you will be storing some values in a cache. These cached values are useful for computing gradients. In the backpropagation module, you can then use the cache to calculate the gradients. Don't worry, this assignment will show you exactly how to carry out each of these steps! <a name='3'></a> ## 3 - Initialization You will write two helper functions to initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one generalizes this initialization process to $L$ layers. <a name='3-1'></a> ### 3.1 - 2-layer Neural Network <a name='ex-1'></a> ### Exercise 1 - initialize_parameters Create and initialize the parameters of the 2-layer neural network. **Instructions**: - The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*. - Use this random initialization for the weight matrices: `np.random.randn(shape)*0.01` with the correct shape - Use zero initialization for the biases: `np.zeros(shape)` ``` # GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: parameters -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) W2 -- weight matrix of shape (n_y, n_h) b2 -- bias vector of shape (n_y, 1) """ np.random.seed(1) #(≈ 4 lines of code) # W1 = ... # b1 = ... # W2 = ... # b2 = ... # YOUR CODE STARTS HERE W1 = np.random.randn(n_h, n_x) * 0.01 b1 = np.zeros((n_h, 1)) W2 = np.random.randn(n_y, n_h) * 0.01 b2 = np.zeros((n_y, 1)) # YOUR CODE ENDS HERE parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters parameters = initialize_parameters(3,2,1) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"])) initialize_parameters_test(initialize_parameters) ``` ***Expected output*** ``` W1 = [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] b1 = [[0.] [0.]] W2 = [[ 0.01744812 -0.00761207]] b2 = [[0.]] ``` <a name='3-2'></a> ### 3.2 - L-layer Neural Network The initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep` function, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. For example, if the size of your input $X$ is $(12288, 209)$ (with $m=209$ examples) then: <table style="width:100%"> <tr> <td> </td> <td> <b>Shape of W</b> </td> <td> <b>Shape of b</b> </td> <td> <b>Activation</b> </td> <td> <b>Shape of Activation</b> </td> <tr> <tr> <td> <b>Layer 1</b> </td> <td> $(n^{[1]},12288)$ </td> <td> $(n^{[1]},1)$ </td> <td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td> <td> $(n^{[1]},209)$ </td> <tr> <tr> <td> <b>Layer 2</b> </td> <td> $(n^{[2]}, n^{[1]})$ </td> <td> $(n^{[2]},1)$ </td> <td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td> <td> $(n^{[2]}, 209)$ </td> <tr> <tr> <td> $\vdots$ </td> <td> $\vdots$ </td> <td> $\vdots$ </td> <td> $\vdots$</td> <td> $\vdots$ </td> <tr> <tr> <td> <b>Layer L-1</b> </td> <td> $(n^{[L-1]}, n^{[L-2]})$ </td> <td> $(n^{[L-1]}, 1)$ </td> <td>$Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td> <td> $(n^{[L-1]}, 209)$ </td> <tr> <tr> <td> <b>Layer L</b> </td> <td> $(n^{[L]}, n^{[L-1]})$ </td> <td> $(n^{[L]}, 1)$ </td> <td> $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$</td> <td> $(n^{[L]}, 209)$ </td> <tr> </table> Remember that when you compute $W X + b$ in python, it carries out broadcasting. For example, if: $$ W = \begin{bmatrix} w_{00} & w_{01} & w_{02} \\ w_{10} & w_{11} & w_{12} \\ w_{20} & w_{21} & w_{22} \end{bmatrix}\;\;\; X = \begin{bmatrix} x_{00} & x_{01} & x_{02} \\ x_{10} & x_{11} & x_{12} \\ x_{20} & x_{21} & x_{22} \end{bmatrix} \;\;\; b =\begin{bmatrix} b_0 \\ b_1 \\ b_2 \end{bmatrix}\tag{2}$$ Then $WX + b$ will be: $$ WX + b = \begin{bmatrix} (w_{00}x_{00} + w_{01}x_{10} + w_{02}x_{20}) + b_0 & (w_{00}x_{01} + w_{01}x_{11} + w_{02}x_{21}) + b_0 & \cdots \\ (w_{10}x_{00} + w_{11}x_{10} + w_{12}x_{20}) + b_1 & (w_{10}x_{01} + w_{11}x_{11} + w_{12}x_{21}) + b_1 & \cdots \\ (w_{20}x_{00} + w_{21}x_{10} + w_{22}x_{20}) + b_2 & (w_{20}x_{01} + w_{21}x_{11} + w_{22}x_{21}) + b_2 & \cdots \end{bmatrix}\tag{3} $$ <a name='ex-2'></a> ### Exercise 2 - initialize_parameters_deep Implement initialization for an L-layer Neural Network. **Instructions**: - The model's structure is *[LINEAR -> RELU] $ \times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function. - Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`. - Use zeros initialization for the biases. Use `np.zeros(shape)`. - You'll store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for last week's Planar Data classification model would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers! - Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network). ```python if L == 1: parameters["W" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01 parameters["b" + str(L)] = np.zeros((layer_dims[1], 1)) ``` ``` # GRADED FUNCTION: initialize_parameters_deep def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1]) bl -- bias vector of shape (layer_dims[l], 1) """ np.random.seed(3) parameters = {} L = len(layer_dims) # number of layers in the network for l in range(1, L): #(≈ 2 lines of code) # parameters['W' + str(l)] = ... # parameters['b' + str(l)] = ... # YOUR CODE STARTS HERE parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01 parameters['b' + str(l)] = np.zeros((layer_dims[l], 1)) # YOUR CODE ENDS HERE assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1])) assert(parameters['b' + str(l)].shape == (layer_dims[l], 1)) return parameters parameters = initialize_parameters_deep([5,4,3]) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"])) initialize_parameters_deep_test(initialize_parameters_deep) ``` ***Expected output*** ``` W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]] b1 = [[0.] [0.] [0.] [0.]] W2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716] [-0.01023785 -0.00712993 0.00625245 -0.00160513] [-0.00768836 -0.00230031 0.00745056 0.01976111]] b2 = [[0.] [0.] [0.]] ``` <a name='4'></a> ## 4 - Forward Propagation Module <a name='4-1'></a> ### 4.1 - Linear Forward Now that you have initialized your parameters, you can do the forward propagation module. Start by implementing some basic functions that you can use again later when implementing the model. Now, you'll complete three functions in this order: - LINEAR - LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. - [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID (whole model) The linear forward module (vectorized over all the examples) computes the following equations: $$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\tag{4}$$ where $A^{[0]} = X$. <a name='ex-3'></a> ### Exercise 3 - linear_forward Build the linear part of forward propagation. **Reminder**: The mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help. ``` # GRADED FUNCTION: linear_forward def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) Returns: Z -- the input of the activation function, also called pre-activation parameter cache -- a python tuple containing "A", "W" and "b" ; stored for computing the backward pass efficiently """ #(≈ 1 line of code) # Z = ... # YOUR CODE STARTS HERE Z = np.dot(W, A) + b # YOUR CODE ENDS HERE cache = (A, W, b) return Z, cache t_A, t_W, t_b = linear_forward_test_case() t_Z, t_linear_cache = linear_forward(t_A, t_W, t_b) print("Z = " + str(t_Z)) linear_forward_test(linear_forward) ``` ***Expected output*** ``` Z = [[ 3.26295337 -1.23429987]] ``` <a name='4-2'></a> ### 4.2 - Linear-Activation Forward In this notebook, you will use two activation functions: - **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. You've been provided with the `sigmoid` function which returns **two** items: the activation value "`a`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call: ``` python A, activation_cache = sigmoid(Z) ``` - **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. You've been provided with the `relu` function. This function returns **two** items: the activation value "`A`" and a "`cache`" that contains "`Z`" (it's what you'll feed in to the corresponding backward function). To use it you could just call: ``` python A, activation_cache = relu(Z) ``` For added convenience, you're going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you'll implement a function that does the LINEAR forward step, followed by an ACTIVATION forward step. <a name='ex-4'></a> ### Exercise 4 - linear_activation_forward Implement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation "g" can be sigmoid() or relu(). Use `linear_forward()` and the correct activation function. ``` # GRADED FUNCTION: linear_activation_forward def linear_activation_forward(A_prev, W, b, activation): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b -- bias vector, numpy array of shape (size of the current layer, 1) activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: A -- the output of the activation function, also called the post-activation value cache -- a python tuple containing "linear_cache" and "activation_cache"; stored for computing the backward pass efficiently """ if activation == "sigmoid": #(≈ 2 lines of code) # Z, linear_cache = ... # A, activation_cache = ... # YOUR CODE STARTS HERE Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = sigmoid(Z) # YOUR CODE ENDS HERE elif activation == "relu": #(≈ 2 lines of code) # Z, linear_cache = ... # A, activation_cache = ... # YOUR CODE STARTS HERE Z, linear_cache = linear_forward(A_prev, W, b) A, activation_cache = relu(Z) # YOUR CODE ENDS HERE cache = (linear_cache, activation_cache) return A, cache t_A_prev, t_W, t_b = linear_activation_forward_test_case() t_A, t_linear_activation_cache = linear_activation_forward(t_A_prev, t_W, t_b, activation = "sigmoid") print("With sigmoid: A = " + str(t_A)) t_A, t_linear_activation_cache = linear_activation_forward(t_A_prev, t_W, t_b, activation = "relu") print("With ReLU: A = " + str(t_A)) linear_activation_forward_test(linear_activation_forward) ``` ***Expected output*** ``` With sigmoid: A = [[0.96890023 0.11013289]] With ReLU: A = [[3.43896131 0. ]] ``` **Note**: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers. <a name='4-3'></a> ### 4.3 - L-Layer Model For even *more* convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID. <img src="images/model_architecture_kiank.png" style="width:600px;height:300px;"> <caption><center> <b>Figure 2</b> : *[LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model</center></caption><br> <a name='ex-5'></a> ### Exercise 5 - L_model_forward Implement the forward propagation of the above model. **Instructions**: In the code below, the variable `AL` will denote $A^{[L]} = \sigma(Z^{[L]}) = \sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\hat{Y}$.) **Hints**: - Use the functions you've previously written - Use a for loop to replicate [LINEAR->RELU] (L-1) times - Don't forget to keep track of the caches in the "caches" list. To add a new value `c` to a `list`, you can use `list.append(c)`. ``` # GRADED FUNCTION: L_model_forward def L_model_forward(X, parameters): """ Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Returns: AL -- activation value from the output (last) layer caches -- list of caches containing: every cache of linear_activation_forward() (there are L of them, indexed from 0 to L-1) """ caches = [] A = X L = len(parameters) // 2 # number of layers in the neural network # Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list. # The for loop starts at 1 because layer 0 is the input for l in range(1, L): A_prev = A #(≈ 2 lines of code) # A, cache = ... # caches ... # YOUR CODE STARTS HERE A, cache = linear_activation_forward(A_prev, parameters["W" + str(l)], parameters["b" + str(l)], activation = "relu") caches.append(cache) # YOUR CODE ENDS HERE # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list. #(≈ 2 lines of code) # AL, cache = ... # caches ... # YOUR CODE STARTS HERE AL, cache = linear_activation_forward(A, parameters["W" + str(L)], parameters["b" + str(L)], activation = "sigmoid") caches.append(cache) # YOUR CODE ENDS HERE return AL, caches t_X, t_parameters = L_model_forward_test_case_2hidden() t_AL, t_caches = L_model_forward(t_X, t_parameters) print("AL = " + str(t_AL)) L_model_forward_test(L_model_forward) ``` ***Expected output*** ``` AL = [[0.03921668 0.70498921 0.19734387 0.04728177]] ``` **Awesome!** You've implemented a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in "caches". Using $A^{[L]}$, you can compute the cost of your predictions. <a name='5'></a> ## 5 - Cost Function Now you can implement forward and backward propagation! You need to compute the cost, in order to check whether your model is actually learning. <a name='ex-6'></a> ### Exercise 6 - compute_cost Compute the cross-entropy cost $J$, using the following formula: $$-\frac{1}{m} \sum\limits_{i = 1}^{m} (y^{(i)}\log\left(a^{[L] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right)) \tag{7}$$ ``` # GRADED FUNCTION: compute_cost def compute_cost(AL, Y): """ Implement the cost function defined by equation (7). Arguments: AL -- probability vector corresponding to your label predictions, shape (1, number of examples) Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples) Returns: cost -- cross-entropy cost """ m = Y.shape[1] # Compute loss from aL and y. # (≈ 1 lines of code) # cost = ... # YOUR CODE STARTS HERE cost = -(np.dot(np.log(AL), Y.T) + np.dot(np.log(1-AL), (1-Y).T)) / m # YOUR CODE ENDS HERE cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17). return cost t_Y, t_AL = compute_cost_test_case() t_cost = compute_cost(t_AL, t_Y) print("Cost: " + str(t_cost)) compute_cost_test(compute_cost) ``` **Expected Output**: <table> <tr> <td><b>cost</b> </td> <td> 0.2797765635793422</td> </tr> </table> <a name='6'></a> ## 6 - Backward Propagation Module Just as you did for the forward propagation, you'll implement helper functions for backpropagation. Remember that backpropagation is used to calculate the gradient of the loss function with respect to the parameters. **Reminder**: <img src="images/backprop_kiank.png" style="width:650px;height:250px;"> <caption><center><font color='purple'><b>Figure 3</b>: Forward and Backward propagation for LINEAR->RELU->LINEAR->SIGMOID <br> <i>The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.</font></center></caption> <!-- For those of you who are experts in calculus (which you don't need to be to do this assignment!), the chain rule of calculus can be used to derive the derivative of the loss $\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows: $$\frac{d \mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \frac{d\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\frac{{da^{[2]}}}{{dz^{[2]}}}\frac{{dz^{[2]}}}{{da^{[1]}}}\frac{{da^{[1]}}}{{dz^{[1]}}} \tag{8} $$ In order to calculate the gradient $dW^{[1]} = \frac{\partial L}{\partial W^{[1]}}$, use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial W^{[1]}}$. During backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted. Equivalently, in order to calculate the gradient $db^{[1]} = \frac{\partial L}{\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial b^{[1]}}$. This is why we talk about **backpropagation**. !--> Now, similarly to forward propagation, you're going to build the backward propagation in three steps: 1. LINEAR backward 2. LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation 3. [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model) For the next exercise, you will need to remember that: - `b` is a matrix(np.ndarray) with 1 column and n rows, i.e: b = [[1.0], [2.0]] (remember that `b` is a constant) - np.sum performs a sum over the elements of a ndarray - axis=1 or axis=0 specify if the sum is carried out by rows or by columns respectively - keepdims specifies if the original dimensions of the matrix must be kept. - Look at the following example to clarify: ``` A = np.array([[1, 2], [3, 4]]) print('axis=1 and keepdims=True') print(np.sum(A, axis=1, keepdims=True)) print('axis=1 and keepdims=False') print(np.sum(A, axis=1, keepdims=False)) print('axis=0 and keepdims=True') print(np.sum(A, axis=0, keepdims=True)) print('axis=0 and keepdims=False') print(np.sum(A, axis=0, keepdims=False)) ``` <a name='6-1'></a> ### 6.1 - Linear Backward For layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation). Suppose you have already calculated the derivative $dZ^{[l]} = \frac{\partial \mathcal{L} }{\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$. <img src="images/linearback_kiank.png" style="width:250px;height:300px;"> <caption><center><font color='purple'><b>Figure 4</b></font></center></caption> The three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$. Here are the formulas you need: $$ dW^{[l]} = \frac{\partial \mathcal{J} }{\partial W^{[l]}} = \frac{1}{m} dZ^{[l]} A^{[l-1] T} \tag{8}$$ $$ db^{[l]} = \frac{\partial \mathcal{J} }{\partial b^{[l]}} = \frac{1}{m} \sum_{i = 1}^{m} dZ^{[l](i)}\tag{9}$$ $$ dA^{[l-1]} = \frac{\partial \mathcal{L} }{\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \tag{10}$$ $A^{[l-1] T}$ is the transpose of $A^{[l-1]}$. <a name='ex-7'></a> ### Exercise 7 - linear_backward Use the 3 formulas above to implement `linear_backward()`. **Hint**: - In numpy you can get the transpose of an ndarray `A` using `A.T` or `A.transpose()` ``` # GRADED FUNCTION: linear_backward def linear_backward(dZ, cache): """ Implement the linear portion of backward propagation for a single layer (layer l) Arguments: dZ -- Gradient of the cost with respect to the linear output (of current layer l) cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer Returns: dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the cost with respect to W (current layer l), same shape as W db -- Gradient of the cost with respect to b (current layer l), same shape as b """ A_prev, W, b = cache m = A_prev.shape[1] ### START CODE HERE ### (≈ 3 lines of code) # dW = ... # db = ... sum by the rows of dZ with keepdims=True # dA_prev = ... # YOUR CODE STARTS HERE dW = np.dot(dZ, A_prev.T) / m db = np.sum(dZ, axis=1, keepdims=True) / m dA_prev = np.dot(W.T, dZ) # YOUR CODE ENDS HERE return dA_prev, dW, db t_dZ, t_linear_cache = linear_backward_test_case() t_dA_prev, t_dW, t_db = linear_backward(t_dZ, t_linear_cache) print("dA_prev: " + str(t_dA_prev)) print("dW: " + str(t_dW)) print("db: " + str(t_db)) linear_backward_test(linear_backward) ``` **Expected Output**: ``` dA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712] [ 0.60345879 -3.72508701 5.81700741 -3.84326836] [-0.4319552 -1.30987417 1.72354705 0.05070578] [-0.38981415 0.60811244 -1.25938424 1.47191593] [-2.52214926 2.67882552 -0.67947465 1.48119548]] dW: [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716] [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808] [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]] db: [[-0.14713786] [-0.11313155] [-0.13209101]] ``` <a name='6-2'></a> ### 6.2 - Linear-Activation Backward Next, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. To help you implement `linear_activation_backward`, two backward functions have been provided: - **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows: ```python dZ = sigmoid_backward(dA, activation_cache) ``` - **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows: ```python dZ = relu_backward(dA, activation_cache) ``` If $g(.)$ is the activation function, `sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}). \tag{11}$$ <a name='ex-8'></a> ### Exercise 8 - linear_activation_backward Implement the backpropagation for the *LINEAR->ACTIVATION* layer. ``` # GRADED FUNCTION: linear_activation_backward def linear_activation_backward(dA, cache, activation): """ Implement the backward propagation for the LINEAR->ACTIVATION layer. Arguments: dA -- post-activation gradient for current layer l cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu" Returns: dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev dW -- Gradient of the cost with respect to W (current layer l), same shape as W db -- Gradient of the cost with respect to b (current layer l), same shape as b """ linear_cache, activation_cache = cache if activation == "relu": #(≈ 2 lines of code) # dZ = ... # dA_prev, dW, db = ... # YOUR CODE STARTS HERE dZ = relu_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) # YOUR CODE ENDS HERE elif activation == "sigmoid": #(≈ 2 lines of code) # dZ = ... # dA_prev, dW, db = ... # YOUR CODE STARTS HERE dZ = sigmoid_backward(dA, activation_cache) dA_prev, dW, db = linear_backward(dZ, linear_cache) # YOUR CODE ENDS HERE return dA_prev, dW, db t_dAL, t_linear_activation_cache = linear_activation_backward_test_case() t_dA_prev, t_dW, t_db = linear_activation_backward(t_dAL, t_linear_activation_cache, activation = "sigmoid") print("With sigmoid: dA_prev = " + str(t_dA_prev)) print("With sigmoid: dW = " + str(t_dW)) print("With sigmoid: db = " + str(t_db)) t_dA_prev, t_dW, t_db = linear_activation_backward(t_dAL, t_linear_activation_cache, activation = "relu") print("With relu: dA_prev = " + str(t_dA_prev)) print("With relu: dW = " + str(t_dW)) print("With relu: db = " + str(t_db)) linear_activation_backward_test(linear_activation_backward) ``` **Expected output:** ``` With sigmoid: dA_prev = [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] With sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]] With sigmoid: db = [[-0.05729622]] With relu: dA_prev = [[ 0.44090989 0. ] [ 0.37883606 0. ] [-0.2298228 0. ]] With relu: dW = [[ 0.44513824 0.37371418 -0.10478989]] With relu: db = [[-0.20837892]] ``` <a name='6-3'></a> ### 6.3 - L-Model Backward Now you will implement the backward function for the whole network! Recall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you'll use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you'll iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. <img src="images/mn_backward.png" style="width:450px;height:300px;"> <caption><center><font color='purple'><b>Figure 5</b>: Backward pass</font></center></caption> **Initializing backpropagation**: To backpropagate through this network, you know that the output is: $A^{[L]} = \sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \frac{\partial \mathcal{L}}{\partial A^{[L]}}$. To do so, use this formula (derived using calculus which, again, you don't need in-depth knowledge of!): ```python dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL ``` You can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : $$grads["dW" + str(l)] = dW^{[l]}\tag{15} $$ For example, for $l=3$ this would store $dW^{[l]}$ in `grads["dW3"]`. <a name='ex-9'></a> ### Exercise 9 - L_model_backward Implement backpropagation for the *[LINEAR->RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model. ``` # GRADED FUNCTION: L_model_backward def L_model_backward(AL, Y, caches): """ Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) caches -- list of caches containing: every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2) the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1]) Returns: grads -- A dictionary with the gradients grads["dA" + str(l)] = ... grads["dW" + str(l)] = ... grads["db" + str(l)] = ... """ grads = {} L = len(caches) # the number of layers m = AL.shape[1] Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL # Initializing the backpropagation #(1 line of code) # dAL = ... # YOUR CODE STARTS HERE dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # YOUR CODE ENDS HERE # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "dAL, current_cache". Outputs: "grads["dAL-1"], grads["dWL"], grads["dbL"] #(approx. 5 lines) # current_cache = ... # dA_prev_temp, dW_temp, db_temp = ... # grads["dA" + str(L-1)] = ... # grads["dW" + str(L)] = ... # grads["db" + str(L)] = ... # YOUR CODE STARTS HERE current_cache = caches[L-1] dA_prev_temp, dW_temp, db_temp = linear_activation_backward(dAL, current_cache, "sigmoid") grads["dA" + str(L-1)] = dA_prev_temp grads["dW" + str(L)] = dW_temp grads["db" + str(L)] = db_temp # YOUR CODE ENDS HERE # Loop from l=L-2 to l=0 for l in reversed(range(L-1)): # lth layer: (RELU -> LINEAR) gradients. # Inputs: "grads["dA" + str(l + 1)], current_cache". Outputs: "grads["dA" + str(l)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)] #(approx. 5 lines) # current_cache = ... # dA_prev_temp, dW_temp, db_temp = ... # grads["dA" + str(l)] = ... # grads["dW" + str(l + 1)] = ... # grads["db" + str(l + 1)] = ... # YOUR CODE STARTS HERE current_cache = caches[l] dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l+1)], current_cache, "relu") grads["dA" + str(l)] = dA_prev_temp grads["dW" + str(l+1)] = dW_temp grads["db" + str(l+1)] = db_temp # YOUR CODE ENDS HERE return grads t_AL, t_Y_assess, t_caches = L_model_backward_test_case() grads = L_model_backward(t_AL, t_Y_assess, t_caches) print("dA0 = " + str(grads['dA0'])) print("dA1 = " + str(grads['dA1'])) print("dW1 = " + str(grads['dW1'])) print("dW2 = " + str(grads['dW2'])) print("db1 = " + str(grads['db1'])) print("db2 = " + str(grads['db2'])) L_model_backward_test(L_model_backward) ``` **Expected output:** ``` dA0 = [[ 0. 0.52257901] [ 0. -0.3269206 ] [ 0. -0.32070404] [ 0. -0.74079187]] dA1 = [[ 0.12913162 -0.44014127] [-0.14175655 0.48317296] [ 0.01663708 -0.05670698]] dW1 = [[0.41010002 0.07807203 0.13798444 0.10502167] [0. 0. 0. 0. ] [0.05283652 0.01005865 0.01777766 0.0135308 ]] dW2 = [[-0.39202432 -0.13325855 -0.04601089]] db1 = [[-0.22007063] [ 0. ] [-0.02835349]] db2 = [[0.15187861]] ``` <a name='6-4'></a> ### 6.4 - Update Parameters In this section, you'll update the parameters of the model, using gradient descent: $$ W^{[l]} = W^{[l]} - \alpha \text{ } dW^{[l]} \tag{16}$$ $$ b^{[l]} = b^{[l]} - \alpha \text{ } db^{[l]} \tag{17}$$ where $\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary. <a name='ex-10'></a> ### Exercise 10 - update_parameters Implement `update_parameters()` to update your parameters using gradient descent. **Instructions**: Update parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$. ``` # GRADED FUNCTION: update_parameters def update_parameters(params, grads, learning_rate): """ Update parameters using gradient descent Arguments: params -- python dictionary containing your parameters grads -- python dictionary containing your gradients, output of L_model_backward Returns: parameters -- python dictionary containing your updated parameters parameters["W" + str(l)] = ... parameters["b" + str(l)] = ... """ parameters = params.copy() L = len(parameters) // 2 # number of layers in the neural network # Update rule for each parameter. Use a for loop. #(≈ 2 lines of code) for l in range(L): # parameters["W" + str(l+1)] = ... # parameters["b" + str(l+1)] = ... # YOUR CODE STARTS HERE parameters["W" + str(l+1)] = params["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)] parameters["b" + str(l+1)] = params["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)] # YOUR CODE ENDS HERE return parameters t_parameters, grads = update_parameters_test_case() t_parameters = update_parameters(t_parameters, grads, 0.1) print ("W1 = "+ str(t_parameters["W1"])) print ("b1 = "+ str(t_parameters["b1"])) print ("W2 = "+ str(t_parameters["W2"])) print ("b2 = "+ str(t_parameters["b2"])) update_parameters_test(update_parameters) ``` **Expected output:** ``` W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008] [-1.76569676 -0.80627147 0.51115557 -1.18258802] [-1.0535704 -0.86128581 0.68284052 2.20374577]] b1 = [[-0.04659241] [-1.28888275] [ 0.53405496]] W2 = [[-0.55569196 0.0354055 1.32964895]] b2 = [[-0.84610769]] ``` ### Congratulations! You've just implemented all the functions required for building a deep neural network, including: - Using non-linear units improve your model - Building a deeper neural network (with more than 1 hidden layer) - Implementing an easy-to-use neural network class This was indeed a long assignment, but the next part of the assignment is easier. ;) In the next assignment, you'll be putting all these together to build two models: - A two-layer neural network - An L-layer neural network You will in fact use these models to classify cat vs non-cat images! (Meow!) Great work and see you next time.
github_jupyter
``` import os import numpy as np from torch.utils.data import DataLoader from torchvision import transforms as T import cv2 import pandas as pd from self_sup_data.chest_xray import SelfSupChestXRay from model.resnet import resnet18_enc_dec from train_chest_xray import SETTINGS from experiments.chest_xray_tasks import test_real_anomalies def test(test_dat, setting, device, preact=False, pool=True, final=True, show=True, plots=False): if final: fname = os.path.join(model_dir, setting.get('out_dir'), 'final_' + setting.get('fname')) else: fname = os.path.join(model_dir, setting.get('out_dir'), setting.get('fname')) print(fname) if not os.path.exists(fname): return np.nan, np.nan model = resnet18_enc_dec(num_classes=1, preact=preact, pool=pool, in_channels=1, final_activation=setting.get('final_activation')).to(device) if final: model.load_state_dict(torch.load(fname)) else: model.load_state_dict(torch.load(fname).get('model_state_dict')) if plots: sample_ap, sample_auroc, fig = test_real_anomalies(model, test_dat, device=device, batch_size=16, show=show, full_size=True) fig.savefig(os.path.join(out_dir, setting.get('fname')[:-3] + '.png')) plt.close(fig) else: sample_ap, sample_auroc, _ = test_real_anomalies(model, test_dat, device=device, batch_size=16, show=show, plots=plots, full_size=True) return sample_ap, sample_auroc model_dir = 'put/your/path/here' if not os.path.exists(model_dir): os.makedirs(model_dir) out_dir = 'put/your/path/here' if not os.path.exists(out_dir): os.makedirs(out_dir) data_dir = 'put/your/path/here' device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f'Using {device}') ``` # Evaluation for male PA ``` with open('self_sup_data/chest_xray_lists/norm_MaleAdultPA_test_curated_list.txt', "r") as f: normal_test_files = f.read().splitlines() with open('self_sup_data/chest_xray_lists/anomaly_MaleAdultPA_test_curated_list.txt', "r") as f: anom_test_files = f.read().splitlines() modes = list(SETTINGS.keys()) sample_ap_df = pd.DataFrame(columns=modes) sample_auroc_df = pd.DataFrame(columns=modes) test_dat = SelfSupChestXRay(data_dir=data_dir, normal_files=normal_test_files, anom_files=anom_test_files, is_train=False, res=256, transform=T.CenterCrop(224)) sample_aps, sample_aurocs = {}, {} for mode in modes: sample_aps[mode], sample_aurocs[mode] = test( test_dat, SETTINGS.get(mode), device, preact=False, pool=True, final=True) sample_ap_df = sample_ap_df.append(sample_aps, ignore_index=True).transpose() sample_auroc_df = sample_auroc_df.append(sample_aurocs, ignore_index=True).transpose() pd.options.display.float_format = '{:3.1f}'.format sample_table = 100 * sample_auroc_df.transpose() cols_shift = sample_table.loc[: , 'Shift-M':'Shift-M-123425'] cols_shift_int = sample_table.loc[: , 'Shift-Intensity-M':'Shift-Intensity-M-123425'] cols_shift_raw_int = sample_table.loc[: , 'Shift-Raw-Intensity-M':'Shift-Raw-Intensity-M-123425'] cols_pii = sample_table.loc[: , 'FPI-Poisson':'FPI-Poisson-123425'] merge_func = lambda x: r'{:3.1f} {{\tiny $\pm$ {:3.1f}}}'.format(*x) sample_table['Shift'] = list(map(merge_func, zip(cols_shift.mean(axis=1), cols_shift.std(axis=1)))) sample_table['Shift-Intensity'] = list(map(merge_func, zip(cols_shift_int.mean(axis=1), cols_shift_int.std(axis=1)))) sample_table['Shift-Raw-Intensity'] = list(map(merge_func, zip(cols_shift_raw_int.mean(axis=1), cols_shift_raw_int.std(axis=1)))) sample_table['FPI-Poisson'] = list(map(merge_func, zip(cols_pii.mean(axis=1), cols_pii.std(axis=1)))) sample_table = sample_table[['CutPaste', 'FPI', 'FPI-Poisson', 'Shift', 'Shift-Raw-Intensity', 'Shift-Intensity']].rename( columns={'Shift':'Ours (binary)', 'Shift-Intensity':'Ours (logistic)', 'Shift-Raw-Intensity':'Ours (continous)'}) print(sample_table.to_latex(escape=False)) sample_table # male ``` # Evaluation for female PA ``` with open('self_sup_data/chest_xray_lists/norm_FemaleAdultPA_test_curated_list.txt', "r") as f: normal_test_files = f.read().splitlines() with open('self_sup_data/chest_xray_lists/anomaly_FemaleAdultPA_test_curated_list.txt', "r") as f: anom_test_files = f.read().splitlines() modes = list(SETTINGS.keys()) sample_ap_df = pd.DataFrame(columns=modes) sample_auroc_df = pd.DataFrame(columns=modes) test_dat = SelfSupChestXRay(data_dir=data_dir, normal_files=normal_test_files, anom_files=anom_test_files, is_train=False, res=256, transform=T.CenterCrop(224)) sample_aps, sample_aurocs = {}, {} for mode in modes: sample_aps[mode], sample_aurocs[mode] = test( test_dat, SETTINGS.get(mode), device, preact=False, pool=True, final=True) sample_ap_df = sample_ap_df.append(sample_aps, ignore_index=True).transpose() sample_auroc_df = sample_auroc_df.append(sample_aurocs, ignore_index=True).transpose() pd.options.display.float_format = '{:3.1f}'.format sample_table = 100 * sample_auroc_df.transpose() cols_shift = sample_table.loc[: , 'Shift-M':'Shift-M-123425'] cols_shift_int = sample_table.loc[: , 'Shift-Intensity-M':'Shift-Intensity-M-123425'] cols_shift_raw_int = sample_table.loc[: , 'Shift-Raw-Intensity-M':'Shift-Raw-Intensity-M-123425'] cols_pii = sample_table.loc[: , 'FPI-Poisson':'FPI-Poisson-123425'] merge_func = lambda x: r'{:3.1f} {{\tiny $\pm$ {:3.1f}}}'.format(*x) sample_table['Shift'] = list(map(merge_func, zip(cols_shift.mean(axis=1), cols_shift.std(axis=1)))) sample_table['Shift-Intensity'] = list(map(merge_func, zip(cols_shift_int.mean(axis=1), cols_shift_int.std(axis=1)))) sample_table['Shift-Raw-Intensity'] = list(map(merge_func, zip(cols_shift_raw_int.mean(axis=1), cols_shift_raw_int.std(axis=1)))) sample_table['FPI-Poisson'] = list(map(merge_func, zip(cols_pii.mean(axis=1), cols_pii.std(axis=1)))) sample_table = sample_table[['CutPaste', 'FPI', 'FPI-Poisson', 'Shift', 'Shift-Raw-Intensity', 'Shift-Intensity']].rename( columns={'Shift':'Ours (binary)', 'Shift-Intensity':'Ours (logistic)', 'Shift-Raw-Intensity':'Ours (continous)'}) print(sample_table.to_latex(escape=False)) sample_table # female ```
github_jupyter
# Trumpler 1930 Dust Extinction Figure 6.2 from Chapter 6 of *Interstellar and Intergalactic Medium* by Ryden & Pogge, 2021, Cambridge University Press. Data are from [Trumpler, R. 1930, Lick Observatory Bulletin #420, 14, 154](https://ui.adsabs.harvard.edu/abs/1930LicOB..14..154T), Table 3. The extinction curve derived uses a different normalization in the bulletin paper than in the oft-reproduced figure from the Trumpler 1930 PASP paper ([Trumpler, R. 1930, PASP, 42, 267](https://ui.adsabs.harvard.edu/abs/1930PASP...42..267T), Figure 1). Table 3 gives distances and linear diameters to open star clusters. We've created two data files: * Trumpler_GoodData.txt - Unflagged * Trumpler_BadData.txt - Trumpler's "somewhat uncertain or less reliable" data, designed by the entry being printed in italics in Table 3. The distances we use are from Table 3 column 8 ("Obs."distance from spectral types) and column 10 ("from diam."), both converted to kiloparsecs. ``` %matplotlib inline import os import sys import math import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, LogLocator, NullFormatter import warnings warnings.filterwarnings('ignore',category=UserWarning, append=True) ``` ## Standard Plot Format Setup the standard plotting format and make the plot. Fonts and resolution adopted follow CUP style. ``` figName = 'Fig6_2' # graphic aspect ratio = width/height aspect = 4.0/3.0 # 4:3 # Text width in inches - don't change, this is defined by the print layout textWidth = 6.0 # inches # output format and resolution figFmt = 'png' dpi = 600 # Graphic dimensions plotWidth = dpi*textWidth plotHeight = plotWidth/aspect axisFontSize = 10 labelFontSize = 6 lwidth = 0.5 axisPad = 5 wInches = textWidth hInches = wInches/aspect # Plot filename plotFile = f'{figName}.{figFmt}' # LaTeX is used throughout for markup of symbols, Times-Roman serif font plt.rc('text', usetex=True) plt.rc('font', **{'family':'serif','serif':['Times-Roman'],'weight':'bold','size':'16'}) # Font and line weight defaults for axes matplotlib.rc('axes',linewidth=lwidth) matplotlib.rcParams.update({'font.size':axisFontSize}) # axis and label padding plt.rcParams['xtick.major.pad'] = f'{axisPad}' plt.rcParams['ytick.major.pad'] = f'{axisPad}' plt.rcParams['axes.labelpad'] = f'{axisPad}' ``` ## Trumpler (1930) Data and Extinction Curve The data are derived from the Table 3 in Trumpler 1930, converted to modern units of kiloparsecs. We've divided the data into two files based on Trumpler's 2-fold division of the data into reliable and ""somewhat uncertain or less reliable", which we abbreviate as "good" and "bad", respectively. This is the division used for Trumpler's original diagram. The Trumpler extintion curve is of the form: $$ d_{L} = d_{A} e^{\kappa d_{A}/2}$$ where the extinction coefficient plotted is $\kappa=0.6$kpc$^{-1}$, plotted as a dashed line. ``` # Good data data = pd.read_csv('Trumpler_GoodData.txt',sep=r'\s+',comment='#') dLgood = np.array(data['dL']) # luminosity distance dAgood = np.array(data['dA']) # angular diameter distance # Bad data data = pd.read_csv('Trumpler_BadData.txt',sep=r'\s+',comment='#') dLbad = np.array(data['dL']) # luminosity distance dAbad = np.array(data['dA']) # angular diameter distance # Trumpler extinction curve k = 0.6 # kpc^-1 [modern units] dAext = np.linspace(0.0,4.0,401) dLext = dAext*np.exp(k*dAext/2) ``` ## Cluster angular diameter distance vs. luminosity distance Plot open cluster angular distance against luminosity distance (what Trumpler called "photometric distance"). Good data are ploted as filled circles, the bad (less-reliable) data are plotted as open circles. The unextincted 1:1 relation is plotted as a dotted line. ``` fig,ax = plt.subplots() fig.set_dpi(dpi) fig.set_size_inches(wInches,hInches,forward=True) ax.tick_params('both',length=6,width=lwidth,which='major',direction='in',top='on',right='on') ax.tick_params('both',length=3,width=lwidth,which='minor',direction='in',top='on',right='on') # Limits ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_minor_locator(MultipleLocator(0.2)) ax.set_xlabel(r'Luminosity distance [kpc]') ax.set_xlim(0,5) ax.yaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_minor_locator(MultipleLocator(0.2)) ax.set_ylabel(r'Angular diameter distance [kpc]') ax.set_ylim(0,4) plt.plot(dLgood,dAgood,'o',mfc='black',mec='black',ms=3,zorder=10,mew=0.5) plt.plot(dLbad,dAbad,'o',mfc='white',mec='black',ms=3,zorder=9,mew=0.5) plt.plot([0,4],[0,4],':',color='black',lw=1,zorder=5) plt.plot(dLext,dAext,'--',color='black',lw=1,zorder=7) plt.plot() plt.savefig(plotFile,bbox_inches='tight',facecolor='white') ```
github_jupyter
``` #Mounts your google drive into this virtual machine from google.colab import drive, files import sys drive.mount('/content/drive') #Now we need to access the files downloaded, copy the path where you saved the files downloaded from the github repo and paste below sys.path.append('/content/drive/MyDrive/YOURPATH/SignalValidation/') %cd /content/drive/MyDrive/YOURPATH/SignalValidation/ !pip install neurokit2 !pip install mne !pip install --upgrade pandas %matplotlib inline import signal_formatpeaks import time import numpy as np import pandas as pd import matplotlib import neurokit2 as nk import mne import matplotlib.pyplot as plt import os import random from sklearn.cross_decomposition import CCA from scipy import signal from scipy.signal import butter, lfilter from scipy.fft import fft, fftfreq, ifft import pickle plt.rcParams['figure.figsize'] = [30, 20] ``` ## **Offline EOG data visualization and processing** ``` data = pd.read_csv('/content/drive/MyDrive/YOURPATH/SharedPublicly/Data/Blink_EOG_RAW-2021-09-03_12-03-27.txt',header=4 ,sep=r'\s*,\s*',engine='python') data.columns = ["Sample Index", "EMG Channel 0", "EMG Channel 1", "EMG Channel 2", "EMG Channel 3", "EOG Channel 0", "EOG Channel 1", "EEG Channel 0", "EEG Channel 1", "EEG Channel 2", "EEG Channel 3", "EEG Channel 4", "EEG Channel 5", "EEG Channel 6", "EEG Channel 7", "EEG Channel 8", "EEG Channel 9", "PPG Channel 0", "PPG Channel 1", "EDA_Channel_0", "Other", "Raw PC Timestamp", "Raw Device Timestamp", "Other.1", "Timestamp", "Marker", "Timestamp (Formatted)"] data def eog_process_detrend(veog_signal, sampling_rate=1000, **kwargs): """Process an EOG signal. Convenience function that automatically processes an EOG signal. Parameters ---------- veog_signal : Union[list, np.array, pd.Series] The raw vertical EOG channel. Note that it must be positively oriented, i.e., blinks must appear as upward peaks. sampling_rate : int The sampling frequency of `eog_signal` (in Hz, i.e., samples/second). Defaults to 1000. **kwargs Other arguments passed to other functions. Returns ------- signals : DataFrame A DataFrame of the same length as the `eog_signal` containing the following columns: - *"EOG_Raw"*: the raw signal. - *"EOG_Clean"*: the cleaned signal. - *"EOG_Blinks"*: the blinks marked as "1" in a list of zeros. - *"EOG_Rate"*: eye blinks rate interpolated between blinks. info : dict A dictionary containing the samples at which the eye blinks occur, accessible with the key "EOG_Blinks" as well as the signals' sampling rate. See Also -------- eog_clean, eog_findpeaks Examples -------- >>> import neurokit2 as nk >>> >>> # Get data >>> eog_signal = nk.data('eog_100hz') >>> >>> signals, info = nk.eog_process(eog_signal, sampling_rate=100) References ---------- - Agarwal, M., & Sivakumar, R. (2019, September). Blink: A Fully Automated Unsupervised Algorithm for Eye-Blink Detection in EEG Signals. In 2019 57th Annual Allerton Conference on Communication, Control, and Computing (Allerton) (pp. 1113-1121). IEEE. """ # Sanitize input eog_signal = nk.as_vector(veog_signal) # Clean signal # eog_cleaned = eog_clean(eog_signal, sampling_rate=sampling_rate, **kwargs) eog_cleaned = nk.signal_detrend(eog_signal) eog_cleaned = nk.signal_filter(eog_cleaned, lowcut=0.05, highcut=100) eog_cleaned = eog_cleaned - np.mean(eog_cleaned) eog_signal = eog_signal - np.mean(eog_signal) # Find peaks peaks = nk.eog_findpeaks(eog_cleaned, sampling_rate=sampling_rate, **kwargs) info = {"EOG_Blinks": peaks} info['sampling_rate'] = sampling_rate # Add sampling rate in dict info # Mark (potential) blink events signal_blinks = signal_formatpeaks._signal_from_indices(peaks, desired_length=len(eog_cleaned)) # Rate computation rate = nk.signal_rate(peaks, sampling_rate=sampling_rate, desired_length=len(eog_cleaned)) # Prepare output signals = pd.DataFrame( {"EOG_Raw": eog_signal, "EOG_Clean": eog_cleaned, "EOG_Blinks": signal_blinks, "EOG_Rate": rate} ) return signals, info #Collect and process EOG eog_signal =data["EOG Channel 0"] eog_signal = nk.as_vector(eog_signal) # Extract the only column as a vector signals2, info = eog_process_detrend(eog_signal[1250:], sampling_rate=250) #make sure to split eog_signal correctly plt.rcParams['figure.figsize'] = [10, 5] plot = nk.eog_plot(signals2, info, sampling_rate=250) path = '/content/drive/MyDrive/YOURPATH/SharedPublicly/Figures' image_format = 'eps' # e.g .png, .svg, etc. image_name = 'galea_eog.eps' plot.savefig(path+image_name, format=image_format, dpi=1200) plt.tight_layout() plt.rcParams['figure.figsize'] = [15, 2] nk.signal_plot(signals2.EOG_Clean) ``` ### Signal Validation ``` #Difference in Power Spectrum print("PSD Closed vs. Open difference", np.mean(avg_psds_close) - np.mean(avg_psds_open)) #Computing EOG SNR: mean_Pow_signal = [] mean_Pow_background = [] d = signals2['EOG_Clean'].to_numpy() #Compute fourier transform N = d.shape[-1] Fs = 250 dt = 1/Fs T = N*dt df = Fs/N X = fft(d)/N #fourier spectrum #Compute power from fourier spectrum Pow = np.abs(X)**2 freq = df*np.arange(N) mean_Pow_signal = np.mean(Pow[(freq<10)]) mean_Pow_background = np.mean(Pow[(freq>10)]) print("EOG SNR: ", 10*np.log10((mean_Pow_signal-mean_Pow_background)/mean_Pow_background)) ```
github_jupyter
``` import numpy as np import tensorflow as tf from tensorflow import keras import pandas as pd import seaborn as sns from pylab import rcParams import matplotlib.pyplot as plt from matplotlib import rc from pandas.plotting import register_matplotlib_converters from sklearn.model_selection import train_test_split import urllib import os import csv import cv2 import time from PIL import Image from keras_retinanet import models from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image from keras_retinanet.utils.visualization import draw_box, draw_caption from keras_retinanet.utils.colors import label_color PATH = '/home/kimsoohyun/00-Research/02-Graph/02-image_detection/04-clickable/dataset/03-models/retinanet/resnet50_csv_49.h5' model = models.load_model(PATH) import numpy as np import tensorflow as tf from tensorflow import keras model.save('my_model') reconstructed_model = models.load_model("my_model") import tensorflow as tf import shutil import os # Helper For getting the model Size import os from tensorflow.python import ops def get_size(model_dir, model_file='saved_model.pb'): model_file_path = os.path.join(model_dir, model_file) print(model_file_path, '') pb_size = os.path.getsize(model_file_path) variables_size = 0 if os.path.exists( os.path.join(model_dir,'variables/variables.data-00000-of-00001')): variables_size = os.path.getsize(os.path.join( model_dir,'variables/variables.data-00000-of-00001')) variables_size += os.path.getsize(os.path.join( model_dir,'variables/variables.index')) print('Model size: {} KB'.format(round(pb_size/(1024.0),3))) print('Variables size: {} KB'.format(round( variables_size/(1024.0),3))) print('Total Size: {} KB'.format(round((pb_size + variables_size)/(1024.0),3))) # To Freeze the Saved Model # We need to freeze the model to do further optimisation on it from tensorflow.python.saved_model import tag_constants from tensorflow.python.tools import freeze_graph from tensorflow.python import ops from tensorflow.tools.graph_transforms import TransformGraph def freeze_model(saved_model_dir, output_node_names, output_filename): output_graph_filename = os.path.join(saved_model_dir, output_filename) initializer_nodes = '' freeze_graph.freeze_graph( input_saved_model_dir=saved_model_dir, output_graph=output_graph_filename, saved_model_tags = tag_constants.SERVING, output_node_names=output_node_names, initializer_nodes=initializer_nodes, input_graph=None, input_saver=False, input_binary=False, input_checkpoint=None, restore_op_name=None, filename_tensor_name=None, clear_devices=True, input_meta_graph=False, ) ```
github_jupyter
``` from os.path import join, dirname from os import listdir import numpy as np import pandas as pd # GUI library import panel as pn import panel.widgets as pnw # Chart libraries from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Legend from bokeh.palettes import Spectral5, Set2 from bokeh.events import SelectionGeometry # Dimensionality reduction from sklearn.decomposition import PCA from sklearn.manifold import MDS from sklearn.preprocessing import StandardScaler, LabelEncoder # from shapely.geometry import MultiPoint, MultiLineString, Polygon, MultiPolygon, LineString from shapely.ops import unary_union from shapely.ops import triangulate # local scripts from Embedding.Rangeset import Rangeset pn.extension() ``` # Parameters ``` l = str(len(pd.read_csv('data/BLI_30102020171001105.csv'))) dataset_name = l bins = 5 show_labels = True labels_column = 'index' overview_height = 700 small_multiples_ncols = 3 histogram_width = 250 show_numpy_histogram = True rangeset_threshold = 1 ``` # Load data ``` from bokeh.sampledata.iris import flowers df = flowers label_encoder = LabelEncoder().fit(df.species) df['class'] = label_encoder.transform(df.species) ``` # Preprocessing ``` # attributes to be included in the overlays selected_var = list(df.columns[:-2]) + ['class'] #selected_var = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'projection quality'] # custom selection # maximal slider range and step size # {'variable_name': (min,max,stepsize)} custom_range = {'projection quality': (0,1,0.01)} # custom min/max settings for sliders # {'variable_name': (min,max)} default_range = {'projection quality': (0.4,0.9)} # which variables to use for the embedding selected_var_embd = selected_var[:-1] # set up embedding #embedding = PCA(n_components=2) embedding = MDS(n_components=2, random_state=42) scaler = StandardScaler() X_scaled = scaler.fit_transform(df[selected_var_embd]) # some projections change the original data, so we make a copy # this can cost a lot of memory for large data X = X_scaled.copy() pp = embedding.fit_transform(X) x_range = pp[:,0].max() - pp[:,0].min() y_range = pp[:,1].max() - pp[:,1].min() # keep the aspect ration of the projected data overview_width = int(overview_height * x_range / y_range) histogram_height = int(histogram_width * y_range / x_range) from Embedding.ProjectionQuality import projection_quality df['projection quality'] = projection_quality(X_scaled, pp) selected_var += ['projection quality'] rangeset = Rangeset(pp, df) rangeset.threshold = rangeset_threshold rangeset.size_inside = 8 rangeset.size_outside = 12 ``` # GUI ## Vis elements **overview chart** shows a large version of the embedding ``` TOOLS = "pan,wheel_zoom,box_zoom,box_select,lasso_select,help,reset,save" overview = figure(tools=TOOLS, width=overview_width, height=overview_height, active_drag="lasso_select") overview.scatter(x=pp[:,0], y=pp[:,1], color="#333333", muted_alpha=0, size=7, level='underlay', name='points', line_color=None, legend_label='data') if show_labels: labels = df.index.astype(str) if labels_column == 'index' else df[labels_column].astype(str) overview.text(x=pp[:,0], y=pp[:,1], text=labels, legend_label='labels', font_size="10pt", x_offset=5, y_offset=5, muted_alpha=0, text_baseline="middle", text_align="left", color='#666666', level='glyph') source_selection = ColumnDataSource({'x': [], 'y': []}) overview.patch(source=source_selection, x='x', y='y', fill_color=None, line_width=4, line_color='#aaaaaa', level='annotation') overview.legend.location = 'bottom_right' overview.legend.label_height=1 overview.legend.click_policy='mute' overview.legend.visible = True overview.outline_line_color = None overview.xgrid.visible = False overview.ygrid.visible = False overview.xaxis.visible = False overview.yaxis.visible = False overview.toolbar.logo = None # Check the embedding with the code below # pn.Row(overview) ``` **small multiples** charts are created upon request ``` def _make_chart( var, df_polys, df_scatter, bounds, cnt_in, cnt_out ): global df xvals = df[var].unique() is_categorical = False if len(xvals) < 10: is_categorical = True xvals = sorted(xvals.astype(str)) global histogram_width p = figure(width=histogram_width, height=histogram_height, title=var) df_scatter['size'] = df_scatter['size'] * histogram_height / overview_height p.multi_polygons(source=df_polys, xs='xs', ys='ys', color='color', fill_alpha=0.5, level='image', line_color=None) p.scatter(source=df_scatter, x='x', y='y', color='color', size='size', level='overlay') global source_selection p.patch(source=source_selection, x='x', y='y', fill_color=None, level='annotation', line_width=2, line_color='#333333') p.xgrid.visible = False p.ygrid.visible = False p.xaxis.visible = False p.yaxis.visible = False p.toolbar.logo = None p.toolbar_location = None p.border_fill_color = '#f0f0f0' p_histo = figure(height=100, width=histogram_width, name='histo') if is_categorical: p_histo = figure(height=100, width=histogram_width, name='histo', x_range=xvals) p_histo.vbar(x=xvals, top=cnt_in, bottom=0, width=0.9, line_color='white', color=rangeset.colormap) p_histo.vbar(x=xvals, top=0, bottom=np.array(cnt_out)*-1, width=0.9, line_color='white', color=rangeset.colormap) else: p_histo.quad(bottom=[0]*len(cnt_in), top=cnt_in, left=bounds[:-1], right=bounds[1:], line_color='white', color=rangeset.colormap) p_histo.quad(bottom=np.array(cnt_out)*(-1), top=[0]*len(cnt_out), left=bounds[:-1], right=bounds[1:], line_color='white', color=rangeset.colormap) df_select = df[df[var] < bounds[0]] p_histo.square(df_select[var], -.5, color=rangeset.colormap[0]) df_select = df[df[var] > bounds[-1]] p_histo.square(df_select[var], -.5, color=rangeset.colormap[-1]) p_histo.toolbar.logo = None p_histo.toolbar_location = None p_histo.xgrid.visible = False p_histo.xaxis.minor_tick_line_color = None p_histo.yaxis.minor_tick_line_color = None p_histo.outline_line_color = None p_histo.border_fill_color = '#f0f0f0' global show_numpy_histogram if show_numpy_histogram: if is_categorical: frequencies, edges = np.histogram(df[var], bins=len(xvals)) p_histo.vbar(x=xvals, bottom=0, width=.5, top=frequencies*-1, line_color='white', color='gray', line_alpha=.5, fill_alpha=0.5) else: frequencies, edges = np.histogram(df[var]) p_histo.quad(bottom=[0]*len(frequencies), top=frequencies*-1, left=edges[:-1], right=edges[1:], line_color='white', color='gray', line_alpha=.5, fill_alpha=0.5) return (p, p_histo) ``` ## Create input widget (buttons, sliders, etc) and layout ``` class MyCheckbox(pnw.Checkbox): variable = "" def __init__(self, variable="", slider=None, **kwds): super().__init__(**kwds) self.variable = variable self.slider = slider def init_slider_values(var): vmin = df[var].min() vmax = df[var].max() step = 0 if var in custom_range: vmin,vmax,step = custom_range[var] value = (vmin,vmax) if var in default_range: value = default_range[var] return (vmin, vmax, step, value) ranges_embd = pn.Column() ranges_aux = pn.Column() sliders = {} def create_slider(var): vmin, vmax, step, value = init_slider_values(var) slider = pnw.RangeSlider(name=var, start=vmin, end=vmax, step=step, value=value) checkbox = MyCheckbox(name='', variable=var, value=False, width=20, slider=slider) return pn.Row(checkbox,slider) for var in selected_var: s = create_slider(var) sliders[var] = s if var in selected_var_embd: ranges_embd.append(s) else: ranges_aux.append(s) selected_var = [] for r in ranges_embd: selected_var.append(r[1].name) for r in ranges_aux: selected_var.append(r[1].name) gui_colormap = pn.Row(pn.pane.Str(background=rangeset.colormap[0], height=30, width=20), "very low", pn.pane.Str(background=rangeset.colormap[1], height=30, width=20), "low", pn.pane.Str(background=rangeset.colormap[2], height=30, width=20), "medium", pn.pane.Str(background=rangeset.colormap[3], height=30, width=20), "high", pn.pane.Str(background=rangeset.colormap[4], height=30, width=20), "very high", sizing_mode='stretch_width') selectColoring = pn.widgets.Select(name='', options=['None']+selected_var) # set up the GUI layout = pn.Row(pn.Column( pn.Row(pn.pane.Markdown('''# NoLiES: The non-linear embedding surveyor\n NoLiES augments the projected data with additional information. The following interactions are supported:\n * **Attribute-based coloring** Chose an attribute from the drop-down menu below the embedding to display contours for multiple value ranges. * **Selective muting**: Click on the legend to mute/hide parts of the chart. Press _labels_ to hide the labels. * **Contour control** Change the slider range to change the contours. * **Histograms** Select the check-box next to the slider to view the attribute's histogram. * **Selection** Use the selection tool to outline a set of points and share this outline across plots.''', sizing_mode='stretch_width'), margin=(0, 25,0,25)), pn.Row( pn.Column(pn.pane.Markdown('''# Attributes\nEnable histograms with the checkboxes.'''), '## Embedding', ranges_embd, #pn.layout.Divider(), '## Auxiliary', ranges_aux, margin=(0, 25, 0, 0)), pn.Column(pn.pane.Markdown('''# Embedding - '''+type(embedding).__name__+'''&nbsp;&nbsp; Dataset - '''+dataset_name, sizing_mode='stretch_width'), overview, pn.Row(selectColoring, gui_colormap) ), margin=(0,25,25,25) ), #pn.Row(sizing_mode='stretch_height'), pn.Row(pn.pane.Markdown('''Data source: Fisher,R.A. "The use of multiple measurements in taxonomic problems" Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to Mathematical Statistics" (John Wiley, NY, 1950). ''', width=800), sizing_mode='stretch_width', margin=(0,25,0,25))), pn.GridBox(ncols=small_multiples_ncols, sizing_mode='stretch_both', margin=(220,25,0,0)), background='#efefef' ) # Check the GUI with the following code - this version is not interactive yet layout ``` ## Callbacks Callbacks for **slider interactions** ``` visible = [False]*len(selected_var) mapping = {v: k for k, v in dict(enumerate(selected_var)).items()} def onSliderChanged(event): '''Actions upon attribute slider change. Attributes ---------- event: bokeh.Events.Event information about the event that triggered the callback ''' var = event.obj.name v_range = event.obj.value # if changed variable is currently displayed if var == layout[0][1][1][2][0].value: setColoring(var, v_range) # find the matching chart and update it for col in layout[1]: if col.name == var: df_polys, df_scatter, bounds, cnt_in, cnt_out = rangeset.compute_contours(var, v_range, bins=20 if col.name == 'groups' else 5) p,histo = _make_chart(var, df_polys, df_scatter, bounds, cnt_in, cnt_out) col[0].object = p col[1].object = histo def onSliderChanged_released(event): '''Actions upon attribute slider change. Attributes ---------- event: bokeh.Events.Event information about the event that triggered the callback ''' var = event.obj.name v_range = event.obj.value print('\''+var+'\': ('+str(v_range[0])+','+str(v_range[1])+')') def onAttributeSelected(event): '''Actions upon attribute checkbox change. Attributes ---------- event: bokeh.Events.Event information about the event that triggered the callback ''' var = event.obj.variable i = mapping[var] if event.obj.value == True: v_range = event.obj.slider.value df_polys, df_scatter, bounds, cnt_in, cnt_out = rangeset.compute_contours(var, v_range) p,p_histo = _make_chart(var, df_polys, df_scatter, bounds, cnt_in, cnt_out) pos_insert = sum(visible[:i]) layout[1].insert(pos_insert, pn.Column(p,pn.panel(p_histo), name=var, margin=5)) else: pos_remove = sum(visible[:i]) layout[1].pop(pos_remove) visible[i] = event.obj.value # link widgets to their callbacks for var in sliders.keys(): sliders[var][0].param.watch(onAttributeSelected, 'value') sliders[var][1].param.watch(onSliderChanged, 'value') sliders[var][1].param.watch(onSliderChanged_released, 'value_throttled') ``` Callbacks **rangeset selection** in overview plot ``` def clearColoring(): '''Remove rangeset augmentation from the embedding.''' global overview overview.legend.visible = False for r in overview.renderers: if r.name is not None and ('poly' in r.name or 'scatter' in r.name): r.visible = False r.muted = True def setColoring(var, v_range=None): '''Compute and render the rangeset for a selected variable. Attributes ---------- var: str the selected variable v_range: tuple (min,max) the user define value range for the rangeset ''' global overview overview.legend.visible = True df_polys, df_scatter, bounds, cnt,cnt = rangeset.compute_contours(var, val_range=v_range, bins=bins) for r in overview.renderers: if r.name is not None and ('poly' in r.name or 'scatter' in r.name): r.visible = False r.muted = True if len(df_polys) > 0: for k in list(rangeset.labels.keys())[::-1]: g = df_polys[df_polys.color == k] r = overview.select('poly '+k) if len(r) > 0: r[0].visible = True r[0].muted = False r[0].data_source.data = dict(ColumnDataSource(g).data) else: overview.multi_polygons(source = g, xs='xs', ys='ys', name='poly '+k, color='color', alpha=.5, legend_label=rangeset.color2label(k), line_color=None, muted_color='gray', muted_alpha=.1) g = df_scatter[df_scatter.color == k] r = overview.select('scatter '+k) if len(r) > 0: r[0].visible = True r[0].muted = False r[0].data_source.data = dict(ColumnDataSource(g).data) else: overview.circle(source = g, x='x', y='y', size='size', name='scatter '+k, color='color', alpha=1, legend_label=rangeset.color2label(k), muted_color='gray', muted_alpha=0) def onChangeColoring(event): '''Actions upon change of the rangeset attribute. Attributes ---------- event: bokeh.Events.Event information about the event that triggered the callback ''' var = event.obj.value if var == 'None': clearColoring() else: v_range = sliders[var][1].value setColoring(var, v_range) selectColoring.param.watch( onChangeColoring, 'value' ) ``` User **selection of data points** in the overview chart. ``` def onSelectionChanged(event): if event.final: sel_pp = pp[list(overview.select('points').data_source.selected.indices)] if len(sel_pp) == 0: source_selection.data = dict({'x': [], 'y': []}) else: points = MultiPoint(sel_pp) poly = unary_union([polygon for polygon in triangulate(points) if rangeset._max_edge(polygon) < 5]).boundary.parallel_offset(-0.05).coords.xy source_selection.data = dict({'x': poly[0].tolist(), 'y': poly[1].tolist()}) overview.on_event(SelectionGeometry, onSelectionChanged) layout.servable('NoLies') ```
github_jupyter
# AskReddit Troll Question Detection Challenge ## Imports ``` import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer import re train_df = pd.read_csv("train.csv") test_df = pd.read_csv("test.csv") sentences1 = train_df['question_text'] # .values.astype('U') sentences2 = test_df['question_text'] # .values.astype('U') sentences1 = sentences1.tolist() sentences2 = sentences2.tolist() # print(len(sentences1)) # print(len(sentences2)) # print(sentences1[0:10]) # print(sentences2[0:10]) sentences = [] sentences = sentences1 + sentences2 print(len(sentences)) N = 1306122 sentences = sentences[:N] ``` ## Trying Methods ### Bag Of Words ``` cv = CountVectorizer(ngram_range=(1,3)) cv.fit(sentences) train_X1 = cv.transform(sentences1) test_X1 = cv.transform(sentences2) train_X1 = train_X1.astype(float) test_X1 = test_X1.astype(float) Y1 = train_df['target'].to_numpy().astype(np.float64) Y1 = Y1[:N] ``` ### TF IDF ``` cv = TfidfVectorizer(ngram_range=(1,3)) cv.fit(sentences) train_X2 = cv.transform(sentences1) test_X2 = cv.transform(sentences2) train_X2 = train_X1.astype(float) test_X2 = test_X1.astype(float) Y2 = Y1 ``` ## Model generation ``` from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, f1_score, roc_auc_score ``` ### For data genrated by "Bag of words" method ``` lreg1 = LogisticRegression(solver='liblinear') lreg1.fit(train_X1,Y1) ``` ### For data generated by "TD IDF" method ``` lreg2 = LogisticRegression(solver='liblinear') lreg2.fit(train_X2,Y2) ``` ### Predict for X1, Y1 ``` test_yhat1 = lreg1.predict_proba(test_X1) threshold = 0.20139999999999986 test_output1 = (test_yhat1[:,1] > threshold).astype(int) ``` ### Predict for X2, Y2 ``` test_yhat2 = lreg2.predict_proba(test_X2) threshold = 0.20049999999999996 test_output2 = (test_yhat2[:,1] > threshold).astype(int) ``` ## Reshaping To Store Data ``` test_output1 = test_output1.reshape(-1,1) test_output1 = test_output1.astype(int) test_output2 = test_output2.reshape(-1,1) test_output2 = test_output2.astype(int) ``` ### Making a submission file ``` y_pred_df1 = pd.DataFrame(data=test_output1[:,0], columns = ["target"]) submission_df1 = pd.concat([test_df["qid"], y_pred_df1["target"]], axis=1, join='inner') submission_df1.to_csv("submission1.csv", index = False) print(submission_df1.shape) y_pred_df2 = pd.DataFrame(data=test_output2[:,0], columns = ["target"]) submission_df2 = pd.concat([test_df["qid"], y_pred_df2["target"]], axis=1, join='inner') submission_df2.to_csv("submission2.csv", index = False) print(submission_df2.shape) print(train_X1.shape) ```
github_jupyter
# Triplet Loss for Implicit Feedback Neural Recommender Systems The goal of this notebook is first to demonstrate how it is possible to build a bi-linear recommender system only using positive feedback data. In a latter section we show that it is possible to train deeper architectures following the same design principles. This notebook is inspired by Maciej Kula's [Recommendations in Keras using triplet loss]( https://github.com/maciejkula/triplet_recommendations_keras). Contrary to Maciej we won't use the BPR loss but instead will introduce the more common margin-based comparator. ## Loading the movielens-100k dataset For the sake of computation time, we will only use the smallest variant of the movielens reviews dataset. Beware that the architectural choices and hyperparameters that work well on such a toy dataset will not necessarily be representative of the behavior when run on a more realistic dataset such as [Movielens 10M](https://grouplens.org/datasets/movielens/10m/) or the [Yahoo Songs dataset with 700M rating](https://webscope.sandbox.yahoo.com/catalog.php?datatype=r). ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import os.path as op from zipfile import ZipFile try: from urllib.request import urlretrieve except ImportError: # Python 2 compat from urllib import urlretrieve ML_100K_URL = "http://files.grouplens.org/datasets/movielens/ml-100k.zip" ML_100K_FILENAME = ML_100K_URL.rsplit('/', 1)[1] ML_100K_FOLDER = 'ml-100k' if not op.exists(ML_100K_FILENAME): print('Downloading %s to %s...' % (ML_100K_URL, ML_100K_FILENAME)) urlretrieve(ML_100K_URL, ML_100K_FILENAME) if not op.exists(ML_100K_FOLDER): print('Extracting %s to %s...' % (ML_100K_FILENAME, ML_100K_FOLDER)) ZipFile(ML_100K_FILENAME).extractall('.') data_train = pd.read_csv(op.join(ML_100K_FOLDER, 'ua.base'), sep='\t', names=["user_id", "item_id", "rating", "timestamp"]) data_test = pd.read_csv(op.join(ML_100K_FOLDER, 'ua.test'), sep='\t', names=["user_id", "item_id", "rating", "timestamp"]) data_train.describe() data_train.head() # data_test.describe() max_user_id = max(data_train['user_id'].max(), data_test['user_id'].max()) max_item_id = max(data_train['item_id'].max(), data_test['item_id'].max()) n_users = max_user_id + 1 n_items = max_item_id + 1 print('n_users=%d, n_items=%d' % (n_users, n_items)) ``` ## Implicit feedback data Consider ratings >= 4 as positive feed back and ignore the rest: ``` pos_data_train = data_train.query("rating >= 4") pos_data_test = data_test.query("rating >= 4") ``` Because the median rating is around 3.5, this cut will remove approximately half of the ratings from the datasets: ``` pos_data_train['rating'].count() pos_data_test['rating'].count() ``` ## The Triplet Loss The following section demonstrates how to build a low-rank quadratic interaction model between users and items. The similarity score between a user and an item is defined by the unormalized dot products of their respective embeddings. The matching scores can be use to rank items to recommend to a specific user. Training of the model parameters is achieved by randomly sampling negative items not seen by a pre-selected anchor user. We want the model embedding matrices to be such that the similarity between the user vector and the negative vector is smaller than the similarity between the user vector and the positive item vector. Furthermore we use a margin to further move appart the negative from the anchor user. Here is the architecture of such a triplet architecture. The triplet name comes from the fact that the loss to optimize is defined for triple `(anchor_user, positive_item, negative_item)`: <img src="images/rec_archi_implicit_2.svg" style="width: 600px;" /> We call this model a triplet model with bi-linear interactions because the similarity between a user and an item is captured by a dot product of the first level embedding vectors. This is therefore not a deep architecture. ``` import tensorflow as tf def identity_loss(y_true, y_pred): """Ignore y_true and return the mean of y_pred This is a hack to work-around the design of the Keras API that is not really suited to train networks with a triplet loss by default. """ return tf.reduce_mean(y_pred + 0 * y_true) def margin_comparator_loss(inputs, margin=1.): """Comparator loss for a pair of precomputed similarities If the inputs are cosine similarities, they each have range in (-1, 1), therefore their difference have range in (-2, 2). Using a margin of 1. can therefore make sense. If the input similarities are not normalized, it can be beneficial to use larger values for the margin of the comparator loss. """ positive_pair_sim, negative_pair_sim = inputs return tf.maximum(negative_pair_sim - positive_pair_sim + margin, 0) ``` Here is the actual code that builds the model(s) with shared weights. Note that here we use the cosine similarity instead of unormalized dot products (both seems to yield comparable results). ``` from keras.models import Model from keras.layers import Embedding, Flatten, Input, Dense, merge from keras.regularizers import l2 from keras_fixes import dot_mode, cos_mode def build_models(n_users, n_items, latent_dim=64, l2_reg=0): """Build a triplet model and its companion similarity model The triplet model is used to train the weights of the companion similarity model. The triplet model takes 1 user, 1 positive item (relative to the selected user) and one negative item and is trained with comparator loss. The similarity model takes one user and one item as input and return compatibility score (aka the match score). """ # Common architectural components for the two models: # - symbolic input placeholders user_input = Input((1,), name='user_input') positive_item_input = Input((1,), name='positive_item_input') negative_item_input = Input((1,), name='negative_item_input') # - embeddings l2_reg = None if l2_reg == 0 else l2(l2_reg) user_layer = Embedding(n_users, latent_dim, input_length=1, name='user_embedding', W_regularizer=l2_reg) # The following embedding parameters will be shared to encode both # the positive and negative items. item_layer = Embedding(n_items, latent_dim, input_length=1, name="item_embedding", W_regularizer=l2_reg) user_embedding = Flatten()(user_layer(user_input)) positive_item_embedding = Flatten()(item_layer(positive_item_input)) negative_item_embedding = Flatten()(item_layer(negative_item_input)) # - similarity computation between embeddings positive_similarity = merge([user_embedding, positive_item_embedding], mode=cos_mode, output_shape=(1,), name="positive_similarity") negative_similarity = merge([user_embedding, negative_item_embedding], mode=cos_mode, output_shape=(1,), name="negative_similarity") # The triplet network model, only used for training triplet_loss = merge([positive_similarity, negative_similarity], mode=margin_comparator_loss, output_shape=(1,), name='comparator_loss') triplet_model = Model(input=[user_input, positive_item_input, negative_item_input], output=triplet_loss) # The match-score model, only use at inference to rank items for a given # model: the model weights are shared with the triplet_model therefore # we do not need to train it and therefore we do not need to plug a loss # and an optimizer. match_model = Model(input=[user_input, positive_item_input], output=positive_similarity) return triplet_model, match_model triplet_model, match_model = build_models(n_users, n_items, latent_dim=64, l2_reg=1e-6) ``` ### Exercise: How many trainable parameters does each model. Count the shared parameters only once per model. ``` print(match_model.summary()) print(triplet_model.summary()) # %load solutions/triplet_parameter_count.py # Analysis: # # Both models have exactly the same number of parameters, # namely the parameters of the 2 embeddings: # # - user embedding: n_users x embedding_dim # - item embedding: n_items x embedding_dim # # The triplet model uses the same item embedding twice, # once to compute the positive similarity and the other # time to compute the negative similarity. However because # those two nodes in the computation graph share the same # instance of the item embedding layer, the item embedding # weight matrix is shared by the two branches of the # graph and therefore the total number of parameters for # each model is in both cases: # # (n_users x embedding_dim) + (n_items x embedding_dim) ``` ## Quality of Ranked Recommendations Now that we have a randomly initialized model we can start computing random recommendations. To assess their quality we do the following for each user: - compute matching scores for items (except the movies that the user has already seen in the training set), - compare to the positive feedback actually collected on the test set using the ROC AUC ranking metric, - average ROC AUC scores across users to get the average performance of the recommender model on the test set. ``` from sklearn.metrics import roc_auc_score def average_roc_auc(match_model, data_train, data_test): """Compute the ROC AUC for each user and average over users""" max_user_id = max(data_train['user_id'].max(), data_test['user_id'].max()) max_item_id = max(data_train['item_id'].max(), data_test['item_id'].max()) user_auc_scores = [] for user_id in range(1, max_user_id + 1): pos_item_train = data_train[data_train['user_id'] == user_id] pos_item_test = data_test[data_test['user_id'] == user_id] # Consider all the items already seen in the training set all_item_ids = np.arange(1, max_item_id + 1) items_to_rank = np.setdiff1d(all_item_ids, pos_item_train['item_id'].values) # Ground truth: return 1 for each item positively present in the test set # and 0 otherwise. expected = np.in1d(items_to_rank, pos_item_test['item_id'].values) if np.sum(expected) >= 1: # At least one positive test value to rank repeated_user_id = np.empty_like(items_to_rank) repeated_user_id.fill(user_id) predicted = match_model.predict([repeated_user_id, items_to_rank], batch_size=4096) user_auc_scores.append(roc_auc_score(expected, predicted)) return sum(user_auc_scores) / len(user_auc_scores) ``` By default the model should make predictions that rank the items in random order. The **ROC AUC score** is a ranking score that represents the **expected value of correctly ordering uniformly sampled pairs of recommendations**. A random (untrained) model should yield 0.50 ROC AUC on average. ``` average_roc_auc(match_model, pos_data_train, pos_data_test) ``` ## Training the Triplet Model Let's now fit the parameters of the model by sampling triplets: for each user, select a movie in the positive feedback set of that user and randomly sample another movie to serve as negative item. Note that this sampling scheme could be improved by removing items that are marked as positive in the data to remove some label noise. In practice this does not seem to be a problem though. ``` def sample_triplets(pos_data, max_item_id, random_seed=0): """Sample negatives at random""" rng = np.random.RandomState(random_seed) user_ids = pos_data['user_id'].values pos_item_ids = pos_data['item_id'].values neg_item_ids = rng.randint(low=1, high=max_item_id + 1, size=len(user_ids)) return [user_ids, pos_item_ids, neg_item_ids] ``` Let's train the triplet model: ``` # we plug the identity loss and the a fake target variable ignored by # the model to be able to use the Keras API to train the triplet model triplet_model.compile(loss=identity_loss, optimizer="adam") fake_y = np.ones_like(pos_data_train['user_id']) n_epochs = 15 for i in range(n_epochs): # Sample new negatives to build different triplets at each epoch triplet_inputs = sample_triplets(pos_data_train, max_item_id, random_seed=i) # Fit the model incrementally by doing a single pass over the # sampled triplets. triplet_model.fit(triplet_inputs, fake_y, shuffle=True, batch_size=64, nb_epoch=1, verbose=2) # Monitor the convergence of the model test_auc = average_roc_auc(match_model, pos_data_train, pos_data_test) print("Epoch %d/%d: test ROC AUC: %0.4f" % (i + 1, n_epochs, test_auc)) ``` ## Training a Deep Matching Model on Implicit Feedback Instead of using hard-coded cosine similarities to predict the match of a `(user_id, item_id)` pair, we can instead specify a deep neural network based parametrisation of the similarity. The parameters of that matching model are also trained with the margin comparator loss: <img src="images/rec_archi_implicit_1.svg" style="width: 600px;" /> ### Exercise to complete as a home assignment: - Implement a `deep_match_model`, `deep_triplet_model` pair of models for the architecture described in the schema. The last layer of the embedded Multi Layer Perceptron outputs a single scalar that encodes the similarity between a user and a candidate item. - Evaluate the resulting model by computing the per-user average ROC AUC score on the test feedback data. - Check that the AUC ROC score is close to 0.50 for a randomly initialized model. - Check that you can reach at least 0.91 ROC AUC with this deep model (you might need to adjust the hyperparameters). Hints: - it is possible to reuse the code to create embeddings from the previous model definition; - the concatenation between user and the positive item embedding can be obtained with: ```py positive_embeddings_pair = merge([user_embedding, positive_item_embedding], mode='concat', name="positive_embeddings_pair") negative_embeddings_pair = merge([user_embedding, negative_item_embedding], mode='concat', name="negative_embeddings_pair") ``` - those embedding pairs should be fed to a shared MLP instance to compute the similarity scores. ``` from keras.models import Sequential def make_interaction_mlp(input_dim, n_hidden=1, hidden_size=64, dropout=0, l2_reg=None): mlp = Sequential() # TODO: return mlp def build_models(n_users, n_items, user_dim=32, item_dim=64, n_hidden=1, hidden_size=64, dropout=0, l2_reg=0): # TODO: # Inputs and the shared embeddings can be defined as previously. # Use a single instance of the MLP created by make_interaction_mlp() # and use it twice: once on the positive pair, once on the negative # pair interaction_layers = make_interaction_mlp( user_dim + item_dim, n_hidden=n_hidden, hidden_size=hidden_size, dropout=dropout, l2_reg=l2_reg) # Build the models: one for inference, one for triplet training deep_match_model = None deep_triplet_model = None return deep_match_model, deep_triplet_model # %load solutions/deep_implicit_feedback_recsys.py from keras.models import Model, Sequential from keras.layers import Embedding, Flatten, Input, Dense, Dropout, merge from keras.regularizers import l2 def make_interaction_mlp(input_dim, n_hidden=1, hidden_size=64, dropout=0, l2_reg=None): """Build the shared multi layer perceptron""" mlp = Sequential() if n_hidden == 0: # Plug the output unit directly: this is a simple # linear regression model. Not dropout required. mlp.add(Dense(1, input_dim=input_dim, activation='relu', W_regularizer=l2_reg)) else: mlp.add(Dense(hidden_size, input_dim=input_dim, activation='relu', W_regularizer=l2_reg)) mlp.add(Dropout(dropout)) for i in range(n_hidden - 1): mlp.add(Dense(hidden_size, activation='relu', W_regularizer=l2_reg)) mlp.add(Dropout(dropout)) mlp.add(Dense(1, activation='relu', W_regularizer=l2_reg)) return mlp def build_models(n_users, n_items, user_dim=32, item_dim=64, n_hidden=1, hidden_size=64, dropout=0, l2_reg=0): """Build models to train a deep triplet network""" user_input = Input((1,), name='user_input') positive_item_input = Input((1,), name='positive_item_input') negative_item_input = Input((1,), name='negative_item_input') l2_reg = None if l2_reg == 0 else l2(l2_reg) user_layer = Embedding(n_users, user_dim, input_length=1, name='user_embedding', W_regularizer=l2_reg) # The following embedding parameters will be shared to encode both # the positive and negative items. item_layer = Embedding(n_items, item_dim, input_length=1, name="item_embedding", W_regularizer=l2_reg) user_embedding = Flatten()(user_layer(user_input)) positive_item_embedding = Flatten()(item_layer(positive_item_input)) negative_item_embedding = Flatten()(item_layer(negative_item_input)) # Similarity computation between embeddings using a MLP similarity positive_embeddings_pair = merge([user_embedding, positive_item_embedding], mode='concat', name="positive_embeddings_pair") positive_embeddings_pair = Dropout(dropout)(positive_embeddings_pair) negative_embeddings_pair = merge([user_embedding, negative_item_embedding], mode='concat', name="negative_embeddings_pair") negative_embeddings_pair = Dropout(dropout)(negative_embeddings_pair) # Instanciate the shared similarity architecture interaction_layers = make_interaction_mlp( user_dim + item_dim, n_hidden=n_hidden, hidden_size=hidden_size, dropout=dropout, l2_reg=l2_reg) positive_similarity = interaction_layers(positive_embeddings_pair) negative_similarity = interaction_layers(negative_embeddings_pair) # The triplet network model, only used for training triplet_loss = merge([positive_similarity, negative_similarity], mode=margin_comparator_loss, output_shape=(1,), name='comparator_loss') deep_triplet_model = Model(input=[user_input, positive_item_input, negative_item_input], output=triplet_loss) # The match-score model, only used at inference deep_match_model = Model(input=[user_input, positive_item_input], output=positive_similarity) return deep_match_model, deep_triplet_model hyper_parameters = dict( user_dim=32, item_dim=64, n_hidden=1, hidden_size=128, dropout=0.1, l2_reg=0 ) deep_match_model, deep_triplet_model = build_models(n_users, n_items, **hyper_parameters) deep_triplet_model.compile(loss=identity_loss, optimizer='adam') fake_y = np.ones_like(pos_data_train['user_id']) n_epochs = 15 for i in range(n_epochs): # Sample new negatives to build different triplets at each epoch triplet_inputs = sample_triplets(pos_data_train, max_item_id, random_seed=i) # Fit the model incrementally by doing a single pass over the # sampled triplets. deep_triplet_model.fit(triplet_inputs, fake_y, shuffle=True, batch_size=64, nb_epoch=1, verbose=2) # Monitor the convergence of the model test_auc = average_roc_auc(deep_match_model, pos_data_train, pos_data_test) print("Epoch %d/%d: test ROC AUC: %0.4f" % (i + 1, n_epochs, test_auc)) ``` ### Exercise: Count the number of parameters in `deep_match_model` and `deep_triplet_model`. Which model has the largest number of parameters? ``` print(deep_match_model.summary()) print(deep_triplet_model.summary()) # %load solutions/deep_triplet_parameter_count.py # Analysis: # # Both models have again exactly the same number of parameters, # namely the parameters of the 2 embeddings: # # - user embedding: n_users x user_dim # - item embedding: n_items x item_dim # # and the parameters of the MLP model used to compute the # similarity score of an (user, item) pair: # # - first hidden layer weights: (user_dim + item_dim) * hidden_size # - first hidden biases: hidden_size # - extra hidden layers weights: hidden_size * hidden_size # - extra hidden layers biases: hidden_size # - output layer weights: hidden_size * 1 # - output layer biases: 1 # # The triplet model uses the same item embedding layer # twice and the same MLP instance twice: # once to compute the positive similarity and the other # time to compute the negative similarity. However because # those two lanes in the computation graph share the same # instances for the item embedding layer and for the MLP, # their parameters are shared. # # Reminder: MLP stands for multi-layer perceptron, which is a # common short-hand for Feed Forward Fully Connected Neural # Network. ``` ## Possible Extensions You can implement any of the following ideas if you want to get a deeper understanding of recommender systems. ### Leverage User and Item metadata As we did for the Explicit Feedback model, it's also possible to extend our models to take additional user and item metadata as side information when computing the match score. ### Better Ranking Metrics In this notebook we evaluated the quality of the ranked recommendations using the ROC AUC metric. This score reflect the ability of the model to correctly rank any pair of items (sampled uniformly at random among all possible items). In practice recommender systems will only display a few recommendations to the user (typically 1 to 10). It is typically more informative to use an evaluatio metric that characterize the quality of the top ranked items and attribute less or no importance to items that are not good recommendations for a specific users. Popular ranking metrics therefore include the **Precision at k** and the **Mean Average Precision**. You can read up online about those metrics and try to implement them here. ### Hard Negatives Sampling In this experiment we sampled negative items uniformly at random. However, after training the model for a while, it is possible that the vast majority of sampled negatives have a similarity already much lower than the positive pair and that the margin comparator loss sets the majority of the gradients to zero effectively wasting a lot of computation. Given the current state of the recsys model we could sample harder negatives with a larger likelihood to train the model better closer to its decision boundary. This strategy is implemented in the WARP loss [1]. The main drawback of hard negative sampling is increasing the risk of sever overfitting if a significant fraction of the labels are noisy. ### Factorization Machines A very popular recommender systems model is called Factorization Machines [2][3]. They two use low rank vector representations of the inputs but they do not use a cosine similarity or a neural network to model user/item compatibility. It is be possible to adapt our previous code written with Keras to replace the cosine sims / MLP with the low rank FM quadratic interactions by reading through [this gentle introduction](http://tech.adroll.com/blog/data-science/2015/08/25/factorization-machines.html). If you choose to do so, you can compare the quality of the predictions with those obtained by the [pywFM project](https://github.com/jfloff/pywFM) which provides a Python wrapper for the [official libFM C++ implementation](http://www.libfm.org/). Maciej Kula also maintains a [lighfm](http://www.libfm.org/) that implements an efficient and well documented variant in Cython and Python. ## References: [1] Wsabie: Scaling Up To Large Vocabulary Image Annotation Jason Weston, Samy Bengio, Nicolas Usunier, 2011 https://research.google.com/pubs/pub37180.html [2] Factorization Machines, Steffen Rendle, 2010 https://www.ismll.uni-hildesheim.de/pub/pdfs/Rendle2010FM.pdf [3] Factorization Machines with libFM, Steffen Rendle, 2012 in ACM Trans. Intell. Syst. Technol., 3(3), May. http://doi.acm.org/10.1145/2168752.2168771
github_jupyter
``` import tensorflow as tf tf.constant([[1.,2.,3.], [4.,5.,6.]]) tf.constant(42) # 스칼라 t = tf.constant([[1.,2.,3.], [4.,5.,6.]]) t.shape # TensorShape([2, 3]) t.dtype # tf.float32 t[:, 1:] t[..., 1, tf.newaxis] t + 10 tf.square(t) # 제곱 t @ tf.transpose(t) # transpose는 행렬 변환 import numpy as np a = np.array([2., 4., 5.]) tf.constant(a) # <tf.Tensor: shape=(3,), dtype=float64, numpy=array([2., 4., 5.])> np.array(t) # array([[1., 2., 3.], # [4., 5., 6.]], dtype=float32) tf.square(a) # <tf.Tensor: shape=(3,), dtype=float64, numpy=array([ 4., 16., 25.])> np.square(t) # array([[ 1., 4., 9.], # [16., 25., 36.]], dtype=float32) t2 = tf.constant(40., dtype=tf.float64) tf.constant(2.0) + tf.cast(t2, tf.float32) # <tf.Tensor: shape=(), dtype=float32, numpy=42.0> v = tf.Variable([[1.,2.,3.], [4.,5.,6.]]) v v.assign(2 * v) v[0,1].assign(42) v[:,2].assign([0., 1.]) v.scatter_nd_update(indices=[[0,0], [1,2]], updates=[100., 200.]) def huber_fn(y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) < 1 squared_loss = tf.square(error) / 2 linear_loss = tf.abs(error) - 0.5 return tf.where(is_small_error, squared_loss, linear_loss) model.compile(loss=huber_fn, optimizer='nadam') model.fit(X_train, y_train, [...]) from tensorflow.keras.models import load_model model = load_model("my_model_with_a_custom_loss.h5", custom_objects={"huber_fn": huber_fn}) def create_huber(threshold=1.0): def huber_fn(y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) < threshold squared_loss = tf.square(error) / 2 linear_loss = threshold * tf.abs(error) - threshold**2 / 2 return tf.where(is_small_error, squared_loss, linear_loss) return huber_fn model.compile(loss=create_huber(2.0), optimizer="nadam") model = load_model("my_model_with_a_custom_loss_threshold_2.h5", custom_objects={"huber_fn": create_huber(2.0)}) from tensorflow.keras.losses import Loss class HuberLoss(Loss): def __init__(self, threshold=1.0, **kwargs): self.threshold = threshold super().__init__(**kwargs) def call(self, y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) < self.threshold squared_loss = tf.square(error) / 2 linear_loss = self.threshold * tf.abs(error) - self.threshold**2 / 2 return tf.where(is_small_error, squared_loss, linear_loss) def get_config(self): base_config = super().get_config() return {**base_config, "threshold": self.threshold} model.compile(loss=HuberLoss(2.), optimizer="nadam") model = load_model("my_model_with_a_custom_loss_class.h5", custom_objects={"HuberLoss": HuberLoss}) import tensorflow as tf # 사용자 정의 활성화 함수 (keras.activations.softplus()) def my_softplus(z): return tf.math.log(tf.exp(z) + 1.0) # 사용자 정의 글로럿 초기화 (keras.initializers.glorot_normal()) def my_glorot_initializer(shape, dtype=tf.float32): stddev = tf.sqrt(2. / (shape[0] + shape[1])) return tf.random.normal(shape, stddev=stddev, dtype=dtype) def my_l1_regularizer(weights): return tf.reduce_sum(tf.abs(0.01 * weights)) def my_positive_weights(weights): return tf.where(weights < 0., tf.zeros_like(weights), weights) from tensorflow.keras.layers import Dense layer = Dense(30 activation=my_softplus, kernel_initializer=my_glorot_initializer, kernel_regularizer=my_l1_regularizer, kernel_constarint=my_positive_weights) model.compile(loss='mse', optimizer='nadam', metrics=[create_huber(2.0)]) from tensorflow.keras.metrics import Metric import tensorflow as tf class HuberMetric(Metric): def __init__(self, threshold=1.0, **kwargs): super().__init__(**kwargs) self.threshold = threshold self.huber_fn = create_huber(threshold) self.total = self.add_weight('total', initializer='zeros') self.count = self.add_Weight('count', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): metric = self.huber_fn(y_true, y_pred) self.total.assign_add(tf.reduce_sum(metric)) self.count.assign_add(tf.cast(Tf.size(y_true), tf.float32)) def result(self): return self.total / self.count def get_config(self): basㅠㅠe_config = super().get_config() return {**base_config, "threshold":self.threshold} from tensorflow.keras.layers import Layer class MyDense(Layer): def __init__(self, units, activation=None, **kwargs): super().__init__(**kwargs) self.units = units self.activation = tf.keras.activations.get(activation) def build(self, batch_input_shape): self.kernel = self.add_weight( name='kernel', shape=[batch_input_shape[-1], self.units], initializer = 'glorot_normal' ) self.bias = self.add_weight( name='bias', shape=[self.units], initializer='zeros' ) super().build(batch_input_shape) def call(self, X): return self.activation(X @ self.kernel + self.bias) def comput_output_shape(self, batch_input_shape): return tf.TensorShape(batch_input_shape.as_list()[:-1] + [self.units]) def get_config(self): base_config = super().get_config() return {**base_config, 'units':self.units, 'activation': tf.keras.activations.serialize(self.activation)} class MyMultiLayer(tf.keras.layers.Layer): def call(self, X): X1, X2 = X return [X1 + X2, X1 * X2, X1 / X2] def compute_output_shape(self, batch_input_shape): b1, b2 = batch_input_shape return [b1, b1, b1] class MyGaussianNoise(tf.keras.layers.Layer): def __init__(self, stddev, **kwargs): super().__init__(**kwargs) self.stddev = stddev def call(self, X, training=None): if training: noise = tf.random.normal(tf.shape(X), stddev=self.stddev) return X + noise else: return X def compute_output_shape(self, batch_input_shape): return batch_input_shape import tensorflow as tf class ResidualBlock(tf.keras.layers.Layer): def __init__(self, n_layers, n_neurons, **kwargs): super().__init__(**kwargs) self.hidden = [tf.keras.layers.Dense(n_neurons, activation='elu', kernel_initializer='he_normal') for _ in range(n_layers)] def call(self, inputs): Z = inputs for layer in self.hidden: Z = layer(Z) return inputs + Z class ResidualRegressor(tf.keras.Model): def __init__(self, output_dim, **kwargs): super().__init__(**kwargs) self.hidden1 = tf.keras.layers.Dense(30, activation='elu', kernel_initializer='he_normal') self.block1 = ResidualBlock(2, 30) self.block2 = ResidualBlock(2, 30) self.out = tf.keras.layers.Dense(output_dim) def call(self, inputs): Z = self.hidden1(inputs) for _ in range(1 + 3): Z = self.block1(Z) Z = self.block2(Z) return self.out(Z) class ReconstructingRegressor(tf.keras.Model): def __init__(self, output_dim, **kwargs): super().__init__(**kwargs) self.hidden = [tf.keras.layers.Dense(30, activation='selu', kernel_initializer='lecun_normal') for _ in range(5)] self.out = tf.keras.layers.Dense(output_dim) def build(self, batch_input_shape): n_inputs = batch_input_shape[-1] self.reconstruct = tf.keras.layers.Dense(n_inputs) super().build(batch_input_shape) def call(self, inputs): Z = inputs for layer in self.hidden: Z = layer(Z) reconstruction = self.reconstruct(Z) recon_loss = tf.reduce_mean(tf.square(reconstruction - inputs)) self.add_loss(0.05 * recon_loss) return self.out(Z) def f(w1, w2): return 3 * w1 ** 2 + 2 * w1 * w2 w1, w2 = 5, 3; eps = 1e-6 print((f(w1 + eps, w2) - f(w1, w2)) / eps) # 36.000003007075065 print((f(w1, w2 + eps) - f(w1, w2)) / eps) # 10.000000003174137 w1, w2 = tf.Variable(5.), tf.Variable(3.) with tf.GradientTape() as tape: z = f(w1, w2) gradients = tape.gradient(z, [w1, w2]) gradients # [<tf.Tensor: shape=(), dtype=float32, numpy=36.0>, # <tf.Tensor: shape=(), dtype=float32, numpy=10.0>] l2_reg = tf.keras.regularizers.l2(0.05) model = tf.keras.models.Sequential([ tf.keras.layers.Dense(30, activation='elu', kernel_initializer='he_normal', kernel_regulaizer=l2_reg), tf.keras.layers.Dense(1, kernel_regularizer=l2_reg) ]) def random_batch(X, y, batch_size=32): idx = np.random.randint(len(X), size=batch_size) return X[idx], y[idx] def print_status_bar(iteration, total, loss, metrics=None): metrics = " - ".join(["{}: {:.4f}".format(m.name, m.result()) for m in [loss] + (metrics or [])]) end = "" if iteration < total else "\n" print("\r{}/{} - ".format(iteration, total) + metrics, end=end) n_epochs = 5 batch_size = 32 n_steps = len(X_train) // batch_size optimizer = tf.keras.optimizers.Nadam(lr=0.01) loss_fn = tf.keras.losses.mean_squared_error mean_loss = tf.keras.metrics.Mean() metrics = [tf.keras.metrics.MeanAbsoluteError()] for epoch in range(1, n_epochs + 1): print('에포크 {}/{}'.format(epoch, n_epochs)) for step in range(1, n_steps + 1): X_batch, y_batch = random_batch(X_train_scaled, y_train) with tf.GradientTape() as tape: y_pred = model(X_batch, training=True) main_loss = tf.reduce_mean(loss_fn(y_batch, y_pred)) loss = tf.add_n([main_loss] + model.losses) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) mean_loss(loss) for metric in metrics: metric(y_batch, y_pred) print_status_bar(step * batch_size, len(y_train), mean_loss, metrics) print_status_bar(len(y_train), len(y_train), mean_loss, metrics) for metric in [mean_loss] + metrics: metric.reset_states() ```
github_jupyter
*Регулярное выражение* — это последовательность символов, используемая для поиска и замены текста в строке или файле Регулярные выражения используют два типа символов: - специальные символы: как следует из названия, у этих символов есть специальные значения. Аналогично символу *, который как правило означает «любой символ» (но в регулярных выражениях работает немного иначе, о чем поговорим ниже); - литералы (например: a, b, 1, 2 и т. д.). ``` # Реализовано тут import re help(re) re.match() # Try to apply the pattern at the start of the string, returning a match object, or None if no match was found. re.search() # Scan through string looking for a match to the pattern, returning a match object, or None if no match was found. re.findall() # Return a list of all non-overlapping matches in the string. re.split() # Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. re.sub() # Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the #replacement repl re.compile() # Чтобы собрать регулярки в отдельный объект ``` ## re.match(pattern, string): ``` result = re.match('AV', 'AV Analytics Vidhya') print (result) print (result.start()) # начало и конец найденной подстроки print (result.end()) result.group(0) # что именно result = re.match(r'Analytics', 'AV Analytics Vidhya AV') print (result) ``` ## re.search(pattern, string): ``` result = re.search(r'AV', 'AV Analytics Vidhya AV') print (result.group(0)) result ``` ## re.findall(pattern, string): ``` result = re.findall(r'AV', 'AV Analytics Vidhya AV') result ``` ## re.split(pattern, string, [maxsplit=0]): ``` result = re.split(r'y', 'Analytics') print (result) ``` ``` result = re.split(r'i', 'Analytics Vidhya') print (result) # все возможные участки. result = re.split(r'i', 'Analytics Vidhya',maxsplit=1) print (result) ``` ## re.sub(pattern, repl, string): ``` result = re.sub(r'India', 'the World', 'AV is largest Analytics community of India') print (result) ``` ## re.compile(pattern, repl, string): ``` pattern = re.compile('AV') result = pattern.findall('AV Analytics Vidhya AV') print (result) result2 = pattern.findall('AV is largest analytics community of India') print (result2) ``` ## Определение количества вхождений ``` import re c = re.compile(r'[0-9]+?') str = '32 43 23423424' print(re.findall(c, str)) # Пример 1. Как получить все числа из строки price = '324234dfgdg34234DFDJ343' b = "[a-zA-Z]*" # регулярное выражение для последовательности букв любой длины nums = re.sub(b,"",price) print (nums) ``` ### Задача 1 ``` #попробуем вытащить каждый символ (используя .) # в конечный результат не попал пробел # Теперь вытащим первое слово # А теперь вытащим первое слово ``` ### Задача 2 ``` #используя \w, вытащить два последовательных символа, кроме пробельных, из каждого слова # вытащить два последовательных символа, используя символ границы слова (\b) ``` ### Задача 3 вернуть список доменов из списка адресов электронной почты ``` #Сначала вернем все символы после «@»: str = 'abc.test@gmail.com, xyz@test.in, test.first@analyticsvidhya.com, first.test@rest.biz 111@asd.ry@@' #Если части «.com», «.in» и т. д. не попали в результат. Изменим наш код: # вытащить только домен верхнего уровня, используя группировку — ( ) # Получить список почтовых адресов ``` ### Задача 4: ``` # Извлечь дату из строки str = 'Amit 34-3456 12-05-2007, XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009' #А теперь только года, с помощью скобок и группировок: ``` ### Задача 5 ``` #Извлечь все слова, начинающиеся на гласную. Но сначала получить все слова (\b - границы слов) ``` ### Задача 6: Проверить телефонный номер (номер должен быть длиной 10 знаков и начинаться с 8 или 9) ``` li = ['9999999999', '999999-999', '99999x9999'] for val in li: print() ``` ### Задача 7: Разбить строку по нескольким разделителям ``` line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (";",","," "). ``` # Жадный против нежадного ``` s = '<html><head><title>Title</title>' print (len(s)) print (re.match('<.*>', s).span()) print (re.match('<.*>', s).group()) ``` ``` print re.match('<.*?>', s).group() c = re.compile(r'\d+') str = '0123456789' tuples = re.findall(c, str) print(tuples) #Но как сделать так, чтобы получить каждой отдельное число ``` ## Разное ### Просмотр с возращением ``` #(?=...) - положительный просмотр вперед s = "textl, text2, textЗ text4" p = re.compile(r"\w+(?=[,])", re.S | re.I) # все слова, после которых есть запятая print (p.findall(s)) #(?!...) - отрицательный просмотр вперед import re s = "textl, text2, textЗ text4" p = re.compile(r"[a-z]+[0-9](?![,])", re.S | re.I) # все слова, после которых нет запятой print(p.findall(s)) #(?<=...) - положительный просмотр назад import re s = "textl, text2, textЗ text4" p = re.compile(r"(?<=[,][ ])([a-z]+[0-9])", re.S | re.I) # все слова, перед которыми есть запятая с пробелм print (p.findall(s) ) #(?<!...) - отрицательный просмотр назад s = "textl, text2, textЗ text4" p = re.compile(r"(?<![,]) ([a-z]+[0-9])", re.S | re.I) # все слова, перед которыми есть пробел но нет запятой print (p.findall(s)) #Дано текст: str = 'ruby python 456 java 789 j2not clash2win' #Задача: Найти все упоминания языков программирования в строке. pattern = 'ruby|java|python|c#|fortran|c\+\+' string = 'ruby python 456 java 789 j2not clash2win' re.findall(pattern, string) ``` ## Определитесь, нужны ли вам регулярные выражения для данной задачи. Возможно, получится гораздо быстрее, если вы примените другой способ решения.
github_jupyter
``` import pandas as pd ios = pd.read_csv('app_reviews/rv_ios_app_reviews.csv') ios['Content'] = ios['label_title']+ios['review'] ios = ios.drop(['app_name','app_version','label_title','review'], axis=1) print(ios.shape) ios.head() ios['store_rating'].value_counts() android = pd.read_csv('app_reviews/rv_android_reviews.csv') # android = android.drop(['Unnamed: 0','Unnamed: 0.1','Date','App_name'], axis=1) # android = android.rename(columns={'Numbers':'store_rating'}) print(android.shape) android.head() android = pd.read_csv('app_reviews/rv_android_reviews.csv') # android = android.drop(['Unnamed: 0','Unnamed: 0.1','Date','App_name'], axis=1) # android = android.rename(columns={'Numbers':'store_rating'}) print(android.shape) android.head() android['Star'].value_counts() df = pd.concat([android, ios], join='outer', ignore_index=True, axis=0, sort=True) print(df.shape) df.head() df.isnull().sum() df['store_rating'].value_counts() df['rating'] = df['store_rating'].replace({4:5, 2:1, 3:1}).astype(float).astype(str) # df['rating'] = df['store_rating'] # df['rating'] = df['rating'] df['rating'].value_counts() df.dtypes import spacy import scattertext import pandas as pd pd.set_option('display.max_columns', 500) # Make sure we can see all of the columns pd.set_option('display.max_rows', 200) nlp = spacy.load("en_core_web_lg") # add stop words with open('stopwords.txt', 'r') as f: str = f.read() set_stopwords = set(str.split('\n')) nlp.Defaults.stop_words |= set_stopwords corpus = (scattertext.CorpusFromPandas(Shopping_yelp_sample, category_col='rating', text_col='Content', nlp=nlp) .build() .remove_terms(nlp.Defaults.stop_words, ignore_absences=True) ) term_freq_df = corpus.get_term_freq_df() term_freq_df['highratingscore'] = corpus.get_scaled_f_scores('5.0') term_freq_df['poorratingscore'] = corpus.get_scaled_f_scores('1.0') df_high = term_freq_df.sort_values(by='highratingscore', ascending = False) df_poor = term_freq_df.sort_values(by='poorratingscore', ascending=False) # df_high = df_high[['highratingscore', 'poorratingscore']] df_high['highratingscore'] = round(df_high['highratingscore'], 2) df_high['poorratingscore'] = round(df_high['poorratingscore'], 2) df_high = df_high.reset_index(drop=False) # df_high = df_high.head(20) # df_poor = df_poor[['highratingscore', 'poorratingscore']] df_poor['highratingscore'] = round(df_poor['highratingscore'], 2) df_poor['poorratingscore'] = round(df_poor['poorratingscore'], 2) df_poor = df_poor.reset_index(drop=False) # df_poor = df_poor.head(20) # df_terms = pd.concat([df_high, df_poor], # ignore_index=True) # df_terms Shopping_yelp_sample_high = df_high Shopping_yelp_sample_poor = df_poor Shopping_yelp_sample_high.sort_values(by='5.0 freq', ascending = False).head(100) Shopping_yelp_sample_poor.sort_values(by='1.0 freq', ascending = False).head(100) Auto_Repair_yelp_high.sort_values(by='5.0 freq', ascending = False).head(100) Auto_Repair_yelp_poor.sort_values(by='1.0 freq', ascending = False).head(100) Hair_Salons_yelp_high.sort_values(by='5.0 freq', ascending = False).head(100) Hair_Salons_yelp_poor.sort_values(by='1.0 freq', ascending = False).head(100) Fashion_yelp_high.sort_values(by='5.0 freq', ascending = False) Fashion_yelp_poor.sort_values(by='1.0 freq', ascending = False).head(100) Professional_Services_yelp_poor_json = Professional_Services_yelp_poor_json.drop([136,3577,2707,664626,1979,2678]) Professional_Services_yelp_poor_json.sort_values(by='1 freq', ascending = False).head(10) Professional_Services_yelp_poor.sort_values(by='1 freq', ascending = False).head(100) Professional_Services_yelp_high_json = Professional_Services_yelp_high_json.drop([1777]) Professional_Services_yelp_best_json = Professional_Services_yelp_high_json.sort_values(by='5 freq', ascending = False).head() Professional_Services_yelp_high.sort_values(by='5 freq', ascending = False).head() Professional_Services_yelp_poor_json.sort_values(by='1 freq', ascending = False).head() df = df.head() df.to_json('Fashion_yelp_high_rating_words.json', orient='records', lines=True) ```
github_jupyter
Define the network: ``` import torch # PyTorch base from torch.autograd import Variable # Tensor class w gradients import torch.nn as nn # modules, layers, loss fns import torch.nn.functional as F # Conv,Pool,Loss,Actvn,Nrmlz fns from here class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # Kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an Affine Operation: y = Wx + b self.fc1 = nn.Linear(16*5*5, 120) # Linear is Dense/Fully-Connected self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window # x = torch.nn.functional.max_pool2d(torch.nn.functional.relu(self.conv1(x)), (2,2)) x = F.max_pool2d(F.relu(self.conv1(x)), (2,2)) # If size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features net = Net() print(net) ``` You just have to define the `forward` function, and the `backward` function (where the gradients are computed) is automatically defined for you using `autograd`. You can use any of the Tensor operations in the `forward` function. The learnable parameteres of a model are returns by `net.parameters()` ``` pars = list(net.parameters()) print(len(pars)) print(pars[0].size()) # conv1's .weight ``` The input to the forward is an `autograd.Variable`, and so is the output. **NOTE**: Expected input size to this net(LeNet) is 32x32. To use this net on MNIST dataset, please resize the images from the dataset to 32x32. ``` input = Variable(torch.randn(1, 1, 32, 32)) out = net(input) print(out) ``` Zero the gradient buffers of all parameters and backprops with random gradients: ``` net.zero_grad() out.backward(torch.randn(1, 10)) ``` **!NOTE¡**: `torch.nn` only supports mini-batches. The entire `torch.nn` package only supports inputs that are a mini-batch of samples, and not a single sample. For example, `nn.Conv2d` will take in a 4D Tensor of `nSamples x nChannels x Height x Width`. If you have a single sample, just use `input.unsqueeze(0)` to add a fake batch dimension. Before proceeding further, let's recap all the classes you've seen so far. **Recap**: * `torch.Tensor` - A *multi-dimensional array*. * `autograd.Variable` - *Wraps a Tensor and records the history of operations* applied to it. Has the same API as a `Tensor`, with some additions like `backward()`. Also *holds the gradient* wrt the tensor. * `nn.Module` - Neural network module. *Convenient way of encapsulating parameters*, with helpers for moving them to GPU, exporting, loading, etc. * `nn.Parameter` - A kind of Variable, that is *automatically registered as a parameter when assigned as an attribute to a* `Module`. * `autograd.Function` - Implements *forward and backward definitions of an autograd operation*. Every `Variable` operation creates at least a single `Function` node that connects to functions that created a `Variable` and *encodes its history*. **At this point, we covered:** * Defining a neural network * Processing inputs and calling backward. **Still Left:** * Computing the loss * Updating the weights of the network
github_jupyter
``` import os import numpy as np import keras import tensorflow as tf import pandas as pd import glob import json import random import time from PIL import Image BATCH_SIZE = 128 TRAINING_SPLIT = 0.8 EPOCHS = 20 prefix = '/opt/ml/' input_path = prefix + 'input/data' output_path = os.path.join(prefix, 'output') model_path = os.path.join(prefix, 'model') param_path = os.path.join(prefix, 'input/config/hyperparameters.json') model_loc = os.path.join(model_path, 'car-model.pkl') # This algorithm has a single channel of input data called 'training'. Since we run in # File mode, the input files are copied to the directory specified here. channel_name='training' training_path = os.path.join(input_path, channel_name) INPUT_TENSOR_NAME = "inputs" SIGNATURE_NAME = "serving_default" LEARNING_RATE = 0.001 def train(): print('Starting the training.') try: # Read in any hyperparameters that the user passed with the training job with open(param_path, 'r') as tc: trainingParams = json.load(tc) input_files = [ os.path.join(training_path, file) for file in os.listdir(training_path) ] if len(input_files) == 0: raise ValueError(('There are no files in {}.\n' + 'This usually indicates that the channel ({}) was incorrectly specified,\n' + 'the data specification in S3 was incorrectly specified or the role specified\n' + 'does not have permission to access the data.').format(training_path, channel_name)) tubgroup = TubGroup(input_path) total_records = len(tubgroup.df) total_train = int(total_records * TRAINING_SPLIT) total_val = total_records - total_train steps_per_epoch = total_train // BATCH_SIZE X_keys = ['cam/image_array'] y_keys = ['user/angle', 'user/throttle'] train_gen, val_gen = tubgroup.get_train_val_gen(X_keys, y_keys, record_transform=rt, batch_size=BATCH_SIZE, train_frac=TRAINING_SPLIT) save_best = keras.callbacks.ModelCheckpoint(model_loc, monitor='val_loss', verbose=1, save_best_only=True, mode='min') #stop training if the validation error stops improving. early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.0005, patience=5, verbose=1, mode='auto') callbacks_list = [save_best] callbacks_list.append(early_stop) model = default_categorical() hist = model.fit_generator( train_gen, steps_per_epoch=11, epochs=EPOCHS, verbose=1, validation_data=val_gen, callbacks=callbacks_list, validation_steps=11*(1.0 - TRAINING_SPLIT)) print('Training complete.') except Exception as e: # Write out an error file. This will be returned as the failureReason in the # DescribeTrainingJob result. trc = traceback.format_exc() with open(os.path.join(output_path, 'failure'), 'w') as s: s.write('Exception during training: ' + str(e) + '\n' + trc) # Printing this causes the exception to be in the training job logs, as well. print('Exception during training: ' + str(e) + '\n' + trc, file=sys.stderr) # A non-zero exit code causes the training job to be marked as Failed. sys.exit(255) if __name__ == '__main__': train() # A zero exit code causes the job to be marked a Succeeded. sys.exit(0) class Tub(object): """ A datastore to store sensor data in a key, value format. Accepts str, int, float, image_array, image, and array data types. For example: #Create a tub to store speed values. >>> path = '~/mydonkey/test_tub' >>> inputs = ['user/speed', 'cam/image'] >>> types = ['float', 'image'] >>> t=Tub(path=path, inputs=inputs, types=types) """ def __init__(self, path, inputs=None, types=None): self.path = os.path.expanduser(path) print('path_in_tub:', self.path) self.meta_path = os.path.join(self.path, 'meta.json') self.df = None exists = os.path.exists(self.path) if exists: #load log and meta print("Tub exists: {}".format(self.path)) with open(self.meta_path, 'r') as f: self.meta = json.load(f) self.current_ix = self.get_last_ix() + 1 elif not exists and inputs: print('Tub does NOT exist. Creating new tub...') #create log and save meta os.makedirs(self.path) self.meta = {'inputs': inputs, 'types': types} with open(self.meta_path, 'w') as f: json.dump(self.meta, f) self.current_ix = 0 print('New tub created at: {}'.format(self.path)) else: msg = "The tub path you provided doesn't exist and you didnt pass any meta info (inputs & types)" + \ "to create a new tub. Please check your tub path or provide meta info to create a new tub." raise AttributeError(msg) self.start_time = time.time() def get_last_ix(self): index = self.get_index() return max(index) def update_df(self): df = pd.DataFrame([self.get_json_record(i) for i in self.get_index(shuffled=False)]) self.df = df def get_df(self): if self.df is None: self.update_df() return self.df def get_index(self, shuffled=True): files = next(os.walk(self.path))[2] record_files = [f for f in files if f[:6]=='record'] def get_file_ix(file_name): try: name = file_name.split('.')[0] num = int(name.split('_')[1]) except: num = 0 return num nums = [get_file_ix(f) for f in record_files] if shuffled: random.shuffle(nums) else: nums = sorted(nums) return nums @property def inputs(self): return list(self.meta['inputs']) @property def types(self): return list(self.meta['types']) def get_input_type(self, key): input_types = dict(zip(self.inputs, self.types)) return input_types.get(key) def write_json_record(self, json_data): path = self.get_json_record_path(self.current_ix) try: with open(path, 'w') as fp: json.dump(json_data, fp) #print('wrote record:', json_data) except TypeError: print('troubles with record:', json_data) except FileNotFoundError: raise except: print("Unexpected error:", sys.exc_info()[0]) raise def get_num_records(self): import glob files = glob.glob(os.path.join(self.path, 'record_*.json')) return len(files) def make_record_paths_absolute(self, record_dict): #make paths absolute d = {} for k, v in record_dict.items(): if type(v) == str: #filename if '.' in v: v = os.path.join(self.path, v) d[k] = v return d def check(self, fix=False): ''' Iterate over all records and make sure we can load them. Optionally remove records that cause a problem. ''' print('Checking tub:%s.' % self.path) print('Found: %d records.' % self.get_num_records()) problems = False for ix in self.get_index(shuffled=False): try: self.get_record(ix) except: problems = True if fix == False: print('problems with record:', self.path, ix) else: print('problems with record, removing:', self.path, ix) self.remove_record(ix) if not problems: print("No problems found.") def remove_record(self, ix): ''' remove data associate with a record ''' record = self.get_json_record_path(ix) os.unlink(record) def put_record(self, data): """ Save values like images that can't be saved in the csv log and return a record with references to the saved values that can be saved in a csv. """ json_data = {} self.current_ix += 1 for key, val in data.items(): typ = self.get_input_type(key) if typ in ['str', 'float', 'int', 'boolean']: json_data[key] = val elif typ is 'image': path = self.make_file_path(key) val.save(path) json_data[key]=path elif typ == 'image_array': img = Image.fromarray(np.uint8(val)) name = self.make_file_name(key, ext='.jpg') img.save(os.path.join(self.path, name)) json_data[key]=name else: msg = 'Tub does not know what to do with this type {}'.format(typ) raise TypeError(msg) self.write_json_record(json_data) return self.current_ix def get_json_record_path(self, ix): return os.path.join(self.path, 'record_'+str(ix)+'.json') def get_json_record(self, ix): path = self.get_json_record_path(ix) try: with open(path, 'r') as fp: json_data = json.load(fp) except UnicodeDecodeError: raise Exception('bad record: %d. You may want to run `python manage.py check --fix`' % ix) except FileNotFoundError: raise except: print("Unexpected error:", sys.exc_info()[0]) raise record_dict = self.make_record_paths_absolute(json_data) return record_dict def get_record(self, ix): json_data = self.get_json_record(ix) data = self.read_record(json_data) return data def read_record(self, record_dict): data={} for key, val in record_dict.items(): typ = self.get_input_type(key) #load objects that were saved as separate files if typ == 'image_array': img = Image.open((val)) val = np.array(img) data[key] = val return data def make_file_name(self, key, ext='.png'): name = '_'.join([str(self.current_ix), key, ext]) name = name = name.replace('/', '-') return name def delete(self): """ Delete the folder and files for this tub. """ import shutil shutil.rmtree(self.path) def shutdown(self): pass def get_record_gen(self, record_transform=None, shuffle=True, df=None): if df is None: df = self.get_df() while True: for row in self.df.iterrows(): if shuffle: record_dict = df.sample(n=1).to_dict(orient='record')[0] if record_transform: record_dict = record_transform(record_dict) record_dict = self.read_record(record_dict) yield record_dict def get_batch_gen(self, keys, record_transform=None, batch_size=128, shuffle=True, df=None): record_gen = self.get_record_gen(record_transform, shuffle=shuffle, df=df) if keys == None: keys = list(self.df.columns) while True: record_list = [] for _ in range(batch_size): record_list.append(next(record_gen)) batch_arrays = {} for i, k in enumerate(keys): arr = np.array([r[k] for r in record_list]) # if len(arr.shape) == 1: # arr = arr.reshape(arr.shape + (1,)) batch_arrays[k] = arr yield batch_arrays def get_train_gen(self, X_keys, Y_keys, batch_size=128, record_transform=None, df=None): batch_gen = self.get_batch_gen(X_keys + Y_keys, batch_size=batch_size, record_transform=record_transform, df=df) while True: batch = next(batch_gen) X = [batch[k] for k in X_keys] Y = [batch[k] for k in Y_keys] yield X, Y def get_train_val_gen(self, X_keys, Y_keys, batch_size=128, record_transform=None, train_frac=.8): train_df = train=self.df.sample(frac=train_frac,random_state=200) val_df = self.df.drop(train_df.index) train_gen = self.get_train_gen(X_keys=X_keys, Y_keys=Y_keys, batch_size=batch_size, record_transform=record_transform, df=train_df) val_gen = self.get_train_gen(X_keys=X_keys, Y_keys=Y_keys, batch_size=batch_size, record_transform=record_transform, df=val_df) return train_gen, val_gen class TubHandler(): def __init__(self, path): self.path = os.path.expanduser(path) def get_tub_list(self,path): folders = next(os.walk(path))[1] return folders def next_tub_number(self, path): def get_tub_num(tub_name): try: num = int(tub_name.split('_')[1]) except: num = 0 return num folders = self.get_tub_list(path) numbers = [get_tub_num(x) for x in folders] #numbers = [i for i in numbers if i is not None] next_number = max(numbers+[0]) + 1 return next_number def create_tub_path(self): tub_num = self.next_tub_number(self.path) date = datetime.datetime.now().strftime('%y-%m-%d') name = '_'.join(['tub',str(tub_num),date]) tub_path = os.path.join(self.path, name) return tub_path def new_tub_writer(self, inputs, types): tub_path = self.create_tub_path() tw = TubWriter(path=tub_path, inputs=inputs, types=types) return tw class TubImageStacker(Tub): ''' A Tub for training a NN with images that are the last three records stacked togther as 3 channels of a single image. The idea is to give a simple feedforward NN some chance of building a model based on motion. If you drive with the ImageFIFO part, then you don't need this. Just make sure your inference pass uses the ImageFIFO that the NN will now expect. ''' def rgb2gray(self, rgb): ''' take a numpy rgb image return a new single channel image converted to greyscale ''' return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) def stack3Images(self, img_a, img_b, img_c): ''' convert 3 rgb images into grayscale and put them into the 3 channels of a single output image ''' width, height, _ = img_a.shape gray_a = self.rgb2gray(img_a) gray_b = self.rgb2gray(img_b) gray_c = self.rgb2gray(img_c) img_arr = np.zeros([width, height, 3], dtype=np.dtype('B')) img_arr[...,0] = np.reshape(gray_a, (width, height)) img_arr[...,1] = np.reshape(gray_b, (width, height)) img_arr[...,2] = np.reshape(gray_c, (width, height)) return img_arr def get_record(self, ix): ''' get the current record and two previous. stack the 3 images into a single image. ''' data = super(TubImageStacker, self).get_record(ix) if ix > 1: data_ch1 = super(TubImageStacker, self).get_record(ix - 1) data_ch0 = super(TubImageStacker, self).get_record(ix - 2) json_data = self.get_json_record(ix) for key, val in json_data.items(): typ = self.get_input_type(key) #load objects that were saved as separate files if typ == 'image': val = self.stack3Images(data_ch0[key], data_ch1[key], data[key]) data[key] = val elif typ == 'image_array': img = self.stack3Images(data_ch0[key], data_ch1[key], data[key]) val = np.array(img) return data class TubTimeStacker(TubImageStacker): ''' A Tub for training N with records stacked through time. The idea here is to force the network to learn to look ahead in time. Init with an array of time offsets from the current time. ''' def __init__(self, frame_list, *args, **kwargs): ''' frame_list of [0, 10] would stack the current and 10 frames from now records togther in a single record with just the current image returned. [5, 90, 200] would return 3 frames of records, ofset 5, 90, and 200 frames in the future. ''' super(TubTimeStacker, self).__init__(*args, **kwargs) self.frame_list = frame_list def get_record(self, ix): ''' stack the N records into a single record. Each key value has the record index with a suffix of _N where N is the frame offset into the data. ''' data = {} for i, iOffset in enumerate(self.frame_list): iRec = ix + iOffset try: json_data = self.get_json_record(iRec) except FileNotFoundError: pass except: pass for key, val in json_data.items(): typ = self.get_input_type(key) #load only the first image saved as separate files if typ == 'image' and i == 0: val = Image.open(os.path.join(self.path, val)) data[key] = val elif typ == 'image_array' and i == 0: d = super(TubTimeStacker, self).get_record(ix) data[key] = d[key] else: ''' we append a _offset to the key so user/angle out now be user/angle_0 ''' new_key = key + "_" + str(iOffset) data[new_key] = val return data class TubGroup(Tub): def __init__(self, tub_paths_arg): tub_paths = expand_path_arg(tub_paths_arg) print('TubGroup:tubpaths:', tub_paths) tubs = [Tub(path) for path in tub_paths] self.input_types = {} record_count = 0 for t in tubs: t.update_df() record_count += len(t.df) self.input_types.update(dict(zip(t.inputs, t.types))) print('joining the tubs {} records together. This could take {} minutes.'.format(record_count, int(record_count / 300000))) self.meta = {'inputs': list(self.input_types.keys()), 'types': list(self.input_types.values())} self.df = pd.concat([t.df for t in tubs], axis=0, join='inner') def expand_path_arg(path_str): path_list = path_str.split(",") expanded_paths = [] for path in path_list: paths = expand_path_mask(path) expanded_paths += paths return expanded_paths def expand_path_mask(path): matches = [] path = os.path.expanduser(path) for file in glob.glob(path): if os.path.isdir(file): matches.append(os.path.join(os.path.abspath(file))) return matches def linear_bin(a): a = a + 1 b = round(a / (2/14)) arr = np.zeros(15) arr[int(b)] = 1 return arr def rt(record): record['user/angle'] = linear_bin(record['user/angle']) return record def default_categorical(): from keras.layers import Input, Dense, merge from keras.models import Model from keras.layers import Convolution2D, MaxPooling2D, Reshape, BatchNormalization from keras.layers import Activation, Dropout, Flatten, Dense img_in = Input(shape=(160, 120, 3), name='img_in') # First layer, input layer, Shape comes from camera.py resolution, RGB x = img_in x = Convolution2D(24, (5,5), strides=(2,2), activation='relu')(x) # 24 features, 5 pixel x 5 pixel kernel (convolution, feauture) window, 2wx2h stride, relu activation x = Convolution2D(32, (5,5), strides=(2,2), activation='relu')(x) # 32 features, 5px5p kernel window, 2wx2h stride, relu activatiion x = Convolution2D(64, (5,5), strides=(2,2), activation='relu')(x) # 64 features, 5px5p kernal window, 2wx2h stride, relu x = Convolution2D(64, (3,3), strides=(2,2), activation='relu')(x) # 64 features, 3px3p kernal window, 2wx2h stride, relu x = Convolution2D(64, (3,3), strides=(1,1), activation='relu')(x) # 64 features, 3px3p kernal window, 1wx1h stride, relu # Possibly add MaxPooling (will make it less sensitive to position in image). Camera angle fixed, so may not to be needed x = Flatten(name='flattened')(x) # Flatten to 1D (Fully connected) x = Dense(100, activation='relu')(x) # Classify the data into 100 features, make all negatives 0 x = Dropout(.1)(x) # Randomly drop out (turn off) 10% of the neurons (Prevent overfitting) x = Dense(50, activation='relu')(x) # Classify the data into 50 features, make all negatives 0 x = Dropout(.1)(x) # Randomly drop out 10% of the neurons (Prevent overfitting) #categorical output of the angle angle_out = Dense(15, activation='softmax', name='angle_out')(x) # Connect every input with every output and output 15 hidden units. Use Softmax to give percentage. 15 categories and find best one based off percentage 0.0-1.0 #continous output of throttle throttle_out = Dense(1, activation='relu', name='throttle_out')(x) # Reduce to 1 number, Positive number only model = Model(inputs=[img_in], outputs=[angle_out, throttle_out]) model.compile(optimizer='adam', loss={'angle_out': 'categorical_crossentropy', 'throttle_out': 'mean_absolute_error'}, loss_weights={'angle_out': 0.9, 'throttle_out': .001}) return model ```
github_jupyter
# Recommendations with IBM For this project I analyze the interactions that users have with articles on the IBM Watson Studio platform, and make recommendations to them about new articles they will like. ## Table of Contents I. [Exploratory Data Analysis](#Exploratory-Data-Analysis)<br> II. [Rank Based Recommendations](#Rank)<br> III. [User-User Based Collaborative Filtering](#User-User)<br> IV. [Content Based Recommendations (EXTRA - NOT REQUIRED)](#Content-Recs)<br> V. [Matrix Factorization](#Matrix-Fact)<br> VI. [Extras & Concluding](#conclusions)<br> VII. [Resources](#resources) ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import project_tests as t import pickle %matplotlib inline df = pd.read_csv('data/user-item-interactions.csv') df_content = pd.read_csv('data/articles_community.csv') del df['Unnamed: 0'] del df_content['Unnamed: 0'] # Show df to get an idea of the data df.head() # Show df_content to get an idea of the data df_content.head() # check number of rows and columns df.shape, df_content.shape # check the data sets df.info() # check the data sets df_content.info() # check for missing values df.isnull().sum() # check for missing values df_content.isnull().sum() # number of unique articles df['article_id'].nunique() # number of unique users df['email'].nunique() ``` ### <a class="anchor" id="Exploratory-Data-Analysis">Part I : Exploratory Data Analysis</a> Use the dictionary and cells below to provide some insight into the descriptive statistics of the data. `1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of times each user interacts with an article. Using the seaborn distplot for vizualizations http://seaborn.pydata.org/generated/seaborn.distplot.html ``` # assigning pivot table to a variable user_interact = df.groupby('email').count()['article_id'] # plotting with seaborn sns.distplot(user_interact, bins=40) # seaborn rug plot version sns.distplot(user_interact, rug=True, hist=False, vertical=True) # plotting with pandas user_interact.hist(bins=40) # the max number of user_article interactions df.groupby('email')['article_id'].count().max() # the medin number of user_article interactions df.groupby('email')['article_id'].count().median() # Fill in the median and maximum number of user_article interactios below # 50% of individuals interact with ___ number of articles or fewer. median_val = df.groupby('email')['article_id'].count().median() # The maximum number of user-article interactions by any 1 user is ______. max_views_by_user = df.groupby('email')['article_id'].count().max() ``` `2.` Explore and remove duplicate articles from the **df_content** dataframe. ``` # check number of rows and columns of df_content df_content.shape # Find and explore duplicate articles df_content.duplicated().sum() # Remove any rows that have the same article_id - only keep the first df_content.drop_duplicates(inplace = True) ``` `3.` Use the cells below to find: **a.** The number of unique articles that have an interaction with a user. **b.** The number of unique articles in the dataset (whether they have any interactions or not).<br> **c.** The number of unique users in the dataset. (excluding null values) <br> **d.** The number of user-article interactions in the dataset. ``` # checking df for uniuqe values df.nunique() # checking df_content for unique values df_content.nunique() # The number of unique articles that have at least one interaction df.article_id.nunique() # The number of unique articles on the IBM platform df_content.article_id.nunique() # The number of unique users (email column refers to users) df.email.nunique() # The number of user-article interactions = the number of rows in df len(df) # The number of unique articles that have at least one interaction unique_articles = df.article_id.nunique() # The number of unique articles on the IBM platform total_articles = df_content.article_id.nunique() # The number of unique users unique_users = df.email.nunique() # The number of user-article interactions user_article_interactions = len(df) ``` `4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belonged to a single user (which is how they are stored using the function below). ``` # check for the most viewed article_id df['article_id'].value_counts() most_viewed_article_id = '1429.0' # The most viewed article in the dataset as a string with one value following the decimal max_views = 937 # The most viewed article in the dataset was viewed how many times? ## No need to change the code here - this will be helpful for later parts of the notebook # Run this cell to map the user email to a user_id column and remove the email column def email_mapper(): coded_dict = dict() cter = 1 email_encoded = [] for val in df['email']: if val not in coded_dict: coded_dict[val] = cter cter+=1 email_encoded.append(coded_dict[val]) return email_encoded email_encoded = email_mapper() del df['email'] df['user_id'] = email_encoded # show header df.head() ## If you stored all your results in the variable names above, ## you shouldn't need to change anything in this cell sol_1_dict = { '`50% of individuals have _____ or fewer interactions.`': median_val, '`The total number of user-article interactions in the dataset is ______.`': user_article_interactions, '`The maximum number of user-article interactions by any 1 user is ______.`': max_views_by_user, '`The most viewed article in the dataset was viewed _____ times.`': max_views, '`The article_id of the most viewed article is ______.`': most_viewed_article_id, '`The number of unique articles that have at least 1 rating ______.`': unique_articles, '`The number of unique users in the dataset is ______`': unique_users, '`The number of unique articles on the IBM platform`': total_articles } # Test your dictionary against the solution t.sol_1_test(sol_1_dict) ``` ### <a class="anchor" id="Rank">Part II: Rank-Based Recommendations</a> Unlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with. `1.` Fill in the function below to return the **n** top articles ordered with most interactions as the top. Test your function using the tests below. ``` df.head() # testing a function df['article_id'].value_counts().iloc[:10].index # testing a function 2 df.groupby(by='title').count().sort_values(by='user_id', ascending=False).head().index.tolist() # testing a function 3 df.groupby(by='article_id').count().sort_values(by='user_id', ascending=False).head(10).index.tolist() # testing a funciton 4 list(df.groupby(by='article_id').count().sort_values(by='user_id', ascending=False).head(10).index) def get_top_articles(n, df=df): ''' INPUT: n - (int) the number of top articles to return df - (pandas dataframe) df as defined at the top of the notebook OUTPUT: top_articles - (list) A list of the top 'n' article titles ''' # creating a list with top articles using 'title' top_articles = df['title'].value_counts().iloc[:n].index.tolist() return top_articles # Return the top article titles from df (not df_content) def get_top_article_ids(n, df=df): ''' INPUT: n - (int) the number of top articles to return df - (pandas dataframe) df as defined at the top of the notebook OUTPUT: top_articles - (list) A list of the top 'n' article titles ''' # creating a list with top article ids top_articles_ids = df['article_id'].value_counts().iloc[:n].index.tolist() return top_articles_ids # Return the top article ids print(get_top_articles(10)) print(get_top_article_ids(10)) print(get_top_articles(20)) print(get_top_article_ids(20)) # Test your function by returning the top 5, 10, and 20 articles top_5 = get_top_articles(5) top_10 = get_top_articles(10) top_20 = get_top_articles(20) # Test each of your three lists from above t.sol_2_test(get_top_articles) ``` ### <a class="anchor" id="User-User">Part III: User-User Based Collaborative Filtering</a> `1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. * Each **user** should only appear in each **row** once. * Each **article** should only show up in one **column**. * **If a user has interacted with an article, then place a 1 where the user-row meets for that article-column**. It does not matter how many times a user has interacted with the article, all entries where a user has interacted with an article should be a 1. * **If a user has not interacted with an item, then place a zero where the user-row meets for that article-column**. Use the tests to make sure the basic structure of your matrix matches what is expected by the solution. ``` df.groupby(['user_id', 'article_id']).agg(lambda x: 1).unstack().fillna(0) # create the user-article matrix with 1's and 0's def create_user_item_matrix(df): ''' INPUT: df - pandas dataframe with article_id, title, user_id columns OUTPUT: user_item - user item matrix Description: Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with an article and a 0 otherwise ''' # Using groupby and lambda function to create the matrix user_item = df.groupby(['user_id', 'article_id']).agg(lambda x: 1).unstack().fillna(0) return user_item # return the user_item matrix user_item = create_user_item_matrix(df) ## Tests: You should just need to run this cell. Don't change the code. assert user_item.shape[0] == 5149, "Oops! The number of users in the user-article matrix doesn't look right." assert user_item.shape[1] == 714, "Oops! The number of articles in the user-article matrix doesn't look right." assert user_item.sum(axis=1)[1] == 36, "Oops! The number of articles seen by user 1 doesn't look right." print("You have passed our quick tests! Please proceed!") ``` `2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here are binary, it (perhaps) makes sense to compute similarity as the dot product of two users. Use the tests to test your function. ``` def find_similar_users(user_id, user_item=user_item): ''' INPUT: user_id - (int) a user_id user_item - (pandas dataframe) matrix of users by articles: 1's when a user has interacted with an article, 0 otherwise OUTPUT: similar_users - (list) an ordered list where the closest users (largest dot product users) are listed first Description: Computes the similarity of every pair of users based on the dot product Returns an ordered list ''' # compute similarity of each user to the provided user similar_mat = user_item.dot(user_item.loc[user_id].T) # sort by similarity most_similar_users = similar_mat.sort_values(ascending=False).index.tolist() most_similar_users.remove(user_id) return most_similar_users # return a list of the users in order from most to least similar # Do a spot check of your function print("The 10 most similar users to user 1 are: {}".format(find_similar_users(1)[:10])) print("The 5 most similar users to user 3933 are: {}".format(find_similar_users(3933)[:5])) print("The 3 most similar users to user 46 are: {}".format(find_similar_users(46)[:3])) ``` `3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user. ``` def get_article_names(article_ids, df=df): ''' INPUT: article_ids - (list) a list of article ids df - (pandas dataframe) df as defined at the top of the notebook OUTPUT: article_names - (list) a list of article names associated with the list of article ids (this is identified by the title column) ''' # create article names article_names = [df[df['article_id'] == float(id)]['title'].values[0] for id in article_ids] return article_names # Return the article names associated with list of article ids def get_user_articles(user_id, user_item=user_item): ''' INPUT: user_id - (int) a user id user_item - (pandas dataframe) matrix of users by articles: 1's when a user has interacted with an article, 0 otherwise OUTPUT: article_ids - (list) a list of the article ids seen by the user article_names - (list) a list of article names associated with the list of article ids (this is identified by the doc_full_name column in df_content) Description: Provides a list of the article_ids and article titles that have been seen by a user ''' # Your code here article_ids = [str(id) for id in list(user_item.loc[user_id][user_item.loc[user_id]==1].title.index)] article_names = get_article_names(article_ids) return article_ids, article_names # return the ids and names def user_user_recs(user_id, m=10): ''' INPUT: user_id - (int) a user id m - (int) the number of recommendations you want for the user OUTPUT: recs - (list) a list of recommendations for the user Description: Loops through the users based on closeness to the input user_id For each user - finds articles the user hasn't seen before and provides them as recs Does this until m recommendations are found Notes: Users who are the same closeness are chosen arbitrarily as the 'next' user For the user where the number of recommended articles starts below m and ends exceeding m, the last items are chosen arbitrarily ''' # create user-user recommendation recs = [] most_similar_users = find_similar_users(user_id) the_user_articles, the_article_names = get_user_articles(user_id) for user in most_similar_users: article_ids, article_names = get_user_articles(user) for id in article_ids: if id not in the_user_articles: recs.append(id) if len(recs) >= m: break if len(recs) >= m: break if len(recs) < m: for id in str(df['article_id']): if id not in the_user_articles: recs.append(id) if len(recs) >= m: break return recs # return your recommendations for this user_id # Check Results get_article_names(user_user_recs(1, 10)) # Return 10 recommendations for user 1 ``` `4.` Now we are going to improve the consistency of the **user_user_recs** function from above. * Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions. * Instead of arbitrarily choosing articles from the user where the number of recommended articles starts below m and ends exceeding m, choose articles with the articles with the most total interactions before choosing those with fewer total interactions. This ranking should be what would be obtained from the **top_articles** function you wrote earlier. ``` def get_top_sorted_users(user_id, df=df, user_item=user_item): ''' INPUT: user_id - (int) df - (pandas dataframe) df as defined at the top of the notebook user_item - (pandas dataframe) matrix of users by articles: 1's when a user has interacted with an article, 0 otherwise OUTPUT: neighbors_df - (pandas dataframe) a dataframe with: neighbor_id - is a neighbor user_id similarity - measure of the similarity of each user to the provided user_id num_interactions - the number of articles viewed by the user - if a u Other Details - sort the neighbors_df by the similarity and then by number of interactions where highest of each is higher in the dataframe ''' # creating a variable based on panda dataframe of the columns we need neighbors_df = pd.DataFrame(columns=['neighbor_id', 'similarity', 'num_interactions']) for i in user_item.index.values: if i == user_id: continue neighbor_id = i similarity = user_item[user_item.index == user_id].dot(user_item.loc[i].T).values[0] num_interactions = user_item.loc[i].values.sum() neighbors_df.loc[neighbor_id] = [neighbor_id, similarity, num_interactions] neighbors_df['similarity'] = neighbors_df['similarity'].astype('int') neighbors_df['neighbor_id'] = neighbors_df['neighbor_id'].astype('int') neighbors_df = neighbors_df.sort_values(by = ['similarity', 'neighbor_id'], ascending = [False, True]) return neighbors_df # Return the dataframe specified in the doc_string def user_user_recs_part2(user_id, m=10): ''' INPUT: user_id - (int) a user id m - (int) the number of recommendations you want for the user OUTPUT: recs - (list) a list of recommendations for the user by article id rec_names - (list) a list of recommendations for the user by article title Description: Loops through the users based on closeness to the input user_id For each user - finds articles the user hasn't seen before and provides them as recs Does this until m recommendations are found Notes: * Choose the users that have the most total article interactions before choosing those with fewer article interactions. * Choose articles with the articles with the most total interactions before choosing those with fewer total interactions. ''' # create a list with recommendations based on total article interactions top_df = get_top_sorted_users(user_id) uid_list = top_df['neighbor_id'].values.tolist() recs = [] name_ids = [] exp_article_ids = list(set(df[df['user_id'] == user_id]['article_id'].values.tolist())) for uid in uid_list: recs += df[df['user_id'] == uid]['article_id'].values.tolist() recs = list(set(recs)) recs = [ x for x in recs if x not in exp_article_ids ] rec_all = df[df.article_id.isin(recs)][['article_id','title']].drop_duplicates().head(m) recs = rec_all['article_id'].values.tolist() rec_names = rec_all['title'].values.tolist() return recs, rec_names # Quick spot check - don't change this code - just use it to test your functions rec_ids, rec_names = user_user_recs_part2(20, 10) print("The top 10 recommendations for user 20 are the following article ids:") print(rec_ids) print() print("The top 10 recommendations for user 20 are the following article names:") print(rec_names) ``` `5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below. ``` # Find the user that is most similar to user 1 find_similar_users(1)[0] # Find the 10th most similar user to user 131 find_similar_users(131)[10] get_top_sorted_users(1).head() get_top_sorted_users(131).head(10) ### Tests with a dictionary of results # Find the user that is most similar to user 1 user1_most_sim = find_similar_users(1)[0] # Find the 10th most similar user to user 131 user131_10th_sim = find_similar_users(131)[10] ## Dictionary Test Here sol_5_dict = { 'The user that is most similar to user 1.': user1_most_sim, 'The user that is the 10th most similar to user 131': user131_10th_sim, } t.sol_5_test(sol_5_dict) ``` `6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users. **Provide your response here.** RESPONSE: The reccomendations for new users is always challenging. New users have no previous records thus it's impossible to use user collaborative filtering based recommendations methods. The solution would be to use a content based recommendations. While in collaborative filtering we used the connections of users and items, in content based method, we would use the information about the users and items, but not the connections between them. **Rank based filtering would help here with new users: get_top_articles and get_top_articles_ids are the fucntions that we can use.** `7.` Using your existing functions, provide the top 10 recommended articles you would provide for the a new user below. You can test your function against our thoughts to make sure we are all on the same page with how we might make a recommendation. ``` new_user = '0.0' # What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles. # Provide a list of the top 10 article ids you would give to new_user = get_top_article_ids(10) new_user_recs = map(str, new_user) assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1304.0','1170.0','1431.0','1330.0']), "Oops! It makes sense that in this case we would want to recommend the most popular articles, because we don't know anything about these users." print("That's right! Nice job!") ``` ### <a class="anchor" id="Content-Recs">Part IV: Content Based Recommendations (EXTRA - NOT REQUIRED)</a> Another method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the **doc_body**, **doc_description**, or **doc_full_name**. There isn't one way to create a content based recommendation, especially considering that each of these columns hold content related information. `1.` Use the function body below to create a content based recommender. Since there isn't one right answer for this recommendation tactic, no test functions are provided. Feel free to change the function inputs if you decide you want to try a method that requires more input values. The input values are currently set with one idea in mind that you may use to make content based recommendations. One additional idea is that you might want to choose the most popular recommendations that meet your 'content criteria', but again, there is a lot of flexibility in how you might make these recommendations. ### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills. ``` def make_content_recs(): ''' INPUT: OUTPUT: ''' ``` `2.` Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender? ### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills. https://view3f484599.udacity-student-workspaces.com/notebooks/Content%20Based%20Recommendations%20-%20Solution.ipynb **Write an explanation of your content based recommendation system here.** `3.` Use your content-recommendation system to make recommendations for the below scenarios based on the comments. Again no tests are provided here, because there isn't one right answer that could be used to find these content based recommendations. ### This part is NOT REQUIRED to pass this project. However, you may choose to take this on as an extra way to show off your skills. ``` # make recommendations for a brand new user # make a recommendations for a user who only has interacted with article id '1427.0' ``` ### <a class="anchor" id="Matrix-Fact">Part V: Matrix Factorization</a> In this part of the notebook, you will build user matrix factorization to make article recommendations to the users on the IBM Watson Studio platform. `1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will just require that you run the cells to get things set up for the rest of **Part V** of the notebook. ``` # Load the matrix here user_item_matrix = pd.read_pickle('user_item_matrix.p') # quick look at the matrix user_item_matrix.head() ``` `2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson. ``` # Perform SVD on the User-Item Matrix Here u, s, vt = np.linalg.svd(user_item_matrix) # use the built in to get the three matrices s.shape, u.shape, vt.shape ``` **Provide your response here.** RESPONSE: Latent features in the lesson were just 4, however here we're talking about 714 latent features. So, the scale is very different comparing to the lesson. Plus, in the lessons there were null values in the data so FunkSVD was used, while here there were no null values. `3.` Now for the tricky part, how do we choose the number of latent features to use? Running the below cell, you can see that as the number of latent features increases, we obtain a lower error rate on making predictions for the 1 and 0 values in the user-item matrix. Run the cell below to get an idea of how the accuracy improves as we increase the number of latent features. ``` num_latent_feats = np.arange(10,700+10,20) sum_errs = [] for k in num_latent_feats: # restructure with k latent features s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :] # take dot product user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new)) # compute error for each prediction to actual value diffs = np.subtract(user_item_matrix, user_item_est) # total errors and keep track of them err = np.sum(np.sum(np.abs(diffs))) sum_errs.append(err) # plot results with seaborn graph = sns.lineplot(num_latent_feats, 1 - np.array(sum_errs)/df.shape[0]) graph.set(xlabel ='Number of Latent Features', ylabel = 'Accuracy', title ='Accuracy vs. Number of Latent Features') ``` `4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in the cell below. Use the code from question 3 to understand the impact on accuracy of the training and test sets of data with different numbers of latent features. Using the split below: * How many users can we make predictions for in the test set? * How many users are we not able to make predictions for because of the cold start problem? * How many articles can we make predictions for in the test set? * How many articles are we not able to make predictions for because of the cold start problem? ``` df_train = df.head(40000) df_test = df.tail(5993) def create_test_and_train_user_item(df_train, df_test): ''' INPUT: df_train - training dataframe df_test - test dataframe OUTPUT: user_item_train - a user-item matrix of the training dataframe (unique users for each row and unique articles for each column) user_item_test - a user-item matrix of the testing dataframe (unique users for each row and unique articles for each column) test_idx - all of the test user ids test_arts - all of the test article ids ''' # create matrix user_item_train = create_user_item_matrix(df_train) user_item_test = create_user_item_matrix(df_test) test_idx = list(user_item_test.index.values) test_arts = user_item_test.title.columns.values return user_item_train, user_item_test, test_idx, test_arts user_item_train, user_item_test, test_idx, test_arts = create_test_and_train_user_item(df_train, df_test) user_item_train.head() user_item_train.shape # 'How many users can we make predictions for in the test set users = user_item_train.index.isin(test_idx) users.sum() # How many users in the test set are we not able to make predictions for because of the cold start problem? len(test_idx) # How many movies can we make predictions for in the test set?' articles = user_item_train.title.columns.isin(test_arts) articles.sum() # Replace the values in the dictionary below a = 662 b = 574 c = 20 d = 0 sol_4_dict = { 'How many users can we make predictions for in the test set?': c, # letter here, 'How many users in the test set are we not able to make predictions for because of the cold start problem?': a, # letter here, 'How many movies can we make predictions for in the test set?': b, # letter here, 'How many movies in the test set are we not able to make predictions for because of the cold start problem?':d # letter here } t.sol_4_test(sol_4_dict) ``` `5.` Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accuracy on the test data. This will require combining what was done in questions `2` - `4`. Use the cells below to explore how well SVD works towards making predictions for recommendations on the test data. ``` # fit SVD on the user_item_train matrix # fit svd similar to above then use the cells below u_train, s_train, vt_train = np.linalg.svd(user_item_train) s_train.shape, u_train.shape, vt_train.shape # Use these cells to see how well you can use the training # decomposition to predict on test data # find the users that exists in both training and test datasets user_present_both = np.intersect1d(user_item_test.index, user_item_train.index) user_item_test_predictable = user_item_test[user_item_test.index.isin(user_present_both)] user_present_both.shape, user_item_test_predictable.shape # create u_test and vt_test variables common_ids = user_item_train.index.isin(test_idx) common_articles = user_item_train.title.columns.isin(test_arts) u_test = u_train[common_ids, :] vt_test = vt_train[:, common_articles] # initialize testing parameters num_latent_feats = np.arange(10,700+10,20) sum_errs_train = [] sum_errs_test = [] for k in num_latent_feats: # restructure with k latent features for both training and test sets s_train_lat, u_train_lat, vt_train_lat = np.diag(s_train[:k]), u_train[:, :k], vt_train[:k, :] u_test_lat, vt_test_lat = u_test[:, :k], vt_test[:k, :] # take dot product for both training and test sets user_item_train_est = np.around(np.dot(np.dot(u_train_lat, s_train_lat), vt_train_lat)) user_item_test_est = np.around(np.dot(np.dot(u_test_lat, s_train_lat), vt_test_lat)) # compute error for each prediction to actual value diffs_train = np.subtract(user_item_train, user_item_train_est) diffs_test = np.subtract(user_item_test_predictable, user_item_test_est) # total errors and keep track of them for both training and test sets err_train = np.sum(np.sum(np.abs(diffs_train))) err_test = np.sum(np.sum(np.abs(diffs_test))) sum_errs_train.append(err_train) sum_errs_test.append(err_test) # plot the results with seaborn, set graph size to fit the screen plt.figure(figsize=(5, 5)) # plot the train data pic = sns.lineplot(num_latent_feats, 1 - np.array(sum_errs_train)/(user_item_train.shape[0] * user_item_test_predictable.shape[1]), label='Train') # plot the test data pic = sns.lineplot(num_latent_feats, 1 - np.array(sum_errs_test)/(user_item_test_predictable.shape[0] * user_item_test_predictable.shape[1]), label='Test') # add labels and title pic.set(xlabel ='Latent Features', ylabel = 'Accuracy', title ='Train & Test Accuracy vs. Latent Features') ``` `6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? **Your response here.** RESPONSE: The train set and test set are showing completely different patterns. **While the accuracy of the train test increases, the one of the test set decreases with the higher number of latent features**. It appears that there are only 20 matched users in the two data sets for whcih collaborative filtering method can be used. For the rest content based and rank based filtering recommendations can be used. In collaborative filtering, we are using the connections of users and items. In content based techniques, we are using information about the users and items, but not connections (hence the usefulness when we do not have a lot of internal data already available to use). For just 20 users we can confirm that the number of users is not enough to make conclusive results about the model. Furheremore, we should be careful with the accuracy metric (number of correct predictions/number of rows in data). As many authors claim, counting only on accuracy is very often misleading. As for validating the test, we can use A/B test experiment to get more isnights and vlaidate the methods in use. We can separate two groups of users (A and B). One half will use our recommendation engine and the other half will use a random recommendation. The below steps can help: 1. Plan the experiment (we should divide users by cookie, as we can split visitors on their initial visit and it's fairly reliable for tracking). The test can be run for 21 days. 2. Decide on metrics (ex. invariant metric can be the number of cookies at the home page) 3. Decide on sizing - we should take into consideration the number of unique visitors per day. 4. Analize data 5. Draw conclusions ### <a class="anchor" id="resources">Part VII : Resources </a> During my work I used several sources to complete the exercises like Udacity Lessons, Scikitlearn, Github, Pandas, and more. I list a few links below that might help other students. - Machine Learning Overfitting - https://elitedatascience.com/overfitting-in-machine-learning - T function in python https://www.geeksforgeeks.org/pandas-dataframe-t-function-in-python/ - Seaborn https://seaborn.pydata.org/generated/seaborn.lineplot.html - Seaborn labels https://www.geeksforgeeks.org/how-to-set-axes-labels-limits-in-a-seaborn-plot/ - duplicate values https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html - Pandas https://pandas.pydata.org/ - Numpy https://numpy.org/
github_jupyter
``` # sample try with jewelry from os import listdir directory_name = "/Users/J.Alvarez/jtv/images" image_names = listdir("/Users/J.Alvarez/jtv/images") #image_names.remove('.DS_Store') #image_names.remove('._.DS_Store') from keras import backend as K #"/Users/J.Alvarez/the_simpsons/kaggle_simpson_testset" from PIL import Image import cv2 imported_images = [] #resize all images in the dataset for processing for image_name in image_names: foo = cv2.imread("/Users/J.Alvarez/jtv/images/" + image_name) foo = cv2.resize(foo, (256, 256)) imported_images.append(foo) import numpy as np #turn image into a 1D array def process_image(image, width): out = [] for x in range(width): for y in range(width): for z in range(3): #account for RGB out.append(image[x][y][z]) return np.asarray(out) #process all images into 1D arrays image_set = np.array([process_image(image, width = 256) for image in imported_images]) print(image_set) #Script for Autoencoder import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from keras import backend as K image_width = 256 pixels = image_width * image_width * 3 hidden = 1000 corruption_level = 0.25 X = tf.placeholder("float", [None, pixels], name = 'X') mask = tf.placeholder("float", [None, pixels], name = 'mask') weight_max = 4 * np.sqrt(4 / (6. * (pixels + hidden))) weight_initial = tf.random_uniform(shape = [pixels, hidden], minval = -weight_max, maxval = weight_max) W = tf.Variable(weight_initial, name = 'W') b = tf.Variable(tf.zeros([hidden]), name = 'b') W_prime = tf.transpose(W) b_prime = tf.Variable(tf.zeros([pixels]), name = 'b_prime') def reparameterize(W = W, b = b): epsilon = K.random_normal(shape = (1, hidden), mean = 0.) return W + K.exp(b/2) * epsilon def model(X, mask, W, b, W_prime, b_prime): tilde_X = mask * X hidden_state = tf.nn.sigmoid(tf.matmul(tilde_X, W) + b) out = tf.nn.sigmoid(tf.matmul(hidden_state, W_prime) + b_prime) return out out = model(X, mask, W, b, W_prime, b_prime) cost = tf.reduce_sum(tf.pow(X-out, 2)) optimization = tf.train.GradientDescentOptimizer(0.02).minimize(cost) x_train, x_test = train_test_split(image_set) sess = tf.Session() #you need to initialize all variables sess.run(tf.global_variables_initializer()) for i in range(1): for start, end in zip(range(0, len(x_train), 128), range(128, len(x_train), 128)): input_ = x_train[start:end] mask_np = np.random.binomial(1, 1 - corruption_level, input_.shape) sess.run(optimization, feed_dict = {X: input_, mask: mask_np}) mask_np = np.random.binomial(1, 1 - corruption_level, x_test.shape) print(i, sess.run(cost, feed_dict = {X: x_test, mask: mask_np})) masknp = np.random.binomial(1, 1 - corruption_level, image_set.shape) def hidden_state(X, mask, W, b): tilde_X = mask * X state = tf.nn.sigmoid(tf.matmul(tilde_X, W) + b) return state def euclidean_distance(arr1, arr2): x = 0 for i in range(len(arr1)): x += pow(arr1[i] - arr2[i], 2) return np.sqrt(x) def search(image): hidden_states = [sess.run(hidden_state(X, mask, W, b), feed_dict={X: im.reshape(1, pixels), mask: np.random.binomial(1, 1-corruption_level, (1, pixels))}) for im in image_set] query = sess.run(hidden_state(X, mask, W, b), feed_dict={X: image.reshape(1,pixels), mask: np.random.binomial(1, 1-corruption_level, (1, pixels))}) starting_state = int(np.random.random()*len(hidden_states)) #choose random starting state best_states = [imported_images[starting_state]] distance = euclidean_distance(query[0], hidden_states[starting_state][0]) #Calculate similarity between hidden states for i in range(len(hidden_states)): dist = euclidean_distance(query[0], hidden_states[i][0]) if dist <= distance: distance = dist #as the method progresses, it gets better at identifying similiar images best_states.append(imported_images[i]) if len(best_states)>0: return best_states else: return best_states[len(best_states)-101:] image_name = "/Users/J.Alvarez/jtv/test/ABA054.jpg" #Image to be used as query image = cv2.imread(image_name) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off') plt.show() import matplotlib.pyplot as plt import matplotlib.image as mpimg image_name = "/Users/J.Alvarez/jtv/test/ABA054.jpg" #Image to be used as query #image_name = "/Users/J.Alvarez/the_simpsons/test.jpg" #Image to be used as query image = cv2.imread(image_name) image = cv2.resize(image, (256, 256)) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off') image = process_image(image, 256) plt.show() results = search(image) #Search the database using image print(len(results)) slots = 0 plt.figure(figsize = (256,256)) for im in results[::-1]: #reads through results backwards (more similiar images first) plt.subplot(20, 20, slots + 1) plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off') slots += 1 plt.show() ```
github_jupyter