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
Now when we list our clusters again, we should see the cluster we created.
!gcloud container clusters list
NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUS asl-cluster us-central1-a 1.20.10-gke.1600 34.71.2.241 e2-medium 1.20.10-gke.1600 3 RUNNING cluster-1 us-central1-a 1.19.14-gke.1900 35.193.84.252 custom-2-4352 1.19.14-gke.1900 2...
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
Get authentication credentials and deploy and applicationAfter creating your cluster, you need authentication credentials to interact with it. Use `get-credentials` to authenticate the cluster.**Exercise**Use `gcloud container clusters get-credentials` to authenticate the cluster you created.
%%bash gcloud container clusters get-credentials asl-cluster --zone $ZONE
Fetching cluster endpoint and auth data. kubeconfig entry generated for asl-cluster.
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
You can now deploy a containerized application to the cluster. For this lab, you'll run `hello-app` in your cluster.GKE uses Kubernetes objects to create and manage your cluster's resources. Kubernetes provides the [Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) object for deploying ...
%%bash kubectl create deployment hello-server --image=gcr.io/google-samples/hello-app:1.0
deployment.apps/hello-server created
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
This Kubernetes command creates a Deployment object that represents `hello-server`. To create a Kubernetes Service, which is a Kubernetes resource that lets you expose your application to external traffic, run the `kubectl expose` command. **Exercise**Use the `kubectl expose` to expose the application. In this command,...
%%bash kubectl expose deployment hello-server --type=LoadBalancer --port 8080
service/hello-server exposed
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
Use the `kubectl get service` command to inspect the `hello-server` Service.**Note**: It might take a minute for an external IP address to be generated. Run the previous command again if the `EXTERNAL-IP` column for `hello-server` status is pending.
!kubectl get service hello-server
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE hello-server LoadBalancer 10.7.245.50 34.135.234.4 8080:30333/TCP 73s
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
You can now view the application from your web browser, open a new tab and enter the following address, replacing `EXTERNAL IP` with the EXTERNAL-IP for `hello-server`:```bashhttp://[EXTERNAL_IP]:8080```You should see a simple page which displays```bashHello, world!Version: 1.0.0Hostname: hello-server-5bfd595c65-7jqkn`...
%%bash kubectl delete deployment hello-server
deployment.apps "hello-server" deleted
Apache-2.0
notebooks/docker_and_kubernetes/labs/2_intro_k8s.ipynb
ctivanovich/asl-ml-immersion
Advanced Usage Exampes for Seldon Client Istio Gateway Request with token over HTTPS - no SSL verificationTest against a current kubeflow cluster with Dex token authentication. 1. Install kubeflow with Dex authentication
INGRESS_HOST=!kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}' ISTIO_GATEWAY=INGRESS_HOST[0] ISTIO_GATEWAY
_____no_output_____
Apache-2.0
notebooks/seldon_client.ipynb
OrthoDex/seldon-core
Get a token from the Dex gateway. At present as Dex does not support curl password credentials you will need to get it from your browser logged into the cluster. Open up a browser console and run `document.cookie`
TOKEN="eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjM2MjA0ODYsImlhdCI6MTU2MzUzNDA4NiwiaXNzIjoiMzQuNjUuNzMuMjU1IiwianRpIjoiYjllNDQxOGQtZjNmNC00NTIyLTg5ODEtNDcxOTY0ODNmODg3IiwidWlmIjoiZXlKcGMzTWlPaUpvZEhSd2N6b3ZMek0wTGpZMUxqY3pMakkxTlRvMU5UVTJMMlJsZUNJc0luTjFZaUk2SWtOcFVYZFBSMFUwVG1wbk1GbHBNV3RaYW1jMFRGUlNhVTU2VFhS...
_____no_output_____
Apache-2.0
notebooks/seldon_client.ipynb
OrthoDex/seldon-core
Start Seldon CoreUse the setup notebook to [Install Seldon Core](seldon_core_setup.ipynbInstall-Seldon-Core) with [Istio Ingress](seldon_core_setup.ipynbIstio). Instructions [also online](./seldon_core_setup.html).**Note** When running helm install for this example you will need to set the istio.gateway flag to kubefl...
deployment_name="test1" namespace="default" from seldon_core.seldon_client import SeldonClient, SeldonChannelCredentials, SeldonCallCredentials sc = SeldonClient(deployment_name=deployment_name,namespace=namespace,gateway_endpoint=ISTIO_GATEWAY,debug=True, channel_credentials=SeldonChannelCredentials(v...
_____no_output_____
Apache-2.0
notebooks/seldon_client.ipynb
OrthoDex/seldon-core
Its not presently possible to use gRPC without getting access to the certificates. We will update this once its clear how to obtain them from a Kubeflow cluser setup. Istio - SSL Endpoint - Client Side Verification - No Authentication 1. First run through the [Istio Secure Gateway SDS example](https://istio.io/docs/t...
# Set to folder where the httpbin certificates are ISTIO_HTTPBIN_CERT_FOLDER='/home/clive/work/istio/httpbin.example.com'
_____no_output_____
Apache-2.0
notebooks/seldon_client.ipynb
OrthoDex/seldon-core
Start Seldon CoreUse the setup notebook to [Install Seldon Core](seldon_core_setup.ipynbInstall-Seldon-Core) with [Istio Ingress](seldon_core_setup.ipynbIstio). Instructions [also online](./seldon_core_setup.html).**Note** When running ```helm install``` for this example you will need to set the ```istio.gateway``` fl...
deployment_name="mymodel" namespace="default" from seldon_core.seldon_client import SeldonClient, SeldonChannelCredentials, SeldonCallCredentials sc = SeldonClient(deployment_name=deployment_name,namespace=namespace,gateway_endpoint="httpbin.example.com",debug=True, channel_credentials=SeldonChannelCre...
_____no_output_____
Apache-2.0
notebooks/seldon_client.ipynb
OrthoDex/seldon-core
<div id="image_img" class="header_image_13"> Download, Install and Execute Anaconda Difficu...
from biosignalsnotebooks.__notebook_support__ import css_style_apply css_style_apply() %%html <script> // AUTORUN ALL CELLS ON NOTEBOOK-LOAD! require( ['base/js/namespace', 'jquery'], function(jupyter, $) { $(jupyter.events).on("kernel_ready.Kernel", function () { con...
_____no_output_____
MIT
notebookToHtml/biosignalsnotebooks_html_publish/Categories/Install/prepare_anaconda.ipynb
biosignalsnotebooks/biosignalsnotebooks
Testing cosmoganApril 19, 2021Borrowing pieces of code from : - https://github.com/pytorch/tutorials/blob/11569e0db3599ac214b03e01956c2971b02c64ce/beginner_source/dcgan_faces_tutorial.py- https://github.com/exalearn/epiCorvid/tree/master/cGAN
import os import random import logging import sys import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from torchsummary import summary from torch.utils.data import DataLoader, TensorDataset import torch.distributed as dist...
_____no_output_____
BSD-3-Clause-LBNL
code/4_basic_3d_GAN/1_main_code/train_3dgan.ipynb
vmos1/cosmogan_pytorch
Modules
### Transformation functions for image pixel values def f_transform(x): return 2.*x/(x + 4.) - 1. def f_invtransform(s): return 4.*(1. + s)/(1. - s) # Generator Code class View(nn.Module): def __init__(self, shape): super(View, self).__init__() self.shape = shape def forward(self, ...
_____no_output_____
BSD-3-Clause-LBNL
code/4_basic_3d_GAN/1_main_code/train_3dgan.ipynb
vmos1/cosmogan_pytorch
Train loop
### Train code ### def f_train_loop(gan_model,Dset,metrics_df,gdict,fixed_noise): ''' Train epochs ''' ## Define new variables from dict keys=['image_size','start_epoch','epochs','iters','best_chi1','best_chi2','save_dir','device','flip_prob','nz','batch_size','bns'] image_size,start_epoch,epochs,iters,...
_____no_output_____
BSD-3-Clause-LBNL
code/4_basic_3d_GAN/1_main_code/train_3dgan.ipynb
vmos1/cosmogan_pytorch
Start
### Setup modules ### def f_manual_add_argparse(): ''' use only in jpt notebook''' args=argparse.Namespace() args.config='config_3dgan_128_cori.yaml' args.mode='fresh' args.local_rank=0 args.facility='cori' args.distributed=False # args.mode='continue' return args def f_parse_...
_____no_output_____
BSD-3-Clause-LBNL
code/4_basic_3d_GAN/1_main_code/train_3dgan.ipynb
vmos1/cosmogan_pytorch
Main
######################### ### Main code ####### ######################### if __name__=="__main__": jpt=False jpt=True ##(different for jupyter notebook) t0=time.time() t0=time.time() args=f_parse_args() if not jpt else f_manual_add_argparse() ################################# ### Set up gl...
_____no_output_____
BSD-3-Clause-LBNL
code/4_basic_3d_GAN/1_main_code/train_3dgan.ipynb
vmos1/cosmogan_pytorch
Debug
# class Generator(nn.Module): # def __init__(self, gdict): # super(Generator, self).__init__() # ## Define new variables from dict # keys=['ngpu','nz','nc','ngf','kernel_size','stride','g_padding'] # ngpu, nz,nc,ngf,kernel_size,stride,g_padding=list(collections.OrderedDict({key:gdic...
_____no_output_____
BSD-3-Clause-LBNL
code/4_basic_3d_GAN/1_main_code/train_3dgan.ipynb
vmos1/cosmogan_pytorch
Exploring Clustering ResultsThe file containing the clustering results is stored in the processed data folder with the suffix clean. The index is set to the first __Product group key__.As a reminder the file is organized in three columns: _Product Group Key_, _Cluster Number_ and the corresponding _Centroid_ of the cl...
import os import sys # add the 'src' directory as one where we can import modules root_dir = os.path.join(os.getcwd(),os.pardir,os.pardir) import pandas as pd import math import numpy as np import pandas as pd import numpy as np import matplotlib.pyplot as plt import copy as cp import seaborn as sns import statsmo...
(382, 2)
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Get clients description
file_name1 = "data_client_bnd_ita.csv" file_name2 = "data_client_bnd_ita2.csv" non_unique_features = ["Key_lvl1","Key_lvl2","Key_lvl3","CONCESS PDL","CLIENTE FATT","CONCESS FATT","PTF SPEDIZIONE","TYPE_DISTRIB"] unique_features = ["Key_lvl4","Key_lvl5"] client_df1 = pd.read_csv(raw_path+file_name1, sep=';', encodin...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Get Products descriptionIn order to get the product features description, an inner join on the product group key is operated on the cluster result with the products description file.Since the clustering was calculated on the second level group, some columns of the description file must be dropped in order to avoid dup...
file_name1 = "bnd_products_desc.csv" file_name2 = "bnd_products_desc2.csv" non_unique_features=["Key","Description","CONFEZIONE",\ "CONFEZIONE (Description)","IMBALLO","STD/PROMO","IMBALLO (Description)","STD/PROMO (Description)",\ "TIPO ARTICOLO","TIPO ARTICOLO (De...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Merge Products and Clients tables
# produit_client_cluster = pd.merge(product_cluster,client_df,how='inner', left_on=["Client"],right_on =["Key_lvl4"] )#.drop(["Key_lvl4"],axis=1) # clusters = produit_client_cluster["Cluster"] # centroids = produit_client_cluster["Centroid"] # produit_client_cluster = produit_client_cluster.drop(["Cluster","Centroid...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Save the final result into a csv file for further exploration
filename = 'bnd_product_cluster_clean.csv' file_name = "p2_clustering_clean_mois.csv" product_cluster.to_csv(processed_path+filename,sep=';',encoding='iso8859_2')
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Homogeneity TestIn order to detect specific caraterstics for each resulted cluster we perform a statistic test based on Pearsons chi-square score with the hypothesis of a uniform distribution.Features with the pvalues lower than 0.1 are displayed for analysis
def cramer_v(chisq,n,k,r=1): return math.sqrt(chisq/(n * min(k-1,r-1) ))
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Calculate modalities frequency through clustersAs a first step, all the distrubtions of modalities across features and clusters are calculated and stored in one array structered as follows:One array for each cluster which contains a dictionnary of features. Each feature is again a dictionary of modalities and their oc...
#get the features features = all_features #get the clusters (actually its a range(1,nb_cluster)) clusters = set(product_cluster['Cluster'].values) #array to store each cluster and freq for all the features clusters_feature_dist = [0] #to shift the indices to clusters #loop trhough features for c in clusters: fe...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Chi-square test over clusters
from scipy.stats import chisquare pthreashold = 0.2 #get the features features = all_features clusters = [6] res_features_over_cluster = [0] for c in clusters: #align each feature with its distrubtion in this cluster c cluster_feature_dist = clusters_feature_dist[c] dist = [len(x) for x in list(cluster...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Calculate modalities frequency through features
#get the features features = all_features #get the clusters (actually its a range(1,nb_cluster)) clusters = set(product_cluster['Cluster'].values) #dict to store each feater and freq for all the clusters features_clust_dist = dict() #invert the dict and get it by feature for f in features: freq = dict() for...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Chi-square test over features
pthreashold = 0.2 clusters = set(product_cluster['Cluster'].values) features = all_features features = ["FAM MARKETING (Description)"] for f in features: for c in clusters: #get information from the previous array feature_clust_dist = features_clust_dist[f] feature_distribution = list(feat...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Modalities distribution
clusters = set(product_cluster['Cluster'].values) nclusters = len(clusters) #get the features features = product_cluster.columns[0:-2] features = features.drop(unbalanced) modalities_clust_dist = dict() for f in features: feature_sum=[] modalities = set(product_cluster[f].values) modalities_distribution=...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Chi-square test for modalities over clusters
%matplotlib inline clusters = set(product_cluster['Cluster'].values) nclusters = len(clusters) pthreashold = 0.2 n_min_dist = 1 min_members = 5 min_dust = True for f in features: modalities = set(product_cluster[f].values) r = len(modalities) for m in modalities: modality_dist = modalities_cl...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
MCA Analysis Remove unbalanced columns
features_df = product_cluster.iloc[:,3:-2] plt.figure(figsize=(16,20)) features = features_df.columns for i,f in enumerate(features): counts = features_df.groupby([f])[f].count().to_dict() dist = list(counts.values()) keys = list(counts.keys()) chisq, p = chisquare(dist) plt.subplot(6,3,i+1) plt...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Apply MCA on Products
import prince unbalanced = ["CANALE DISTRIB (Description)","CLASSE COGE (Description)","BIOLOGICO (Description)"] features_df = product_cluster.iloc[:,1:-2].drop(unbalanced,axis=1) features_df = df_produit mca = prince.MCA(features_df) mca.plot_relationship_square() plt.show()
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Apply MCA on Clients
import prince features_df = client_df.astype(str).fillna("NA") mca = prince.MCA(features_df) mca.plot_relationship_square() plt.show()
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Classification Tree
from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import subprocess from sklearn.tree import export_graphviz from sklearn.preprocessing import OneHotEncoder,LabelBinarizer,LabelEncoder def visualize_tree(tree, feature_names,class_names=None): with open(r...
_____no_output_____
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Evaluation the algorithm
from sklearn.metrics import classification_report, confusion_matrix from sklearn.metrics import precision_recall_fscore_support as report #print(confusion_matrix(y_test, y_pred)) precision,recall,fscore,support = report(y_test, y_pred,warn_for=()) print(precision.mean(),recall.mean(),fscore.mean(),support.sum()) #p...
<sklearn.tree._tree.Tree object at 0x000000000A407C60>
MIT
notebooks/p2c4/0.4-imad-cluster-analysis.ipynb
imad24/pc_clustering
Decoding in time-frequency space using Common Spatial Patterns (CSP)The time-frequency decomposition is estimated by iterating over raw data thathas been band-passed at different frequencies. This is used to compute acovariance matrix over each epoch or a rolling time-window and extract the CSPfiltered signals. A line...
# Authors: Laura Gwilliams <laura.gwilliams@nyu.edu> # Jean-Remi King <jeanremi.king@gmail.com> # Alex Barachant <alexandre.barachant@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mne import...
_____no_output_____
MIT
practical_classes/Week_7/plot_decoding_csp_timefreq_practical_7.ipynb
victor-m-p/adv_cognitive_neuroscience
Set parameters and read data
event_id = dict(hands=2, feet=3) # motor imagery: hands vs feet subject = 1 runs = [6, 10, 14] raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f) for f in raw_fnames]) # Extract information from the raw file sfreq = raw.info['sfreq'] events, _ = events_from_annotations(raw, event_id=...
_____no_output_____
MIT
practical_classes/Week_7/plot_decoding_csp_timefreq_practical_7.ipynb
victor-m-p/adv_cognitive_neuroscience
Loop through frequencies, apply classifier and save scores
# init scores freq_scores = np.zeros((n_freqs - 1,)) # Loop through each frequency range of interest for freq, (fmin, fmax) in enumerate(freq_ranges): # Infer window size based on the frequency being used w_size = n_cycles / ((fmax + fmin) / 2.) # in seconds # Apply band-pass filter to isolate the speci...
_____no_output_____
MIT
practical_classes/Week_7/plot_decoding_csp_timefreq_practical_7.ipynb
victor-m-p/adv_cognitive_neuroscience
Plot frequency results
plt.bar(freqs[:-1], freq_scores, width=np.diff(freqs)[0], align='edge', edgecolor='black') plt.xticks(freqs) plt.ylim([0, 1]) plt.axhline(len(epochs['feet']) / len(epochs), color='k', linestyle='--', label='chance level') plt.legend() plt.xlabel('Frequency (Hz)') plt.ylabel('Decoding Scores') plt.ti...
_____no_output_____
MIT
practical_classes/Week_7/plot_decoding_csp_timefreq_practical_7.ipynb
victor-m-p/adv_cognitive_neuroscience
Loop through frequencies and time, apply classifier and save scores
# init scores tf_scores = np.zeros((n_freqs - 1, n_windows)) # Loop through each frequency range of interest for freq, (fmin, fmax) in enumerate(freq_ranges): # Infer window size based on the frequency being used w_size = n_cycles / ((fmax + fmin) / 2.) # in seconds # Apply band-pass filter to isolate t...
_____no_output_____
MIT
practical_classes/Week_7/plot_decoding_csp_timefreq_practical_7.ipynb
victor-m-p/adv_cognitive_neuroscience
Plot time-frequency results
# Set up time frequency object av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :], centered_w_times, freqs[1:], 1) chance = np.mean(y) # set chance level to white in the plot av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores", cmap=plt.cm.Reds)
_____no_output_____
MIT
practical_classes/Week_7/plot_decoding_csp_timefreq_practical_7.ipynb
victor-m-p/adv_cognitive_neuroscience
week03: Логистическая регрессия и анализ изображенийВ этом ноутбуке предлагается построить классификатор изображений на основе логистической регрессии. *Забегая вперед, мы попробуем решить задачу классификации изображений используя лишь простые методы. В третьей части нашего курса мы вернемся к этой задаче.*
import numpy as np import matplotlib.pyplot as plt import h5py %matplotlib inline
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
1. Постановка задачи **Задача**: Есть датасет [прямая ссылка](https://drive.google.com/file/d/15tOimf2QYWsMtPJXTUCwgZaOTF8Nxcsm/view?usp=sharing) ("catvnoncat.h5") состоящий из: - обучающей выборки из m_train изображений, помеченных "cat" (y=1) или "non-cat" (y=0) - тестовой выборки m_test изображений, помеченны...
# Uncomment this cell to download the data # !wget "https://downloader.disk.yandex.ru/disk/7ef1d1e30e23740a4a30799a825319154815ddc85bf689542add0a3d11ccb91c/5d7fdcb0/3dcxK38Q0fG3ui0g2gMZgKkLls8ULwVpoYNkWpBm9d24EceJ6mIoH5l3_wKkFv3PfZ0WMGYjfJULynuJkuGaug%3D%3D?uid=76549735&filename=data.zip&disposition=attachment&hash=&l...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
1.1 Загрузка данных и визуализация
def load_dataset(): train_data = h5py.File("data/train_catvnoncat.h5", "r") train_set_x_orig = np.array(train_data["train_set_x"][:]) # признаки train_set_y_orig = np.array(train_data["train_set_y"][:]) # метки классов test_data = h5py.File("data/test_catvnoncat.h5", "r") test_set_x_orig = np.array...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
Цветные изображения в формате RGB представлены в виде трёхмерных numpy.array.Порядок измерений $H \times W \times C$: $H$ - высота, $W$ - ширина и $C$ - число каналов.Значение каждого пиксела находится в интервале $[0;255]$.
from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets def show_image_interact(i=0): f, ax = plt.subplots(1,4, figsize=(15,20), sharey=True) ax[0].imshow(train_set_x_orig[i]) ax[0].set_title('RGB image') ax[1].imshow(train_set_x_orig[i][:,:,0], cmap='gray...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
При работе с данными полезно будет сохранить размерности входных изображений для дальнейшей обработки.
m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] src_size = train_set_x_orig.shape[1] print ("Размер обучающей выборки: m_train = " + str(m_train)) print ("Размер тестовой выборки: m_test = " + str(m_test)) print ("Ширина/Высота каждого изображения: src_size = " + str(src_size)) print ("Размерны т...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
2. Предварительная обработка Преобразуем входные изображения размера (num_px, num_px, 3) в вектор признаков размера (num_px $*$ num_px $*$ 3, 1), чтобы сформировать матрицы объект-признак в виде numpy-array для обучающей и тестовой выборок.Каждой строке матрицы объект-признак соответствует входное развёрнутое в вектор...
def image_preprocessing_simple(data): assert type(data) == np.ndarray assert data.ndim == 4 n,h,w,c = data.shape data_vectorized = <ваш код> data_normalized = <ваш код> return data_normalized # Изменить размеры входных данных train_set_x_vectorized = image_preprocessing_simple(train_s...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
3. Классификация
from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV import warnings warnings.filterwarnings('ignore')
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
**Вопрос**: Какую метрику качества стоит использовать? 3.1 Построение модели Построим модель с параметрами по умолчанию и посмотрим, как хорошо она справится с задачей.
clf = # <ваш код> score = <ваш код> print('Точность для простой модели с параметрами по умолчанию: {:.4f}'.format(score)) # from sklearn.metrics import f1_score y_predicted = clf.predict(test_set_x_vectorized) correct_score = <ваш код> print('<Имя метрики> для простой модели: {:.4f}'.format(correct_score))
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
Попробуем подобрать параметры регуляризации в надежде, что это повысит точность предсказаний.
<ваш код> print('Оптимальные параметры: {}'.format(<ваш код>)) print('Наилучшее значение метрики качества: {}'.format(<ваш код>))
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
Обучим модель с оптимальными параметрами на всей обучающей выборке и посмотрим на метрики качества:
best_clf = <ваш код> best_clf.fit(train_set_x_vectorized, train_set_y) y_predicted = best_clf.predict(test_set_x_vectorized) metric_score = <ваш код>(y_predicted, test_set_y) print('Optimal model hyperparameters accuracy score: {:.4f}'.format(metric_score))
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
3.2 Анализ ошибок
is_outlier = (y_predicted != test_set_y) test_outliers_x, test_outliers_y, predicted_y = test_set_x_orig[is_outlier], test_set_y[is_outlier], y_predicted[is_outlier] def show_image_outliers(i=0): f = plt.figure(figsize=(5,5)) plt.imshow(test_outliers_x[i]) plt.title('RGB image') fmt_string = "Sampl...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
**Вопрос**: Как по-вашему можно повысить точность? Каким недостатком обладает данный подход к классификации? 3.3 Модель с аугментациями Как можно увеличить количество данных для обучения?Сформировать новые примеры из уже имеющихся!Например, можно пополнить class 'cat' обучающей выборки [зеркально отображёнными](https:...
def augment_sample(src, label): <ваш код> def image_preprocessing_augment(data, labels): assert type(data) == np.ndarray assert data.ndim == 4 ## ВАШ КОД ## data_augmented = labels_augmented = ## ВАШ КОД ЗАКАНЧИВАЕТСЯ ЗДЕСЬ ## n,h,w,c = data_augmented.shape dat...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
4. Проверьте работу классификатора на своей картинке Библиотека [OpenCV](https://opencv.org) для работы с изображениями для [python](https://pypi.org/project/opencv-python/):`pip install opencv-python`Вместе с contrib-модулями:`pip install opencv-contrib-python`
import cv2 # Путь к картинке на вашем ПК fname = "cat-non-cat.jpg" # Считываем картинку через scipy src = cv2.cvtColor(cv2.imread((fname)), cv2.COLOR_BGR2RGB) src_resized = cv2.resize(src, (src_size,src_size), interpolation=cv2.INTER_LINEAR).reshape(1, src_size*src_size*3) my_image_predict = clf.predict(src_resized)[0...
_____no_output_____
MIT
week0_03_logistic/week03_extra_image_classifier.ipynb
GendalfSeriyy/ml-mipt
Extracted from text tokentweet_feature_mentions: list of ints (or None):- Mentions extracted from the tweet.tweet_feature_number_of_mentions: int:- Number of mentions in the tweet.tweet_feature_token_length: int:- Number of BERT tokens in the tweet.tweet_feature_token_length_unique: int:- Number of unique bert tokens ...
import sys sys.path.append('..') import core.config as conf from utils.preprocessing import * import numpy as np from tqdm import tqdm from datetime import datetime import matplotlib.pyplot as plt import tensorflow as tf from transformers import * from tensorflow.keras.preprocessing.sequence import pad_sequences fro...
_____no_output_____
Apache-2.0
preprocessing/tweet_features.ipynb
RecKIE7/recsys2021-twitter
Load data
data_path = '/hdd/twitter/dataset_mini/train' df = read_data(data_path) text_tokens = df['text_tokens'] text_tokens df['len_text_tokens'] = df['text_tokens'].apply(lambda x: len(x.split('\t'))) df['decoded_text_tokens'] = df['text_tokens'].progress_apply(lambda x: tokenizer.decode(x.split('\t'), skip_special_tokens=Tru...
_____no_output_____
Apache-2.0
preprocessing/tweet_features.ipynb
RecKIE7/recsys2021-twitter
Using resultsSince json is a dictionary, you can pull out a single datapoint using the key.```{ "source": "ensembl_havana", "object_type": "Gene", "logic_name": "ensembl_havana_gene", "version": 12, "species": "homo_sapiens", "description": "B-Raf proto-oncogene, serine/threonine kinase [Source:HGNC Symbol;Acc:H...
import requests, json from pprint import pprint def fetch_endpoint(server, request, content_type): r = requests.get(server+request, headers={ "Accept" : content_type}) if not r.ok: r.raise_for_status() sys.exit() if content_type == 'application/json': return r.json() else: ...
BRAF
Apache-2.0
Python3/3_Using_results.ipynb
fabiolib/rest-api-jupyter-course
Exercises 31\. Write a script to lookup the gene called *ESPN* in human and print the stable ID of this gene.
# Exercise 3.1 #!/usr/bin/env python # Get modules needed for script import sys, requests, json from pprint import pprint def fetch_endpoint(server, request, content_type): r = requests.get(server+request, headers={ "Accept" : content_type}) if not r.ok: r.raise_for_status() sys.exit() ...
'ENSG00000187017'
Apache-2.0
Python3/3_Using_results.ipynb
fabiolib/rest-api-jupyter-course
2\. Get all variants that are associated with the phenotype 'Coffee consumption'. For each variant print a. the p-value for the association b. the PMID for the publication which describes the association between that variant and ‘Coffee consumption’ c. the risk allele and the associated gene.
# Exercise 3.2 pprint(get_lookup)
{'assembly_name': 'GRCh38', 'biotype': 'protein_coding', 'db_type': 'core', 'description': 'espin [Source:HGNC Symbol;Acc:HGNC:13281]', 'display_name': 'ESPN', 'end': 6461367, 'id': 'ENSG00000187017', 'logic_name': 'ensembl_havana_gene_homo_sapiens', 'object_type': 'Gene', 'seq_region_name': '1', 'source': 'e...
Apache-2.0
Python3/3_Using_results.ipynb
fabiolib/rest-api-jupyter-course
3\. Get the mouse homologue of the human BRCA2 and print the ID and sequence of both.Note that the JSON for the endpoint you need is several layers deep, containing nested lists (appear as square brackets [ ] in the JSON) and key value sets (dictionary; appear as curly brackets { } in the JSON). Pretty print (pprint) c...
# Exercise 3.3
_____no_output_____
Apache-2.0
Python3/3_Using_results.ipynb
fabiolib/rest-api-jupyter-course
1. Welcome to the Hour of Callysto!Lesson created and taught by [Discover Coding](https://discovercoding.ca).With support and funding from [Callysto](https://callysto.ca/) and the [Pacific Institute for Mathematical Sciences](https://www.pims.math.ca/) 2. What is Callysto?- **Callysto** is a free and online collectio...
# My First Turtle Program! from mobilechelonian import Turtle ted = Turtle() ted.forward(50)
_____no_output_____
MIT
hour-of-callysto-2.ipynb
callysto/hour-of-callysto
Let's break down what we each line of code that we see:1. ` My First Turtle Program!` - Any line starting with a `` is a comment (or notes). It is NOT CODE!1. `from mobilechelonian import Turtle` - This lets use some `Turtle` code that someone else wrote. We won't worry about it for this class.1. `ted = Turtle()` - Thi...
# My Turtle is now 2D! from mobilechelonian import Turtle ted = Turtle() ted.speed(5) ted.forward(100) ted.left(120) ted.forward(100) ted.left(120) ted.forward(100)
_____no_output_____
MIT
hour-of-callysto-2.ipynb
callysto/hour-of-callysto
*ACTIVITY 5.2*Can you change the color of the triangle?Try inserting this line of code into Example 5.1:`ted.pencolor('red')`Try other [colors named here](https://www.w3schools.com/tags/ref_colornames.asp)**Observe**1. What happens if you write this BEFORE the first move `forward` (on line 5)?1. What happens if you wr...
# My Turtle is now 2D! from mobilechelonian import Turtle ted = Turtle() ted.speed(1) # hint 1 - copy and paste the previous code # hint 2 - the next turn should be 30 degrees # hint 3 - forward, turn, forward, turn, forward...
_____no_output_____
MIT
hour-of-callysto-2.ipynb
callysto/hour-of-callysto
6. LOOPSDid you notice that drawing shapes used the same lines of code over and over?Instead of typing the same things over and over, we can use a *loop* to run the same code multiple times.Loops run code __*OVER and OVER and OVER and . . .*__Loops have two parts:1. A line starting with the special keyword `for` or `w...
from mobilechelonian import Turtle ted = Turtle() ted.speed(5) # This loop runs (how many?) times for index in range(10): ted.forward(50) ted.right(80)
_____no_output_____
MIT
hour-of-callysto-2.ipynb
callysto/hour-of-callysto
*ACTIVITY 6.2*Experiment with the code in Example 6.1, and try different values.Can you:1. Make turtle draw faster?1. Change how BIG the shape is? (Hint: change the distance turtle moves `forward`)1. Change how much the turtle turns each time? 1. What happens when turtle turns less than 90? 1. What happens when ...
from mobilechelonian import Turtle import random ted = Turtle() ted.speed(10) # This loop runs 10 times for index in range(10): red = random.randint(0,255) green = random.randint(0,255) blue = random.randint(0,255) random_color = "RGB(%d,%d,%d)" % (red,green,blue) ted.pencolor(random_color) ...
_____no_output_____
MIT
hour-of-callysto-2.ipynb
callysto/hour-of-callysto
*ACTIVITY 7.2*Let's experiment with the code in Example 7.11. On line 9, we pick a random number between 0 to 255 for `red`. What happens if we pick a random number between 200 to 255?1. What happens if we pick a random number between 0 and 10 for the color `red`?1. Try to change the range of random numbers for `green...
from mobilechelonian import Turtle import random ted = Turtle() ted.speed(10) # Now we'll run a loop. for index in range(5): red = random.randint(0,255) green = random.randint(0,255) blue = random.randint(0,255) random_color = "RGB(%d,%d,%d)" % (red,green,blue) ted.pencolor(random_color) ...
_____no_output_____
MIT
hour-of-callysto-2.ipynb
callysto/hour-of-callysto
ZigZag
das_template_x = np.array([2.5*np.sqrt(2)*i for i in range(24)]) das_template_y = np.array([2.5*np.sqrt(2)*i for i in range(24)]) das_template_x2 = np.hstack([das_template_x,das_template_x[::-1],das_template_x,das_template_x[::-1]]) das_template_y2 = np.hstack([das_template_y,das_template_y+das_template_y[-1],das_templ...
_____no_output_____
MIT
OptimalDesign/DAS_Designs.ipynb
jbmuir/DAS-Reconstruction
Spiral
das_theta2 = np.linspace(0,(360*4)**2, 192*2) das_theta = np.deg2rad(np.sqrt(das_theta2)) a = 0 b = 1 das_r = b*das_theta das_x = das_r * np.cos(das_theta) das_y = das_r * np.sin(das_theta) raz = np.pi/2-np.arctan2(b*np.tan(das_theta)+(a+b*das_theta), b-(a+b*das_theta)*np.tan(das_theta)) das_az = np.rad2deg(raz) xwid...
_____no_output_____
MIT
OptimalDesign/DAS_Designs.ipynb
jbmuir/DAS-Reconstruction
Crossing
template = np.linspace(0,320, 65) template = (template[1:]+template[:-1])/2 das_x = np.hstack([template, template, template,[80 for i in range(len(template))], [160 for i in range(len(template))], [240 for i in range(len(template))]]) das_y = np.hstack([[80 for i in range(len(template))], [160 for i in range(len(templ...
_____no_output_____
MIT
OptimalDesign/DAS_Designs.ipynb
jbmuir/DAS-Reconstruction
Random
template = np.linspace(0,320, 65) template = (template[1:]+template[:-1])/2 np.random.seed(94899109) das_x = np.random.uniform(5,315,384) das_y = np.random.uniform(5,315,384) das_az = np.random.uniform(0,360,384) raz = np.deg2rad(das_az) L = 10 #gauge length ll = np.linspace(-L/2, L/2, 2**5+1) dl = ll[1]-ll[0] p1 = ...
_____no_output_____
MIT
OptimalDesign/DAS_Designs.ipynb
jbmuir/DAS-Reconstruction
Eigenvalue Spectrum
G_full = np.vstack([np.hstack([G3, np.zeros(G3.shape)]), np.hstack([np.zeros(G3.shape), G3])]) idet = 1e-10*np.eye(G_zigzag.shape[1]) ezig = np.sort(np.linalg.eigvals(G_zigzag.T@G_zigzag+idet))[::-1] espi = np.sort(np.linalg.eigvals(G_spiral.T@G_spiral+idet))[::-1] ecro = np.sort(np.linalg.eigvals(G_cross.T@G_cross+id...
_____no_output_____
MIT
OptimalDesign/DAS_Designs.ipynb
jbmuir/DAS-Reconstruction
$\newcommand{\xv}{\mathbf{x}} \newcommand{\wv}{\mathbf{w}} \newcommand{\yv}{\mathbf{y}} \newcommand{\zv}{\mathbf{z}} \newcommand{\Chi}{\mathcal{X}} \newcommand{\R}{\rm I\!R} \newcommand{\sign}{\text{sign}} \newcommand{\Tm}{\mathbf{T}} \newcommand{\Xm}{\mathbf{X}} \newcommand{\Xlm}{\mathbf{X1}} \newcommand{\Wm}{\mathbf{...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline fig, ax = plt.subplots() # x - y axis ax.axhline(y=0, color='k', linewidth=1) ax.axvline(x=0, color='k', linewidth=1) # step function in blue plt.plot([0, 6], [1, 1], 'b-', linewidth=3) plt.plot([-6, 0], [-1, -1], 'b-', linewidth=3) plt.plot([0,...
_____no_output_____
MIT
reading_assignments/6_Note-Neural Networks.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
Non-linear Extension of Linear ModelAs we discussed, feed forward neural networks have a rich representation. Thus, it can represent the linear model with single layer. Considering the multiple outputs, we formulated this in matrix: $$\begin{align}E &= \frac{1}{N} \frac{1}{K} \sum_{n=1}^{N} \sum_{k=1}^{K} (t_{nk} - y_...
# polinomial function def h_poly(x): return x**4 + 3 * x**2 + 7 * x + 3 # sigmoid function def h_sigmoid(x): return np.tanh(x) ##### Gradient functions # polinomial function def dh_poly(x): return 4 * x**3 + 6 * x + 7 # polinomial function def dh_sigmoid(x): h = h_sigmoid(x) return 1 - h ** ...
_____no_output_____
MIT
reading_assignments/6_Note-Neural Networks.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
Here, we can see the polinomial gradients are very huge when $x$ is moving away from 0. A gradient descent procedure takes this huge step for the large positive or negative $x$ values, which can make learning divergent and unstable.In the right figure, we can see the gradient is nearly turned off for large $x$ values. ...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import IPython.display as ipd # for display and clear_output import time # for sleep # Make some training data n = 20 X = np.linspace(0.,20.0,n).reshape((n,1)) - 10 T = 0.2 + 0.05 * (X+10) + 0.4 * np.sin(X+10) + 0.2 * np.random.normal(size=(n,1)) ...
V: (2, 10) X1: (2, 20) error: (20, 1) W.T: (1, 11) Z: (20, 10) (20, 10)
MIT
reading_assignments/6_Note-Neural Networks.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
$\newcommand{\xv}{\mathbf{x}} \newcommand{\wv}{\mathbf{w}} \newcommand{\yv}{\mathbf{y}} \newcommand{\zv}{\mathbf{z}} \newcommand{\av}{\mathbf{a}} \newcommand{\Chi}{\mathcal{X}} \newcommand{\R}{\rm I\!R} \newcommand{\sign}{\text{sign}} \newcommand{\Tm}{\mathbf{T}} \newcommand{\Xm}{\mathbf{X}} \newcommand{\Xlm}{\mathbf{X...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import scipy.optimize as opt from scipy.optimize import rosen, minimize # examples are from http://people.duke.edu/~ccc14/sta-663-2017/14C_Optimization_In_Python.html x = np.linspace(-5, 5, 1000) y = np.linspace(-5, 5, 1000) xs, ys = np.meshgrid(x...
_____no_output_____
MIT
reading_assignments/6_Note-Neural Networks.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
Vs. others?Now, let us take a look at other optimization tools including naive steepest descent and scaled conjugate gradient ([Moller, 1997](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.50.8063&rep=rep1&type=pdf)). To run this properly, you need to download [grad.py](https://webpages.uncc.edu/mlee173/teac...
from grad import steepest res = steepest(np.array(x0), rosen_der, rosen, stepsize=0.0001, wtracep=True, ftracep=True) ps = np.array(res['wtrace']) plt.figure(figsize=(16, 8)) plt.subplot(121) plt.contour(xs, ys, zs, np.arange(10)**5, cmap='jet') plt.plot(ps[:, 0], ps[:, 1], '-ro') plt.subplot(122) plt.semilogy(range(...
_____no_output_____
MIT
reading_assignments/6_Note-Neural Networks.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
Neural Network! Now, let us use this optimization trick for our neural networks.
# standardization class class Standardizer: """ class version of standardization """ def __init__(self, X, explore=False): self._mu = np.mean(X,0) self._sigma = np.std(X,0) if explore: print ("mean: ", self._mu) print ("sigma: ", self._sigma) print ...
_____no_output_____
MIT
reading_assignments/6_Note-Neural Networks.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
Reinforcement Learning for seq2seqThis time we'll solve a problem of transribing hebrew words in english, also known as g2p (grapheme2phoneme) * word (sequence of letters in source language) -> translation (sequence of letters in target language)Unlike what most deep learning practicioners do, we won't only train it t...
import sys if 'google.colab' in sys.modules: !wget https://raw.githubusercontent.com/yandexdataschool/Practical_RL/spring20/week07_seq2seq/basic_model_torch.py -O basic_model_torch.py !wget https://raw.githubusercontent.com/yandexdataschool/Practical_RL/spring20/week07_seq2seq/main_dataset.txt -O main_dataset.t...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Step 1: preprocessingWe shall store dataset as a dictionary`{ word1:[translation1,translation2,...], word2:[...],...}`.This is mostly due to the fact that many words have several correct translations.We have implemented this thing for you so that you can focus on more interesting parts.__Attention python2 users!__ You...
import numpy as np from collections import defaultdict word_to_translation = defaultdict(list) # our dictionary bos = '_' eos = ';' with open("main_dataset.txt", encoding="utf-8") as fin: for line in fin: en, he = line[:-1].lower().replace(bos, ' ').replace(eos, ...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
split the datasetWe hold out 10% of all words to be used for validation.
from sklearn.model_selection import train_test_split train_words, test_words = train_test_split( all_words, test_size=0.1, random_state=42)
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Building vocabulariesWe now need to build vocabularies that map strings to token ids and vice versa. We're gonna need these fellas when we feed training data into model or convert output matrices into english words.
from voc import Vocab inp_voc = Vocab.from_lines(''.join(all_words), bos=bos, eos=eos, sep='') out_voc = Vocab.from_lines(''.join(all_translations), bos=bos, eos=eos, sep='') # Here's how you cast lines into ids and backwards. batch_lines = all_words[:5] batch_ids = inp_voc.to_matrix(batch_lines) batch_lines_restored =...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Draw word/translation length distributions to estimate the scope of the task.
import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=[8, 4]) plt.subplot(1, 2, 1) plt.title("words") plt.hist(list(map(len, all_words)), bins=20) plt.subplot(1, 2, 2) plt.title('translations') plt.hist(list(map(len, all_translations)), bins=20)
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Step 3: deploy encoder-decoder (1 point)__assignment starts here__Our architecture consists of two main blocks:* Encoder reads words character by character and outputs code vector (usually a function of last RNN state)* Decoder takes that code vector and produces translations character by characterThan it gets fed int...
import torch import torch.nn as nn import torch.nn.functional as F from basic_model_torch import BasicTranslationModel model = BasicTranslationModel(inp_voc, out_voc, emb_size=64, hid_size=256) # Play around with symbolic_translate and symbolic_score inp = torch.tensor(np.random.randint(0,...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Scoring functionLogLikelihood is a poor estimator of model performance.* If we predict zero probability once, it shouldn't ruin entire model.* It is enough to learn just one translation if there are several correct ones.* What matters is how many mistakes model's gonna make when it translates!Therefore, we will use mi...
import editdistance # !pip install editdistance def get_distance(word, trans): """ A function that takes word and predicted translation and evaluates (Levenshtein's) edit distance to closest correct translation """ references = word_to_translation[word] assert len(references) != 0, "wrong/unk...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Step 2: Supervised pre-training (2 points)Here we define a function that trains our model through maximizing log-likelihood a.k.a. minimizing crossentropy.
import random def sample_batch(words, word_to_translation, batch_size): """ sample random batch of words and random correct translation for each word example usage: batch_x,batch_y = sample_batch(train_words, word_to_translations,10) """ # choose words batch_words = np.random.choice(words,...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Actually train the modelMinibatches and stuff...
from IPython.display import clear_output from tqdm import tqdm, trange # or use tqdm_notebook,tnrange loss_history = [] editdist_history = [] entropy_history = [] opt = torch.optim.Adam(model.parameters()) for i in trange(25000): loss = compute_loss_on_batch(*sample_batch(train_words, word_to_translation, 32)) ...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
__How to interpret the plots:__* __Train loss__ - that's your model's crossentropy over minibatches. It should go down steadily. Most importantly, it shouldn't be NaN :)* __Val score distribution__ - distribution of translation edit distance (score) within batch. It should move to the left over time.* __Val score / tra...
for word in train_words[:10]: print("%s -> %s" % (word, translate([word])[0])) test_scores = [] for start_i in trange(0, len(test_words), 32): batch_words = test_words[start_i:start_i+32] batch_trans = translate(batch_words) distances = list(map(get_distance, batch_words, batch_trans)) test_scores.e...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Self-critical policy gradient (2 points)In this section you'll implement algorithm called self-critical sequence training (here's an [article](https://arxiv.org/abs/1612.00563)).The algorithm is a vanilla policy gradient with a special baseline. $$ \nabla J = E_{x \sim p(s)} E_{y \sim \pi(y|x)} \nabla log \pi(y|x) \cd...
def compute_reward(input_sequence, translations): """ computes sample-wise reward given token ids for inputs and translations """ distances = list(map(get_distance, inp_voc.to_lines(input_sequence.data.numpy()), out_voc.to_lines(translations.data.numpy()))) ...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Policy gradient training
entropy_history = [np.nan] * len(loss_history) opt = torch.optim.Adam(model.parameters(), lr=1e-5) for i in trange(100000): loss, ent = scst_objective_on_batch( sample_batch(train_words, word_to_translation, 32)[0]) # [0] = only source sentence # train with backprop loss.backward() opt.step() ...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
__Debugging tips:__ * As usual, don't expect improvements right away, but in general the model should be able to show some positive changes by 5k steps. * Entropy is a good indicator of many problems. * If it reaches zero, you may need greater entropy regularizer. * If it has rapid changes time to time, you may ne...
for word in train_words[:10]: print("%s -> %s" % (word, translate([word])[0])) test_scores = [] for start_i in trange(0, len(test_words), 32): batch_words = test_words[start_i:start_i+32] batch_trans = translate(batch_words) distances = list(map(get_distance, batch_words, batch_trans)) test_scores.e...
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
Step 6: Make it actually work (5++ pts)In this section we want you to finally __restart with EASY_MODE=False__ and experiment to find a good model/curriculum for that task.We recommend you to start with the following architecture```encoder---decoder P(y|h) ^ LSTM -> LSTM ^ ^ biLSTM ...
assert not EASY_MODE, "make sure you set EASY_MODE = False at the top of the notebook."
_____no_output_____
Unlicense
week07_seq2seq/practice_torch.ipynb
dmgirdyuk/Practical_RL
DEAP DEAP is a novel evolutionary computation framework for rapid prototyping and testing of ideas. It seeks to make algorithms explicit and data structures transparent. It works in perfect harmony with parallelisation mechanism such as multiprocessing and SCOOP. The following documentation presents the key concepts a...
import random from deap import base from deap import creator from deap import tools # creator is a class factory that can build new classes at run-time creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) # a toolbox stores functions and their argume...
Best individual is [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],...
MIT
ipython-notebooks/notebooks/libraries/DEAP.ipynb
gopala-kr/ds-notebooks
Symbolic Regression (GP) Symbolic regression is one of the best known problems in GP. It is commonly used as a tuning problem for new algorithms, but is also widely used with real-life distributions, where other regression methods may not work.All symbolic regression problems use an arbitrary data distribution, and tr...
import operator import math import random import numpy from deap import algorithms from deap import base from deap import creator from deap import tools from deap import gp # define a new function for divison that guards against divide by 0 def protectedDiv(left, right): try: return left / right exce...
fitness size --------------------------------------- ------------------------------- gen nevals avg max min std avg max min std 0 300 2.39949 59.2593 0.165572 4.64122 3.69667 7 2 1.61389 1 146 1.0971 ...
MIT
ipython-notebooks/notebooks/libraries/DEAP.ipynb
gopala-kr/ds-notebooks
Introdução
import pandas as pd; dados_enem = pd.read_csv('https://github.com/alura-cursos/imersao-dados-2-2020/blob/master/MICRODADOS_ENEM_2019_SAMPLE_43278.csv?raw=true') # retorna as 5 primeiras linhas da colecao dados_enem.head() # para acessar apenas uma coluna -> dados_enem['nome_da_coluna'] dados_enem['SG_UF_RESIDENCIA'...
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2
Continuação
# visualização em histograma #dados_enem['NU_IDADE'].hist() dados_enem['NU_IDADE'].hist(bins=100,figsize=(11,9),legend=True) treineiros = dados_enem.query('IN_TREINEIRO == 1') treineiros['NU_IDADE'].value_counts() # Notas Redacao dados_enem['NU_NOTA_REDACAO'].hist(bins=20) # analise geral provas = ["NU_NOTA_CN","NU_NOT...
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2
Desafios - 01 : Informar a proporção de inscritos por idades
# desafio 1 def proporcao(total_itens): def funcao_calculo(x): res = x * 100 / total_itens return round(res, 6); return funcao_calculo total = len(dados_enem) inscritos_por_idade = dados_enem['NU_IDADE'].value_counts() inscritos_por_idade.apply(proporcao(total))
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2
- 02: Descobrir de quais estados são os inscritos com 13 anos
# desafio 02 cabecalhos= ['SG_UF_RESIDENCIA','NU_IDADE'] inscritos=dados_enem[cabecalhos] inscritos.query('NU_IDADE==13')
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2
- 03: Qual a proporcao dos alunos com 18 anos por estado
# desafio 3 cabecalhos = ['SG_UF_RESIDENCIA','NU_IDADE'] novo_df = dados_enem[cabecalhos] inscritos = novo_df.query('NU_IDADE==18') total_inscritos = len(inscritos) inscritos.value_counts().apply(proporcao(total_inscritos))
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2
- 04: Plotar Histogramas das idades de treineiros e não treineiros
# desafio 4 inscritos_treineiros = dados_enem.query('IN_TREINEIRO == 1')['NU_IDADE'].value_counts(); inscritos_treineiros.hist(bins=30,figsize=(10,7),legend=True) inscritos_nao_treineiros = dados_enem.query('IN_TREINEIRO == 0')['NU_IDADE'].value_counts(); inscritos_nao_treineiros.hist(bins=30,figsize=(10,7),legend=True...
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2
- 05: Comparar as distribuições das provas em ingles e espanhol
# desafio 5 # TP_LINGUA==0 -> Ingles # TP_LINGUA==1 -> Espanhol dados_enem.query('TP_LINGUA==1')['TP_LINGUA'].hist(bins=20,figsize=(10,7),legend=True) dados_enem.query('TP_LINGUA==0')['TP_LINGUA'].hist(bins=20,figsize=(10,7),legend=True)
_____no_output_____
MIT
imersao_dados_aula_1.ipynb
CarlosNeto2804/imersao-dados-2