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
Examples Intro cartoons
t = 500e-3 dt = 1e-3 times = create_times(t, dt) s = .5 noi = np.random.normal(0, s, size=times.shape[0]) f = 10 r = 1 ro = 2 n = 1 l = 11.7e-3 n_bursts = 2 stim = boxcar(times, r, 2, l, dt, offset=200e-3) + ro re = stim + noi m_post = np.logical_and(times > 0.39, times < 0.42) m_pre = np.logical_and(times > 0.36, ...
_____no_output_____
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
Model examples Random phase
%run /home/ejp/src/bluemass/bm.py ../data/fig4/ ../pars/fig4/mathewson_constant_osc_r72.2222222222.yaml -t 0.5 --sigma 3 --loc r_E res1 = load_kdf("../data/fig4/result.hdf5") idx1 = load_kdf("../data/fig4/index.hdf5") %run /home/ejp/src/bluemass/bm.py ../data/fig4/ ../pars/fig4/mathewson_constant_osc_r72.2222222222.ya...
_____no_output_____
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
Locked burst
%run /home/ejp/src/bluemass/bm.py ../data/fig4/ ../pars/fig4/mathewson_lockedburst_osc_r72.2222222222.yaml -t 0.7 --sigma 1 --loc r_E res = load_kdf("../data/fig4/result.hdf5") idx = load_kdf("../data/fig4/index.hdf5") times = res['times'] stim = res['stims'][:,0] ys = res['ys'] re = ys[:, idx['r_E']] rates = res['rate...
_____no_output_____
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
Results Phase experiments
a1 = load_kdf("../data/fig4/a_part1.hdf5") # a2 = load_kdf("../data/fig4/a_part2.hdf5") a3 = load_kdf("../data/fig4/a_part3.hdf5") a4 = load_kdf("../data/fig4/a_part4.hdf5") # a5 = load_kdf("../data/fig4/a_part5.hdf5") a6 = load_kdf("../data/fig4/a_part6.hdf5") b1 = load_kdf("../data/fig4/b_part1.hdf5") # b2 = load_kd...
[u'n_stim', u'hits', u'stims', u'd_primes', u'misses', u'rates', u'false_alarms', u'correct_rejections'] (360, 10)
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
2 SD threshold
plt.figure(figsize=(3, 3)) r = a3['rates'] / 10.0 # 10 Hz is the noise level M = a3['d_primes'].mean(0) SD = a3['d_primes'].std(0) plt.plot(r, M, color='k', linewidth=3, label='!0 Hz oscillation') plt.fill_between(r, M+SD, M-SD, facecolor='black', alpha=0.1) r = a6['rates'] / 10 M = a6['d_primes'].mean(0) SD = a6['d...
_____no_output_____
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
1 SD threshold
plt.figure(figsize=(3, 3)) # osc r = a1['rates'] / 10.0 # 10 Hz is the noise level M = a1['d_primes'].mean(0) SD = a1['d_primes'].std(0) SEM = SD / np.sqrt(len(SD)) plt.plot(r, M, color='k', linewidth=3, label='!0 Hz oscillation') plt.fill_between(r, M+SEM, M-SEM, facecolor='black', alpha=0.1) # const r = a4['rates'...
_____no_output_____
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
Amplitude experiments
res = load_kdf("../data/fig4/4p.hdf5") plt.figure(figsize=(3, 3)) p = res['powers2'] M = res['d_primes'].mean(0) SD = res['d_primes'].std(0) SEM = SD / np.sqrt(len(SD)) plt.plot(p, M, color='black', linewidth=3) plt.fill_between(p, M+SEM, M-SEM, facecolor='black', alpha=0.1) plt.xlabel("Rel. power (AU)") plt.ylabel("...
_____no_output_____
MIT
figs/fig4.ipynb
voytekresearch/alphalogical
ReferenceThis example is taken from the book [DL with Python](https://www.manning.com/books/deep-learning-with-python) by F. Chollet. All the notebooks from the book are available for free on [Github](https://github.com/fchollet/deep-learning-with-python-notebooks)If you like to run the example locally follow the inst...
import keras keras.__version__
Using TensorFlow backend.
MIT
samples/notebooks/week06-04-introduction-to-gans.ipynb
gu-ma/ba_218_comppx_h1901
Introduction to generative adversarial networksThis notebook contains the second code sample found in Chapter 8, Section 5 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more content, in particular further exp...
import keras from keras import layers import numpy as np latent_dim = 32 height = 32 width = 32 channels = 3 generator_input = keras.Input(shape=(latent_dim,)) # First, transform the input into a 16x16 128-channels feature map x = layers.Dense(128 * 16 * 16)(generator_input) x = layers.LeakyReLU()(x) x = layers.Resh...
Using TensorFlow backend.
MIT
samples/notebooks/week06-04-introduction-to-gans.ipynb
gu-ma/ba_218_comppx_h1901
The discriminatorThen, we develop a `discriminator` model, that takes as input a candidate image (real or synthetic) and classifies it into one of two classes, either "generated image" or "real image that comes from the training set".
discriminator_input = layers.Input(shape=(height, width, channels)) x = layers.Conv2D(128, 3)(discriminator_input) x = layers.LeakyReLU()(x) x = layers.Conv2D(128, 4, strides=2)(x) x = layers.LeakyReLU()(x) x = layers.Conv2D(128, 4, strides=2)(x) x = layers.LeakyReLU()(x) x = layers.Conv2D(128, 4, strides=2)(x) x = lay...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 32, 32, 3) 0 ________________________________________________________...
MIT
samples/notebooks/week06-04-introduction-to-gans.ipynb
gu-ma/ba_218_comppx_h1901
The adversarial networkFinally, we setup the GAN, which chains the generator and the discriminator. This is the model that, when trained, will move the generator in a direction that improves its ability to fool the discriminator. This model turns latent space points into a classification decision, "fake" or "real", an...
# Set discriminator weights to non-trainable # (will only apply to the `gan` model) discriminator.trainable = False gan_input = keras.Input(shape=(latent_dim,)) gan_output = discriminator(generator(gan_input)) gan = keras.models.Model(gan_input, gan_output) gan_optimizer = keras.optimizers.RMSprop(lr=0.0004, clipvalu...
_____no_output_____
MIT
samples/notebooks/week06-04-introduction-to-gans.ipynb
gu-ma/ba_218_comppx_h1901
How to train your DCGANNow we can start training. To recapitulate, this is schematically what the training loop looks like:```for each epoch: * Draw random points in the latent space (random noise). * Generate images with `generator` using this random noise. * Mix the generated images with real ones. * Tra...
import os from keras.preprocessing import image # Load CIFAR10 data (x_train, y_train), (_, _) = keras.datasets.cifar10.load_data() # Select frog images (class 6) x_train = x_train[y_train.flatten() == 6] # Normalize data x_train = x_train.reshape( (x_train.shape[0],) + (height, width, channels)).astype('float32...
discriminator loss at step 0: 0.685675 adversarial loss at step 0: 0.667591 discriminator loss at step 100: 0.756201 adversarial loss at step 100: 0.820905 discriminator loss at step 200: 0.699047 adversarial loss at step 200: 0.776581 discriminator loss at step 300: 0.684602 adversarial loss at step 300: 0.513813 disc...
MIT
samples/notebooks/week06-04-introduction-to-gans.ipynb
gu-ma/ba_218_comppx_h1901
Let's display a few of our fake images:
import matplotlib.pyplot as plt # Sample random points in the latent space random_latent_vectors = np.random.normal(size=(10, latent_dim)) # Decode them to fake images generated_images = generator.predict(random_latent_vectors) for i in range(generated_images.shape[0]): img = image.array_to_img(generated_images[...
_____no_output_____
MIT
samples/notebooks/week06-04-introduction-to-gans.ipynb
gu-ma/ba_218_comppx_h1901
Part 1: Join the Duet Server the Data Owner connected to
duet = sy.join_duet(loopback=True)
_____no_output_____
Apache-2.0
examples/private-ai-series/duet_basics/exercise/Exercise_Duet_Basics_Data_Scientist.ipynb
Bhuvan-21/PySyft
Checkpoint 0 : Now STOP and run the Data Owner notebook until Checkpoint 1. Part 2: Search for Available Data
# The data scientist can check the list of searchable data in Data Owner's duet store duet.store.pandas # Data Scientist finds that there are Heights and Weights of a group of people. There are some analysis he/she can do with them together. heights_ptr = duet.store[0] weights_ptr = duet.store[1] # heights_ptr is a r...
_____no_output_____
Apache-2.0
examples/private-ai-series/duet_basics/exercise/Exercise_Duet_Basics_Data_Scientist.ipynb
Bhuvan-21/PySyft
Calculate BMI (Body Mass Index) and weight statusUsing the heights and weights pointers of the people of Group A, calculate their BMI and get a pointer to their individual BMI. From the BMI pointers, you can check if a person is normal-weight, overweight or obese, without knowing their actual heights and weights and e...
for i in range(6): print("Pointer to Weight of person", i + 1, weights_ptr[i]) print("Pointer to Height of person", i + 1, heights_ptr[i]) def BMI_calculator(w_ptr, h_ptr): bmi_ptr = 0 ##TODO "Write your code here for calculating bmi_ptr" ### return bmi_ptr def weight_status(w_ptr...
_____no_output_____
Apache-2.0
examples/private-ai-series/duet_basics/exercise/Exercise_Duet_Basics_Data_Scientist.ipynb
Bhuvan-21/PySyft
На нескольких алгоритмах кластеризации, умеющих работать с sparse матрицами, проверьте, что работает лучше Count_Vectorizer или TfidfVectorizer (попробуйте выжать максимум из каждого - попробуйте нграммы, символьные нграммы, разные значения max_features и min_df) (3 балла)На нескольких алгоритмах кластеризации проверьт...
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer import pandas as pd from sklearn.decomposition import TruncatedSVD, NMF from sklearn.cluster import AffinityPropagation, AgglomerativeClustering, DBSCAN, \ KMeans, MiniBatchKMeans, Birch, MeanShift, SpectralClusteri...
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
На нескольких алгоритмах кластеризации, умеющих работать с sparse матрицами, проверьте, что работает лучше Count_Vectorizer или TfidfVectorizer (попробуйте выжать максимум из каждого - попробуйте нграммы, символьные нграммы, разные значения max_features и min_df) (3 балла)
def eval_clusterization(X, y, cluster_labels): silhouette = silhouette_score(X, cluster_labels) homogeneity = homogeneity_score(y, cluster_labels) completeness = completeness_score(y, cluster_labels) v_measure = v_measure_score(y, cluster_labels) adj_rand = adjusted_rand_score(y, cluster_labels) ...
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Affinity Propagation
sample = data.sample(frac=0.01) y = sample['category_name']
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*TfidfVectorizer*
tf = TfidfVectorizer(min_df=2, max_df=0.9, max_features=500, ngram_range=(1, 2)) X_tf = tf.fit_transform(sample['title']) cluster = AffinityPropagation(damping=0.7, preference=-2, max_iter=400, verbose=2, convergence_iter=10) fit_and_eval(X_tf, y, cluster)
Did not converge Clusterization metrics Silhouette score: 0.496 Homogeneity score: 0.591 Completeness score: 0.389 V-measure: 0.469 Ajusted Rand Index: -0.013 Adjusted Mutual Information score: 0.198
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*CountVectorizer*
cv = CountVectorizer(min_df=3, max_df=0.6, max_features=1000) X_cv = cv.fit_transform(sample['title']) cluster = AffinityPropagation(damping=0.7, preference=-2, max_iter=400, verbose=2, convergence_iter=10) fit_and_eval(X_cv, y, cluster)
Converged after 244 iterations. Clusterization metrics Silhouette score: 0.481 Homogeneity score: 0.601 Completeness score: 0.371 V-measure: 0.459 Ajusted Rand Index: -0.010 Adjusted Mutual Information score: 0.155
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Для этого алгоритма оба способа векторизации выдают близкие значения V-measure. У tf преимущество по silhouette score, а у cv по homogeneity. У tf выше показатели completeness и MI score, поэтому, на мой взгляд, в данном случае он лучше подходит для данного алгоритма. K-means
sample = data.sample(frac=0.01) y = sample['category_name']
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*TfidfVectorizer*
tf = TfidfVectorizer(min_df=2, max_df=0.8, max_features=500) X_tf = tf.fit_transform(sample['title']) cluster = KMeans(n_clusters=47, n_jobs=-1, random_state=0) fit_and_eval(X_tf, y, cluster)
Clusterization metrics Silhouette score: 0.224 Homogeneity score: 0.318 Completeness score: 0.406 V-measure: 0.357 Ajusted Rand Index: -0.001 Adjusted Mutual Information score: 0.249
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*CountVectorizer*
cv = CountVectorizer(min_df=3, max_df=0.4, max_features=1000) X_cv = cv.fit_transform(sample['title']) cluster = KMeans(n_clusters=47, n_jobs=-1, random_state=0) fit_and_eval(X_cv, y, cluster)
Clusterization metrics Silhouette score: 0.184 Homogeneity score: 0.276 Completeness score: 0.405 V-measure: 0.328 Ajusted Rand Index: 0.003 Adjusted Mutual Information score: 0.212
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
У tf выше homogeneity, но ниже completeness. У tf значительно выше silhouette score. MI score также выше. tf здесь опять же лучше. Если получится, используйте метод локтя. (1 бонусный балл)
def elbow_method(X, clusterizer, left_boundary, right_boundary, step): scores = [] for i in range(left_boundary, right_boundary, step): cluster = clusterizer(n_clusters=i, n_jobs=-1, random_state=0) cluster.fit(X) labels = cluster.labels_ score = silhouette_score(X, labels) ...
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Видим, что в районе 1100 кластеров перестает расти silhouette score.
cluster = KMeans(n_clusters=1100, n_jobs=-1, random_state=0) cluster.fit(X_tf) c_labels = cluster.labels_ eval_clusterization(X_tf, y, c_labels)
Clusterization metrics Silhouette score: 0.627 Homogeneity score: 0.742 Completeness score: 0.390 V-measure: 0.511 Ajusted Rand Index: -0.003 Adjusted Mutual Information score: 0.111
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Все метрики действительно повысились. При этом не ясно как интерпретировать такое количество кластеров. Spectral Clustering
sample = data.sample(frac=0.01) y = sample['category_name']
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*TfidfVectorizer*
tf = TfidfVectorizer(min_df=2, max_df=0.8, max_features=500) X_tf = tf.fit_transform(sample['title']) cluster = SpectralClustering(n_clusters=47, n_jobs=-1, random_state=0) fit_and_eval(X_tf, y, cluster)
Clusterization metrics Silhouette score: 0.216 Homogeneity score: 0.243 Completeness score: 0.377 V-measure: 0.296 Ajusted Rand Index: -0.021 Adjusted Mutual Information score: 0.171
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*CountVectorizer*
cv = CountVectorizer(min_df=3, max_df=0.4, max_features=1000) X_cv = cv.fit_transform(sample['title']) cluster = SpectralClustering(n_clusters=47, n_jobs=-1, random_state=0) fit_and_eval(X_cv, y, cluster)
Clusterization metrics Silhouette score: 0.211 Homogeneity score: 0.125 Completeness score: 0.593 V-measure: 0.207 Ajusted Rand Index: 0.025 Adjusted Mutual Information score: 0.086
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
На этом алгоритме видим явное преимущество tf почти по всем метрикам. На нескольких алгоритмах кластеризации проверьте, какое матричное разложение (TruncatedSVD или NMF) работает лучше для кластеризации. (3 балла) Mean Shift
sample = data.sample(frac=0.01) y = sample['category_name'] cv = CountVectorizer(min_df=3, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) svd = TruncatedSVD(50, random_state=0) X_svd = svd.fit_transform(X_cv)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*SVD*
cluster = MeanShift(cluster_all=False, bandwidth=0.8, n_jobs=-1) fit_and_eval(X_svd, y, cluster)
Clusterization metrics Silhouette score: 0.714 Homogeneity score: 0.339 Completeness score: 0.377 V-measure: 0.357 Ajusted Rand Index: -0.008 Adjusted Mutual Information score: 0.212
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*NMF*
cv = CountVectorizer(min_df=3, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) nmf = NMF(50, random_state=0) X_nmf = nmf.fit_transform(X_cv) cluster = MeanShift(cluster_all=False, bandwidth=0.8, n_jobs=-1) fit_and_eval(X_nmf, y, cluster)
Clusterization metrics Silhouette score: 0.608 Homogeneity score: 0.002 Completeness score: 0.307 V-measure: 0.004 Ajusted Rand Index: 0.000 Adjusted Mutual Information score: 0.001
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Для данного алгоритма значительное преимущество у SVD разложения: V-measure, MI score. Agglomerative Clustering
sample = data.sample(frac=0.05) y = sample['category_name']
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*SVD*
cv = CountVectorizer(min_df=3, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) svd = TruncatedSVD(50, random_state=0) X_svd = svd.fit_transform(X_cv) cluster = AgglomerativeClustering(n_clusters=47) fit_and_eval(X_svd, y, cluster)
Clusterization metrics Silhouette score: 0.637 Homogeneity score: 0.302 Completeness score: 0.370 V-measure: 0.332 Ajusted Rand Index: -0.001 Adjusted Mutual Information score: 0.282
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*NMF*
cv = CountVectorizer(min_df=3, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) nmf = NMF(50, random_state=0) X_nmf = nmf.fit_transform(X_cv) cluster = AgglomerativeClustering(n_clusters=47) fit_and_eval(X_nmf, y, cluster)
Clusterization metrics Silhouette score: 0.707 Homogeneity score: 0.292 Completeness score: 0.365 V-measure: 0.324 Ajusted Rand Index: -0.003 Adjusted Mutual Information score: 0.272
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
В отличие от предыдущих алгоритмов, здесь NMF в некоторых метриках показывает результат лучше (silhouette score, v-measure), в остальных на почти на равных с SVD. Кажется, в данном случае сложно оценить какое разложение действительно лучше. DBSCAN
sample = data.sample(frac=0.05) y = sample['category_name'] cv = CountVectorizer(min_df=3, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) svd = TruncatedSVD(50, random_state=0) X_svd = svd.fit_transform(X_cv)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*SVD*
cluster = DBSCAN(min_samples=7, eps=0.4, n_jobs=-1) fit_and_eval(X_svd, y, cluster)
Clusterization metrics Silhouette score: 0.672 Homogeneity score: 0.301 Completeness score: 0.343 V-measure: 0.321 Ajusted Rand Index: -0.010 Adjusted Mutual Information score: 0.265
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
*NMF*
# с параметрами как у SVD не работает cluster = DBSCAN(min_samples=10, eps=0.3) fit_and_eval(X_nmf, y, cluster)
Clusterization metrics Silhouette score: 0.507 Homogeneity score: 0.001 Completeness score: 0.053 V-measure: 0.002 Ajusted Rand Index: -0.000 Adjusted Mutual Information score: -0.000
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Здесь SVD лучше по всем параметрам. Данный раздел можно резюмировать тем, что несмотря на то, что tfidfvectorizer лучше работает на алгоритмах с dense матрицами, в алгоритмах со sparse матрицами лучше себя показывает countvectorizer. Честно говоря, достаточно сложно оценить в чем причина такого различия, но это стоит и...
sample = data.sample(frac=0.05) y = sample['category_name'] cv = CountVectorizer(min_df=4, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) svd = TruncatedSVD(50, random_state=0) X_svd = svd.fit_transform(X_cv)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Попробовал разные параметры. Увеличение требований к кластерам (больший `min_sample` и меньший `eps`) приводит к увеличению размера кластера `-1`. В результате получается от 600 до нескольких тысяч строк. Изменение параметра `leaf_size` для алгоритмов, поддерживающих его, не влияет на размер данного кластера.
cluster = DBSCAN(min_samples=6, eps=0.6, n_jobs=-1, algorithm='kd_tree', leaf_size=30) fit_and_eval(X_svd, y, cluster)
Clusterization metrics Silhouette score: 0.431 Homogeneity score: 0.253 Completeness score: 0.338 V-measure: 0.289 Ajusted Rand Index: 0.007 Adjusted Mutual Information score: 0.176
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Не удалось подобрать такую комбинацию параметров, чтобы в кластере -1 было бы менее 600 строк.
len(sample.loc[sample.cluster == -1])
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Кажется, что это обычные объявления. Сложно назвать это выбросами.
sample.loc[sample.cluster == -1].head(10)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Mean Shift
sample = data.sample(frac=0.01) y = sample['category_name'] cv = CountVectorizer(min_df=3, max_df=0.6, max_features=2000) X_cv = cv.fit_transform(sample['title']) svd = TruncatedSVD(100, random_state=0) X_svd = svd.fit_transform(X_cv) cluster = MeanShift(cluster_all=False, bandwidth=0.9, n_jobs=-1) fit_and_eval(X_svd, ...
Clusterization metrics Silhouette score: 0.595 Homogeneity score: 0.412 Completeness score: 0.367 V-measure: 0.388 Ajusted Rand Index: -0.013 Adjusted Mutual Information score: 0.199
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Опять же достаточно обычные объявления. Какой-то особой странности не наблюдается.
len(sample.loc[sample.cluster == -1]) sample.loc[sample.cluster == -1].head(10)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Вообще для определения именно выбросов есть специальные алгоритмы.
from sklearn.ensemble import IsolationForest from sklearn.neighbors import LocalOutlierFactor iforest = IsolationForest(random_state=0) lof = LocalOutlierFactor(n_neighbors=30) sample['forest'] = iforest.fit_predict(X_cv) sample['lof'] = lof.fit_predict(X_cv)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Однако, и они не выдают ничего интересного. IsolationForest в основном выбирает недвижимость.
sample.loc[sample.forest == -1].category_name.value_counts() sample.loc[sample.forest == -1].head(10)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
LocalOutlierFactor скорее стремится к одежде.
sample.loc[sample.lof == -1].category_name.value_counts() sample.loc[sample.lof == -1].head(10)
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Согласны они в небольшом количестве случаев.
sample.loc[(sample.lof == -1) & (sample.forest == -1)]
_____no_output_____
MIT
HW4/HW4.ipynb
slowwavesleep/HSE_ML
Índice do Efeito de Empacotamento ($Q_{a}^*$) Para estimar o índice do efeito de empacotamento da Bricaud et al. (2004):$${Q_{a}}(\lambda) = a_{ph} (\lambda) / a_{sol} (\lambda) $$Onde $a_{ph} (\lambda)$ seria medido da amostra e o $a_{sol} (\lambda) $ seria o coeficiente e absorção caso os pigmentos estivessem na so...
library(repr) #Carregando o arquivo que tem os coeficientes de absorção de cada pigmento Bricaud et al (2004) bricaud_asol = read.csv("Bricaud_et_al_2004.csv", skip=4, na="999") #Padronizando os nomes dos pigmentos names(bricaud_asol)=c("lambda", "Chla", "DVChla", "Chlb", "DVChlb", "Chlc12", "Fuco", "ButFuco", "HexFuc...
_____no_output_____
MIT
Lab_Qa_R.ipynb
Andrealioli/Lab_aph_Qa_Sf
Agora vamos pegar um resultado de HPLC hipotético e estimar o $a_{sol}(\lambda)$:
HPLC = data.frame("Chla"=1, "DVChla"=0.001, "Chlb"=0.03, "DVChlb"=0.01, "Chlc12"=0.3, "Fuco"=1.1, "ButFuco"=0.001, "HexFuco"=0.005, "Perid"=0.5, "Diad"=0.01, "Zea"=0.05, "Allox"=0.5, "betacar"=1, "acar"=0.3) asol=data.frame(wv=bricaud_asol$lambda) for (i in names(...
_____no_output_____
MIT
Lab_Qa_R.ipynb
Andrealioli/Lab_aph_Qa_Sf
Os termos faltantes na reconstrução da Bricaud et al. (2004) e a solução proposta Os autores observaram que muitas vezes os espectros reconstruídos eram menores do que os espectros medidos nas amostras (o que não é esperado uma vez que daria resultados de $Q_a$ maiores do que 1). Como esses erros pareciam ser sistemát...
a_todos = data.frame(wv=seq(400,700,2), "asol_t"=asol_t) a_sol_440 = a_todos[which(a_todos$wv==440), "asol_t"]+(0.0525*(HPLC$Chla + HPLC$DVChla)^0.855) aph_440 = a_sol_440*0.8 ##Considerando o termo faltante Qa_440_miss = aph_440/a_sol_440 Qa_440_miss ##Sem considerar o termo faltante Qa_440 = aph_440/a_todos[which(a_...
_____no_output_____
MIT
Lab_Qa_R.ipynb
Andrealioli/Lab_aph_Qa_Sf
$Q_{a}$ em diferentes tamanhos de células Seguindo o que é apresentado do artigo Bricaud et al. (2004), plotar o $Q_{a}^*$ considerando coeficientes da absorção do conteúdo celular ($acm$) diferentes, nesse exemplo vamos considerar no $\lambda = 440nm$
#Coeficiente de absorção do conteudo celular no 440nm acm.440.1=5*10^4 #menos absorvente acm.440.2= 10^6 #mais absorvente #Intervalo de diametros das células d=(1:50)*10^-6 #Estimando o Qa (440) para os diferentes tamanhos Qa.acm.1 = 1+(2*exp(-acm.440.1*d)/(acm.440.1*d)+2*(exp(-acm.440.1*d)-1)/(acm.440.1*d)^2) Qa.acm...
_____no_output_____
MIT
Lab_Qa_R.ipynb
Andrealioli/Lab_aph_Qa_Sf
Índice de tamanho ($S_{f}$) O índice de tamanho foi elaborado com fundamento teórico que células apresentariam maior indice de empacotamento e teriam uma curva mais achatada para o coeficiente de absorção específico ($a_{ph}^*$) (Ciotti et al., 2002). Experimentalmente Ciotti et al. (2002) obtiveram curvas bases de r...
#Vetores base para o pico e micro Ciotti et al(2002,2006) pico =c(1.7439,1.8264,1.9128,1.9992,2.0895,2.1799,2.2702,2.3684,2.4666,2.5687,2.6669,2.7612,2.8437,2.9183,2.9890,3.0479,3.1029,3.1500,3.1854,3.2089,3.2247,3.2325,3.2286,3.2168,3.1932,3.1540,3.1029,3.0361,2.9576,2.8712,2.7848,2.6944,2.5137,2.4273,2.3488,2.2781,2....
_____no_output_____
MIT
Lab_Qa_R.ipynb
Andrealioli/Lab_aph_Qa_Sf
Considerando a relação estabelecida podemos simular um uma curva de $a_{ph}^*$ a partir dos vetores base:
Sf = 0.4 aph_simulado = (pico_esp*Sf) + ((1-Sf)*micro_esp) matplot(df_esp$wv, df_esp[,c("pico", "micro")],type="l", xlab="", ylab="", lwd=2) matlines(df_esp$wv, aph_simulado, col="green", lwd=2) mtext(side=2, line=2.5, expression({a[ph]}^{"*"}~(m^{2}~mg^{-1}))) mtext(side=1, line=2.5, expression("Wavelength"~(nm))) leg...
_____no_output_____
MIT
Lab_Qa_R.ipynb
Andrealioli/Lab_aph_Qa_Sf
Bayesian Imputation Real-world datasets often contain many missing values. In those situations, we have to either remove those missing data (also known as "complete case") or replace them by some values. Though using complete case is pretty straightforward, it is only applicable when the number of missing entries is s...
!pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro # first, we need some imports import os from IPython.display import set_matplotlib_formats from matplotlib import pyplot as plt import numpy as np import pandas as pd from jax import numpy as jnp from jax import ops, random from jax.scipy.special import ...
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Dataset The data is taken from the competition [Titanic: Machine Learning from Disaster](https://www.kaggle.com/c/titanic) hosted on [kaggle](https://www.kaggle.com/). It contains information of passengers in the [Titanic accident](https://en.wikipedia.org/wiki/Sinking_of_the_RMS_Titanic) such as name, age, gender,......
train_df = pd.read_csv( "https://raw.githubusercontent.com/agconti/kaggle-titanic/master/data/train.csv" ) train_df.info() train_df.head()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 891 non-null int64 1 Survived 891 non-null int64 2 Pclass 891 non-null int64 3 ...
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Look at the data info, we know that there are missing data at `Age`, `Cabin`, and `Embarked` columns. Although `Cabin` is an important feature (because the position of a cabin in the ship can affect the chance of people in that cabin to survive), we will skip it in this tutorial for simplicity. In the dataset, there ar...
for col in ["Survived", "Pclass", "Sex", "SibSp", "Parch", "Embarked"]: print(train_df[col].value_counts(), end="\n\n")
0 549 1 342 Name: Survived, dtype: int64 3 491 1 216 2 184 Name: Pclass, dtype: int64 male 577 female 314 Name: Sex, dtype: int64 0 608 1 209 2 28 4 18 3 16 8 7 5 5 Name: SibSp, dtype: int64 0 678 1 118 2 80 5 5 3 5 4 4 6 1 Name: Parch...
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Prepare data First, we will merge rare groups in `SibSp` and `Parch` columns together. In addition, we'll fill 2 missing entries in `Embarked` by the mode `S`. Note that we can make a generative model for those missing entries in `Embarked` but let's skip doing so for simplicity.
train_df.SibSp.clip(0, 1, inplace=True) train_df.Parch.clip(0, 2, inplace=True) train_df.Embarked.fillna("S", inplace=True)
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Looking closer at the data, we can observe that each name contains a title. We know that age is correlated with the title of the name: e.g. those with Mrs. would be older than those with `Miss.` (on average) so it might be good to create that feature. The distribution of titles is:
train_df.Name.str.split(", ").str.get(1).str.split(" ").str.get(0).value_counts()
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
We will make a new column `Title`, where rare titles are merged into one group `Misc.`.
train_df["Title"] = ( train_df.Name.str.split(", ") .str.get(1) .str.split(" ") .str.get(0) .apply(lambda x: x if x in ["Mr.", "Miss.", "Mrs.", "Master."] else "Misc.") )
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Now, it is ready to turn the dataframe, which includes categorical values, into numpy arrays. We also perform standardization (a good practice for regression models) for `Age` column.
title_cat = pd.CategoricalDtype( categories=["Mr.", "Miss.", "Mrs.", "Master.", "Misc."], ordered=True ) embarked_cat = pd.CategoricalDtype(categories=["S", "C", "Q"], ordered=True) age_mean, age_std = train_df.Age.mean(), train_df.Age.std() data = dict( age=train_df.Age.pipe(lambda x: (x - age_mean) / age_std)...
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Modelling First, we want to note that in NumPyro, the following models```pythondef model1a(): x = numpyro.sample("x", dist.Normal(0, 1).expand([10])```and```pythondef model1b(): x = numpyro.sample("x", dist.Normal(0, 1).expand([10].mask(False)) numpyro.sample("x_obs", dist.Normal(0, 1).expand([10]), obs=x)```...
def model(age, pclass, title, sex, sibsp, parch, embarked, survived=None, bayesian_impute=True): b_pclass = numpyro.sample("b_Pclass", dist.Normal(0, 1).expand([3])) b_title = numpyro.sample("b_Title", dist.Normal(0, 1).expand([5])) b_sex = numpyro.sample("b_Sex", dist.Normal(0, 1).expand([2])) b_sibsp ...
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Note that in the model, the prior for `age` is `dist.Normal(age_mu, age_sigma)`, where the values of `age_mu` and `age_sigma` depend on `title`. Because there are missing values in `age`, we will encode those missing values in the latent parameter `age_impute`. Then we can replace `NaN` entries in `age` with the vector...
mcmc = MCMC(NUTS(model), num_warmup=1000, num_samples=1000) mcmc.run(random.PRNGKey(0), **data, survived=survived) mcmc.print_summary()
sample: 100%|██████████| 2000/2000 [00:18<00:00, 110.91it/s, 63 steps of size 6.48e-02. acc. prob=0.94]
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
To double check that the assumption "age is correlated with title" is reasonable, let's look at the infered age by title. Recall that we performed standarization on `age`, so here we need to scale back to original domain.
age_by_title = age_mean + age_std * mcmc.get_samples()["age_mu"].mean(axis=0) dict(zip(title_cat.categories, age_by_title))
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
The infered result confirms our assumption that `Age` is correlated with `Title`:+ those with `Master.` title has pretty small age (in other words, they are children in the ship) comparing to the other groups,+ those with `Mrs.` title have larger age than those with `Miss.` title (in average).We can also see that the r...
train_df.groupby("Title")["Age"].mean()
_____no_output_____
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
So far so good, we have many information about the regression coefficients together with imputed values and their uncertainties. Let's inspect those results a bit:+ The mean value `-0.44` of `b_Age` implies that those with smaller ages have better chance to survive.+ The mean value `(1.11, -1.07)` of `b_Sex` implies th...
posterior = mcmc.get_samples() survived_pred = Predictive(model, posterior)(random.PRNGKey(1), **data)["survived"] survived_pred = (survived_pred.mean(axis=0) >= 0.5).astype(jnp.uint8) print("Accuracy:", (survived_pred == survived).sum() / survived.shape[0]) confusion_matrix = pd.crosstab( pd.Series(survived, name=...
Accuracy: 0.8271605
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
This is a pretty good result using a simple logistic regression model. Let's see how the model performs if we don't use Bayesian imputation here.
mcmc.run(random.PRNGKey(2), **data, survived=survived, bayesian_impute=False) posterior_1 = mcmc.get_samples() survived_pred_1 = Predictive(model, posterior_1)(random.PRNGKey(2), **data)["survived"] survived_pred_1 = (survived_pred_1.mean(axis=0) >= 0.5).astype(jnp.uint8) print("Accuracy:", (survived_pred_1 == survived...
sample: 100%|██████████| 2000/2000 [00:11<00:00, 166.79it/s, 63 steps of size 7.18e-02. acc. prob=0.93]
Apache-2.0
notebooks/source/bayesian_imputation.ipynb
MarcoGorelli/numpyro
Análisis de Datos Exploratorio Análisis Univariante
from pyspark.sql import functions as F online_df = spark.read.csv(DATA_PATH + 'online_retail.csv', sep=';', header=True, inferSchema=True) online_df.show(2) # Respuesta online_df_2 = online_df.withColumn('timestamp', F.unix_timestamp(F.col('InvoiceDate'), 'dd/MM/yyyy HH:mm')) online_df_2.show(2) # Respuesta online_df_3...
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Primero identifica variables cualitativas y cuantitativas.
# Respuesta quantitative_vars = [c for c,t in online_df.dtypes if t in ['int', 'double']] qualitative_vars = [c for c,t in online_df.dtypes if t in ['boolean', 'string']] # Respuesta quantitative_vars # Respuesta qualitative_vars
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Variables cuantitativas Calcula métricas para una única columna
# Respuesta avgs = [F.avg(col).alias('avg_' + col) for col in quantitative_vars] maxs = [F.max(col).alias('max_' + col) for col in quantitative_vars] mins = [F.min(col).alias('min_' + col) for col in quantitative_vars] stds = [F.stddev(col).alias('std_' + col) for col in quantitative_vars] # Respuesta operations = avgs...
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Variables cualitativasPara variables cualitativas se calculan tablas de frecuencia. Calcula la tabla de frecuencia de las columnas cualitativas, y ordénalas de mayor a menor.
# Respuesta online_df.groupBy('Country').count().sort(F.col("count").desc()).show() # Respuesta online_df.groupBy('Country', 'InvoiceDate').count().sort(F.col('count').desc()).show()
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Análisis Multivariante __Matriz de correlación__
# Respuesta from pyspark.mllib.linalg import Vectors from pyspark.mllib.stat import Statistics import pandas as pd # Respuesta online_df.select(quantitative_vars).rdd.map(lambda v: Vectors.dense(v)) # Respuesta corr_matrix = Statistics.corr(online_df.select(quantitative_vars).rdd.map(lambda v: Vectors.dense(v)), ...
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
_Transforma la matriz en un DataFrame de pandas_
# Respuesta df_corr_matrix = pd.DataFrame(corr_matrix, columns=quantitative_vars, index=quantitative_vars) df_corr_matrix # Respuesta import numpy as np mask = np.zeros_like(corr_matrix, dtype=np.bool) mask[np.triu_indices_from(mask)] = True mask # Respuesta df_corr_matrix_reduced = df_corr_matrix.mask(mask) df_corr_ma...
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Valores Atípicos Detección de outliers para variables que siguen la distribución normal
# Respuesta def remove_tukey_outliers(df, col): """ Returns a new dataframe with outliers removed on column 'col' usting Tukey test """ q1, q3 = df.approxQuantile(col, [0.25, 0.75], 0.01) IQR = q3 - q1 min_thresh = q1 - 1.5 * IQR max_thresh = q3 + 1.5 * IQR df_no_outliers ...
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Valores nulos
# Respuesta def remove_nulls(df): df_no_nulls = df for element in df_no_nulls.columns: if df_no_nulls.where(df_no_nulls[element].isNull()).count() != 0: print('\tThe column "{}" has null values'.format(element)) df_no_nulls = df_no_nulls.where(df_no_nulls[element].isNotNull(...
_____no_output_____
MIT
2021Q1_DSF/5.- Spark/notebooks/spark_sql/respuestas/extra_02_spark_eda_review_con_respuestas.ipynb
serch86/binder-pyspark-DSF_2021Q1
Variables y _placeholders_
import tensorflow as tf import numpy as np
_____no_output_____
Apache-2.0
inteligencia_artificial/03-Variables.ipynb
edwinb-ai/intelicompu
Las _variables_ y _placeholders_ son los pilares de _Tensorflow_. Sin embargo para entender porqué es esto, uno debe entender un poco más sobre la estructura general de _Tensorflow_ y cómo realiza los cálculos correspondientes. _Dataflow_ programming[_Dataflow programming_](https://en.wikipedia.org/wiki/Dataflow_progr...
# Crear una variables con ceros, de dimensiones (3,4) my_var = tf.Variable(tf.zeros((3, 4))) # Iniciar una sesión (en realidad se crea un grafo de computación/operacional) session = tf.Session() # Inicializar las variables inits = tf.global_variables_initializer() # Correr todo el grafo session.run(inits)
_____no_output_____
Apache-2.0
inteligencia_artificial/03-Variables.ipynb
edwinb-ai/intelicompu
Aunque no se muestra nada, en el fondo se creó un **grafo** dirigido, donde un _nodo_ es la variable, y al inicializar el grafo, todas las operaciones pendientes se llevaron a cabo. A continuación se muestra un ejemplo adicional con _placeholders_ donde se puede visualizar mejor este hecho. Ejemplo con _placeholders_
# Crear valores aleatorios de numpy x_vals = np.random.random_sample((2, 2)) print(x_vals) # Crear una sesión; un grafo computacional session = tf.Session() # El placeholder no puede tener otra dimensión diferente a (2,2) x = tf.placeholder(tf.float32, shape=(2,2)) # identity devuelve un tensor con la misma forma y con...
_____no_output_____
Apache-2.0
inteligencia_artificial/03-Variables.ipynb
edwinb-ai/intelicompu
Inicialización independiente de variablesNo siempre se tienen que inicializar las variables de una sola forma, al mismo tiempo, sino que se pueden inicializar una por una según sea conveniente. Se muestra un ejemplo a continuación.
# Crear la sesión session = tf.Session() # Se tiene una primera variable llena de cero first_var = tf.Variable(tf.zeros((3, 4))) # Y ahora se inicializa session.run(first_var.initializer) # Se tiene una segunda variable llena de uno second_var = tf.Variable(tf.ones_like(first_var)) session.run(second_var.initializer)
_____no_output_____
Apache-2.0
inteligencia_artificial/03-Variables.ipynb
edwinb-ai/intelicompu
Solar Resource Data> Get average Direct Normal Irradiance (avg_dni), average Global Horizontal Irradiance (avg_ghi), and average Tilt (avg_lat_tilt) for a location. An example to get solar resource data - average Direct Normal Irradiance, average Global Horizontal Irradiance, and average tilt - from NREL First, let's ...
import os from nrel_dev_api import set_nrel_api_key from nrel_dev_api.solar import SolarResourceData NREL_API_KEY = os.environ["DEMO_NREL_API_KEY"] set_nrel_api_key(NREL_API_KEY)
_____no_output_____
Apache-2.0
docs/Tutorial/solar/solar_resource_data.ipynb
SarthakJariwala/nrel_dev_api
> Alternatively, you can provide your NREL Developer API key with every call. Setting it globally is just for convenience. Let's check available solar resource data for Seattle, WA.
solar_resource_data = SolarResourceData(lat=47, lon=-122)
_____no_output_____
Apache-2.0
docs/Tutorial/solar/solar_resource_data.ipynb
SarthakJariwala/nrel_dev_api
Outputs for solar resource data is available as the `outputs` attribute.
solar_resource_data.outputs
_____no_output_____
Apache-2.0
docs/Tutorial/solar/solar_resource_data.ipynb
SarthakJariwala/nrel_dev_api
We can also provide the address to access the solar resource data.
address = "Seattle, WA" solar_resource_data = SolarResourceData(address=address)
_____no_output_____
Apache-2.0
docs/Tutorial/solar/solar_resource_data.ipynb
SarthakJariwala/nrel_dev_api
The complete response as a dictionary is available as the `response` attribute.
solar_resource_data.response
_____no_output_____
Apache-2.0
docs/Tutorial/solar/solar_resource_data.ipynb
SarthakJariwala/nrel_dev_api
Grid searching parametershttps://machinelearningmastery.com/grid-search-arima-hyperparameters-with-python/
import pandas as pd from pandas import read_csv import numpy as np from datetime import datetime from pandas import Series from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_squared_error import warnings warnings.filterwarnings("ignore") series = Series.from_csv('female.csv', header=0) def e...
Best ARIMANone MSE=inf
Apache-2.0
Gridsearch Parameters.ipynb
BrittGeek/Time-Series-Forecasting
Notebook to perform a sensitivity calculation**Content:**- Calculation of the collection area- Sensitivity calculation in energy bins- Sensitivity calculation in bins of gammaness and theta2 cuts- Optimization of the cuts using Nex/sqrt(Nbg) -> LiMa to be implemented- Plotting of the sensitivity in absolute values
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import h5py import pandas as pd import math import pyhessio from astropy import units as u import eventio from eventio.simtel.simtelfile import SimTelFile simtelfile_gammas = "/home/queenmab/DATA/LST1/Gamma/gamma_20deg_0deg_run8___...
_____no_output_____
BSD-3-Clause
notebooks/Calculate_sensitivity_eventio.ipynb
pawel21/cta-lstchain
Skip-gram Word2VecIn this notebook, I'll lead you through using PyTorch to implement the [Word2Vec algorithm](https://en.wikipedia.org/wiki/Word2vec) using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing w...
# read in the extracted text file with open('data/text8') as f: text = f.read() # print out the first 100 characters print(text[:100])
anarchism originated as a term of abuse first used against early working class radicals including t
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
Pre-processingHere I'm fixing up the text to make training easier. This comes from the `utils.py` file. The `preprocess` function does a few things:>* It converts any punctuation into tokens, so a period is changed to ` `. In this data set, there aren't any periods, but it will help in other NLP problems. * It remove...
import utils # get list of words words = utils.preprocess(text) print(words[:30]) # print some stats about this word data print("Total words in text: {}".format(len(words))) print("Unique words: {}".format(len(set(words)))) # `set` removes any duplicate words
Total words in text: 16680599 Unique words: 63641
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
DictionariesNext, I'm creating two dictionaries to convert words to integers and back again (integers to words). This is again done with a function in the `utils.py` file. `create_lookup_tables` takes in a list of words in a text and returns two dictionaries.>* The integers are assigned in descending frequency order, ...
vocab_to_int, int_to_vocab = utils.create_lookup_tables(words) int_words = [vocab_to_int[word] for word in words] print(int_words[:30])
[5233, 3080, 11, 5, 194, 1, 3133, 45, 58, 155, 127, 741, 476, 10571, 133, 0, 27349, 1, 0, 102, 854, 2, 0, 15067, 58112, 1, 0, 150, 854, 3580]
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
SubsamplingWords that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ i...
from collections import Counter import random import numpy as np threshold = 1e-5 word_counts = Counter(int_words) #print(list(word_counts.items())[0]) # dictionary of int_words, how many times they appear total_count = len(int_words) freqs = {word: count/total_count for word, count in word_counts.items()} p_drop = ...
[5233, 741, 10571, 27349, 15067, 58112, 854, 10712, 19, 708, 2757, 5233, 248, 44611, 2877, 5233, 8983, 4147, 6437, 5233, 1818, 4860, 6753, 7573, 566, 247, 11064, 7088, 5948, 4861]
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to define a surrounding _context_ and grab all the words in a window around that word, with size $C$. From [Mikolov et al.](https://...
def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' R = np.random.randint(1, window_size+1) start = idx - R if (idx - R) > 0 else 0 stop = idx + R target_words = words[start:idx] + words[idx+1:stop+1] return list(target_words) # test your...
Input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Target: [0, 1, 2, 3, 4, 6, 7, 8, 9]
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
Generating Batches Here's a generator function that returns batches of input and target data for our model, using the `get_target` function from above. The idea is that it grabs `batch_size` words from a words list. Then for each of those batches, it gets the target words in a window.
def get_batches(words, batch_size, window_size=5): ''' Create a generator of word batches as a tuple (inputs, targets) ''' n_batches = len(words)//batch_size # only full batches words = words[:n_batches*batch_size] for idx in range(0, len(words), batch_size): x, y = [], [] ...
x [0, 0, 1, 1, 1, 2, 2, 2, 3, 3] y [1, 2, 0, 2, 3, 0, 1, 3, 1, 2]
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
--- ValidationHere, I'm creating a function that will help us observe our model as it learns. We're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them using the cosine similarity: $$\mathrm{similarity} = \cos(\theta) = \frac{\vec{a} \cdot \vec{b}}{|\vec{a}||\vec{b...
def cosine_similarity(embedding, valid_size=16, valid_window=100, device='cpu'): """ Returns the cosine similarity of validation words with words in the embedding matrix. Here, embedding should be a PyTorch embedding module. """ # Here we're calculating the cosine similarity between some random...
_____no_output_____
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
--- SkipGram modelDefine and train the SkipGram model. > You'll need to define an [embedding layer](https://pytorch.org/docs/stable/nn.htmlembedding) and a final, softmax output layer.An Embedding layer takes in a number of inputs, importantly:* **num_embeddings** – the size of the dictionary of embeddings, or how many...
import torch from torch import nn import torch.optim as optim tmp_emb = nn.Embedding(5, 2) print(tmp_emb.weight.shape) tmp_w = tmp_emb.weight print(tmp_w) print(tmp_w.data) tmp_w.data.uniform_(-1,1) print(tmp_w.data) class SkipGramNeg(nn.Module): def __init__(self, n_vocab, n_embed, noise_dist=None): super(...
_____no_output_____
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
TrainingBelow is our training loop, and I recommend that you train on GPU, if available.
device = 'cuda' if torch.cuda.is_available() else 'cpu' # Get our noise distribution # Using word frequencies calculated earlier in the notebook word_freqs = np.array(sorted(freqs.values(), reverse=True)) unigram_dist = word_freqs/word_freqs.sum() noise_dist = torch.from_numpy(unigram_dist**(0.75)/np.sum(unigram_dist*...
_____no_output_____
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
Visualizing the word vectorsBelow we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out [this post from Christopher Olah](http://colah.github.io/posts/2014-10-Visualizing-MNIST/) to lear...
%matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt from sklearn.manifold import TSNE # getting embeddings from the embedding layer of our model, by name embeddings = model.in_embed.weight.to('cpu').data.numpy() viz_words = 380 tsne = TSNE() embed_tsne = tsne.fit_transform...
_____no_output_____
MIT
word2vec-embeddings/Negative_Sampling_My_Solution.ipynb
iromeo/deep-learning-v2-pytorch
Importing modules
import json import pandas as pd import numpy as np
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
Read cowin csv file
data=pd.read_csv('cowin_vaccine_data_districtwise.csv')
/home/sunild/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3169: DtypeWarning: Columns (6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,7...
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
Load modified json file from Q1
## district level # district data from json f=open('neighbor-districts-modified.json') districts_data=json.load(f) district_names=[] district_ids=[] for key in districts_data: district_names.append(key.split('/')[0]) district_ids.append(key.split('/')[1]) Districts=data['District_Key'].str.lower()
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis
Prepare data frames for covaxin and covishield vaccine numbers
## dose1=Covaxin ## dose2=CoviShield data_dose1=data.loc[:,(data.loc[0,]=='Covaxin (Doses Administered)')].iloc[1:,:].fillna(0) first_date_dose1=data_dose1.iloc[:,0] data_dose1=data_dose1.astype(int).diff(axis=1) data_dose1.iloc[:,0]=first_date_dose1 data_dose1['District']=data['District_Key'] data_dose2=data.loc[:,(d...
_____no_output_____
MIT
Q7_Asgn1.nbconvert.ipynb
sunil-dhaka/india-covid19-cases-and-vaccination-analysis