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 |
|---|---|---|---|---|---|
Network setupNow we can set up the architecture of our neural network, we'll use a fully convolutional U-net. This is a widely used architecture that uses a stack of convolutions across different spatial resolutions. The main deviation from a regular conv-net is to introduce _skip connection_ from the encoder to the d... | import os, sys, random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd
import torch.utils.data
def blockUNet(in_c, out_c, name, transposed=False, bn=True, relu=True, size=4, pad=1, dropout=0.):
block = nn.Sequential()
if relu:
block.add_module... | _____no_output_____ | MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
Next, we can initialize an instance of the `DfpNet`.Below, the `EXPO` parameter here controls the exponent for the feature maps of our Unet: this directly scales the network size (3 gives a network with ca. 150k parameters). This is relatively small for a generative NN with $3 \times 128^2 = \text{ca. }49k$ outputs, bu... | # channel exponent to control network size
# EXPO = 5
# setup network
netG = TurbNetG(channelExponent=expo, dropout=dropout)
#print(netG) # to double check the details...
nn_parameters = filter(lambda p: p.requires_grad, netG.parameters())
params = sum([np.prod(p.size()) for p in nn_parameters])
# crucial parameter ... | Trainable params: 2332547 -> crucial! always keep in view...
| MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
With an exponent of 3, this network has 147555 trainable parameters. As the subtle hint in the print statement indicates, this is a crucial number to always have in view when training NNs. It's easy to change settings, and get a network that has millions of parameters, and as a result probably all kinds of convergence ... | # history_L1 = []
# history_L1val = []
# if os.path.isfile("network"):
# print("Found existing network, loading & skipping training")
# net.load_state_dict(torch.load("network")) # optionally, load existing network
# else:
# print("Training from scratch")
# for epoch in range(EPOCHS):
# net.train()
# ... | Training from scratch
Starting epoch 1 / 100
| MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
The NN is finally trained! The losses should have nicely gone down in terms of absolute values: With the standard settings from an initial value of around 0.2 for the validation loss, to ca. 0.02 after 100 epochs. Let's look at the graphs to get some intuition for how the training progressed over time. This is typical... | import matplotlib.pyplot as plt
l1train = np.asarray(history_L1)
l1vali = np.asarray(history_L1val)
plt.plot(np.arange(l1train.shape[0]),l1train,'b',label='Training loss')
plt.plot(np.arange(l1vali.shape[0] ),l1vali ,'g',label='Validation loss')
plt.legend()
plt.show() | _____no_output_____ | MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
You should see a curve that goes down for ca. 40 epochs, and then starts to flatten out. In the last part, it's still slowly decreasing, and most importantly, the validation loss is not increasing. This would be a certain sign of overfitting, and something that we should avoid. (Try decreasing the amount of training da... | netG.eval()
for i, validata in enumerate(valiLoader, 0):
inputs_curr, targets_curr = validata
inputs.data.copy_(inputs_curr.float())
targets.data.copy_(targets_curr.float())
outputs = netG(inputs)
outputs_curr = outputs.data.cpu().numpy()
if i<1: showSbs(targets_curr[0] , outputs_curr[0], t... | /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:3613: UserWarning: Default upsampling behavior when mode=bilinear is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.
"See the documentation of n... | MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
Visually, there should at least be a rough resemblance here between input out network output. We'll save the more detailed evaluation for the test data, though. Test evaluationNow let's look at actual test samples: In this case we'll use new airfoil shapes as out-of-distribution (OOD) data. These are shapes that the n... | # testdata = TurbDataset(prop, shuffle=1,mode=2, dataDir="data/train/",dataDirTest="data/test/" )
# testLoader = torch.utils.data.DataLoader(testdata, batch_size=1, shuffle=False, drop_last=True)
# print("Training batches: {}".format(len(testLoader)))
# if not os.path.isfile('data-airfoils-test.npz'):
# import urll... | Loaded 10/10 test samples
Reducing data to load for tests
Number of data loaded: 10
Using fixed maxima [4.65, 2.04, 2.37]
Data stats, input mean 0.190220, max 0.961052; targets mean 0.289502 , max 1.000000
| MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
The average test error with the default settings should be ca. 0.03. As the inputs are normalized, this means the average error across all three fields is 3% w.r.t. the maxima of each quantity. This is not too bad for new shapes, but clearly leaves room for improvement.Looking at the visualizations, you'll notice that ... | torch.save({
'epoch': epoch,
'model_state_dict': netG.state_dict(),
'optimizer_state_dict': optimizerG.state_dict(),
'loss': lossL1,
# ...
}, f"network_{epoch+1}.pth")
!zip results_train.zip /content/Deep-Flow-Prediction/results_train/* | adding: content/Deep-Flow-Prediction/results_train/epoch0_0_bw.png (deflated 1%)
adding: content/Deep-Flow-Prediction/results_train/epoch0_0.png (deflated 0%)
adding: content/Deep-Flow-Prediction/results_train/epoch10_0_bw.png (deflated 1%)
adding: content/Deep-Flow-Prediction/results_train/epoch10_0.png (defla... | MIT | notebooks/supervised_airfoils_normalized.ipynb | gmshashank/Deep_Flow_Prediction |
Decoding with ANOVA + SVM: face vs house in the Haxby dataset===============================================================This example does a simple but efficient decoding on the Haxby dataset:using a feature selection, followed by an SVM. | import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Retrieve the files of the Haxby dataset---------------------------------------- | from nilearn import datasets
# By default 2nd subject will be fetched
haxby_dataset = datasets.fetch_haxby()
# print basic information on the dataset
print('Mask nifti image (3D) is located at: %s' % haxby_dataset.mask)
print('Functional nifti image (4D) is located at: %s' %
haxby_dataset.func[0]) | Mask nifti image (3D) is located at: /Users/Ralf/nilearn_data/haxby2001/mask.nii.gz
Functional nifti image (4D) is located at: /Users/Ralf/nilearn_data/haxby2001/subj2/bold.nii.gz
| Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Load the behavioral data------------------------- | import pandas as pd
# Load target information as string and give a numerical identifier to each
behavioral = pd.read_csv(haxby_dataset.session_target[0], sep=" ")
conditions = behavioral['labels']
# Restrict the analysis to faces and places
condition_mask = behavioral['labels'].isin(['face', 'house'])
conditions = co... | ['face' 'house']
('labels', 'chunks')
| Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Prepare the fMRI data: smooth and apply the mask------------------------------------------------- | from nilearn.input_data import NiftiMasker
mask_filename = haxby_dataset.mask
# For decoding, standardizing is often very important
# note that we are also smoothing the data
masker = NiftiMasker(mask_img=mask_filename, smoothing_fwhm=4,
standardize=True, memory="nilearn_cache", memory_level=1)
f... | _____no_output_____ | Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Build the decoder------------------Define the prediction function to be used.Here we use a Support Vector Classification, with a linear kernel | from sklearn.svm import SVC
svc = SVC(kernel='linear')
# Define the dimension reduction to be used.
# Here we use a classical univariate feature selection based on F-test,
# namely Anova. When doing full-brain analysis, it is better to use
# SelectPercentile, keeping 5% of voxels
# (because it is independent of the re... | _____no_output_____ | Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Fit the decoder and predict---------------------------- | anova_svc.fit(X, conditions)
y_pred = anova_svc.predict(X) | _____no_output_____ | Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Obtain prediction scores via cross validation----------------------------------------------- | from sklearn.model_selection import LeaveOneGroupOut, cross_val_score
# Define the cross-validation scheme used for validation.
# Here we use a LeaveOneGroupOut cross-validation on the session group
# which corresponds to a leave-one-session-out
cv = LeaveOneGroupOut()
# Compute the prediction accuracy for the differ... | Classification accuracy: 0.7037 / Chance level: 0.500000
| Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Visualize the results----------------------Look at the SVC's discriminating weights | coef = svc.coef_
# reverse feature selection
coef = feature_selection.inverse_transform(coef)
# reverse masking
weight_img = masker.inverse_transform(coef)
# Use the mean image as a background to avoid relying on anatomical data
from nilearn import image
mean_img = image.mean_img(func_filename)
# Create the figure
f... | _____no_output_____ | Apache-2.0 | scripts/03_Decoding_SVM_Haxby_Bonus.ipynb | smgrady-git/medianeuroclass |
Python Flair Basics **(C) 2018-2020 by [Damir Cavar](http://damir.cavar.me/)** **Version:** 0.3, February 2020 **Download:** This and various other Jupyter notebooks are available from my [GitHub repo](https://github.com/dcavar/python-tutorial-for-ipython). **License:** [Creative Commons Attribution-ShareAlike 4.0 Int... | from flair.data import Sentence | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We can now define a sentence: | sentence = Sentence('The grass is green .')
print(sentence) | Sentence: "The grass is green ." - 5 Tokens
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We can access the tokens of a sentence via their token id or with their index: | print(sentence.get_token(4))
print(sentence[3]) | Token: 4 green
Token: 4 green
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We can also iterate over all tokens in a sentence: | for token in sentence:
print(token) | Token: 1 The
Token: 2 grass
Token: 3 is
Token: 4 green
Token: 5 .
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Tokenization There is a simple tokenizer included in the library using the lightweight segtok library to tokenize your text for such a Sentence definition. In the Sentence constructor use the flag *use_tokenize* to tokenize the input string before instantiating a Sentence object: | sentence = Sentence('The grass is green.', use_tokenizer=True)
print(sentence) | Sentence: "The grass is green ." - 5 Tokens
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Tags on Tokens A Token has fields for linguistic annotation:- lemma- part-of-speech tag- named entity tagWe can add a tag by specifying the tag type and the tag value.We will adding an NER tag of type 'color' to the word 'green'. This means that we've tagged this word as an entity of type color: | sentence[3].add_tag('ner', 'color')
print(sentence.to_tagged_string()) | The grass is green <color> .
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Each tag is of class Label. An associated score indicates confidence: | from flair.data import Label
tag: Label = sentence[3].get_tag('ner')
print(f'"{sentence[3]}" is tagged as "{tag.value}" with confidence score "{tag.score}"') | "Token: 4 green" is tagged as "color" with confidence score "1.0"
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
The manually added color tag has a score of 1.0. A tag predicted by a sequence labeler will have a score value that indicates the classifier confidence. A Sentence can have one or multiple labels that can for example be used in text classification tasks. For instance, the example below shows how we add the label 'sport... | sentence = Sentence('France is the current world cup winner.')
sentence.add_label('sports')
sentence.add_labels(['sports', 'world cup'])
sentence = Sentence('France is the current world cup winner.', labels=['sports', 'world cup']) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Labels are also of the Label class. So, you can print a sentence's labels like this: | sentence = Sentence('France is the current world cup winner.', labels=['sports', 'world cup'])
print(sentence)
for label in sentence.labels:
print(label) | Sentence: "France is the current world cup winner." - 7 Tokens - Labels: [sports (1.0), world cup (1.0)]
sports (1.0)
world cup (1.0)
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Tagging Text Using Pre-Trained Sequence Tagging Models Flair has numerous pre-trained models. For the named entity recognition (NER) task there is a model that was trained on the English CoNLL-03 task and can recognize 4 different entity types. Import it using: | from flair.models import SequenceTagger
tagger = SequenceTagger.load('ner') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We use the predict() method of the tagger on a sentence to add predicted tags to the tokens in the sentence: | sentence = Sentence('Washington went to New York .')
tagger.predict(sentence)
print(sentence.to_tagged_string()) | Washington <S-PER> went to New <B-LOC> York <E-LOC> .
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Getting annotated spans for multi-word expressions can be achieved using the following command: | for entity in sentence.get_spans('ner'):
print(entity) | PER-span [1]: "Washington"
LOC-span [4,5]: "New York"
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Which indicates that "George Washington" is a person (PER) and "Washington" is a location (LOC). Each such Span has a text, a tag value, its position in the sentence and "score" that indicates how confident the tagger is that the prediction is correct. You can also get additional information, such as the position offse... | print(sentence.to_dict(tag_type='ner'))
print(sentence.to_dict()) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Flair contains various sequence tagger models. You choose which pre-trained model you load by passing the appropriate string to the load() method of the SequenceTagger class. Currently, the following pre-trained models are provided: As indicated in the list above, we also provide pre-trained models for languages other ... | tagger = SequenceTagger.load('de-ner')
sentence = Sentence('George Washington ging nach Washington .')
tagger.predict(sentence)
print(sentence.to_tagged_string()) | 2020-02-03 18:41:11,589 loading file C:\Users\damir\.flair\models\de-ner-conll03-v0.4.pt
George <B-PER> Washington <E-PER> ging nach Washington <S-LOC> .
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Flair offers access to multi-lingual models for multi-lingual text. | tagger = SequenceTagger.load('pos-multi')
sentence = Sentence('George Washington lebte in Washington . Dort kaufte er a horse .')
tagger.predict(sentence)
print(sentence.to_tagged_string()) | 2020-02-03 18:42:43,387 loading file C:\Users\damir\.flair\models\pos-multi-v0.1.pt
George <PROPN> Washington <PROPN> lebte <VERB> in <ADP> Washington <PROPN> . <PUNCT> Dort <PROPN> kaufte <VERB> er <PRON> a <DET> horse <NOUN> . <PUNCT>
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Semantic Frames For English, Flair provides a pre-trained model that detects semantic frames in text, trained using Propbank 3.0 frames. This provides some sort of word sense disambiguation for frame evoking words. | tagger = SequenceTagger.load('frame')
sentence_1 = Sentence('George returned to Berlin to return his hat .')
sentence_2 = Sentence('He had a look at different hats .')
tagger.predict(sentence_1)
tagger.predict(sentence_2)
print(sentence_1.to_tagged_string())
print(sentence_2.to_tagged_string()) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
The frame detector makes a distinction in sentence 1 between two different meanings of the word 'return'. 'return.01' means returning to a location, while 'return.02' means giving something back.Similarly, in sentence 2 the frame detector finds a light verb construction in which 'have' is the light verb and 'look' is a... | text = "This is a sentence. John read a book. This is another sentence. I love Berlin."
from segtok.segmenter import split_single
sentences = [Sentence(sent, use_tokenizer=True) for sent in split_single(text)]
tagger: SequenceTagger = SequenceTagger.load('ner')
tagger.predict(sentences)
for i in sentences:
print... | 2020-02-03 09:43:07,071 loading file C:\Users\damir\.flair\models\en-ner-conll03-v0.4.pt
This is a sentence .
John <S-PER> read a book .
This is another sentence .
I love Berlin <S-LOC> .
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Using the mini_batch_size parameter of the .predict() method, you can set the size of mini batches passed to the tagger. Depending on your resources, you might want to play around with this parameter to optimize speed. Pre-Trained Text Classification Models Flair provides a pre-trained model for detecting positive or ... | from flair.models import TextClassifier
classifier = TextClassifier.load('en-sentiment') | 2020-02-03 18:45:19,296 loading file C:\Users\damir\.flair\models\imdb-v0.4.pt
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We call the predict() method of the classifier on a sentence. This will add the predicted label to the sentence: | sentence = Sentence('This film hurts. It is so bad that I am confused.')
classifier.predict(sentence)
print(sentence.labels)
sentence = Sentence('This film is fantastic. I love it.')
classifier.predict(sentence)
print(sentence.labels) | [POSITIVE (0.9998914003372192)]
| Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Flair has a pre-trained German and English model. Using Word Embeddings Flair provides a set of classes with which we can embed the words in sentences in various ways. All word embedding classes inherit from the TokenEmbeddings class and implement the embed() method which we need to call to embed our text. This means ... | from flair.embeddings import WordEmbeddings
glove_embedding = WordEmbeddings('glove') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We create an example sentence and call the embedding's embed() method. We can also pass a list of sentences to this method since some embedding types make use of batching to increase speed. | sentence = Sentence('The grass is green .')
glove_embedding.embed(sentence)
for token in sentence:
print(token)
print(token.embedding) | Token: 1 The
tensor([-0.0382, -0.2449, 0.7281, -0.3996, 0.0832, 0.0440, -0.3914, 0.3344,
-0.5755, 0.0875, 0.2879, -0.0673, 0.3091, -0.2638, -0.1323, -0.2076,
0.3340, -0.3385, -0.3174, -0.4834, 0.1464, -0.3730, 0.3458, 0.0520,
0.4495, -0.4697, 0.0263, -0.5415, -0.1552, -0.1411, -0.03... | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
GloVe embeddings are Pytorch vectors of dimensionality 100.We choose which pre-trained embeddings we want to load by passing the appropriate id string to the constructor of the WordEmbeddings class. We would use the two-letter language code to init an embedding, so 'en' for English and 'de' for German and so on. By def... | german_embedding = WordEmbeddings('de') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
If we want to load German FastText embeddings trained over crawls, we instantiate as follows: | german_embedding = WordEmbeddings('de-crawl') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
If the models are not locally available, Flair will automatically download them and install them into the local user cache. It is recommended to use the FastText embeddings, or GloVe if we want a smaller model.If we want to use any other embeddings (not listed in the list above), we can load those by calling: | custom_embedding = WordEmbeddings('path/to/your/custom/embeddings.gensim') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
If we want to load custom embeddings, we need to make sure that the custom embeddings are correctly formatted to gensim.We can, for example, convert FastText embeddings to gensim using the following code snippet: | import gensim
word_vectors = gensim.models.KeyedVectors.load_word2vec_format('/path/to/fasttext/embeddings.txt', binary=False)
word_vectors.save('/path/to/converted') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Character Embeddings Some embeddings - such as character-features - are not pre-trained but rather trained on the downstream task. Normally this requires an implementation of a hierarchical embedding architecture.With Flair, we don't need to worry about such things. Just choose the appropriate embedding class and the ... | from flair.embeddings import CharacterEmbeddings
embedding = CharacterEmbeddings()
sentence = Sentence('The grass is green .')
embedding.embed(sentence) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Sub-Word Embeddings Flair now also includes the byte pair embeddings calulated by @bheinzerling that segment words into subsequences. This can dramatically reduce the model size vis-a-vis using normal word embeddings at nearly the same accuracy. So, if we want to train small models try out the new BytePairEmbeddings c... | from flair.embeddings import BytePairEmbeddings
embedding = BytePairEmbeddings('en')
sentence = Sentence('The grass is green .')
embedding.embed(sentence) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
[Sub-word embeddings](https://nlp.h-its.org/bpemb/) are interesting, since [BPEmb](https://nlp.h-its.org/bpemb/) is a collection of pre-trained subword embeddings in 275 languages, based on Byte-Pair Encoding (BPE) and trained on Wikipedia. Its intended use is as input for neural models in natural language processing.-... | from flair.embeddings import WordEmbeddings, CharacterEmbeddings
glove_embedding = WordEmbeddings('glove')
character_embeddings = CharacterEmbeddings() | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Now instantiate the StackedEmbeddings class and pass it a list containing these two embeddings. | from flair.embeddings import StackedEmbeddings
stacked_embeddings = StackedEmbeddings(
embeddings=[glove_embedding, character_embeddings]) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We use this embedding like all the other embeddings, i.e. call the embed() method over our sentences. | sentence = Sentence('The grass is green .')
stacked_embeddings.embed(sentence)
for token in sentence:
print(token)
print(token.embedding) | Token: 1 The
tensor([-0.0382, -0.2449, 0.7281, ..., -0.0065, -0.0053, 0.0090])
Token: 2 grass
tensor([-0.8135, 0.9404, -0.2405, ..., 0.0354, -0.0255, -0.0143])
Token: 3 is
tensor([-5.4264e-01, 4.1476e-01, 1.0322e+00, ..., -5.3691e-04,
-9.6750e-03, -2.7541e-02])
Token: 4 green
tensor([-0.6791, 0.3491, ... | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Words are now embedded using a concatenation of two different embeddings. This means that the resulting embedding vector is still a single PyTorch vector. Other Embeddings: BERT, ELMo, Flair Next to standard WordEmbeddings and CharacterEmbeddings, Flair also provides classes for BERT, ELMo and Flair embeddings. These ... | from flair.embeddings import FlairEmbeddings
flair_embedding_forward = FlairEmbeddings('news-forward')
sentence = Sentence('The grass is green .')
flair_embedding_forward.embed(sentence) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We can choose which embeddings we load by passing the appropriate string to the constructor of the FlairEmbeddings class. Currently, there are numerous contextual string embeddings provided in models (more coming). See [list](https://github.com/zalandoresearch/flair/blob/master/resources/docs/TUTORIAL_4_ELMO_BERT_FLAIR... | from flair.embeddings import WordEmbeddings, FlairEmbeddings, StackedEmbeddings
stacked_embeddings = StackedEmbeddings([
WordEmbeddings('glove'),
FlairEmbeddings('news-forward'),
FlairEmbeddings('n... | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We would use this embedding like all the other embeddings, i.e. call the embed() method over our sentences. BERT Embeddings BERT embeddings were developed by Devlin et al. (2018) and are a different kind of powerful word embedding based on a bidirectional transformer architecture. Flair is using the implementation of ... | from flair.embeddings import BertEmbeddings
embedding = BertEmbeddings()
sentence = Sentence('The grass is green .')
embedding.embed(sentence)
for i in sentence:
print(i, i.embedding) | Token: 1 The tensor([-0.0323, -0.3904, -1.1946, ..., 0.1305, -0.1365, -0.4323])
Token: 2 grass tensor([-0.3973, 0.2652, -0.1337, ..., 0.3715, 0.1097, -1.1625])
Token: 3 is tensor([ 0.1374, -0.3688, -0.8292, ..., 0.2533, 0.0294, 0.4293])
Token: 4 green tensor([-0.7722, -0.1152, 0.3661, ..., 0.1575, -0.0682,... | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We can load any of the pre-trained BERT models by providing the model string during initialization: - 'bert-base-uncased': English; 12-layer, 768-hidden, 12-heads, 110M parameters- 'bert-large-uncased': English; 24-layer, 1024-hidden, 16-heads, 340M parameters- 'bert-base-cased': English; 12-layer, 768-hidden, 12-heads... | from flair.embeddings import ELMoEmbeddings
embedding = ELMoEmbeddings(model="small")
sentence = Sentence('The grass is green .')
embedding.embed(sentence) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
AllenNLP provides the following pre-trained models. To use any of the following models inside Flair simple specify the embedding id when initializing the ELMoEmbeddings. - 'small': English; 1024-hidden, 1 layer, 14.6M parameters- 'medium': English; 2048-hidden, 1 layer, 28.0M parameters- 'original': English; 4096-hidde... | from flair.embeddings import FlairEmbeddings, BertEmbeddings
flair_forward_embedding = FlairEmbeddings('multi-forward')
flair_backward_embedding = FlairEmbeddings('multi-backward')
bert_embedding = BertEmbeddings('bert-base-multilingual-cased') | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
Now we instantiate the StackedEmbeddings class and pass it a list containing these three embeddings: | from flair.embeddings import StackedEmbeddings
stacked_embeddings = StackedEmbeddings(
embeddings=[flair_forward_embedding, flair_backward_embedding, bert_embedding]) | _____no_output_____ | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
We use this embedding like all the other embeddings, i.e. call the embed() method over our sentences. | sentence = Sentence('The grass is green .')
stacked_embeddings.embed(sentence)
for token in sentence:
print(token)
print(token.embedding) | Token: 1 The
tensor([-1.4812e-07, 4.5007e-08, 6.0273e-07, ..., 3.8287e-01,
4.7210e-01, 2.9850e-01])
Token: 2 grass
tensor([ 1.6254e-04, 1.8764e-07, -7.9034e-09, ..., 8.5283e-01,
-5.0724e-02, 3.4476e-01])
Token: 3 is
tensor([-2.4521e-04, 3.4869e-07, 5.5841e-06, ..., -1.8283e-01,
7.1... | Apache-2.0 | notebooks/Flair Basics.ipynb | peey/python-tutorial-notebooks |
第4章 Matplotlibでグラフを 描画しよう 4-3: 折れ線グラフ | import matplotlib.pyplot as plt
# リスト4.3.1:折れ線グラフの描画
plt.style.use("ggplot")
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 3])
plt.show()
# リスト4.3.2:X値とY値を指定した折れ線グラフの描画
fig = plt.figure()
ax = fig.add_subplot(111)
x = [0, 2, 4]
y = [0, 4, 2]
ax.plot(x, y)
plt.show()
# リスト4.3.3:複数の線の描画
fig = plt.figure()
ax =... | _____no_output_____ | CC0-1.0 | sample-code/notebooks/4-03.ipynb | luka3117/practical_python |
Layers> Common layers, blocks and utils. | #hide
from nbdev.export import notebook2script; notebook2script() | _____no_output_____ | Apache-2.0 | nbs/_template.ipynb | arampacha/generative_models |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License.  ... | import logging
import os
import time
import numpy as np
import pandas as pd
import azureml.core
from azureml.core.compute import DsvmCompute
from azureml.core.experiment import Experiment
from azureml.core.workspace import Workspace
from azureml.train.automl import AutoMLConfig
ws = Workspace.from_config()
# choose ... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Create a Remote Linux DSVMNote: If creation fails with a message about Marketplace purchase eligibilty, go to portal.azure.com, start creating DSVM there, and select "Want to create programmatically" to enable programmatic creation. Once you've enabled it, you can exit without actually creating VM.**Note**: By default... | compute_target_name = 'mydsvmc'
try:
while ws.compute_targets[compute_target_name].provisioning_state == 'Creating':
time.sleep(1)
dsvm_compute = DsvmCompute(workspace=ws, name=compute_target_name)
print('found existing:', dsvm_compute.name)
except:
dsvm_config = DsvmCompute.provisioni... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Data Copy data file to localDownload the data file. | if not os.path.isdir('data'):
os.mkdir('data')
from sklearn.datasets import fetch_20newsgroups
import csv
remove = ('headers', 'footers', 'quotes')
categories = [
'alt.atheism',
'talk.religion.misc',
'comp.graphics',
'sci.space',
]
data_train = fetch_20newsgroups(subset = 't... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Upload data to the cloud Now make the data accessible remotely by uploading that data from your local machine into Azure so it can be accessed for remote training. The datastore is a convenient construct associated with your workspace for you to upload/download data, and interact with it from your remote compute targe... | #blob_datastore = Datastore(ws, blob_datastore_name)
ds = ws.get_default_datastore()
print(ds.datastore_type, ds.account_name, ds.container_name)
# ds.upload_files("data.tsv")
ds.upload(src_dir='./data', target_path='data', overwrite=True, show_progress=True) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Configure & RunFirst let's create a DataReferenceConfigruation object to inform the system what data folder to download to the compute target.The path_on_compute should be an absolute path to ensure that the data files are downloaded only once. The get_data method should use this same path to access the data files. | from azureml.core.runconfig import DataReferenceConfiguration
dr = DataReferenceConfiguration(datastore_name=ds.name,
path_on_datastore='data',
path_on_compute='/tmp/azureml_runs',
mode='download', # download files from datastore to compute target
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Create Get Data FileFor remote executions you should author a get_data.py file containing a get_data() function. This file should be in the root directory of the project. You can encapsulate code to read data either from a blob storage or local disk in this file.The *get_data()* function returns a [dictionary](README.... | if not os.path.exists(project_folder):
os.makedirs(project_folder)
%%writefile $project_folder/get_data.py
import pandas as pd
def get_data():
X_train = pd.read_csv("/tmp/azureml_runs/data/X_train.tsv", delimiter="\t", header=None, quotechar='"')
y_train = pd.read_csv("/tmp/azureml_runs/data/y_train.tsv",... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
TrainYou can specify automl_settings as **kwargs** as well. Also note that you can use the get_data() symantic for local excutions too. Note: For Remote DSVM and Batch AI you cannot pass Numpy arrays directly to AutoMLConfig.|Property|Description||-|-||**primary_metric**|This is the metric that you want to optimize. C... | automl_settings = {
"iteration_timeout_minutes": 60,
"iterations": 4,
"n_cross_validations": 5,
"primary_metric": 'AUC_weighted',
"preprocess": True,
"max_cores_per_iteration": 1,
"verbosity": logging.INFO
}
automl_config = AutoMLConfig(task = 'classification',
d... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
For remote runs the execution is asynchronous, so you will see the iterations get populated as they complete. You can interact with the widgets/models even when the experiment is running to retreive the best model up to that point. Once you are satisfied with the model you can cancel a particular iteration or the whole... | remote_run = experiment.submit(automl_config, show_output=False)
remote_run | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Results Widget for monitoring runsThe widget will sit on "loading" until the first iteration completed, then you will see an auto-updating graph and table show up. It refreshed once per minute, so you should see the graph update as child runs complete.You can click on a pipeline to see run properties and output logs. ... | from azureml.widgets import RunDetails
RunDetails(remote_run).show()
# Wait until the run finishes.
remote_run.wait_for_completion(show_output = True) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Retrieve All Child RunsYou can also use sdk methods to fetch all the child runs and see individual metrics that we log. | children = list(remote_run.get_children())
metricslist = {}
for run in children:
properties = run.get_properties()
metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}
metricslist[int(properties['iteration'])] = metrics
rundata = pd.DataFrame(metricslist).sort_index(1)
rundata | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Canceling RunsYou can cancel ongoing remote runs using the *cancel()* and *cancel_iteration()* functions | # Cancel the ongoing experiment and stop scheduling new iterations
# remote_run.cancel()
# Cancel iteration 1 and move onto iteration 2
# remote_run.cancel_iteration(1) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Pre-process cache cleanupThe preprocess data gets cache at user default file store. When the run is completed the cache can be cleaned by running below cell | remote_run.clean_preprocessor_cache() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Retrieve the Best ModelBelow we select the best pipeline from our iterations. The *get_output* method returns the best run and the fitted model. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*. | best_run, fitted_model = remote_run.get_output() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Best Model based on any other metric | # lookup_metric = "accuracy"
# best_run, fitted_model = remote_run.get_output(metric=lookup_metric) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Model from a specific iteration | # iteration = 1
# best_run, fitted_model = remote_run.get_output(iteration=iteration) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Test | # Load test data.
from pandas_ml import ConfusionMatrix
data_test = fetch_20newsgroups(subset = 'test', categories = categories,
shuffle = True, random_state = 42,
remove = remove)
X_test = np.array(data_test.data).reshape((len(data_test.data),1))
y_test =... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb | waith/MachineLearningNotebooks |
Assignment 3: Question AnsweringWelcome to this week's assignment of course 4. In this you will explore question answering. You will implement the "Text to Text Transfer from Transformers" (better known as T5). Since you implemented transformers from scratch last week you will now be able to use them. Outline- [Ove... | import ast
import string
import textwrap
import itertools
import numpy as np
import trax
from trax import layers as tl
from trax.supervised import decoding
# Will come handy later.
wrapper = textwrap.TextWrapper(width=70)
# Set random seed
np.random.seed(42) | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
Part 1: C4 DatasetThe [C4](https://www.tensorflow.org/datasets/catalog/c4) is a huge data set. For the purpose of this assignment you will use a few examples out of it which are present in `data.txt`. C4 is based on the [common crawl](https://commoncrawl.org/) project. Feel free to read more on their website. Run the ... | # load example jsons
example_jsons = list(map(ast.literal_eval, open('data.txt')))
# Printing the examples to see how the data looks like
for i in range(5):
print(f'example number {i+1}: \n\n{example_jsons[i]} \n') | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
Notice the `b` before each string? This means that this data comes as bytes rather than strings. Strings are actually lists of bytes so for the rest of the assignments the name `strings` will be used to describe the data. To check this run the following cell: | type(example_jsons[0].get('text')) | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
1.1 Pre-Training Objective**Note:** The word "mask" will be used throughout this assignment in context of hiding/removing word(s)You will be implementing the BERT loss as shown in the following image. Assume you have the following text: **Thank you for inviting me to your party last week** Now as input you will m... | # Grab text field from dictionary
natural_language_texts = [example_json['text'] for example_json in example_jsons]
# First text example
natural_language_texts[4] | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
1.2.1 Decode to natural languageThe following functions will help you `detokenize` and`tokenize` the text data. The `sentencepiece` vocabulary was used to convert from text to ids. This vocabulary file is loaded and used in this helper functions.`natural_language_texts` has the text from the examples we gave you. Run... | # Special tokens
PAD, EOS, UNK = 0, 1, 2
def detokenize(np_array):
return trax.data.detokenize(
np_array,
vocab_type='sentencepiece',
vocab_file='sentencepiece.model',
vocab_dir='.')
def tokenize(s):
# The trax.data.tokenize function operates on streams,
# that's why we have to... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
As you can see above, you were able to take a piece of string and tokenize it. Now you will create `input` and `target` pairs that will allow you to train your model. T5 uses the ids at the end of the vocab file as sentinels. For example, it will replace: - `vocab_size - 1` by `` - `vocab_size - 2` by `` - and s... | vocab_size = trax.data.vocab_size(
vocab_type='sentencepiece',
vocab_file='sentencepiece.model',
vocab_dir='.')
def get_sentinels(vocab_size=vocab_size, display=False):
sentinels = {}
for i, char in enumerate(reversed(string.ascii_letters), 1):
decoded_text = detokenize([vocab_size - i])
... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
The functions above make your `inputs` and `targets` more readable. For example, you might see something like this once you implement the masking function below. - Input sentence: Younes and Lukasz were working together in the lab yesterday after lunch. - Input: Younes and Lukasz **Z** together in the **Y** yesterd... | # UNQ_C1
# GRADED FUNCTION: tokenize_and_mask
def tokenize_and_mask(text, vocab_size=vocab_size, noise=0.15,
randomizer=np.random.uniform, tokenize=tokenize):
"""Tokenizes and masks a given input.
Args:
text (str or bytes): Text input.
vocab_size (int, optional): Size of ... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
**Expected Output:**```CPPb'Beginners BBQ Class Taking Place in Missoula!\nDo you want to get better at making delicious BBQ? You will have the opportunity, put this on your calendar now. Thursday, September 22nd join World Class BBQ Champion, Tony Balay from Lonestar Smoke Rangers. He will be teaching a beginner leve... | print('Inputs: \n\n', pretty_decode(inps))
print('\nTargets: \n\n', pretty_decode(targs)) | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
1.4 Creating the PairsYou will now create pairs using your dataset. You will iterate over your data and create (inp, targ) pairs using the functions that we have given you. | # Apply tokenize_and_mask
inputs_targets_pairs = [tokenize_and_mask(text) for text in natural_language_texts]
def display_input_target_pairs(inputs_targets_pairs):
for i, inp_tgt_pair in enumerate(inputs_targets_pairs, 1):
inps, tgts = inp_tgt_pair
inps, tgts = pretty_decode(inps), pretty_decode(tgt... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
Part 2: TransfomerWe now load a Transformer model checkpoint that has been pre-trained using the above C4 dataset and decode from it. This will save you a lot of time rather than have to train your model yourself. Later in this notebook, we will show you how to fine-tune your model.Start by loading in the model. We co... | # UNQ_C2
# GRADED FUNCTION: FeedForwardBlock
def FeedForwardBlock(d_model, d_ff, dropout, dropout_shared_axes, mode, activation):
"""Returns a list of layers implementing a feed-forward block.
Args:
d_model: int: depth of embedding
d_ff: int: depth of feed-forward layer
dropout: float: ... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
**Expected Output:**```CPP [LayerNorm, Dense_2048, Relu, Dropout, Dense_512, Dropout]``` 2.1.2 The Encoder BlockThe encoder block will use the `FeedForwardBlock`. You will have to build two residual connections. Inside the first residual connection you will have the `tl.layerNorm()`, `attention`, and `dropout_` layer... | # UNQ_C3
# GRADED FUNCTION: EncoderBlock
def EncoderBlock(d_model, d_ff, n_heads, dropout, dropout_shared_axes,
mode, ff_activation, FeedForwardBlock=FeedForwardBlock):
"""
Returns a list of layers that implements a Transformer encoder block.
The input to the layer is a pair, (activations,... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
**Expected Output:**```CPP[Serial_in2_out2[ Branch_in2_out3[ None Serial_in2_out2[ LayerNorm Serial_in2_out2[ Dup_out2 Dup_out2 Serial_in4_out2[ Parallel_in3_out3[ Dense_512 Dense_512 Dense_512 ] PureAttention_in4_out2 ... | # UNQ_C4
# GRADED FUNCTION: TransformerEncoder
def TransformerEncoder(vocab_size=vocab_size,
n_classes=10,
d_model=512,
d_ff=2048,
n_layers=6,
n_heads=8,
dropout=0.1,
... | _____no_output_____ | MIT | Course 4 - Natural Language Processing with Attention Models/Week 3/.ipynb_checkpoints/C4_W3_Assignment-checkpoint.ipynb | TRoboto/Natural-Language-Processing-Specialization |
dataset_torch> Module to load the slates dataset into a Pytorch Dataset and Dataloaders with default train/valid test splits. | #export
import torch
import recsys_slates_dataset.data_helper as data_helper
from torch.utils.data import Dataset, DataLoader
import torch
import json
import numpy as np
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level='INFO')
class SequentialDataset(Dataset):
''' A Pytorch Dataset for th... | 2021-08-13 10:15:07,665 Download data if not in data folder..
2021-08-13 10:15:07,666 Downloading data.npz
2021-08-13 10:15:07,667 Downloading ind2val.json
2021-08-13 10:15:07,667 Downloading itemattr.npz
2021-08-13 10:15:07,668 Done downloading all files.
2021-08-13 10:15:07,668 Load data..
2021-08-13 10:15:31,565 Loa... | Apache-2.0 | dataset_torch.ipynb | Pernilleww/recsys_slates_dataset |
Collaborative filtering on the MovieLense Dataset This notebook is based on part of Chapter 9 of [BigQuery: The Definitive Guide](https://www.oreilly.com/library/view/google-bigquery-the/9781492044451/ "http://shop.oreilly.com/product/0636920207399.do") by Lakshmanan and Tigani. MovieLens datasetTo illustrate recomme... | import os
PROJECT = "your-project-here" # REPLACE WITH YOUR PROJECT ID
BUCKET = "your-bucket-here" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["REGION"] = REGION
... | Archive: ml-20m.zip
creating: ml-20m/
inflating: ml-20m/genome-scores.csv
inflating: ml-20m/genome-tags.csv
inflating: ml-20m/links.csv
inflating: ml-20m/movies.csv
inflating: ml-20m/ratings.csv
inflating: ml-20m/README.txt
inflating: ml-20m/tags.csv
Dataset 'c... | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Exploring the dataTwo tables should now be available in BigQuery.Collaborative filtering provides a way to generate product recommendations for users, or user targeting for products. The starting point is a table, movielens.ratings, with three columns: a user id, an item id, and the rating that the user gave the produ... | %%bigquery --project $PROJECT
SELECT *
FROM movielens.ratings
LIMIT 10 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
A quick exploratory query yields that the dataset consists of over 138 thousand users, nearly 27 thousand movies, and a little more than 20 million ratings, confirming that the data has been loaded successfully. | %%bigquery --project $PROJECT
SELECT
COUNT(DISTINCT userId) numUsers,
COUNT(DISTINCT movieId) numMovies,
COUNT(*) totalRatings
FROM movielens.ratings | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
On examining the first few movies using the query following query, we can see that the genres column is a formatted string: | %%bigquery --project $PROJECT
SELECT *
FROM movielens.movies_raw
WHERE movieId < 5 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
We can parse the genres into an array and rewrite the table as follows: | %%bigquery --project $PROJECT
CREATE OR REPLACE TABLE movielens.movies AS
SELECT * REPLACE(SPLIT(genres, "|") AS genres)
FROM movielens.movies_raw
%%bigquery --project $PROJECT
SELECT *
FROM movielens.movies
WHERE movieId < 5 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Matrix factorizationMatrix factorization is a collaborative filtering technique that relies on factorizing the ratings matrix into two vectors called the user factors and the item factors. The user factors is a low-dimensional representation of a user_id and the item factors similarly represents an item_id.We can crea... | %%bigquery --project $PROJECT
CREATE OR REPLACE MODEL movielens.recommender
options(model_type='matrix_factorization',
user_col='userId', item_col='movieId', rating_col='rating')
AS
SELECT
userId, movieId, rating
FROM movielens.ratings
%%bigquery --project $PROJECT
SELECT *
-- Note: remove cloud-training-demo... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Note that we create a model as usual, except that the model_type is matrix_factorization and that we have to identify which columns play what roles in the collaborative filtering setup.What did you get? Our model took an hour to train, and the training loss starts out extremely bad and gets driven down to near-zero ove... | %%bigquery --project $PROJECT
CREATE OR REPLACE MODEL movielens.recommender_l2
options(model_type='matrix_factorization',
user_col='userId', item_col='movieId',
rating_col='rating', l2_reg=0.2)
AS
SELECT
userId, movieId, rating
FROM movielens.ratings
%%bigquery --project $PROJECT
SELECT *
-- Note: re... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Now, we get faster convergence (three iterations instead of five), and a lot less overfitting. Here are our results: Iteration Training Data Loss Evaluation Data Loss Duration (seconds) 2 0.6509 1.4596 198.17 1 1.9829 33,814.3017 1,066.06 0 481,434,346,060.7928 ... | %%bigquery --project $PROJECT
CREATE OR REPLACE MODEL movielens.recommender_16
options(model_type='matrix_factorization',
user_col='userId', item_col='movieId',
rating_col='rating', l2_reg=0.2, num_factors=16)
AS
SELECT
userId, movieId, rating
FROM movielens.ratings
%%bigquery --project $PROJECT
SELE... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
When we did that, we discovered that the evaluation loss was lower (0.97) with num_factors=16 than with num_factors=36 (1.67) or num_factors=24 (1.45). We could continue experimenting, but we are likely to see diminishing returns with further experimentation. So, let’s pick this as the final matrix factorization model ... | %%bigquery --project $PROJECT
SELECT * FROM
ML.PREDICT(MODEL `cloud-training-demos.movielens.recommender_16`, (
SELECT
movieId, title, 903 AS userId
FROM movielens.movies, UNNEST(genres) g
WHERE g = 'Comedy'
))
ORDER BY predicted_rating DESC
LIMIT 5 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Filtering out already rated moviesOf course, this includes movies the user has already seen and rated in the past. Let’s remove them: | %%bigquery --project $PROJECT
SELECT * FROM
ML.PREDICT(MODEL `cloud-training-demos.movielens.recommender_16`, (
WITH seen AS (
SELECT ARRAY_AGG(movieId) AS movies
FROM movielens.ratings
WHERE userId = 903
)
SELECT
movieId, title, 903 AS userId
FROM movielens.movies, UNNEST(genres) g, seen
WH... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
For this user, this happens to yield the same set of movies -- the top predicted ratings didn’t include any of the movies the user has already seen. Customer targetingIn the previous section, we looked at how to identify the top-rated movies for a specific user. Sometimes, we have a product and have to find the custome... | %%bigquery --project $PROJECT
SELECT * FROM
ML.PREDICT(MODEL `cloud-training-demos.movielens.recommender_16`, (
WITH allUsers AS (
SELECT DISTINCT userId
FROM movielens.ratings
)
SELECT
96481 AS movieId,
(SELECT title FROM movielens.movies WHERE movieId=96481) title,
userId
FROM
allU... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Batch predictions for all users and moviesWhat if we wish to carry out predictions for every user and movie combination? Instead of having to pull distinct users and movies as in the previous query, a convenience function is provided to carry out batch predictions for all movieId and userId encountered during training... | %%bigquery --project $PROJECT
SELECT *
FROM ML.RECOMMEND(MODEL `cloud-training-demos.movielens.recommender_16`)
LIMIT 10 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/recommendation_systems/solutions/als_bqml.ipynb | jonesevan007/training-data-analyst |
Downsampling Zarr | from phathom.io.zarr import downsample_zarr
factors = (8, 8, 8)
output_path = os.path.join(working_dir, 'fixed/zarr_down8')
nb_workers = 1
downsample_zarr(fixed_img, factors, output_path, nb_workers)
factors = (8, 8, 8)
output_path = os.path.join(working_dir, 'moving/zarr_down8')
nb_workers = 1
downsample_zarr(moving... | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Downsampling ndarray | from skimage.measure import block_reduce
factors = (16, 16, 16)
def downsample_mean(img, factors):
return block_reduce(img, factors, np.mean, 0)
def downsample_max(img, factors):
return block_reduce(img, factors, np.max, 0)
fixed_downsample = downsample_mean(fixed_img, factors)
moving_downsample = downsampl... | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Gaussian smoothing | from skimage.filters import gaussian
sigma = 1.0
fixed_smooth = gaussian(fixed_downsample, sigma, preserve_range=True)
moving_smooth = gaussian(moving_downsample, sigma, preserve_range=True)
plot_both(fixed_smooth, moving_smooth, viewer) | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Destriping | import pystripe
import multiprocessing
import tqdm
bandwidth = [64, 64]
wavelet = 'db4'
def _filter_streaks(img):
return pystripe.filter_streaks(img, sigma=bandwidth, wavelet=wavelet)
with multiprocessing.Pool(12) as pool:
rf = list(tqdm.tqdm(pool.imap(_filter_streaks, fixed_smooth), total=len(fixed_smooth))... | 100%|██████████| 6/6 [00:00<00:00, 870.73it/s]
100%|██████████| 7/7 [00:00<00:00, 151.45it/s]
9it [00:00, 1582.42it/s]
9it [00:00, 14855.86it/s]
| MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Rigid transformation | from phathom.registration import coarse, pcloud
from phathom import utils
from scipy.ndimage import map_coordinates
t = np.array([0, 0, 0])
thetas = np.array([np.pi/4, 0, 0])
def rigid_warp(img, t, thetas, center, output_shape):
r = pcloud.rotation_matrix(thetas)
idx = np.indices(output_shape)
pts = np.re... | [13.95046336 40.30643648 26.72860826]
[14.57307261 38.4847799 25.10686021]
| MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.