markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Обучение модели Теперь когда данные подготовлены, надо написать пайплайн обучения модели.Для начала мы хотим изменить предобученный BERT так, чтобы он выдавал метки для классификации текстов, а затем файнтюнить его на наших данных. Мы возьмем готовую модификацию BERTа для классификации из pytorch-transformers. Она инт...
from pytorch_transformers import AdamW, BertForSequenceClassification
_____no_output_____
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Аналогичные модели есть и для других задач. Все они построены на основе одной и той же архитектуры и различаются только верхними слоями.
from pytorch_transformers import BertForQuestionAnswering, BertForTokenClassification
_____no_output_____
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Теперь подробнее рассмотрим процесс файн-тюнинга. Как мы помним, первый токен в каждом предложении - это `[CLS]`. В отличие от скрытого состояния, относящего к обычному слову (не метке `[CLS]`), скрытое состояние относящееся к этой метке должно содержать в себе аггрегированное представление всего предложения, которое д...
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2) model.to(device)
_____no_output_____
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Теперь обсудим гиперпараметры для обучения нашей модели. Авторы статьи советуют выбирать `learning rate` `5e-5`, `3e-5`, `2e-5`, а количество эпох не делать слишком большим, 2-4 вполне достаточно. Мы пойдем еще дальше и попробуем дообучить нашу модель всего за одну эпоху.
param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'gamma', 'beta'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.01}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)]...
_____no_output_____
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Оценка качества на отложенной выборке Качество на валидационной выборке оказалось очень хорошим. Не переобучилась ли наша модель? Делаем точно такую же предобработку для тестовых данных, как и в начале ноутбука делали для обучающих данных:
tokenized_texts = [tokenizer.tokenize(sent) for sent in test_sentences] input_ids = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts] input_ids = pad_sequences( input_ids, maxlen=100, dtype="long", truncating="post", padding="post" )
_____no_output_____
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Создаем attention маски и приводим данные в необходимый формат:
attention_masks = [[float(i>0) for i in seq] for seq in input_ids] prediction_inputs = torch.tensor(input_ids) prediction_masks = torch.tensor(attention_masks) prediction_labels = torch.tensor(test_gt) prediction_data = TensorDataset( prediction_inputs, prediction_masks, prediction_labels ) prediction_da...
Неправильных предсказаний: 1282/68051
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Оценка качества работы без fine-tuning
model_wo_finetuning = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2) model_wo_finetuning.cuda() model_wo_finetuning.eval() preds_wo_finetuning, labels_wo_finetuning = [], [] for batch in prediction_dataloader: batch = tuple(t.to(device) for t in batch) b_input_ids, b_input_mas...
Процент правильных предсказаний на отложенной выборке составил: 48.57%
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Сравним точность и полноту предсказаний:
from sklearn.metrics import recall_score, precision_score print('1 эпоха: точность (precision) {0:.2f}%, полнота (recall) {1:.2f}%'.format( precision_score(test_labels, test_preds) * 100, recall_score(test_labels, test_preds) * 100 )) print('Без дообучения: точность (precision) {0:.2f}%, полнота (recall) {1:...
1 эпоха: точность (precision) 99.93%, полнота (recall) 96.34% Без дообучения: точность (precision) 37.68%, полнота (recall) 2.91%
MIT
week1_05_BERT_and_LDA/week05_BERT_Fine_Tunning.ipynb
GendalfSeriyy/ml-mipt
Multi-Sensor Test Angle Threshold - DNN Experiment Aims:Test the influence of the threshold of different steer angles on the classification accuracy, and choose a suitable threshold of the steer angle. Experiment Design:For efficiency purposes, this experiment uses DNN to determine whether the current angle_threshol...
import pandas as pd import numpy as np import os # Read the data, assign a label to each image data according to the threshold, including go, stop, left, right # The default speed_threshold=5, angle_threshold=30 # Finally we generate bounding_box data: X, corresponding label: y import random def process_data(data, spee...
Using cuda device
MIT
DNN threshold test.ipynb
ITSEG-MQ/Box-to-drive
This experiment tried the influence of angle_threshold of 10, 20, 30...90 on the classification results.The classification accuracy is expressed in the form of a confusion matrix. The diagonal line from top left to bottom right corresponds to the accuracy of the four categories. The four types are go, stop, left, and ...
data = pd.read_csv("full_info.tsv", sep ="\t") for i in range(1,10): speed_threshold = 5 angle_threshold = i*10 sign_threshold = 0.5 print("angle_threshold", angle_threshold) data_size = 200 X, y = process_data(data, speed_threshold, angle_threshold, sign_threshold, data_size) X =...
angle_threshold 10 go, stop, left, right 200 200 200 200 X: (800, 105) y: (800,) Test Accuracy: 41.0% [[0.50025253 0.12082591 0.24501594 0.13461275] [0.17687015 0.46573084 0.2025837 0.16768295] [0.29662568 0.19569222 0.29508399 0.2279755 ] [0.27784365 0.19255051 0.24583091 0.28598122]] angle_threshold 20 go, stop,...
MIT
DNN threshold test.ipynb
ITSEG-MQ/Box-to-drive
Cross Training with MIMIC and MLH Imports & Inits
%load_ext autoreload %autoreload 2 import pdb import pandas as pd import pickle import numpy as np np.set_printoptions(precision=4) from tqdm import tqdm_notebook as tqdm from ast import literal_eval from pathlib import Path from scipy import stats from sklearn.feature_extraction.text import TfidfVectorizer import m...
_____no_output_____
Apache-2.0
cross/vectorize_both.ipynb
sudarshan85/phd_code
Testing of queue imbalance for stock 9091Order of this notebook is as follows:1. [Data](Data)2. [Data visualization](Data-visualization)3. [Tests](Tests)4. [Conclusions](Conclusions)Goal is to implement queue imbalance predictor from [[1]](Resources).
%matplotlib inline import warnings import matplotlib.dates as md import matplotlib.pyplot as plt import seaborn as sns from lob_data_utils import lob from sklearn.metrics import roc_curve, roc_auc_score warnings.filterwarnings('ignore')
_____no_output_____
MIT
queue_imbalance/logistic_regression/queue_imbalance-9061.ipynb
vevurka/mt-lob
DataMarket is open between 8-16 on every weekday. We decided to use data from only 9-15 for each day. Test and train dataFor training data we used data from 2013-09-01 - 2013-11-16:* 0901* 0916* 1001* 1016* 1101We took 75% of this data (randomly), the rest is the test data.
df, df_test = lob.load_prepared_data('9061', data_dir='../data/prepared/', length=None) df.head()
Len of data for 9061 is 17245 Training set length for 9061: 13796 Testing set length for 9061: 3449
MIT
queue_imbalance/logistic_regression/queue_imbalance-9061.ipynb
vevurka/mt-lob
Data visualization
df['sum_buy_bid'].plot(label='total size of buy orders', style='--') df['sum_sell_ask'].plot(label='total size of sell orders', style='-') plt.title('Summed volumens for ask and bid lists') plt.xlabel('Time') plt.ylabel('Whole volume') plt.legend() df[['bid_price', 'ask_price', 'mid_price']].plot(style='.') plt.legend(...
_____no_output_____
MIT
queue_imbalance/logistic_regression/queue_imbalance-9061.ipynb
vevurka/mt-lob
TestsWe use logistic regression to predict `mid_price_indicator`. Mean square error We calculate residual $r_i$:$$ r_i = \hat{y_i} - y_i $$where $$ \hat{y}(I) = \frac{1}{1 + e −(x_0 + Ix_1 )}$$Calculating mean square residual for all observations in the testing set is also useful to assess the predictive power.The pre...
reg = lob.logistic_regression(df, 0, len(df)) probabilities = reg.predict_proba(df_test['queue_imbalance'].values.reshape(-1,1)) probabilities = [p1 for p0, p1 in probabilities] err = ((df_test['mid_price_indicator'] - probabilities) ** 2).mean() predictions = reg.predict(df_test['queue_imbalance'].values.reshape(-1,...
Mean square error is 0.30136827396201277
MIT
queue_imbalance/logistic_regression/queue_imbalance-9061.ipynb
vevurka/mt-lob
Logistic regression fit curve
plt.plot(df_test['queue_imbalance'].values, lob.sigmoid(reg.coef_[0] * df_test['queue_imbalance'].values + reg.intercept_)) plt.title('Logistic regression fit curve') plt.xlabel('Imbalance') plt.ylabel('Prediction')
_____no_output_____
MIT
queue_imbalance/logistic_regression/queue_imbalance-9061.ipynb
vevurka/mt-lob
ROC curveFor assessing the predectivity power we can calculate ROC score.
a, b, c = roc_curve(df_test['mid_price_indicator'], predictions) logit_roc_auc = roc_auc_score(df_test['mid_price_indicator'], predictions) plt.plot(a, b, label='predictions (area {})'.format(logit_roc_auc)) plt.plot([0, 1], [0, 1], color='navy', linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positi...
_____no_output_____
MIT
queue_imbalance/logistic_regression/queue_imbalance-9061.ipynb
vevurka/mt-lob
Visualizing the JWST Optical BudgetWebbPSF 1.0 adds a tool to display different components of the optical models used in the PSF calculations. This is based on the formal optical budgets used to track JWST requirements and predicted performance. The total WFE is broken down into three major components: 1. _OTE Static_...
nrc = webbpsf.NIRCam() nrc.pupilopd = 'OPD_RevW_ote_for_NIRCam_predicted.fits.gz' nrc.visualize_wfe_budget()
generating optical models inferring OTE static WFE terms decomposing WFE into controllable and uncontrollable spatial frequencies modeling controllable and uncontrollable spatial frequencies inferring OTE dynamic WFE terms los jitter 0.006 arcsec, as wfe 67.02470144874732 nm inferring ISIM + SI WFE terms displaying p...
BSD-3-Clause
docs/jwst_optical_budgets.ipynb
kammerje/webbpsf
The way to read the above plot is that the total system WFE (at top) is the sum of the 3 OPDs shown in the first column below. And then in each row, the total in the left panel is the sum of the three panels to the right. Note that in each panel, an annotation at lower left states the RMS WFE for that term. In lower r...
nrc.detector = 'NRCA3' nrc.detector_position = (1024, 0) nrc.visualize_wfe_budget()
generating optical models inferring OTE static WFE terms decomposing WFE into controllable and uncontrollable spatial frequencies modeling controllable and uncontrollable spatial frequencies inferring OTE dynamic WFE terms los jitter 0.006 arcsec, as wfe 67.02470144874732 nm inferring ISIM + SI WFE terms displaying p...
BSD-3-Clause
docs/jwst_optical_budgets.ipynb
kammerje/webbpsf
Label Propagation learning a complex structureExample of LabelPropagation learning a complex internal structureto demonstrate "manifold learning". The outer circle should belabeled "red" and the inner circle "blue". Because both label groupslie inside their own distinct shape, we can see that the labelspropagate corre...
print(__doc__) # Authors: Clay Woolam <clay@woolam.org> # Andreas Mueller <amueller@ais.uni-bonn.de> # License: BSD import numpy as np import matplotlib.pyplot as plt from sklearn.semi_supervised import label_propagation from sklearn.datasets import make_circles # generate ring with inner box n_samples = 20...
_____no_output_____
MIT
lab13/semi_supervised/plot_label_propagation_structure.ipynb
cruxiu/MLStudies
Week 7 AssignmentFind a dataset and apply a random forest classifier/regressor on it.
# Data EDA import numpy as np import pandas as pd from sklearn import datasets # Machine Learning from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report
_____no_output_____
CC-BY-3.0
assets/emse6574_assignments/Week_7_Assignment_Michael_Salceda.ipynb
ngau9567/msalceda.github.io
Data LoadingLet's use the breast cancer dataset found in scikit-learn.
cancer_databunch = datasets.load_breast_cancer() # Get features features = cancer_databunch.data # Get target labels (as numbers) labels = cancer_databunch.target # Get column names for DataFrame construction columns = cancer_databunch.feature_names.tolist() + ['class'] # Get mapping of label number to string name ...
_____no_output_____
CC-BY-3.0
assets/emse6574_assignments/Week_7_Assignment_Michael_Salceda.ipynb
ngau9567/msalceda.github.io
Train-Test SplitSince all the features are numeric and scale doesn't really matter for random forests, we can go straight to the train-test split without any major feature engineering steps.
# Do a 80-20 split for train and test sets X_train, X_test, y_train, y_test = train_test_split( cancer.drop(columns = 'class'), cancer['class'], test_size = 0.2, random_state = 1 ) print(f'Training Shape (Features): {X_train.shape}') print(f'Testing Shape (Features): {X_test.shape}') print(f'Training S...
Training Shape (Features): (455, 30) Testing Shape (Features): (114, 30) Training Shape (Labels): (455,) Testing Shape (Labels): (114,) =================TRAINING SAMPLE==================
CC-BY-3.0
assets/emse6574_assignments/Week_7_Assignment_Michael_Salceda.ipynb
ngau9567/msalceda.github.io
Model Training
# Training a random forest model rf = RandomForestClassifier() rf.fit(X_train, y_train) # Get predictions predictions = rf.predict(X_test) # Get metrics print(classification_report(y_test, predictions))
precision recall f1-score support benign 0.93 0.99 0.96 72 malignant 0.97 0.88 0.93 42 accuracy 0.95 114 macro avg 0.95 0.93 0.94 114 weighted avg 0.95 0.95 0.95 ...
CC-BY-3.0
assets/emse6574_assignments/Week_7_Assignment_Michael_Salceda.ipynb
ngau9567/msalceda.github.io
Data types optimization> Convert columns to use more memory efficient dtypes.
import random import itertools import string import timeit import numpy as np import pandas as pd
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
NumPy data types Pandas columns are internally stored as numpy arrays, and so [NumPy data types](https://numpy.org/doc/stable/user/basics.types.html) are used.**Boolean**`np.bool_` takes 1 byte per item, but can not hold missing values. Logical operations on columns return series of this dtype, unless some of the elem...
# floats spacing increases with number magnitude dt = np.float16 info = np.finfo(dt) for exp in range(-16, 17): x = 2**exp npx = dt(x) print(exp, x, npx, np.spacing(npx)) # integer precision limits on floats for dt in [np.float16, np.float32, np.float64]: info = np.finfo(dt) max_int = 2**(info.nmant...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Automatic conversionBe mindful of possible overflow when performing operations with numerical series, as dtypes will not always automatically convert to higher types.Result of series aggregation is numpy scalar with certain numpy dtype. Summation of ints results in `int64`, regardless of input dtype.Summation of `floa...
# going beyond float32 integer precision s = pd.Series([2**24] * 3, dtype='float32') assert ((s + 1) == s).all() # 127 is max int8, but s.sum() does not overflow, because result is stored in int64 s = pd.Series([127, 127, 127], dtype='int8') ss = s.sum() print(ss.dtype, ss, 127 * 3) # 2**24 is largest int that can be e...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Categorical[User guide](https://pandas.pydata.org/docs/user_guide/categorical.html)[](https://pandas.pydata.org/docs/user_guide/categorical.htmlmissing-data)> Missing values should not be included in the Categorical’s categories, only in the values. Instead, it is understood that NaN is different, and is always a poss...
def gen_unique_str(n, l, alphabet=None): """Return list of `n` random unique strings of lenght `l`.""" if alphabet is None: alphabet = string.ascii_lowercase assert len(alphabet) ** l >= n, f'Can not generate {n} unique strings of length {l} from alphabet of length {len(alphabet)}.' str_set = se...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Select and groupbySelection by equality test is x220 faster with categoricals.Groupby aggregation is x27 faster with categoricals.
df = gen_mock_data(1_000_000, str_=1, cat=1) print('select str') needle = df['str0'][0] %timeit _ = (df['str0'] == needle) print('select cat') needle = df['cat0'].cat.categories[0] %timeit _ = (df['cat0'] == needle) df = gen_mock_data(1_000_000, num=1, str_=1, cat=1) print('groupby str') %timeit _ = df.groupby('str0')[...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
String methods[](https://pandas.pydata.org/docs/user_guide/categorical.htmlstring-and-datetime-accessors)`.str` and `.dt` accessors work on categoricals if categories are of an appropriate type.> The work is done on the categories and then a new Series is constructed. This has some performance implication if you have ...
df = gen_mock_data(1_000_000, str_=1, cat=1) print('str: startswith') %timeit _ = df.str0.str.startswith('a') print('cat: startswith') %timeit _ = df.cat0.str.startswith('a') print('str: contains non-regex') %timeit _ = df.str0.str.contains('a', regex=False) print('cat: contains non-regex') %timeit _ = df.cat0.str.co...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Merge[](https://pandas.pydata.org/docs/user_guide/categorical.htmlmerging-concatenation)[](https://pandas.pydata.org/docs/user_guide/merging.htmlmerge-dtypes)> By default, combining Series or DataFrames which contain the same categories results in category dtype, otherwise results will depend on the dtype of the under...
import random import itertools import string import timeit import numpy as np import pandas as pd def gen_cat_data(n_rows, n_cats, cat_len, cat): cat_gen = itertools.product(string.ascii_lowercase, repeat=cat_len) cats = [''.join(next(cat_gen)) for _ in range(n_cats)] assert len(cats) == len(set(cats)) ...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Length of strings does not matter
x = df.unstack('cat_len') x.iloc[:, 1] / x.iloc[:, 0]
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Categoricals improve performance with 100k+ rows, up to x2 speedup with 100M rows
x = df.unstack('cat_len').mean(1) x = x.unstack('cats') x.iloc[:, 1] / x.iloc[:, 0]
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Number of categories slows down.
x = df.unstack('cat_len').mean(1) x = x.unstack('n_cats') (x.iloc[:, 1] / x.iloc[:, 0]).unstack('cats')
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
`time / n_rows` declines when few categoricals are used. No clear pattern otherwise.
x = df.unstack('cat_len').mean(1) x /= x.index.get_level_values('n_rows') x.unstack(['cats', 'n_cats'])
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
If dataframe becomes wideWhen many columns are to be merged on one or both sides, merge starts taking significantly more time, mainly because data are to be copied to a new object.Merge on cat keys becomes slower than on str keys with wide dataframes, although difference is small compared to overall merge time.
# merge on strings df, agg = gen_cat_data(10_000_000, 100, 10, False) print('merge few columns') %time _ = df.merge(agg) for i in range(100): df[f'var{i}'] = np.random.rand(len(df)) print('merge many columns') %time _ = df.merge(agg) for i in range(100): agg[f'agg{i}'] = np.random.rand(len(agg)) print('merge ma...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Container for boolean with NAThis might be a better solution than using `float32` (or less supported `float16`). Each item will only occupy one byte, and NA-related methods will work as expected.`fillna()` will not accept values outside of preset categories, so need to `add_categories()` first.Categories can be `[0, 1...
df = gen_mock_data(100_000, num=1) df['boo'] = (df.num0 > 0.8) df.loc[df.sample(frac=0.1).index, 'boo'] = np.nan print(df.boo.value_counts(dropna=False)) df['boo_cat'] = df.boo.astype('category').cat.rename_categories({0: False, 1: True}) print(df.boo_cat.value_counts(dropna=False)) print(df.memory_usage())
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Date and timeTo be added later when use case arises. Parquet supportInteger and float types are stored and converted automatically with exception of `float16`.
import numpy as np import pandas as pd import fastparquet as pq data = list(range(100)) df = pd.DataFrame() for dt in ['uint8', 'uint16', 'uint32', 'uint64', 'int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64']: df[dt] = pd.Series(data, dtype=dt) dfpq_path = '/tmp/dataframe.pq...
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Categories can not be `[False, True]`. Maybe fastparquet bug.
# df = pd.Series([False, False, True], dtype=pd.CategoricalDtype([False, True])).to_frame('col') # <-- this fails df = pd.Series([False, False, True], dtype=pd.CategoricalDtype([False, True, 2])).to_frame('col') # <-- this works df.to_parquet('/tmp/dataframe.pq', 'fastparquet', None, False)
_____no_output_____
Apache-2.0
nbs/dtypes.ipynb
antonbabkin/ig_format
Homework and bake-off: word-level entailment with neural networks
__author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Spring 2020"
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Contents1. [Overview](Overview)1. [Set-up](Set-up)1. [Data](Data) 1. [Edge disjoint](Edge-disjoint) 1. [Word disjoint](Word-disjoint)1. [Baseline](Baseline) 1. [Representing words: vector_func](Representing-words:-vector_func) 1. [Combining words into inputs: vector_combo_func](Combining-words-into-inputs:-vector_...
from collections import defaultdict import json import numpy as np import os import pandas as pd from torch_shallow_neural_classifier import TorchShallowNeuralClassifier import nli import utils DATA_HOME = 'data' NLIDATA_HOME = os.path.join(DATA_HOME, 'nlidata') wordentail_filename = os.path.join( NLIDATA_HOME, '...
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
DataI've processed the data into two different train/test splits, in an effort to put some pressure on our models to actually learn these semantic relations, as opposed to exploiting regularities in the sample.* `edge_disjoint`: The `train` and `dev` __edge__ sets are disjoint, but many __words__ appear in both `train...
with open(wordentail_filename) as f: wordentail_data = json.load(f)
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
The outer keys are the splits plus a list giving the vocabulary for the entire dataset:
wordentail_data.keys()
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Edge disjoint
wordentail_data['edge_disjoint'].keys()
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
This is what the split looks like; all three have this same format:
wordentail_data['edge_disjoint']['dev'][: 5]
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Let's test to make sure no edges are shared between `train` and `dev`:
nli.get_edge_overlap_size(wordentail_data, 'edge_disjoint')
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
As we expect, a *lot* of vocabulary items are shared between `train` and `dev`:
nli.get_vocab_overlap_size(wordentail_data, 'edge_disjoint')
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
This is a large percentage of the entire vocab:
len(wordentail_data['vocab'])
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Here's the distribution of labels in the `train` set. It's highly imbalanced, which will pose a challenge for learning. (I'll go ahead and reveal that the `dev` set is similarly distributed.)
def label_distribution(split): return pd.DataFrame(wordentail_data[split]['train'])[1].value_counts() label_distribution('edge_disjoint')
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Word disjoint
wordentail_data['word_disjoint'].keys()
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
In the `word_disjoint` split, no __words__ are shared between `train` and `dev`:
nli.get_vocab_overlap_size(wordentail_data, 'word_disjoint')
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Because no words are shared between `train` and `dev`, no edges are either:
nli.get_edge_overlap_size(wordentail_data, 'word_disjoint')
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
The label distribution is similar to that of `edge_disjoint`, though the overall number of examples is a bit smaller:
label_distribution('word_disjoint')
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Baseline Even in deep learning, __feature representation is vital and requires care!__ For our task, feature representation has two parts: representing the individual words and combining those representations into a single network input. Representing words: vector_func Let's consider two baseline word representations...
def randvec(w, n=50, lower=-1.0, upper=1.0): """Returns a random vector of length `n`. `w` is ignored.""" return utils.randvec(n=n, lower=lower, upper=upper) # Any of the files in glove.6B will work here: glove_dim = 50 glove_src = os.path.join(GLOVE_HOME, 'glove.6B.{}d.txt'.format(glove_dim)) # Creates a di...
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Combining words into inputs: vector_combo_func Here we decide how to combine the two word vectors into a single representation. In more detail, where `u` is a vector representation of the left word and `v` is a vector representation of the right word, we need a function `vector_combo_func` such that `vector_combo_func...
def vec_concatenate(u, v): """Concatenate np.array instances `u` and `v` into a new np.array""" return np.concatenate((u, v))
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
`vector_combo_func` could instead be vector average, vector difference, etc. (even combinations of those) – there's lots of space for experimentation here; [homework question 2](Alternatives-to-concatenation-[1-point]) below pushes you to do some exploration. Classifier modelFor a baseline model, I chose `TorchShallow...
net = TorchShallowNeuralClassifier(hidden_dim=50, max_iter=100)
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Baseline resultsThe following puts the above pieces together, using `vector_func=glove_vec`, since `vector_func=randvec` seems so hopelessly misguided for `word_disjoint`!
word_disjoint_experiment = nli.wordentail_experiment( train_data=wordentail_data['word_disjoint']['train'], assess_data=wordentail_data['word_disjoint']['dev'], model=net, vector_func=glove_vec, vector_combo_func=vec_concatenate) word_disjoint_experiment['macro-F1']
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
train_data is a list of examples in the structure {(word1,word2), entail}. The model takes every element of the list, finds its feature representation in vector_func (could be a glove). Then we combine them (concatenete or add them or whatever) and then we append everything to a long list of examples. It should be a li...
def hypothesis_only(u,v): return v def run_hypothesis_only_evaluation(): import sklearn conditions = ['edge_disjoint', 'word_disjoint'] functions = [vec_concatenate, hypothesis_only] results = {} for condition in conditions: for function in functions: experiment = nli.worden...
precision recall f1-score support 0 0.875 0.969 0.920 7376 1 0.570 0.228 0.326 1321 accuracy 0.857 8697 macro avg 0.723 0.599 0.623 8697 weighted avg 0.829 0.857 0.830 ...
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Alternatives to concatenation [2 points]We've so far just used vector concatenation to represent the premise and hypothesis words. This question asks you to explore two simple alternative:1. Write a function `vec_diff` that, for a given pair of vector inputs `u` and `v`, returns the element-wise difference between `u`...
def vec_diff(u, v): return u-v def vec_max(u, v): return np.maximum(u,v) def test_vec_diff(vec_diff): u = np.array([10.2, 8.1]) v = np.array([1.2, -7.1]) result = vec_diff(u, v) expected = np.array([9.0, 15.2]) assert np.array_equal(result, expected), \ "Expected {}; got {}".forma...
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
A deeper network [2 points]It is very easy to subclass `TorchShallowNeuralClassifier` if all you want to do is change the network graph: all you have to do is write a new `define_graph`. If your graph has new arguments that the user might want to set, then you should also redefine `__init__` so that these values are a...
import torch.nn as nn class TorchDeepNeuralClassifier(TorchShallowNeuralClassifier): def __init__(self, dropout_prob=0.7, **kwargs): self.dropout_prob = dropout_prob super().__init__(**kwargs) def define_graph(self): """Complete this method! Returns -------...
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Your original system [3 points]This is a simple dataset, but our focus on the 'word_disjoint' condition ensures that it's a challenging one, and there are lots of modeling strategies one might adopt. You are free to do whatever you like. We require only that your system differ in some way from those defined in the pre...
# Enter your system description in this cell. # Please do not remove this comment. #my approach takes an expanded 300d glove vector embeddingm creates a combine function #that concatenates u and v a after being weighted by their cross product and finally applies #a deeper neural network with RELU Activations ...
Finished epoch 248 of 250; error is 3.6799179315567017
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Bake-off [1 point]The goal of the bake-off is to achieve the highest macro-average F1 score on __word_disjoint__, on a test set that we will make available at the start of the bake-off. The announcement will go out on the discussion forum. To enter, you'll be asked to run `nli.bake_off_evaluation` on the output of you...
# Enter your bake-off assessment code into this cell. # Please do not remove this comment. test_data_filename = os.path.join( NLIDATA_HOME, "bakeoff-wordentail-data", "nli_wordentail_bakeoff_data-test.json") experiment = nli.wordentail_experiment( train_data=wordentail_data['word_disjoint']['train'] + w...
_____no_output_____
Apache-2.0
hw_wordentail.ipynb
robertosemp/cs224u
Python solving with LeNetIn this example, we'll explore learning with Caffe in Python, using the fully-exposed `Solver` interface.
import os os.chdir('..') import sys sys.path.insert(0, './python') import caffe from pylab import * %matplotlib inline
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
We'll be running the provided LeNet example (make sure you've downloaded the data and created the databases, as below).
# Download and prepare data !data/mnist/get_mnist.sh !examples/mnist/create_mnist.sh
Downloading... --2015-06-30 14:41:56-- http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz Resolving yann.lecun.com... 128.122.47.89 Connecting to yann.lecun.com|128.122.47.89|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 9912422 (9.5M) [application/x-gzip] Saving to: 'train-images-i...
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
We need two external files to help out:* the net prototxt, defining the architecture and pointing to the train/test data* the solver prototxt, defining the learning parametersWe start with the net. We'll write the net in a succinct and natural way as Python code that serializes to Caffe's protobuf model format.This net...
from caffe import layers as L from caffe import params as P def lenet(lmdb, batch_size): # our version of LeNet: a series of linear and simple nonlinear transformations n = caffe.NetSpec() n.data, n.label = L.Data(batch_size=batch_size, backend=P.Data.LMDB, source=lmdb, transfo...
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
The net has been written to disk in more verbose but human-readable serialization format using Google's protobuf library. You can read, write, and modify this description directly. Let's take a look at the train net.
!cat examples/mnist/lenet_auto_train.prototxt
layer { name: "data" type: "Data" top: "data" top: "label" transform_param { scale: 0.00392156862745 } data_param { source: "examples/mnist/mnist_train_lmdb" batch_size: 64 backend: LMDB } } layer { name: "conv1" type: "Convolution" bottom: "data" top: "conv1" ...
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Now let's see the learning parameters, which are also written as a `prototxt` file. We're using SGD with momentum, weight decay, and a specific learning rate schedule.
!cat examples/mnist/lenet_auto_solver.prototxt
# The train/test net protocol buffer definition train_net: "examples/mnist/lenet_auto_train.prototxt" test_net: "examples/mnist/lenet_auto_test.prototxt" # test_iter specifies how many forward passes the test should carry out. # In the case of MNIST, we have test batch size 100 and 100 test iterations, # covering ...
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Let's pick a device and load the solver. We'll use SGD (with momentum), but Adagrad and Nesterov's accelerated gradient are also available.
caffe.set_device(0) caffe.set_mode_gpu() solver = caffe.SGDSolver('examples/mnist/lenet_auto_solver.prototxt')
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
To get an idea of the architecture of our net, we can check the dimensions of the intermediate features (blobs) and parameters (these will also be useful to refer to when manipulating data later).
# each output is (batch size, feature dim, spatial dim) [(k, v.data.shape) for k, v in solver.net.blobs.items()] # just print the weight sizes (not biases) [(k, v[0].data.shape) for k, v in solver.net.params.items()]
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Before taking off, let's check that everything is loaded as we expect. We'll run a forward pass on the train and test nets and check that they contain our data.
solver.net.forward() # train net solver.test_nets[0].forward() # test net (there can be more than one) # we use a little trick to tile the first eight images imshow(solver.net.blobs['data'].data[:8, 0].transpose(1, 0, 2).reshape(28, 8*28), cmap='gray') print solver.net.blobs['label'].data[:8] imshow(solver.test_nets[...
[ 7. 2. 1. 0. 4. 1. 4. 9.]
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Both train and test nets seem to be loading data, and to have correct labels.Let's take one step of (minibatch) SGD and see what happens.
solver.step(1)
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Do we have gradients propagating through our filters? Let's see the updates to the first layer, shown here as a $4 \times 5$ grid of $5 \times 5$ filters.
imshow(solver.net.params['conv1'][0].diff[:, 0].reshape(4, 5, 5, 5) .transpose(0, 2, 1, 3).reshape(4*5, 5*5), cmap='gray')
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Something is happening. Let's run the net for a while, keeping track of a few things as it goes.Note that this process will be the same as if training through the `caffe` binary. In particular:* logging will continue to happen as normal* snapshots will be taken at the interval specified in the solver prototxt (here, ev...
%%time niter = 200 test_interval = 25 # losses will also be stored in the log train_loss = zeros(niter) test_acc = zeros(int(np.ceil(niter / test_interval))) output = zeros((niter, 8, 10)) # the main solver loop for it in range(niter): solver.step(1) # SGD by Caffe # store the train loss train_loss[i...
Iteration 0 testing... Iteration 25 testing... Iteration 50 testing... Iteration 75 testing... Iteration 100 testing... Iteration 125 testing... Iteration 150 testing... Iteration 175 testing... CPU times: user 12.3 s, sys: 3.96 s, total: 16.2 s Wall time: 15.7 s
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Let's plot the train loss and test accuracy.
_, ax1 = subplots() ax2 = ax1.twinx() ax1.plot(arange(niter), train_loss) ax2.plot(test_interval * arange(len(test_acc)), test_acc, 'r') ax1.set_xlabel('iteration') ax1.set_ylabel('train loss') ax2.set_ylabel('test accuracy')
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
The loss seems to have dropped quickly and coverged (except for stochasticity), while the accuracy rose correspondingly. Hooray!Since we saved the results on the first test batch, we can watch how our prediction scores evolved. We'll plot time on the $x$ axis and each possible label on the $y$, with lightness indicatin...
for i in range(8): figure(figsize=(2, 2)) imshow(solver.test_nets[0].blobs['data'].data[i, 0], cmap='gray') figure(figsize=(10, 2)) imshow(output[:50, i].T, interpolation='nearest', cmap='gray') xlabel('iteration') ylabel('label')
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
We started with little idea about any of these digits, and ended up with correct classifications for each. If you've been following along, you'll see the last digit is the most difficult, a slanted "9" that's (understandably) most confused with "4".Note that these are the "raw" output scores rather than the softmax-com...
for i in range(8): figure(figsize=(2, 2)) imshow(solver.test_nets[0].blobs['data'].data[i, 0], cmap='gray') figure(figsize=(10, 2)) imshow(exp(output[:50, i].T) / exp(output[:50, i].T).sum(0), interpolation='nearest', cmap='gray') xlabel('iteration') ylabel('label')
_____no_output_____
BSD-2-Clause
examples/01-learning-lenet.ipynb
DuHao10086/skin-caffe
Table of Contents1&nbsp;&nbsp;Seq2Seq1.1&nbsp;&nbsp;Seq2Seq Introduction1.2&nbsp;&nbsp;Data Preparation1.2.1&nbsp;&nbsp;Declaring Fields1.2.2&nbsp;&nbsp;Constructing Dataset1.2.3&nbsp;&nbsp;Constructing Iterator1.3&nbsp;&nbsp;Seq2Seq Implementation1.3.1&nbsp;&nbsp;Encoder Module1.3.2&nbsp;&nbsp;Decoder Module1.3.3&nbsp...
# code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path) # 1. magic for inline plot ...
Ethen 2020-01-07 21:44:32 CPython 3.6.4 IPython 7.9.0 numpy 1.16.5 torch 1.3.1 torchtext 0.4.0 spacy 2.1.6
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Seq2Seq **Seq2Seq (Sequence to Sequence)** is a many to many network where two neural networks, one encoder and one decoder work together to transform one sequence to another. The core highlight of this method is having no restrictions on the length of the source and target sequence. At a high-level, the way it works ...
SEED = 2222 random.seed(SEED) torch.manual_seed(SEED)
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
The next two code chunks:- Downloads the spacy model for the German and English language.- Create the tokenizer functions, which will take in the sentence as the input and return the sentence as a list of tokens. These functions can then be passed to torchtext.
# !python -m spacy download de # !python -m spacy download en # the link below contains explanation of how spacy's tokenization works # https://spacy.io/usage/spacy-101#annotations-token spacy_de = spacy.load('de_core_news_sm') spacy_en = spacy.load('en_core_web_sm') def tokenize_de(text: str) -> List[str]: retur...
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
The tokenizer is language specific, e.g. it knows that in the English language don't should be tokenized into do not (n't).Another thing to note is that **the order of the source sentence is reversed during the tokenization process**. The rationale behind things comes from the original seq2seq paper where they identifi...
source = Field(tokenize=tokenize_de, init_token='<sos>', eos_token='<eos>', lower=True) target = Field(tokenize=tokenize_en, init_token='<sos>', eos_token='<eos>', lower=True)
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Constructing Dataset We've defined the logic of processing our raw text data, now we need to tell the fields what data it should work on. This is where `Dataset` comes in. The dataset we'll be using is the [Multi30k dataset](https://pytorch.org/text/datasets.htmlmulti30k). This is a dataset with ~30,000 parallel Engli...
train_data, valid_data, test_data = Multi30k.splits(exts=('.de', '.en'), fields=(source, target)) print(f"Number of training examples: {len(train_data.examples)}") print(f"Number of validation examples: {len(valid_data.examples)}") print(f"Number of testing examples: {len(test_data.examples)}")
Number of training examples: 29000 Number of validation examples: 1014 Number of testing examples: 1000
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Upon loading the dataset, we can indexed and iterate over the `Dataset` like a normal list. Each element in the dataset bundles the attributes of a single record for us. We can index our dataset like a list and then access the `.src` and `.trg` attribute to take a look at the tokenized source and target sentence.
# equivalent, albeit more verbiage train_data.examples[0].src train_data[0].src train_data[0].trg
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
The next missing piece is to build the vocabulary for the source and target languages. That way we can convert our tokenized tokens into integers so that they can be fed into downstream models. Constructing the vocabulary and word to integer mapping is done by calling the `build_vocab` method of a `Field` on a dataset....
source.build_vocab(train_data, min_freq=2) target.build_vocab(train_data, min_freq=2) print(f"Unique tokens in source (de) vocabulary: {len(source.vocab)}") print(f"Unique tokens in target (en) vocabulary: {len(target.vocab)}")
Unique tokens in source (de) vocabulary: 7855 Unique tokens in target (en) vocabulary: 5893
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Constructing Iterator The final step of preparing the data is to create the iterators. Very similar to `DataLoader` in the standard pytorch package, `Iterator` in torchtext converts our data into batches, so that they can be fed into the model. These can be iterated on to return a batch of data which will have a `src`...
BATCH_SIZE = 128 # pytorch boilerplate that determines whether a GPU is present or not, # this determines whether our dataset or model can to moved to a GPU device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # create batches out of the dataset and sends them to the appropriate device train_iterator...
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
We can list out the first batch, we see each element of the iterator is a `Batch` object, similar to element of a `Dataset`, we can access the fields via its attributes. The next important thing to note that it is of size [sentence length, batch size], and the longest sentence in the first batch of the source language ...
# adjustable parameters INPUT_DIM = len(source.vocab) OUTPUT_DIM = len(target.vocab) ENC_EMB_DIM = 256 DEC_EMB_DIM = 256 HID_DIM = 512 N_LAYERS = 2 ENC_DROPOUT = 0.5 DEC_DROPOUT = 0.5
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
To define our seq2seq model, we first specify the encoder and decoder separately. Encoder Module
class Encoder(nn.Module): """ Input : - source batch Layer : source batch -> Embedding -> LSTM Output : - LSTM hidden state - LSTM cell state Parmeters --------- input_dim : int Input dimension, should equal to the source vocab size. emb_dim...
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Decoder Module The decoder accept a batch of input tokens, previous hidden states and previous cell states. Note that in the decoder module, we are only decoding one token at a time, the input tokens will always have a sequence length of 1. This is different from the encoder module where we encode the entire source se...
class Decoder(nn.Module): """ Input : - first token in the target batch - LSTM hidden state from the encoder - LSTM cell state from the encoder Layer : target batch -> Embedding -- | encoder hidden state ------|--> LSTM -> Linear ...
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Seq2Seq Module For the final part of the implementation, we'll implement the seq2seq model. This will handle: - receiving the input/source sentence- using the encoder to produce the context vectors - using the decoder to produce the predicted output/target sentenceThe `Seq2Seq` model takes in an `Encoder`, `Decoder`, ...
class Seq2Seq(nn.Module): def __init__(self, encoder: Encoder, decoder: Decoder, device: torch.device): super().__init__() self.encoder = encoder self.decoder = decoder self.device = device assert encoder.hid_dim == decoder.hid_dim, \ 'Hidden dimensions of encode...
The model has 13,899,013 trainable parameters
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Training Seq2Seq We've done the hard work of defining our seq2seq module. The final touch is to specify the training/evaluation loop.
optimizer = optim.Adam(seq2seq.parameters()) # ignore the padding index when calculating the loss PAD_IDX = target.vocab.stoi['<pad>'] criterion = nn.CrossEntropyLoss(ignore_index=PAD_IDX) def train(seq2seq, iterator, optimizer, criterion): seq2seq.train() epoch_loss = 0 for batch in iterator: opt...
Epoch: 01 | Time: 1m 12s Train Loss: 5.023 | Train PPL: 151.870 Val. Loss: 4.904 | Val. PPL: 134.856 Epoch: 02 | Time: 1m 12s Train Loss: 4.396 | Train PPL: 81.134 Val. Loss: 4.651 | Val. PPL: 104.687 Epoch: 03 | Time: 1m 12s Train Loss: 4.076 | Train PPL: 58.924 Val. Loss: 4.411 | Val. PPL: 82.381 Epoch...
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Evaluating Seq2Seq
seq2seq.load_state_dict(torch.load('tut1-model.pt')) test_loss = evaluate(seq2seq, test_iterator, criterion) print(f'| Test Loss: {test_loss:.3f} | Test PPL: {math.exp(test_loss):7.3f} |')
| Test Loss: 3.650 | Test PPL: 38.477 |
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
Here, we pick a random example in our dataset, print out the original source and target sentence. Then takes a look at whether the "predicted" target sentence generated by the model.
example_idx = 0 example = train_data.examples[example_idx] print('source sentence: ', ' '.join(example.src)) print('target sentence: ', ' '.join(example.trg)) src_tensor = source.process([example.src]).to(device) trg_tensor = target.process([example.trg]).to(device) print(trg_tensor.shape) seq2seq.eval() with torch.no...
_____no_output_____
MIT
deep_learning/seq2seq/1_torch_seq2seq_intro.ipynb
certara-ShengnanHuang/machine-learning
To call a number of different locations all at once, just call using a dictionary with the location names as the keys and have nested lat and lon keys therein, and then the lat and lon. Save the figures as the dictionary keys+ the .format construction that includes the tilt plot name or w/e. Also allow option to pass a...
location_dataframe = pd.DataFrame(columns=['location','latitude','longitude']) location_dataframe['location']=['Ambler-Shungnak-Kobuk','Anchorage','Bethel','Chickaloon', 'Deering','Denali Park','Fairbanks','Fort Yukon', 'Galena-Koyukuk-Ruby', 'Homer','Naknek','Noatak', ...
Data for Ambler-Shungnak-Kobuk is being calculated Data for Anchorage is being calculated Data for Bethel is being calculated Data for Chickaloon is being calculated Data for Deering is being calculated Data for Denali Park is being calculated Data for Fairbanks is being calculated Data for Fort Yukon is being calculat...
MIT
Bokeh Functionalization.ipynb
acep-uaf/ACEP_solar
Reservoir of Izhikevich neuron models In this script a reservoir of neurons models with the differential equations proposed by Izhikevich is defined.
%matplotlib inline import pyNN.nest as p from pyNN.random import NumpyRNG, RandomDistribution from pyNN.utility import Timer import matplotlib.pyplot as plt import numpy as np timer = Timer() p.setup(timestep=0.1) # 0.1ms
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Definition of Inputs The input can be:- the joint position of the robot arm (rate coded or temporal coded)
poisson_input = p.SpikeSourcePoisson(rate = 10, start = 20.) #input_neuron = p.Population(2, p.SpikeSourcePoisson, {'rate': 0.7}, label='input') input_neuron = p.Population(2, poisson_input, label='input')
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Definition of neural populations Izhikevich spiking model with a quadratic non-linearity: dv/dt = 0.04*v^2 + 5*v + 140 - u + I du/dt = a*(b*v - u)
n = 1500 # number of cells exc_ratio = 0.8 # ratio of excitatory neurons n_exc = int(round(n*0.8)) n_inh = n-n_exc print n_exc, n_inh celltype = p.Izhikevich() # default_parameters = {'a': 0.02, 'c': -65.0, 'd': 2.0, 'b': 0.2, 'i_offset': 0.0}¶ # default_initial_values = {'v': -70.0, 'u': -14.0}¶ exc_cel...
1200 300
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Definition of readout neurons Decide:- 2 readout neurons: representing in which direction to move the joint- 1 readout neuron: representing the desired goal position of the joint
readout_neurons = p.Population(2, celltype, label="readout_neuron")
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Define the connections between the neurons
inp_conn = p.AllToAllConnector() rout_conn = p.AllToAllConnector() w_exc = 20. # later add unit w_inh = 51. # later add unit delay_exc = 1 # defines how long (ms) the synapse takes for transmission delay_inh = 1 stat_syn_exc = p.StaticSynapse(weight =w_exc, delay=delay_exc) stat_syn_inh = p.StaticSynapse(we...
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Setup recording and run the simulation
readout_neurons.record(['v','spikes']) exc_cells.record(['v','spikes']) p.run(1000)
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Plotting the Results
p.end() data_rout = readout_neurons.get_data() data_exc = exc_cells.get_data() fig_settings = { 'lines.linewidth': 0.5, 'axes.linewidth': 0.5, 'axes.labelsize': 'small', 'legend.fontsize': 'small', 'font.size': 8 } plt.rcParams.update(fig_settings) plt.figure(1, figsize=(6,8)) def plot_spiketrain...
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
Plot readout neurons
n_panels = sum(a.shape[1] for a in data_rout.segments[0].analogsignalarrays) + 2 plt.subplot(n_panels, 1, 1) plot_spiketrains(data_rout.segments[0]) panel = 3 for array in data_rout.segments[0].analogsignalarrays: for i in range(array.shape[1]): plt.subplot(n_panels, 1, panel) plot_signal(array, i, ...
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm