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 |
|---|---|---|---|---|---|
Plot of all of the data | all_data = get_sum_heatmap_from_files(data_name = "*", layer = "conv1d_4", verbose = True, dataset = dataset)
# Plot all of the entire data
plot_heatmap(all_data ,all_data.shape[0], all_data.shape[1])
plot_heatmap(all_data, 0, 100) | _____no_output_____ | MIT | scripts/python-scripts/heatmaps/0005_heatmap_sum_from_files.ipynb | TeamMacLean/ruth-effectors-prediction |
Data Augumentation | def get_train_transforms():
return Compose([
RandomResizedCrop(CFG.size, CFG.size),
Transpose(p=0.5),
HorizontalFlip(p=0.5),
VerticalFlip(p=0.5),
ShiftScaleRotate(p=0.5),
# JpegCompression(p=0.5),
HueSaturationValue(hue_shift_limit=... | _____no_output_____ | MIT | image/cassava-leaf-disease-classification/.ipynb_checkpoints/003_albumentations_smoothing-checkpoint.ipynb | Tsuchiya-Hayato/data_compe |
Data Loader | class ImageData(Dataset):
def __init__(self, df, data_dir, transform, output_label=True):
super().__init__()
self.df = df
self.data_dir = data_dir
self.transform = transform
self.output_label = output_label
def __len__(self):
return len(self.df)
def __ge... | _____no_output_____ | MIT | image/cassava-leaf-disease-classification/.ipynb_checkpoints/003_albumentations_smoothing-checkpoint.ipynb | Tsuchiya-Hayato/data_compe |
CrossEntropyLoss | class SmoothCrossEntropyLoss(_WeightedLoss):
def __init__(self, weight=CFG.weights, reduction='mean', smoothing=CFG.smoothing):
super().__init__(weight=weight, reduction=reduction)
self.smoothing = smoothing
self.weight = weight
self.reduction = reduction
@staticmethod
def _... | _____no_output_____ | MIT | image/cassava-leaf-disease-classification/.ipynb_checkpoints/003_albumentations_smoothing-checkpoint.ipynb | Tsuchiya-Hayato/data_compe |
Helper Function | def Plot_Model_History(loss_tra_li,acc_tra_li,loss_val_li,acc_val_li):
plt.figure(figsize=(12, 5))
plt.subplot(2, 2, 1)
plt.plot(loss_tra_li, label="train_loss")
plt.plot(loss_val_li, label="val_loss")
plt.legend()
plt.subplot(2, 2, 2)
plt.plot(acc_tra_li, label="train_acc")
plt.plot(acc... | Loaded pretrained weights for efficientnet-b5
Kfold: 1 - Epoch: 1 - Train_Loss: 1.212992 - Train_Acc: 62.5210 - Val_Loss: 1.329435 - Val_Acc: 60.549558
Kfold: 1 - Epoch: 2 - Train_Loss: 1.114438 - Train_Acc: 66.1105 - Val_Loss: 1.219338 - Val_Acc: 67.068555
Kfold: 1 - Epoch: 3 - Train_Loss: 1.091065 - Train_Acc: 68.045... | MIT | image/cassava-leaf-disease-classification/.ipynb_checkpoints/003_albumentations_smoothing-checkpoint.ipynb | Tsuchiya-Hayato/data_compe |
Предобработка данных и логистическая регрессия для задачи бинарной классификации Programming assignment В задании вам будет предложено ознакомиться с основными техниками предобработки данных, а так же применить их для обучения модели логистической регрессии. Ответ потребуется загрузить в соответствующую форму в виде ... | import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
matplotlib.style.use('ggplot')
%matplotlib inline | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Описание датасета Задача: по 38 признакам, связанных с заявкой на грант (область исследований учёных, информация по их академическому бэкграунду, размер гранта, область, в которой он выдаётся) предсказать, будет ли заявка принята. Датасет включает в себя информацию по 6000 заявкам на гранты, которые были поданы в унив... | data = pd.read_csv('data.csv')
data.shape | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Выделим из датасета целевую переменную Grant.Status и обозначим её за yТеперь X обозначает обучающую выборку, y - ответы на ней | X = data.drop('Grant.Status', 1)
y = data['Grant.Status']
print(X.shape)
print(y.shape) | (6000, 38)
(6000L,)
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Теория по логистической регрессии После осознания того, какую именно задачу требуется решить на этих данных, следующим шагом при реальном анализе был бы подбор подходящего метода. В данном задании выбор метода было произведён за вас, это логистическая регрессия. Кратко напомним вам используемую модель.Логистическая ре... | data.head() | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Видно, что в датасете есть как числовые, так и категориальные признаки. Получим списки их названий: | numeric_cols = ['RFCD.Percentage.1', 'RFCD.Percentage.2', 'RFCD.Percentage.3',
'RFCD.Percentage.4', 'RFCD.Percentage.5',
'SEO.Percentage.1', 'SEO.Percentage.2', 'SEO.Percentage.3',
'SEO.Percentage.4', 'SEO.Percentage.5',
'Year.of.Birth.1', 'Number.of.Succ... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Также в нём присутствуют пропущенные значения. Очевидны решением будет исключение всех данных, у которых пропущено хотя бы одно значение. Сделаем это: | data.dropna().shape | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Видно, что тогда мы выбросим почти все данные, и такой метод решения в данном случае не сработает.Пропущенные значения можно так же интерпретировать, для этого существует несколько способов, они различаются для категориальных и вещественных признаков.Для вещественных признаков:- заменить на 0 (данный признак давать вкл... | def calculate_means(numeric_data):
means = np.zeros(numeric_data.shape[1])
for j in range(numeric_data.shape[1]):
to_sum = numeric_data.iloc[:,j]
indices = np.nonzero(~numeric_data.iloc[:,j].isnull())[0]
correction = np.amax(to_sum[indices])
to_sum /= correction
for i in ... | (6000, 13)
(6000, 13)
(6000, 25)
Type after astype
<type 'str'>
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Преобразование категориальных признаков. В предыдущей ячейке мы разделили наш датасет ещё на две части: в одной присутствуют только вещественные признаки, в другой только категориальные. Это понадобится нам для раздельной последующей обработке этих данных, а так же для сравнения качества работы тех или иных методов.Дл... | from sklearn.linear_model import LogisticRegression as LR
from sklearn.feature_extraction import DictVectorizer as DV
categorial_data = pd.DataFrame({'sex': ['male', 'female', 'male', 'female'],
'nationality': ['American', 'European', 'Asian', 'European']})
print(categorial_data.T.to_d... | {0: {'nationality': 'American', 'sex': 'male'}, 1: {'nationality': 'European', 'sex': 'female'}, 2: {'nationality': 'Asian', 'sex': 'male'}, 3: {'nationality': 'European', 'sex': 'female'}}
[{'nationality': 'American', 'sex': 'male'}, {'nationality': 'European', 'sex': 'female'}, {'nationality': 'Asian', 'sex': 'male'}... | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Как видно, в первые три колонки оказалась закодированна информация о стране, а во вторые две - о поле. При этом для совпадающих элементов выборки строки будут полностью совпадать. Также из примера видно, что кодирование признаков сильно увеличивает их количество, но полностью сохраняет информацию, в том числе о наличии... | encoder = DV(sparse = False)
X_cat_oh = encoder.fit_transform(X_cat.T.to_dict().values())
print(X_cat_oh.shape) | (6000L, 5593L)
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Для построения метрики качества по результату обучения требуется разделить исходный датасет на обучающую и тестовую выборки.Обращаем внимание на заданный параметр для генератора случайных чисел: random_state. Так как результаты на обучении и тесте будут зависеть от того, как именно вы разделите объекты, то предлагается... | from sklearn.cross_validation import train_test_split
(X_train_real_zeros,
X_test_real_zeros,
y_train, y_test) = train_test_split(X_real_zeros, y,
test_size=0.3,
random_state=0)
(X_train_real_mean,
X_test_real_mean) = train_test_split(X_... | (4200, 13)
(4200L, 5593L)
(4200, 13)
(4200L, 5593L)
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Описание классов Итак, мы получили первые наборы данных, для которых выполнены оба ограничения логистической регрессии на входные данные. Обучим на них регрессию, используя имеющийся в библиотеке sklearn функционал по подбору гиперпараметров модели optimizer = GridSearchCV(estimator, param_grid)где:- estimator ... | from sklearn.linear_model import Lasso
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import roc_auc_score
def plot_scores(optimizer):
scores = [[item[0]['C'],
item[1],
(np.sum((item[2]-item[1])**2)/(item[2].size-1))**0.5] for item in optimizer.grid_scores_]
s... | C:\Users\Evgeni\Anaconda2\lib\site-packages\sklearn\grid_search.py:42: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.
DeprecationWarning)
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Масштабирование вещественных признаков. Попробуем как-то улучшить качество классификации. Для этого посмотрим на сами данные: | from pandas.tools.plotting import scatter_matrix
data_numeric = pd.DataFrame(X_train_real_zeros, columns=numeric_cols)
list_cols = ['Number.of.Successful.Grant.1', 'SEO.Percentage.2', 'Year.of.Birth.1']
scatter_matrix(data_numeric[list_cols], alpha=0.5, figsize=(10, 10))
plt.show() | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Как видно из графиков, разные признаки очень сильно отличаются друг от друга по модулю значений (обратите внимание на диапазоны значений осей x и y). В случае обычной регрессии это никак не влияет на качество обучаемой модели, т.к. у меньших по модулю признаков будут большие веса, но при использовании регуляризации, ко... | from sklearn.preprocessing import StandardScaler
# place your code here
scaler = StandardScaler()
X_train_real_scaled = scaler.fit_transform(X_train_real_zeros)
X_test_real_scaled = scaler.transform(X_test_real_zeros)
print(X_train_real_scaled.shape)
print(X_test_real_scaled.shape) | (4200L, 13L)
(1800L, 13L)
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Сравнение признаковых пространств. Построим такие же графики для преобразованных данных: | data_numeric_scaled = pd.DataFrame(X_train_real_scaled, columns=numeric_cols)
list_cols = ['Number.of.Successful.Grant.1', 'SEO.Percentage.2', 'Year.of.Birth.1']
scatter_matrix(data_numeric_scaled[list_cols], alpha=0.5, figsize=(10, 10))
plt.show() | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Как видно из графиков, мы не поменяли свойства признакового пространства: гистограммы распределений значений признаков, как и их scatter-plots, выглядят так же, как и до нормировки, но при этом все значения теперь находятся примерно в одном диапазоне, тем самым повышая интерпретабельность результатов, а также лучше соч... | def write_answer_2(auc):
with open("preprocessing_lr_answer2.txt", "w") as fout:
fout.write(str(auc))
# place your code here
X_train = np.hstack((X_train_real_scaled, X_train_cat_oh))
X_test = np.hstack((X_test_real_scaled, X_test_cat_oh))
optimizer.fit(X_train, y_train)
auc_3 = roc_auc_score(y_tes... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Балансировка классов. Алгоритмы классификации могут быть очень чувствительны к несбалансированным классам. Рассмотрим пример с выборками, сэмплированными из двух гауссиан. Их мат. ожидания и матрицы ковариации заданы так, что истинная разделяющая поверхность должна проходить параллельно оси x. Поместим в обучающую выб... | np.random.seed(0)
"""Сэмплируем данные из первой гауссианы"""
data_0 = np.random.multivariate_normal([0,0], [[0.5,0],[0,0.5]], size=40)
"""И из второй"""
data_1 = np.random.multivariate_normal([0,1], [[0.5,0],[0,0.5]], size=40)
"""На обучение берём 20 объектов из первого класса и 10 из второго"""
example_data_train = n... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Как видно, во втором случае классификатор находит разделяющую поверхность, которая ближе к истинной, т.е. меньше переобучается. Поэтому на сбалансированность классов в обучающей выборке всегда следует обращать внимание.Посмотрим, сбалансированны ли классы в нашей обучающей выборке: | print(np.sum(y_train==0))
print(np.sum(y_train==1)) | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Видно, что нет.Исправить ситуацию можно разными способами, мы рассмотрим два:- давать объектам миноритарного класса больший вес при обучении классификатора (рассмотрен в примере выше)- досэмплировать объекты миноритарного класса, пока число объектов в обоих классах не сравняется Задание 3. Балансировка классов.1. Обуч... | def write_answer_3(auc_1, auc_2):
auc = (auc_1 + auc_2) / 2
with open("preprocessing_lr_answer3.txt", "w") as fout:
fout.write(str(auc))
# place your code here
estimator = LogisticRegression(class_weight="balanced")
optimizer = GridSearchCV(estimator, param_grid, cv=cv)
optimizer.fit(X_train, y... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Стратификация выборок. Рассмотрим ещё раз пример с выборками из нормальных распределений. Посмотрим ещё раз на качество классификаторов, получаемое на тестовых выборках: | print('AUC ROC for classifier without weighted classes', auc_wo_class_weights)
print('AUC ROC for classifier with weighted classes: ', auc_w_class_weights) | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Насколько эти цифры реально отражают качество работы алгоритма, если учесть, что тестовая выборка так же несбалансирована, как обучающая? При этом мы уже знаем, что алгоритм логистический регрессии чувствителен к балансировке классов в обучающей выборке, т.е. в данном случае на тесте он будет давать заведомо заниженные... | """Разделим данные по классам поровну между обучающей и тестовой выборками"""
example_data_train = np.vstack([data_0[:20,:], data_1[:20,:]])
example_labels_train = np.concatenate([np.zeros((20)), np.ones((20))])
example_data_test = np.vstack([data_0[20:,:], data_1[20:,:]])
example_labels_test = np.concatenate([np.zeros... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Как видно, после данной процедуры ответ классификатора изменился незначительно, а вот качество увеличилось. При этом, в зависимости от того, как вы разбили изначально данные на обучение и тест, после сбалансированного разделения выборок итоговая метрика на тесте может как увеличиться, так и уменьшиться, но доверять ей ... | def write_answer_4(auc):
with open("preprocessing_lr_answer4.txt", "w") as fout:
fout.write(str(auc))
# place your code here
(X_train_real_zeros,
X_test_real_zeros,
y_train, y_test) = train_test_split(X_real_zeros, y,
test_size=0.3,
... | auc_6=0.879349
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Теперь вы разобрались с основными этапами предобработки данных для линейных классификаторов.Напомним основные этапы:- обработка пропущенных значений- обработка категориальных признаков- стратификация- балансировка классов- масштабированиеДанные действия с данными рекомендуется проводить всякий раз, когда вы планируете ... | from sklearn.preprocessing import PolynomialFeatures
"""Инициализируем класс, который выполняет преобразование"""
transform = PolynomialFeatures(2)
"""Обучаем преобразование на обучающей выборке, применяем его к тестовой"""
example_data_train_poly = transform.fit_transform(example_data_train)
example_data_test_poly = ... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Видно, что данный метод преобразования данных уже позволяет строить нелинейные разделяющие поверхности, которые могут более тонко подстраиваться под данные и находить более сложные зависимости. Число признаков в новой модели: | print(example_data_train_poly.shape) | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Но при этом одновременно данный метод способствует более сильной способности модели к переобучению из-за быстрого роста числа признаком с увеличением степени $p$. Рассмотрим пример с $p=11$: | transform = PolynomialFeatures(11)
example_data_train_poly = transform.fit_transform(example_data_train)
example_data_test_poly = transform.transform(example_data_test)
optimizer = GridSearchCV(LogisticRegression(class_weight='balanced', fit_intercept=False), param_grid, cv=cv, n_jobs=-1)
optimizer.fit(example_data_tra... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Количество признаков в данной модели: | print(example_data_train_poly.shape) | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Задание 5. Трансформация вещественных признаков.1. Реализуйте по аналогии с примером преобразование вещественных признаков модели при помощи полиномиальных признаков степени 22. Постройте логистическую регрессию на новых данных, одновременно подобрав оптимальные гиперпараметры. Обращаем внимание, что в преобразованных... | def write_answer_5(auc):
with open("preprocessing_lr_answer5.txt", "w") as fout:
fout.write(str(auc))
# place your code here
transform = PolynomialFeatures(2)
X_train_real_zeros_poly = transform.fit_transform(X_train_real_zeros)
print("X_train_real_zeros_poly.shape=", X_train_real_zeros_poly.shape)... | _____no_output_____ | MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
Регрессия Lasso.К логистической регрессии также можно применить L1-регуляризацию (Lasso), вместо регуляризации L2, которая будет приводить к отбору признаков. Вам предлагается применить L1-регуляцию к исходным признакам и проинтерпретировать полученные результаты (применение отбора признаков к полиномиальным так же мо... | def write_answer_6(features):
with open("preprocessing_lr_answer6.txt", "w") as fout:
fout.write(" ".join([str(num) for num in features]))
# place your code here
scaler = StandardScaler()
X_train_real_scaled = scaler.fit_transform(X_train_real_zeros)
X_test_real_scaled = scaler.transform(X_test_rea... | [ 0.01132685 0.04013928 -0.08998798 -0.0679895 0. -0.00387355
0. 0. 0.02661963 -0.00724675 0.23330794 1.06510825
-1.43368432]
[4 6 7]
| MIT | C2W3/Preprocessing_LR.ipynb | nabokov-ef/ml-and-da-by-mipt-and-yandex |
See [osfclient documentation](https://osfclient.readthedocs.io/en/latest/cli-usage.html) for details.OSF storage limits:* private components: 5GB* public components: 50 GB* [Possible providers](https://help.osf.io/hc/en-us/articles/360019737894-FAQs:~:text=OSF%20supports%20many%20third%2Dparty,connect%20to%20Mendeley%2... | # file in working directory with the format
# username=XXXX
# password=XXXX
osf_credentials = {}
with open("osf_credentials.txt", "r") as credfile:
for l in credfile:
osf_credentials[l.split("=")[0]] = l.split("=")[1] | _____no_output_____ | MIT | interface_with_OSF.ipynb | StephanLewandowsky/Honesty-project |
Read a file into a data frame | remote_path = "data/test_csv.csv" # remote file path & file name
storage = "osfstorage" # seems to be the name of the default OSF storage provider
project_ID = "2eyms" # get this from the URL of the project/component in the browser
# initialize the client and authenticate with the API
osf = osfclient.OSF(
username... | 100%|██████████████████████████████████████████████████████████████████████████████████████████████| 1.39M/1.39M [00:00<00:00, 19.5Mbytes/s]
| MIT | interface_with_OSF.ipynb | StephanLewandowsky/Honesty-project |
Download a file | local_path = "../data/osf_test/testfile.txt" # local file path & file name
remote_path = "data/testfile.txt" # remote file path & file name
storage = "osfstorage" # seems to be the name of the default OSF storage provider
project_ID = "2eyms" # get this from the URL of the project in the browser
if local_path is None:... | 100%|████████████████████████████████████████████████████████████████████████████████████████████████| 10.0/10.0 [00:00<00:00, 40.6kbytes/s]
| MIT | interface_with_OSF.ipynb | StephanLewandowsky/Honesty-project |
Parsing Company 10Ks From the SEC In this module, now that we can grab any filing we want from the daily-index filings we are going to move on to the next topic parsing financial documents. The easiest one we can start with is the 10K because the underlying structure provided to us will make grabbing the data accessib... | # import our libraries
import requests
import pandas as pd
from bs4 import BeautifulSoup | _____no_output_____ | MIT | SEC Scraping/03 Web Scraping SEC - 10K Landing Page - Single.ipynb | fkmooney/Analysis |
*** Grab the Filing XML SummarySomething that makes 10-K and for that matter 10-Q filings so unique is we have access to a particular document that gives us a quick way to grab the data we need from a 10-K. This file is the **filing summary** and comes in an either an `XML` or `xlsx` format. While you would think these... | # define the base url needed to create the file url.
base_url = r"https://www.sec.gov"
# convert a normal url to a document url
normal_url = r"https://www.sec.gov/Archives/edgar/data/1265107/0001265107-19-000004.txt"
normal_url = normal_url.replace('-','').replace('.txt','/index.json')
# define a url that leads to a ... | ----------------------------------------------------------------------------------------------------
File Name: FilingSummary.xml
File Path: https://www.sec.gov/Archives/edgar/data/1265107/000126510719000004/FilingSummary.xml
| MIT | SEC Scraping/03 Web Scraping SEC - 10K Landing Page - Single.ipynb | fkmooney/Analysis |
*** Parsing the Filing SummaryOkay, we now have access to a filing summary file. The first thing we need to do is request the file using the `requests` library we will then take the contents of that request and pass through our `BeautifulSoup` object. I encourage individuals who are new to this process to look at the f... | # define a new base url that represents the filing folder. This will come in handy when we need to download the reports.
base_url = xml_summary.replace('FilingSummary.xml', '')
# request and parse the content
content = requests.get(xml_summary).content
soup = BeautifulSoup(content, 'lxml')
# find the 'myreports' tag ... | ----------------------------------------------------------------------------------------------------
https://www.sec.gov/Archives/edgar/data/1265107/000126510719000004/R1.htm
0001000 - Document - Document and Entity Information
Document and Entity Information
Cover
1
----------------------------------------------------... | MIT | SEC Scraping/03 Web Scraping SEC - 10K Landing Page - Single.ipynb | fkmooney/Analysis |
*** Grabbing the Financial StatementsWe now have a nice organized list of all the different components of the 10-K filing, while it won't have all the info it makes the process of getting the data tables a lot easier. We can always revisit the actual text but at this point let's move forward assuming that we want to ge... | # create the list to hold the statement urls
statements_url = []
for report_dict in master_reports:
# define the statements we want to look for.
item1 = r"Consolidated Balance Sheets"
item2 = r"Consolidated Statements of Operations and Comprehensive Income (Loss)"
item3 = r"Consolidated Statements... | ----------------------------------------------------------------------------------------------------
Consolidated Balance Sheets
https://www.sec.gov/Archives/edgar/data/1265107/000126510719000004/R2.htm
----------------------------------------------------------------------------------------------------
Consolidated Sta... | MIT | SEC Scraping/03 Web Scraping SEC - 10K Landing Page - Single.ipynb | fkmooney/Analysis |
*** Scraping the Financial StatementsWe now have each financial statement's URL that we can now request for the content of that specific statement. The first thing we will need to do is a loop through all the URLs, request each one, and then parse the content. Like the **filing xml summary** up above, I encourage indiv... | # let's assume we want all the statements in a single data set.
statements_data = []
# loop through each statement url
for statement in statements_url:
# define a dictionary that will store the different parts of the statement.
statement_data = {}
statement_data['headers'] = []
statement_data['section... | _____no_output_____ | MIT | SEC Scraping/03 Web Scraping SEC - 10K Landing Page - Single.ipynb | fkmooney/Analysis |
*** Converting the Data into a Data FrameGreat, we now have all the data for all the financial statements, and it's in a much better structure that will allow us to work with it. We still have some work to do regarding transforming it into the right data type, but we will handle that later. Let's first get it into a da... | # Grab the proper components
income_header = statements_data[1]['headers'][1]
income_data = statements_data[1]['data']
# Put the data in a DataFrame
income_df = pd.DataFrame(income_data)
# Display
print('-'*100)
print('Before Reindexing')
print('-'*100)
display(income_df.head())
# Define the Index column, rename it... | ----------------------------------------------------------------------------------------------------
Before Reindexing
----------------------------------------------------------------------------------------------------
| MIT | SEC Scraping/03 Web Scraping SEC - 10K Landing Page - Single.ipynb | fkmooney/Analysis |
Configuring pandas /content/Learning-Pandas-Second-Edition | # import numpy and pandas
import numpy as np
import pandas as pd
# used for dates
import datetime
from datetime import datetime, date
# Set some pandas options controlling output format
#pd.set_option('display.notebook_repr_html', False)
#pd.set_option('display.max_columns', 8)
#pd.set_option('display.max_rows', 10)
... | _____no_output_____ | MIT | Chapter02/02_Up and Running with pandas.ipynb | jiayou60/Learning-Pandas-Second-Edition |
The pandas Series | # create a four item Series
s = pd.Series([1, 2, 3, 4])
s
# get value at label 1
s[1]
# return a Series with the row with labels 1 and 3
s[[1, 3]]
type(s[[1, 3]])
# create a series using an explicit index
s = pd.Series([1, 2, 3, 4],
index = ['a', 'b', 'c', 'd'])
s
# look up items the series having index... | _____no_output_____ | MIT | Chapter02/02_Up and Running with pandas.ipynb | jiayou60/Learning-Pandas-Second-Edition |
The pandas DataFrame | # create a DataFrame from the two series objects temp1 and temp2
# and give them column names
temps_df = pd.DataFrame(
{'Missoula': temps1,
'Philadelphia': temps2})
temps_df
# get the column with the name Missoula
temps_df['Missoula']
# likewise we can get just the Philadelphia column
temps_df... | _____no_output_____ | MIT | Chapter02/02_Up and Running with pandas.ipynb | jiayou60/Learning-Pandas-Second-Edition |
Loading data from a CSV file into a DataFrame | import os
print(os.getcwd())
!git clone https://github.com/jiayou60/Learning-Pandas-Second-Edition.git
os.chdir("Learning-Pandas-Second-Edition")
# display the contents of test1.csv
# which command to use depends on your OS
!head data/goog.csv # on non-windows systems
!type data/test1.csv # on windows systems, all... | _____no_output_____ | MIT | Chapter02/02_Up and Running with pandas.ipynb | jiayou60/Learning-Pandas-Second-Edition |
Visualization | # plots the values in the Close column
df.Close.plot(); | _____no_output_____ | MIT | Chapter02/02_Up and Running with pandas.ipynb | jiayou60/Learning-Pandas-Second-Edition |
Lab 4 Import libs and connect to database | import pandas
import configparser
import psycopg2
config=configparser.ConfigParser()
config.read('config.ini')
host=config['myaws']['host']
db=config['myaws']['db']
user=config['myaws']['user']
pwd=config['myaws']['pwd']
conn= psycopg2.connect(
host=host,
user=user,
... | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
q1 | sql_q1= """
select * from gp7.student
"""
df=pandas.read_sql_query(sql_q1, conn)
df[:] | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
q2 | sql_q2="""
select gp7.professor.p_name,
gp7.course.c_name
from gp7.professor
inner join gp7.course
on gp7.professor.p_email=gp7.course.p_email
"""
df=pandas.read_sql_query(sql_q2, conn)
df[:] | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
q3 | sql_q3= """
select c_number,
count(c_number) as enrolled
from gp7.enroll_list
group by c_number
order by enrolled desc
"""
df=pandas.read_sql_query(sql_q3, conn)
df.plot.bar(y='enrolled', x='c_number') | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
q4 | sql_q4="""
select gp7.professor.p_name,
count (gp7.course.c_name) as teaching_number
from gp7.professor
inner join gp7.course
on gp7.professor.p_email=gp7.course.p_email
group by professor.p_name
order by teaching_number desc
"""
df=pandas.read_sql_query(s... | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
q5 | sql_q5_professor= """
insert into gp7.professor(p_email, p_name,office)
values('{}','{}', '{}')
""" .format('new_p2@jmu.edu', 'new_p2', 'new_off')
cur.execute(sql_q5_professor)
conn.commit()
df=pandas.read_sql_query('select * from gp7.professor', conn)
df[:]
sql_q5_cou... | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
q6 | sql_q6_course= """
update gp7.course
set p_email='{}'
where p_email='{}'
""" .format('new_p@jmu.edu','weixx@jmu.edu')
cur.execute(sql_q6_course)
conn.commit()
df=pandas.read_sql_query('select * from gp7.course', conn)
df[:]
sql_q6_professor= """
... | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
close connection | cur.close()
conn.close() | _____no_output_____ | MIT | lab4.ipynb | eisenhlm/IA340 |
I was wondering how ipywidgets use the `display` machinery of IPython to display itself. SinceI couldn't find any use of `_repr_html`, I was puzzled. Also I wanted to understand how create an object composed of various widgets that can display itself.Answer came from [ipython/Custom Display Logic.ipynb at 40c34d3369c... | import json
import uuid
from IPython.display import display_javascript, display_html, display
class FlotPlot(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.uuid = str(uuid.uuid4())
def _ipython_display_(self):
json_data = json.dumps(list(zip(self.x, self.y)))... | _____no_output_____ | Apache-2.0 | notebooks/Using _ipython_display_.ipynb | rdhyee/webtech-learning |
simple compound widget | from ipywidgets import (widgets, VBox, HBox)
from IPython.display import display, display_html, display_javascript
import traitlets
class SimpleCompoundWidget(object):
def __init__(self, init_value=''):
self.text_w = widgets.Text(value=init_value)
self.mirror_w = widgets.HTML(value="<b>{}</b>".form... | _____no_output_____ | Apache-2.0 | notebooks/Using _ipython_display_.ipynb | rdhyee/webtech-learning |
Loading data in PyTorch=======================PyTorch features extensive neural network building blocks with a simple,intuitive, and stable API. PyTorch includes packages to prepare and loadcommon datasets for your model.Introduction------------At the heart of PyTorch data loading utility is the`torch.utils.data.DataLo... | import torch
import torchaudio | _____no_output_____ | MIT | notebooks/loading_data_recipe.ipynb | SamuelHuang2019/machine-learning-lab |
2. Access the data in the dataset~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~The Yesno dataset in ``torchaudio`` features sixty recordings of oneindividual saying yes or no in Hebrew; with each recording being eightwords long (`read more here `__).``torchaudio.datasets.YESNO`` creates a dataset for YesNo.:: torchaudio.datas... | # * ``download``: If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again.
# * ``transform``: Using transforms on your data allows you to take it from its source state and transform it into data that’s joined together, de-normalized, a... | _____no_output_____ | MIT | notebooks/loading_data_recipe.ipynb | SamuelHuang2019/machine-learning-lab |
When using this data in practice, it is best practice to provision thedata into a “training” dataset and a “testing” dataset. This ensuresthat you have out-of-sample data to test the performance of your model.3. Loading the data~~~~~~~~~~~~~~~~~~~~~~~Now that we have access to the dataset, we must pass it through``torc... | data_loader = torch.utils.data.DataLoader(yesno_data,
batch_size=1,
shuffle=True) | _____no_output_____ | MIT | notebooks/loading_data_recipe.ipynb | SamuelHuang2019/machine-learning-lab |
4. Iterate over the data~~~~~~~~~~~~~~~~~~~~~~~~~~~~Our data is now iterable using the ``data_loader``. This will benecessary when we begin training our model! You will notice that noweach data entry in the ``data_loader`` object is converted to a tensorcontaining tensors representing our waveform, sample rate, and lab... | for data in data_loader:
print("Data: ", data)
print("Waveform: {}\nSample rate: {}\nLabels: {}".format(data[0], data[1], data[2]))
break | _____no_output_____ | MIT | notebooks/loading_data_recipe.ipynb | SamuelHuang2019/machine-learning-lab |
5. [Optional] Visualize the data~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~You can optionally visualize your data to further understand the outputfrom your ``DataLoader``. | import matplotlib.pyplot as plt
print(data[0][0].numpy())
plt.figure()
plt.plot(waveform.t().numpy()) | _____no_output_____ | MIT | notebooks/loading_data_recipe.ipynb | SamuelHuang2019/machine-learning-lab |
Word2Vec for Sentiment Analysis in RussianWord2vec [1] is a computationally-efficient predictive model for learning low-dimensional word embeddings from raw textual data. 1. Loding sentiment dataThe corpus of short texts in Russian based on Twitter messages is available at http://study.mokoron.com/ (and also describe... | import re
def preprocess_text(text):
text = text.lower().replace("ё", "е")
text = re.sub('((www\.[^\s]+)|(https?://[^\s]+))','URL', text)
text = re.sub('@[^\s]+','USER', text)
text = re.sub('[^a-zA-Zа-яА-Я1-9]+', ' ', text)
text = re.sub(' +',' ', text)
return text.strip() | _____no_output_____ | MIT | Word2Vec for Sentiment Analysis in Russian.ipynb | MentatRus/twitter-sentiment |
In Python it is easier to work with SQLite databases rather then with SQL databases, so the original SQL file was converted into SQLite using mysql2sqlite script. | import sqlite3
conn = sqlite3.connect('mysqlite3.db')
c = conn.cursor()
with open('tweets.txt', 'w', encoding='utf-8') as f:
for row in c.execute('SELECT ttext FROM sentiment'):
if row[0]:
tweet = preprocess_text(row[0])
print(tweet, file=f)
tweets = open('tweets.txt').read().split... | 0.94599 for sentence_length=20
0.96172 for sentence_length=21
0.97419 for sentence_length=22
0.98353 for sentence_length=23
0.99021 for sentence_length=24
0.99457 for sentence_length=25
0.99712 for sentence_length=26
0.99849 for sentence_length=27
0.99924 for sentence_length=28
0.99959 for sentence_length=29
0.99975 fo... | MIT | Word2Vec for Sentiment Analysis in Russian.ipynb | MentatRus/twitter-sentiment |
2. Training the modelGensim [3] was used for obtaining vector representations of Russian words. The model was trained on the entire dataset, which was collected and pre-processed at the previous steps. | import logging
import multiprocessing
import gensim
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
data = gensim.models.word2vec.LineSentence('tweets.txt')
model = Word2Vec(data, size=200, window=5, min_count=3, workers=multiprocessing.cp... | 2018-06-26 13:09:14,817 : INFO : saving Word2Vec object under w2v/tweets_model.w2v, separately None
2018-06-26 13:09:14,818 : INFO : storing np array 'vectors' to w2v/tweets_model.w2v.wv.vectors.npy
2018-06-26 13:09:16,552 : INFO : not storing attribute vectors_norm
2018-06-26 13:09:16,554 : INFO : storing np array 'sy... | MIT | Word2Vec for Sentiment Analysis in Russian.ipynb | MentatRus/twitter-sentiment |
3. Visualizationt-SNE was used to plot a subset of similar words from trained Word2Vec model. Firstly, similar words were found and appended each of the similar words embedding vector to the matrix. Secondly, t-SNE was applied to the matrix in order to project each word to a 2D space (i.e. dimension reduction). Finall... | from gensim.models import Word2Vec
model = Word2Vec.load('w2v/tweets_model.w2v')
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
% matplotlib inline
def tsne_plot(labels, tokens, classes, clusters):
tsne_model = TSNE(perplexity=15, n_components=2, i... | _____no_output_____ | MIT | Word2Vec for Sentiment Analysis in Russian.ipynb | MentatRus/twitter-sentiment |
https://discourse.julialang.org/t/solving-difference-equation-part-2/67057 | using DynamicalSystems, DelimitedFiles, .Threads, BenchmarkTools, ProgressMeter
## Components of a test DiscreteDynamicalSystem
function dds_constructor(u0 = [0.5, 0.7]; r=1.0, k=2.0)
return DiscreteDynamicalSystem(dds_rule, u0, [r, k], dds_jac)
end
## equations of motion:
function dds_rule(x, par, n)
r, k = ... | Variables
#self#[36m::Core.Const(isoperiodic_test_rev2)[39m
init[36m::Vector{Float64}[39m
par_area[36m::Matrix{Float64}[39m
NIter[36m::Int64[39m
nxblock[36m::Int64[39m
nyblock[36m::Int64[39m
NTr[36m::Int64[39m
xpts[36m::Int64[39m
ypts[36m::Int64[39m
@_10[33m[1m::Union{Nothing, Tu... | MIT | 0018/DynamicalSystem/Revised.ipynb | genkuroki/public |
Configuration initialization | # Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')
# # Locate path of data in 'google drive'
# DATA_PATH = '/content/drive/MyDrive/MinorThesis/'
# SEED_NUMBER = 19900506 | _____no_output_____ | Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
BERT Evaluator for Minor Thesis**Student Name:** Jirarote Jirasirikul**Student ID:** 31334679 Import LibraryAll Library and File Path will be added here | # # Installation (Uncomment if need to installation or update library)
# !pip install spacy #==2.0.11
# !pip install transformers
!pip install transformers
import transformers as ppb
import pandas as pd
import numpy as np
import glob
import os
from pathlib import Path
from sklearn.linear_model import LogisticRegressio... | _____no_output_____ | Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
Check Available Device (CPU/GPU) | import torch
# If there's a GPU available...
if torch.cuda.is_available():
# Tell PyTorch to use the GPU.
DEVICE_AVAILABLE = torch.device("cuda")
print('There are %d GPU(s) available.' % torch.cuda.device_count())
print('We will use the GPU:', torch.cuda.get_device_name(0))
# If not...
else:
... | There are 1 GPU(s) available.
We will use the GPU: Tesla T4
| Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
---BERT Text RepresentationTransform Language ModelWhen using BERT, technically we are transforming our sentence into a vector that represent each sentence. The process is call Language Model a representation of each word. BERT add [CLS] token infront of each sentence. This token representation vector could later be us... | # BERT weight Options
# - 'distilbert-base-uncased'
# - 'bert-base-uncased'
# - 'dmis-lab/biobert-base-cased-v1.1'
# - 'dmis-lab/biobert-v1.1' : Data Mining and Information Systems Lab, Korea University's picture Updated May 19 • 41k
# - 'microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext'
class my_BERT:
... | _____no_output_____ | Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
--- Downstream Model Class: my_downstream | class my_downstream:
def __init__(self, train_x, train_y, test_x = None, test_y = None, ENABLE_LOGS = 1):
self.train_x = train_x
self.train_y = train_y
self.test_x = test_x
self.test_y = test_y
self.predict_x = None
self.predict_y = None
self.model = None
... | _____no_output_____ | Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
--- Run Evaluator | def run_evaluator(datapath,dataset,label='label',pretrain_model = 'bert-base-uncased',token_size=128, seed_number = 19900506):
print_log("Run Evaluator","Function")
print_log("pretrain_model:",pretrain_model)
print_log("token_size:",token_size)
print_log("seed_number",seed_number)
temppath_train = ... | [Info] Run Evaluator Function
[Info] pretrain_model: bert-base-uncased
[Info] token_size: 128
[Info] seed_number 19900506
[Info] Train file exist: True ( /content/drive/MyDrive/MinorThesis/datasets/blurb_hoc/train.json )
[Info] Test file exist: True ( /content/drive/MyDrive/MinorThesis/datasets/blurb_hoc/test.json )
[I... | Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
Read Results | import os
import pandas as pd
TARGET_PATH = '/content/drive/MyDrive/MinorThesis/'
temp_list = []
datasets = os.listdir(TARGET_PATH+"results")
print(datasets)
for ds in datasets:
files = os.listdir(TARGET_PATH+"results/"+ds)
# print(arr2)
for f in files:
print(TARGET_PATH+"results/"+ds+"/"+f)
... | _____no_output_____ | Apache-2.0 | BERT_Evaluator.ipynb | blizrys/BERT-Classification-Tutorial |
Tutorial for "Advances in machine learning for molecules" -- Solutions_Summer school for Machine Learning in Bioinformatics, Moscow_ John Bradshaw, August 2020This notebook has been designed to complement Miguel's lecture earlier this afternoon by demonstrating some of the concepts he discussed. We will begin by impo... |
# Some standard library imports that we need to run the rest of this cell:
import os
import sys
import requests
import subprocess
import shutil
from logging import getLogger, StreamHandler, INFO
# We are first going to check if we are in Colab.
IN_COLAB = 'google.colab' in sys.modules
# If in Colab then we will ins... | Not in Colab, ensure that you have setup the required packages in an alternative way (e.g. via Conda).
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
ImportsWe can now check that the installation worked correctly by making sure we can import the required Python modules by running the code cells below. | # = import items from the Python standard library
import functools
import typing
import importlib
import itertools
import copy
# = import numpy, matplotlib and other useful common libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.core.debugger import set_trace # for debugg... | CPython 3.7.7
IPython 7.17.0
numpy 1.19.1
scipy 1.5.2
torch 1.6.0
Git hash: 7033e97884b1009a6adf26902ac6aaf0a9ee03e8
RDKit: 2020.03.1
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
If that all worked, great! We can move onto the next section where we describe how to get started with RDKit. 2. Manipulating Molecules using RDKitThis section will describe different ways to represent molecules. We reintroduce the SMILES string format (you should have already seen this in Miguel's lecture) and descri... | paracetemol_str = 'CC(=O)Nc1ccc(O)cc1'
paracetemol_mol = Chem.MolFromSmiles(paracetemol_str)
Draw.MolToImage(paracetemol_mol) | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Note that there is a one-to-many mapping between molecules and their SMILES string representations depending on how one traverses the molecular graph. For instance below we print out 5 different SMILES representations for paracetemol: | rng = np.random.RandomState(10)
# We will then print 5
paracetemol_random_smiles = [ss_utils.random_ordered_smiles(paracetemol_str, rng) for _ in range(5)]
print(f"Paracetemol can be represented by any of these SMILES (and others): {', '.join(paracetemol_random_smiles)}.") | Paracetemol can be represented by any of these SMILES (and others): O=C(Nc1ccc(O)cc1)C, c1(O)ccc(NC(=O)C)cc1, c1(O)ccc(NC(=O)C)cc1, O=C(C)Nc1ccc(O)cc1, c1c(NC(C)=O)ccc(O)c1.
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
However, sometimes we want to ensure that we print out a unique SMILES for each molecule, which is useful for instance when comparing two SMILES strings. For this we can use RDKit to compute the _canonical_ SMILES. So in the next cell we read in each of these randomly chosen SMILES for paracetemol back in and convert t... | set([Chem.MolToSmiles(Chem.MolFromSmiles(smi), canonical=True) for smi in paracetemol_random_smiles])
# ^ set should only have one string in it -- incidently the same as we started with as I began with the canonical representation.
| _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
See we have ended up with only one representation, the canonical representation!Once we have converted the SMILES to a RDKit `Mol` object (which happened when running `Chem.MolFromSmiles`) we can manipulate it in different ways. For example, we can iterate through the atoms or bonds: | # Iterate through the atoms. Print their symbol, atomic number, and number of Hydrogens
for atm in paracetemol_mol.GetAtoms():
print(f"Atom element: {atm.GetSymbol()}, atomic number: {atm.GetAtomicNum()}, number of hydrogens {atm.GetTotalNumHs()}")
print("\n\n")
# Iterate through the bonds..
for bnd in par... | Atom element: C, atomic number: 6, number of hydrogens 3
Atom element: C, atomic number: 6, number of hydrogens 0
Atom element: O, atomic number: 8, number of hydrogens 0
Atom element: N, atomic number: 7, number of hydrogens 1
Atom element: C, atomic number: 6, number of hydrogens 0
Atom element: C, atomic number: 6, ... | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Can you match up the two oxygens printed out to the two oxygens in the molecular graph plotted earlier?If you want you can experiment with obtaining more details about the particular atoms or bonds, the APIs are [here](https://www.rdkit.org/docs/cppapi/classRDKit_1_1Atom.html) and [here](https://www.rdkit.org/docs/cppa... | print(Chem.MolToSmiles(paracetemol_mol, allHsExplicit=True)) | [CH3][C](=[O])[NH][c]1[cH][cH][c]([OH])[cH][cH]1
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
We can also print out to other string representations. For instance below we will print out the InChI and InChIKey representations (Heller, 2013): | print(Chem.MolToInchi(paracetemol_mol))
print(Chem.MolToInchiKey(paracetemol_mol)) | InChI=1S/C8H9NO2/c1-6(10)9-7-2-4-8(11)5-3-7/h2-5,11H,1H3,(H,9,10)
RZVAJINKPMORJF-UHFFFAOYSA-N
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
2.2 Moving beyond character string representationsOf course, as you saw in the lecture earlier, character strings are not the only way to represent molecules. An alternative approach is to represent molecules as molecular fingerprints. For instance if we want to compute the Morgan fingerprints of the paracetemol molec... |
# We'll define a function to take in the SMILES string and return the Morgan fingerprint as a numpy array.
# this function will be wrapped inside a least recently used (LRU) cache -- you can ignore this,
# it just saves a bit of compute later
@functools.lru_cache(int(1e6))
def morgan_fp_from_smiles(smiles_str, radiu... | Morgan fingerprint for paracetemol is [0. 0. 0. ... 0. 0. 0.]
The non-zero indices of the Morgan fingerprint for paracetemol are (array([ 33, 53, 128, 191, 245, 289, 356, 530, 578, 650, 726,
745, 754, 792, 807, 843, 849, 893, 1017]),)
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Note unlike the mapping from SMILES to molecule, there is not necessarily a one-to-one mapping from fingerprint to molecule. These fingerprints can be used as feature vectors for ML models (as we shall see later). Fingerprints can also be used to compare molecules and obtain a relatively cheap-to-compute notion of simi... | def tanimoto_similarity(smiles_str_1, smiles_str_2):
fp1 = morgan_fp_from_smiles(smiles_str_1)
fp2 = morgan_fp_from_smiles(smiles_str_2)
# nb although the fingerprints are binary we are treating them as floats in numpy
return np.sum(fp1*fp2) / np.sum((fp1+fp2) > 0)
molecules_to_compare = {
'Glucos... | Glucose
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Which is most similar using this metric? Does this match your intuitions?🕰 **(optional) Task A -- Similarity Maps:** Look at producing a similarity map to visualize the similarity between paracetemol and the other molecules considered. RDKit has built-in functionality to produce these plots, which is documented [here... | # Compute the node feature list
class SymbolFeaturizer:
"""
Symbol featurizer takes in a symbol and returns an array representing its
one-hot encoding.
"""
def __init__(self, symbols, feature_size=None):
self.atm2indx = {k:i for i, k in enumerate(symbols)}
self.indx2atm = {v:k for k,... | Node features:
[[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[1. 0. 0.]
[1. 0. 0.]]
Adjacency matrix:
[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[1. 0. 2. 1. 0. 0. 0. 0. 0. 0. 0. ]
[0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 1. ... | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Note that many of the elements of the adjacency matrix are zero -- our graph is sparse. The adjacency matrix is a useful representation in many ways, for instance we can quickly compute the degree of a node by looking along the relebant row. However, when we want to batch up multiple graphs together, using the adjacenc... | def mol_to_edge_list_graph(mol: Chem.Mol, atm_featurizer: SymbolFeaturizer) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Function that takes in a RDKit molecule (of N atoms, E bonds) and returns three numpy arrays:
* the node features array (of dtype np.float32, shape [N, d]), which is a one hot... | Node feature list:
[[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 0. 1.]
[1. 0. 0.]
[1. 0. 0.]]
Edge list:
[[ 0 1]
[ 1 0]
[ 1 2]
[ 2 1]
[ 1 3]
[ 3 1]
[ 3 4]
[ 4 3]
[ 4 5]
[ 5 4]
[ 5 6]
[ 6 5]
[ 6 7]
[ 7 6]
[ 7 8]
[ 8 7]
[ 7 9]
[ ... | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
To check that the code you wrote is working correctly I have written a function that goes the other way (i.e. from these arrays back to a SMILES string). Note that the function you wrote is not reversible for all molecules (e.g. in the graph arrays representation we ignore stereochemistry) but should work okay and act ... | sanity_check_passed = (Chem.MolToSmiles(paracetemol_mol, canonical=True) ==
ss_utils.graph_as_edge_list_to_canon_smiles(node_features, edge_list,
edge_feature_list, atm_featurizer))
sanity_check_passed | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
2.3 Summary and further readingThis section described how we can represent molecules as fingerprints, SMILES strings and as node features/edge list arrays. In the section that follows we will train ML regressors on each of these representations.**RDKit** If you want to learn more about how to use RDKit, the RDKit [doc... | df = pd.read_csv('data/delaney-processed.csv')
df.head()
# We can also use Pandas to quickly summarize the data:
df.describe() | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
The variable which we want to predict is in the "measured log solubility in mols per litre" column🧪 **Task 3:** Plot a histogram of these measured log solubility values. | df['measured log solubility in mols per litre'].hist() | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Note that RDKit includes a series of useful tools for working with Pandas, which are [documented here](http://rdkit.org/docs/source/rdkit.Chem.PandasTools.html). For instance, we can include the relevant molecule in each row of the dataframe: | PandasTools.AddMoleculeColumnToFrame(df,'smiles','Molecule',includeFingerprints=False)
df.head() | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Before moving on, we'll split this dataframe into train and validation dataframes: | def split_into_train_and_val_dfs(df: pd.DataFrame, train_proportion:float,
rng: typing.Optional[np.random.RandomState]=None
) -> typing.Tuple[pd.DataFrame, pd.DataFrame]:
"""
splits this dataset into two: a training portion and a validation
po... | Shapes are: (1016, 11) (112, 11)
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
3.2 Training a NN on fingerprintsHaving set up our dataset we are now ready to create our first model! We first will train a regular feed forward NN on the fingerprints. I have written in the `ss_utils` module the training code for you, as the function `train_neural_network`. I highly encourage you to read over this f... | # Write a simple (1-hidden layer NN) in PyTorch
ff_nn: nn.Module = nn.Sequential(nn.Linear(1024, 128), nn.ReLU(), nn.Linear(128, 1))
# We also will need to add a transform for our datasets such that
# the network gets fed in fingerprint tensors rather than SMILES strings
def transform_ff_nn(smiles: str) -> torch.Tens... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Having defined the network we can now train it: | # A quick check that the ff_nn has been subclassed from nn.Module correctly
assert isinstance(ff_nn, nn.Module), "The function you have written should be a subclass of nn.Module"
# Then we train and evaluate
out = ss_utils.train_neural_network(train_df, val_df, "smiles",
"measured l... | Train dataset is of size 1016 and valid of size 112
Epoch - 0
Training Results - Epoch: 0 Avg loss: 13.18
Validation Results - Epoch: 0 Avg loss: 11.13
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
We can plot these training and validation losses to better understand how training went (if the network has not converged feel free to run training for longer): | # We'll plot using Matplotlib and Altair.
# Altair is interactive which is nice, although I think matplotlib makes better static images when saving
# this notebook to GitHub.
ss_utils.plot_train_and_val_using_mpl(out['train_loss_list'], out['val_lost_list'])
ss_utils.plot_train_and_val_using_altair(out['train_loss_lis... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
We can also add our predictions to the dataframe such that we can compare them more easily with the ground truth: | val_df['NN FP predictions'] = out['val_predictions']
val_df.head() | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
🕰 **(optional) Task C -- Different Feedforward NNs/Fingeprint Sizes:** Here we used 1024 dimensional features and a simple 2 layer NN. Explore using different dimensional fingerprints and different network architectures. As you use smaller fingerprints one bit may correspond to more substructures.How about trying als... | # This will calculate the maximum SMILES string size in our data, which is the
# same as the length we should ensure all tensors are padded to so that they can
# be batched:
max_seq_size = df['smiles'].map(len).max()
# This will calculate all the possible symbols in the smiles string:
symbols_in_smiles = set(itertool... | /Users/john/anaconda3/envs/ss_moscow_2020/lib/python3.7/site-packages/ipykernel_launcher.py:24: UserWarning: This overload of nonzero is deprecated:
nonzero(Tensor input, *, Tensor out)
Consider using one of the following signatures instead:
nonzero(Tensor input, *, bool as_tuple) (Triggered internally at /Users/dis... | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Having coded up a suitable transform we are left with creating the model! Let's start first with the RNN and then move onto the CNN.🧪 **Task 6:** Complete the code below for a RNN to run on this sequence of one-hot encodings. For instance, you could use either a [GRU](https://pytorch.org/docs/stable/generated/torch.... |
class RNNModel(nn.Module):
def __init__(self, symbol_vocab_size: int):
"""
:param symbol_vocab_size: the dimension of the one-hot vectors, ie how many symbols we have
in total (and also the initial channel size being fed into the RNN.)
"""
super().__init__()
h_size =... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
This done, we can train and evaluate our new model: | # Train and evaluate
out = ss_utils.train_neural_network(train_df, val_df, "smiles", "measured log solubility in mols per litre",
transform_seq_model, rnn_model)
# And then we print out as a table some of the results.
display(HTML(tabulate.tabulate(out['out_table'], tablefmt="html")... | Train dataset is of size 1016 and valid of size 112
Epoch - 0
Training Results - Epoch: 0 Avg loss: 13.66
Validation Results - Epoch: 0 Avg loss: 11.52
| MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
We can again plot the train/validation loss curves and check for too little training time or any overfitting: | ss_utils.plot_train_and_val_using_mpl(out['train_loss_list'], out['val_lost_list'])
ss_utils.plot_train_and_val_using_altair(out['train_loss_list'], out['val_lost_list']) | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
This model can actually be harder to tune and choose sensible hyperparameters for than the simple feed forward neural network that we considered before. It is therefore useful to get a good baseline for performance, for instance by looking at the loss obtained by predicting the mean of the training set everwhere: | # Your model's loss should hopefully be lower than this dummy baseline's loss:
np.mean((val_df['measured log solubility in mols per litre'].values -
train_df['measured log solubility in mols per litre'].mean())**2) | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Did your model do better? If not, you probably want to go back and tune the RNN hyperparameters until it does. How do the different hyperparameters of the model affect performance?When you've finished exploring that, let's move on to creating the convolutional neural network (CNN). This network, shown on the bottom of ... | class CNNModel(nn.Module):
def __init__(self, symbol_vocab_size: int, seq_len:int):
"""
:param symbol_vocab_size: the size of the one hot vectors (also the initial channel size for the CNN)
:param seq_len: the size of all sequences.
"""
super().__init__()
# c... | _____no_output_____ | MIT | ML_for_Molecules_solutions.ipynb | john-bradshaw/ml-in-bioinformatics-summer-school-2020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.