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 |
|---|---|---|---|---|---|
2. Prepare test data- Download test data: PhaseNet picks of the 2019 Ridgecrest earthquake sequence1. picks file: picks.json2. station information: stations.csv3. events in SCSN catalog: events.csv4. config file: config.pkl```bashwget https://github.com/wayneweiqiang/GMMA/releases/download/test_data/test_data.zipunzip... | !wget https://github.com/wayneweiqiang/GMMA/releases/download/test_data/test_data.zip
!unzip test_data.zip
data_dir = lambda x: os.path.join("test_data", x)
station_csv = data_dir("stations.csv")
pick_json = data_dir("picks.json")
catalog_csv = data_dir("catalog_gamma.csv")
picks_csv = data_dir("picks_gamma.csv")
if no... | GaMMA catalog:
| MIT | docs/example_interactive.ipynb | wayneweiqiang/GMMA |
μ€μ²© 쑰건문 nested conditionalμ°μ§ μλ κ²μ΄ μ’μif λΈλμμ λ λ€λ₯Έ if λΈλμ΄ μλ κ² | # μ€μ²© 쑰건문 νμ© μ€μ΅
info = input('input your name, phone number, address, sex: ')
info_list = info.split(', ')
if info_list[0][0] == 'λ°':
if info_list[1][0:3] == '010':
if info_list[2] == 'μμΈ':
if info_list[3] == 'λ¨μ±':
print('μ°λ¦¬κ° μ°Ύλ μ¬λμ
λλ€.')
else:
print('... | input your name, phone number, address, sex: λ°μ°¬νΈ, 01011234567, μμΈ, λ¨μ±
μ°λ¦¬κ° μ°Ύλ μ¬λμ
λλ€.
| MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
λ
Όλ¦¬μ°μ°μλΉκ΅μ°μ°μκ° μ¬λ¬λ² μ¬μ©λ λ νμ©ν¨a < 0 < bμ κ°μ ννλ νμ΄μ¬μμλ§ μ¬μ© κ°λ₯ | a = True
if a == True:
print('μ΄λ κ² μ°μ§ λ§κ². νλ¦° νν')
if a:
print('μ΄λ κ² μ¨μΌλ§ ν¨.')
fruit = ['banana', 'apple', 'pear', 'berry']
answer = input('what is your favorite fruit?: ')
if answer in fruit:
print('we have your favorite food!')
else:
print('we do not have your favorite food!')
option = input('would ... | what is your favorite fruit?: strawberry
we do not have your favorite food!
would you like to add your favorite food? [y/n]: y
now we have ['banana', 'apple', 'pear', 'berry', 'strawberry'] in our list
| MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
λ°λ€ μ½λΌλ¦¬ μ°μ°μλμ
μ°μ°μ + ννμμ λ§λ€μ΄λλ°°μ΄ λ€λ₯Έ λ΄μ©λ€κ³Ό λ¬λ¦¬ μ λ λ§μ΄ μ¨λ³΄μ§ μμ μΈλΆ μλ£λ€μ 보며 μ‘°κΈ λ μμΈν 곡λΆνμκ³ , λ¨μ νμ©ν μ€μ΅μ΄ μλλΌ κ°λ
μ μΈ λΆλΆλ νκΈ°νμμ΅λλ€. | # νμ΄μ¬μ κΈ°λ³Έ μ΄λ
μ ν μ€μ νλμ μλ―Έλ§ λ΄κ²¨μΌλ§ ν¨.
"""
print(student = 'μ² μ') << μ€λ₯κ° λ°μνκ² λ¨.
λμ μ,
student = 'μ² μ'
print(student) << μ΄λ° μμΌλ‘ μμ±νκ±°λ, λ°λ€ μ½λΌλ¦¬ μ°μ°μλ₯Ό νμ©ν΄μΌν¨.
"""
print(student := 'μ² μ')
while s := input('input: '):
if s == 'quit':
break
else:
print('output: ' + s)
print('program ended') | input: hello
output: hello
input: quit
program ended
| MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
Stringλ¬Έμμ΄ | # !pip install nltk => ν°λ―Έλλ‘ ν¨ν€μ§ μ€μΉνλ μ½λ
import nltk
nltk.download('book', quiet=True)
from nltk import book | *** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4... | MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
String λ° nltk μ€μ΅ | genesis = book.text3
genesis_tokens = genesis.tokens
len(genesis_tokens) | _____no_output_____ | MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
μΆκ° κ°μΈ μ€μ΅ | from wordcloud import WordCloud
import matplotlib.pyplot as plt
from collections import Counter
from PIL import Image
import numpy as np
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = set(stopwords.words('english'))
filtered_text = [w for w in genesis_tokens if not w.lower() in s... | _____no_output_____ | MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
Quiz λ΅μ | thursday = book.text9
print(len(set(thursday.tokens)) / len(thursday.tokens))
monty = book.text6
sorted(set(monty.tokens), reverse=True)[:10]
reversed_token = sorted(set(monty.tokens), reverse=True)
reversed_processed_token = []
for token in reversed_token:
if 'z' in token:
token = token.replace('z', 'Z')
... | λΉμ μ μ νλ²νΈλ 010-1234-5678μ
λλ€.
λΉμ μ μ΄λ©μΌμ£Όμλ 1010@gmail.comμ
λλ€.
| MIT | week_03.ipynb | HUFS-Programming-2022/JongbeenSong_202001862 |
Load necessary modules | # show images inline
%matplotlib inline
# automatically reload modules when they have changed
%load_ext autoreload
%autoreload 2
import os
os.environ['CUDA_VISIBLE_DEVICES'] = str(1)
# import keras
import keras
# import keras_retinanet
from keras_retinanet import models
from keras_retinanet.utils.image import read... | Using TensorFlow backend.
| MIT | keras_retinanet/examples/ResNet50RetinaNetcustom.ipynb | MarviB16/CVSP-Object-Detection-Historical-Videos |
Load RetinaNet model | # load label to names mapping for visualization purposes
labels_to_names = {0: 'crowd', 1: 'civilian', 2: 'soldier', 3: 'civil vehicle', 4: 'mv'} | _____no_output_____ | MIT | keras_retinanet/examples/ResNet50RetinaNetcustom.ipynb | MarviB16/CVSP-Object-Detection-Historical-Videos |
Run detection on example | for filename in os.listdir(dataset_path):
image = None
if filename.endswith('.jpg'):
# Open the file:
image = cv2.imread(os.path.join(dataset_path,filename))
if image is not None:
# copy to draw on
draw = image.copy()
draw_regression = image.copy()
draw = cv2... | processing time: 14.983539581298828
processing time: 0.12204432487487793
processing time: 0.09300637245178223
[607.5637 225.40349 737.20013 603.96277] 1 0.88375086
processing time: 0.09206128120422363
[486.1151 155.2592 717.5609 624.07947] 1 0.52050894
processing time: 0.09435248374938965
processing time: 0.0... | MIT | keras_retinanet/examples/ResNet50RetinaNetcustom.ipynb | MarviB16/CVSP-Object-Detection-Historical-Videos |
BAEKJOON 1021λ² λ¬Έμ - νμ νλ νhttps://www.acmicpc.net/problem/1021 λ¬Έμ μ§λ―Όμ΄λ Nκ°μ μμλ₯Ό ν¬ν¨νκ³ μλ μλ°©ν₯ μν νλ₯Ό κ°μ§κ³ μλ€. μ§λ―Όμ΄λ μ΄ νμμ λͺ κ°μ μμλ₯Ό λ½μλ΄λ €κ³ νλ€.μ§λ―Όμ΄λ μ΄ νμμ λ€μκ³Ό κ°μ 3κ°μ§ μ°μ°μ μνν μ μλ€.- 첫λ²μ§Έ μμλ₯Ό λ½μλΈλ€. μ΄ μ°μ°μ μννλ©΄, μλ νμ μμκ° a1, ..., akμ΄μλ κ²μ΄ a2, ..., akμ κ°μ΄ λλ€.- μΌμͺ½μΌλ‘ ν μΉΈ μ΄λμν¨λ€. μ΄ μ°μ°μ μννλ©΄, a1, ..., akκ° a2, ..., ak, a1μ΄ λλ€.- μ€λ₯Έμͺ½μΌλ‘ ν μΉΈ ... | n, m = map(int, input().split())
goal = list(map(int, input().split()))
ls = list(range(1, n+1)) # 1λΆν° nκΉμ§μ 리μ€νΈλ₯Ό λ§λ€μ΄μ goalμ΄ λ°λ‘ ls μμμ match
count = 0
while len(goal) > 0:
if goal[0] == ls[0]:
ls.pop(0)
goal.pop(0)
elif ls.index(goal[0]) <= len(ls) / 2: # goal[0]μ μμΉκ° ls κΈΈμ΄μ λ°λ³΄λ€ μ... | _____no_output_____ | MIT | Algorithm Problems/deque_baekjoon_1021_rotating_queue.ipynb | hyeshinoh/Study_Algorithm |
Zindi - Sentiment Analysis_Tunisian Arabizi.ipynb | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_style("white")
from sklearn.model_selection import train_test_split # function for splitting data to train and test sets
import re, string
import nltk
from nltk.corpus import stopwords
from nltk.cla... | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Data Cleaning | df.head()
positive = df[df['label'] == 1]
negative = df[df['label'] == -1]
df = pd.concat([positive, negative], axis=0)
df.head(10)
df.isna().sum()
df.dropna(inplace=True)
df.isna().sum()
df.duplicated().sum()
test.isna().sum()
test.duplicated().sum() | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Explore Corpus Character Set | from nltk import FreqDist
import re
corpus_as_char_list = "".join(df.text.tolist())
print(type(corpus_as_char_list),len(corpus_as_char_list))
fdist1 = FreqDist([c for c in corpus_as_char_list])
print("number of characters:" + str(fdist1.N()))
print("number of unique characters:" + str(fdist1.B()))
print('List of distin... | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
**Select unwanted characters**For this corpus, unwanted characters are characters in the standard Arabic character set. | idx1 = corpus_chars_df.unicode_hex.str.startswith('0x6')
idx2 = (corpus_chars_df.frequency>=5)
idx1.sum(), idx2.sum(), (idx1&idx2).sum()
unwanted_characters = sorted(corpus_chars_df.loc[~(idx1)].index.tolist())
print(len(unwanted_characters)) | 97
| MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Text Preprocessing | def clean_text(text):
'''Make text lowercase, remove text in square brackets,remove links,remove punctuation
and remove words containing numbers.'''
text = str(text).lower()
#text = re.sub('<.*?>+', '', text)
#text = re.sub("s+"," ", text)
#text = re.sub("[^-9A-Za-z ]", "" , text)
return tex... | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Unwanted characters | '''unwanted_characters_regexp = '[' + ''.join(unwanted_characters) + ']'
unwanted_characters_regexp'''
'''idx = train.text.map(lambda x: re.search(unwanted_characters_regexp,x)!=None)
idx.sum()'''
'''# Words that contain Arabic letters (that will be removed)
print(train.loc[idx].text.tolist())'''
'''train[idx].head()... | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Modelling Split data into train and test | X = train['text']
y = train['label']
# Splitting the dataset into train and test set
from sklearn.model_selection import train_test_split
seed = 12
X_train, X_test, y_train, y_test = train_test_split(X, y,test_size = 0.10, shuffle=True, random_state=0)
X.shape, y.shape | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Logistic Regression | from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, TfidfTransformer
from sklearn.feature_selection import SelectKBest, chi2
# Building a pipeline: We can write less code and do all of the above, by building a pipeline as follows:
# The nam... | ------------------
81.52206100088836
------------------
| MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Tokenization | X_train.shape, y_train.shape
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import LSTM, Conv1D, MaxPooling1D, Dropout
MAX_NB_WORDS = 20000
# get the raw text data
X_train = X_train.astype(str)
X_test = X_test.astype(str)
# finally, vectorize t... | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
The tokenizer object stores a mapping (vocabulary) from word strings to token ids that can be inverted to reconstruct the original message (without formatting): | type(tokenizer.word_index), len(tokenizer.word_index)
index_to_word = dict((i, w) for w, i in tokenizer.word_index.items())
" ".join([index_to_word[i] for i in sequences[0]]) | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Let's have a closer look at the tokenized sequences: | seq_lens = [len(s) for s in sequences]
print("average length: %0.1f" % np.mean(seq_lens))
print("max length: %d" % max(seq_lens))
%matplotlib inline
plt.hist(seq_lens, bins=50);
plt.hist([l for l in seq_lens if l < 30], bins=2);
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape) | (54027,)
(54027,)
(13507,)
(13507,)
| MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
SDGClassifier | # Training Support Vector Machines - SVM and calculating its performance
from sklearn.linear_model import SGDClassifier
text_clf_svm = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()),
('clf-svm', SGDClassifier(loss='hinge', penalty='l2',alpha=1e-9, max_iter=3, shuffle=True... | /usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_stochastic_gradient.py:557: ConvergenceWarning: Maximum number of iteration reached before convergence. Consider increasing max_iter to improve the fit.
ConvergenceWarning)
| MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
MultinomialNB | # Extracting features from text files
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
X_train_counts.shape
# TF-IDF
from sklearn.feature_extraction.text import TfidfTransformer
tfidf_transformer = TfidfTransformer()
X_train_t... | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
SDG Classifier | # Training Support Vector Machines - SVM and calculating its performance
from sklearn.linear_model import SGDClassifier
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
text_clf_svm = Pipeline([('vect', CountVectorizer()),
... | /usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_stochastic_gradient.py:557: ConvergenceWarning: Maximum number of iteration reached before convergence. Consider increasing max_iter to improve the fit.
ConvergenceWarning)
| MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Submission | sub = pd.read_csv("SampleSubmission.csv")
submission = pd.DataFrame()
submission['ID'] = test['ID']
submission.head()
submission.shape
pred = lr_clf.predict(test['text'])
pred
len(pred) | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
The index is still there, so we will set the column ID as the dataframe index. | submission['label'] = pred
submission.set_index('ID', inplace=True)
submission.head() | _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
We have successfully replaced the index with the column ID.Now Let us create our submission file. | submission.to_csv("lr_submission.csv")
| _____no_output_____ | MIT | Zindi_Sentiment_Analysis_Tunisian_Arabizi.ipynb | Paul-mwaura/Zindi-Sentiment-Analysis_Tunisian-Arabizi |
Imports | import numpy as np
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
plt.style.use('seaborn-white') | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Read and process data. Download the file from this URL: https://drive.google.com/file/d/1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS/view?usp=sharing | import gdown
gdown.download('https://drive.google.com/uc?id=1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS','text.txt', quiet=False)
data = open('text.txt', 'r').read() | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Process data and calculate indices | chars = list(set(data))
data_size, X_size = len(data), len(chars)
print("Corona Virus article has %d characters, %d unique characters" %(data_size, X_size))
char_to_idx = {ch:i for i,ch in enumerate(chars)}
idx_to_char = {i:ch for i,ch in enumerate(chars)} | Corona Virus article has 10223 characters, 75 unique characters
| MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Constants and Hyperparameters | Hidden_Layer_size = 100 #size of the hidden layer
Time_steps = 40 # Number of time steps (length of the sequence) used for training
learning_rate = 1e-1 # Learning Rate
weight_sd = 0.1 #Standard deviation of weights for initialization
z_size = Hidden_Layer_size + X_size #Size of concatenation(H, X) vector | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Activation Functions and Derivatives | def sigmoid(x): # sigmoid function
return 1/(1+np.exp(-x))
def dsigmoid(y): # derivative of sigmoid function
return y * (1-y)
def tanh(x): # tanh function
return np.tanh(x)
def dtanh(y): # derivative of tanh
return 1-y*y | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Quiz Question 1What is the value of sigmoid(0) calculated from your code? (Answer up to 1 decimal point, e.g. 4.2 and NOT 4.29999999, no rounding off). Quiz Question 2What is the value of dsigmoid(sigmoid(0)) calculated from your code?? (Answer up to 2 decimal point, e.g. 4.29 and NOT 4.29999999, no rounding off). Q... | print('Quiz 1', sigmoid(0))
print('Quiz 2', dsigmoid(sigmoid(0)))
print('Quiz 3', tanh(dsigmoid(sigmoid(0))))
print('Quiz 4', dtanh(tanh(dsigmoid(sigmoid(0))))) | Quiz 1 0.5
Quiz 2 0.25
Quiz 3 0.24491866240370913
Quiz 4 0.940014848806378
| MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Parameters | class Param:
def __init__(self, name, value):
self.name = name
self.v = value # parameter value
self.d = np.zeros_like(value) # derivative
self.m = np.zeros_like(value) # momentum for Adagrad | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
We use random weights with normal distribution (0, weight_sd) for tanh activation function and (0.5, weight_sd) for `sigmoid` activation function.Biases are initialized to zeros. LSTM You are making this network, please note f, i, c and o (also "v") in the image below::
self.W_f = Param('W_f', np.random.randn(size_a, size_b) * weight_sd + 0.5)
self.b_f = Param('b_f', np.zeros((size_a, 1)))
self.W_i = Param('W_i', np.random.randn(size_a, size_b) * weight_sd + 0... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Look at these operations which we'll be writing:**Concatenation of h and x:**$z\:=\:\left[h_{t-1},\:x\right]$$f_t=\sigma\left(W_f\cdot z\:+\:b_f\:\right)$$i_i=\sigma\left(W_i\cdot z\:+\:b_i\right)$$\overline{C_t}=\tanh\left(W_C\cdot z\:+\:b_C\right)$$C_t=f_t\ast C_{t-1}+i_t\ast \overline{C}_t$$o_t=\sigma\left(W_o\cdot ... | def forward(x, h_prev, C_prev, p = parameters):
assert x.shape == (X_size, 1)
assert h_prev.shape == (Hidden_Layer_size, 1)
assert C_prev.shape == (Hidden_Layer_size, 1)
z = np.row_stack((h_prev, x))
f = sigmoid(np.dot(parameters.all()[0].v, z)+ parameters.all()[5].v)
i = sigmoid(np.dot(par... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
You must finish the function above before you can attempt the questions below. Quiz Question 5What is the output of 'print(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters)))'? | print(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters))) | 9
| MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Quiz Question 6. Assuming you have fixed the forward function, run this command: z, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))Now, find these values:1. print(z.shape)2. print(np.sum(z))3. print(np.sum(f))Copy and paste exact val... | z, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))
print(z.shape)
print(np.sum(z))
print(np.sum(f)) | (175, 1)
0.0
50.0
| MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
BackpropagationHere we are defining the backpropagation. It's too complicated, here is the whole code. (Please note that this would work only if your earlier code is perfect). | def backward(target, dh_next, dC_next, C_prev,
z, f, i, C_bar, C, o, h, v, y,
p = parameters):
assert z.shape == (X_size + Hidden_Layer_size, 1)
assert v.shape == (X_size, 1)
assert y.shape == (X_size, 1)
for param in [dh_next, dC_next, C_prev, f, i, C_bar, C, o, h]:
... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Forward and Backward Combined PassLet's first clear the gradients before each backward pass | def clear_gradients(params = parameters):
for p in params.all():
p.d.fill(0) | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Clip gradients to mitigate exploding gradients | def clip_gradients(params = parameters):
for p in params.all():
np.clip(p.d, -1, 1, out=p.d) | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Calculate and store the values in forward pass. Accumulate gradients in backward pass and clip gradients to avoid exploding gradients.input, target are list of integers, with character indexes.h_prev is the array of initial h at hβ1 (size H x 1)C_prev is the array of initial C at Cβ1 (size H x 1)Returns loss, final... | def forward_backward(inputs, targets, h_prev, C_prev):
global paramters
# To store the values for each time step
x_s, z_s, f_s, i_s, = {}, {}, {}, {}
C_bar_s, C_s, o_s, h_s = {}, {}, {}, {}
v_s, y_s = {}, {}
# Values at t - 1
h_s[-1] = np.copy(h_prev)
C_s[-1] = np.copy(C_prev... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Sample the next character | def sample(h_prev, C_prev, first_char_idx, sentence_length):
x = np.zeros((X_size, 1))
x[first_char_idx] = 1
h = h_prev
C = C_prev
indexes = []
for t in range(sentence_length):
_, _, _, _, C, _, h, _, p = forward(x, h, C)
idx = np.random.choice(range(X_size), p=p.ravel())
... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Training (Adagrad)Update the graph and display a sample output | def update_status(inputs, h_prev, C_prev):
#initialized later
global plot_iter, plot_loss
global smooth_loss
# Get predictions for 200 letters with current model
sample_idx = sample(h_prev, C_prev, inputs[0], 200)
txt = ''.join(idx_to_char[idx] for idx in sample_idx)
# Clear and plot
... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Update Parameters\begin{align}\theta_i &= \theta_i - \eta\frac{d\theta_i}{\sum dw_{\tau}^2} \\d\theta_i &= \frac{\partial L}{\partial \theta_i}\end{align} | def update_paramters(params = parameters):
for p in params.all():
p.m += p.d * p.d # Calculate sum of gradients
#print(learning_rate * dparam)
p.v += -(learning_rate * p.d / np.sqrt(p.m + 1e-8)) | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
To delay the keyboard interrupt to prevent the training from stopping in the middle of an iteration | # Exponential average of loss
# Initialize to a error of a random model
smooth_loss = -np.log(1.0 / X_size) * Time_steps
iteration, pointer = 0, 0
# For the graph
plot_iter = np.zeros((0))
plot_loss = np.zeros((0)) | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Training Loop | iter = 50000
while iter > 0:
# Reset
if pointer + Time_steps >= len(data) or iteration == 0:
g_h_prev = np.zeros((Hidden_Layer_size, 1))
g_C_prev = np.zeros((Hidden_Layer_size, 1))
pointer = 0
inputs = ([char_to_idx[ch]
for ch in data[pointer: pointer + Time_steps]])
targets =... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Quiz Question 7. Run the above code for 50000 iterations making sure that you have 100 hidden layers and time_steps is 40. What is the loss value you're seeing? | iter = 50000
while iter > 0:
# Reset
if pointer + Time_steps >= len(data) or iteration == 0:
g_h_prev = np.zeros((Hidden_Layer_size, 1))
g_C_prev = np.zeros((Hidden_Layer_size, 1))
pointer = 0
inputs = ([char_to_idx[ch]
for ch in data[pointer: pointer + Time_steps]])
targets =... | _____no_output_____ | MIT | S10/EVA P2S3_Q7.ipynb | pankaj90382/TSAI-2 |
Triangle MeshesAlong with [points](2_Points.ipynb), [timeseries](3_Timeseries.ipynb), [trajectories](4_Trajectories.ipynb), and structured [grids](5_Grids.ipynb), Datashader can rasterize large triangular meshes, such as those often used to simulate data on an irregular grid:Any polygon can be represented as a set of ... | import numpy as np, datashader as ds, pandas as pd
import datashader.utils as du, datashader.transfer_functions as tf
from scipy.spatial import Delaunay
import dask.dataframe as dd
n = 10
np.random.seed(2)
x = np.random.uniform(size=n)
y = np.random.uniform(size=n)
z = np.random.uniform(0,1.0,x.shape)
pts = np.stack... | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
Here we have a set of random x,y locations and associated z values. We can see the numeric values with "head" and plot them (with color for z) using datashader's usual points plotting: | cvs = ds.Canvas(plot_height=400,plot_width=400)
tf.Images(verts.head(15), tf.spread(tf.shade(cvs.points(verts, 'x', 'y', agg=ds.mean('z')), name='Points'))) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
To make a trimesh, we need to connect these points together into a non-overlapping set of triangles. One well-established way of doing so is [Delaunay triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation): | def triangulate(vertices, x="x", y="y"):
"""
Generate a triangular mesh for the given x,y,z vertices, using Delaunay triangulation.
For large n, typically results in about double the number of triangles as vertices.
"""
triang = Delaunay(vertices[[x,y]].values)
print('Given', len(vertices), "ver... | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
The result of triangulation is a set of triangles, each composed of three indexes into the vertices array. The triangle data can then be visualized by datashader's ``trimesh()`` method: | tf.Images(tris.head(15), tf.shade(cvs.trimesh(verts, tris))) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
By default, datashader will rasterize your trimesh using z values [linearly interpolated between the z values that are specified at the vertices](https://en.wikipedia.org/wiki/Barycentric_coordinate_systemInterpolation_on_a_triangular_unstructured_grid). The shading will then show these z values as colors, as above. ... | from colorcet import rainbow as c
tf.Images(tf.shade(cvs.trimesh(verts, tris, interpolate='nearest'), cmap=c, name='10 Vertices'),
tf.shade(cvs.trimesh(verts, tris, interpolate='linear'), cmap=c, name='10 Vertices Interpolated')) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
More complex exampleThe small example above should demonstrate how triangle-mesh rasterization works, but in practice datashader is intended for much larger datasets. Let's consider a sine-based function `f` whose frequency varies with radius: | rad = 0.05,1.0
def f(x,y):
rsq = x**2+y**2
return np.where(np.logical_or(rsq<rad[0],rsq>rad[1]), np.nan, np.sin(10/rsq)) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
We can easily visualize this function by sampling it on a raster with a regular grid: | n = 400
ls = np.linspace(-1.0, 1.0, n)
x,y = np.meshgrid(ls, ls)
img = f(x,y)
raster = tf.shade(tf.Image(img, name="Raster"))
raster | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
However, you can see pronounced aliasing towards the center of this function, as the frequency starts to exceed the sampling density of the raster. Instead of sampling at regularly spaced locations like this, let's try evaluating the function at random locations whose density varies towards the center: | def polar_dropoff(n, r_start=0.0, r_end=1.0):
ls = np.linspace(0, 1.0, n)
ex = np.exp(2-5*ls)/np.exp(2)
radius = r_start+(r_end-r_start)*ex
theta = np.random.uniform(0.0,1.0, n)*np.pi*2.0
x = radius * np.cos( theta )
y = radius * np.sin( theta )
return x,y
x,y = polar_dropoff(n*n, np.sqrt(... | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
We can now plot the x,y points and optionally color them with the z value (the value of the function f(x,y)): | cvs = ds.Canvas(plot_height=400,plot_width=400)
tf.Images(tf.shade(cvs.points(verts, 'x', 'y'), name='Points'),
tf.shade(cvs.points(verts, 'x', 'y', agg=ds.mean('z')), name='PointsZ')) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
The points are clearly covering the area of the function that needs dense sampling, and the shape of the function can (roughly) be made out when the points are colored in the plot. But let's go ahead and triangulate so that we can interpolate between the sampled values for display: | %time tris = triangulate(verts) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
And let's pre-compute the combined mesh data structure for these vertices and triangles, which for very large meshes (much larger than this one!) would save plotting time later: | %time mesh = du.mesh(verts,tris) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
This mesh can be used for all future plots as long as we don't change the number or ordering of vertices or triangles, which saves time for much larger grids.We can now plot the trimesh to get an approximation of the function with noisy sampling locally to disrupt the interference patterns observed in the regular-grid ... | tf.shade(cvs.trimesh(verts, tris, mesh=mesh)) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
The fine detail in the heavily sampled regions is visible when zooming in closer (without resampling the function): | tf.Images(*([tf.shade(ds.Canvas(x_range=r, y_range=r).trimesh(verts, tris, mesh=mesh))
for r in [(0.1,0.8), (0.14,0.4), (0.15,0.2)]])) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
Notice that the central disk is being filled in above, even though the function is not defined in the center. That's a limitation of Delaunay triangulation, which will create convex regions covering the provided vertices. You can use other tools for creating triangulations that have holes, align along certain regions... | tf.Images(tf.shade(cvs.trimesh(verts, tris, mesh=mesh, agg=ds.mean('z')),name='mean'),
tf.shade(cvs.trimesh(verts, tris, mesh=mesh, agg=ds.max('z')), name='max'),
tf.shade(cvs.trimesh(verts, tris, mesh=mesh, agg=ds.min('z')), name='min')) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
The three plots above should be nearly identical, except near the center disk where individual pixels start to have contributions from a large number of triangles covering different portions of the function space. In this inner ring, ``mean`` reports the average value of the surface inside that pixel, ``max`` reports ... | tf.Images(tf.shade(cvs.trimesh(verts, tris, mesh=mesh, agg=ds.any('z')), name='any'),
tf.shade(cvs.trimesh(verts, tris, mesh=mesh, agg=ds.count()), name='count'),
tf.shade(cvs.trimesh(verts, tris, mesh=mesh, agg=ds.std('z')), name='std')).cols(3) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
Parallelizing trimesh aggregation with DaskThe trimesh aggregation process can be parallelized by providing `du.mesh` and `Canvas.trimesh` with partitioned Dask dataframes.**Note:** While the calls to `Canvas.trimesh` will be parallelized across the partitions of the Dask dataframe, the construction of the partitioned... | verts_ddf = dd.from_pandas(verts, npartitions=4)
tris_ddf = dd.from_pandas(tris, npartitions=4)
mesh_ddf = du.mesh(verts_ddf, tris_ddf)
mesh_ddf
tf.shade(cvs.trimesh(verts_ddf, tris_ddf, mesh=mesh_ddf)) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
Interactive plotsBy their nature, fully exploring irregular grids needs to be interactive, because the resolution of the screen and the visual system are fixed. Trimesh renderings can be generated as above and then displayed interactively using the datashader support in [HoloViews](http://holoviews.org). | import holoviews as hv
from holoviews.operation.datashader import datashade
hv.extension("bokeh") | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
HoloViews is designed to make working with data easier, including support for large or small trimeshes. With HoloViews, you first declare a ``hv.Trimesh`` object, then you apply the ``datashade()`` (or just ``aggregate()``) operation if the data is large enough to require datashader. Notice that HoloViews expects the ... | wireframe = datashade(hv.TriMesh((tris,verts), label="Wireframe").edgepaths)
trimesh = datashade(hv.TriMesh((tris,hv.Points(verts, vdims='z')), label="TriMesh"), aggregator=ds.mean('z'))
(wireframe + trimesh).opts(width=400, height=400) | _____no_output_____ | BSD-3-Clause | examples/user_guide/6_Trimesh.ipynb | odidev/datashader |
Reformer Efficient Attention: Ungraded LabThe videos describe two 'reforms' made to the Transformer to make it more memory and compute efficient. The *Reversible Layers* reduce memory and *Locality Sensitive Hashing(LSH)* reduces the cost of the Dot Product attention for large input sizes. This ungraded lab will look ... | import os
import trax
from trax import layers as tl # core building block
import jax
from trax import fastmath # uses jax, offers numpy on steroids
# fastmath.use_backend('tensorflow-numpy')
import functools
from trax.fastmath import numpy as np # note, using fastmath subset of numpy!
from trax.layers import (
... | INFO:tensorflow:tokens_length=568 inputs_length=512 targets_length=114 noise_density=0.15 mean_noise_span_length=3.0
| MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Part 2 Full Dot-Product Self Attention Part 2.1 DescriptionFigure 3: Project datapath and primary data structures and where they are implementedThe diagram above shows many of the familiar data structures and operations related to attention and describes the routines in which they are implemented. We will start by wo... | def mask_self_attention(
dots, q_info, kv_info, causal=True, exclude_self=True, masked=False
):
"""Performs masking for self-attention."""
if causal:
mask = fastmath.lt(q_info, kv_info).astype(np.float32)
dots = dots - 1e9 * mask
if exclude_self:
mask = np.equal(q_info, kv_info).... | _____no_output_____ | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
A SoftMax is applied per row of the *Dot* matrix to scale the values in the row between 0 and 1.Figure 6: SoftMax per row of Dot Part 2.1.1 our_softmax This code uses a separable form of the softmax calculation. Recall the softmax:$$ softmax(x_i)=\frac{\exp(x_i)}{\sum_j \exp(x_j)}\tag{1}$$This can be alternately imple... | def our_softmax(x, passthrough=False):
""" softmax with passthrough"""
logsumexp = fastmath.logsumexp(x, axis=-1, keepdims=True)
o = np.exp(x - logsumexp)
if passthrough:
return (x, np.zeros_like(logsumexp))
else:
return (o, logsumexp) | _____no_output_____ | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Let's check our implementation. | ## compare softmax(a) using both methods
a = np.array([1.0, 2.0, 3.0, 4.0])
sma = np.exp(a) / sum(np.exp(a))
print(sma)
sma2, a_logsumexp = our_softmax(a)
print(sma2)
print(a_logsumexp) | [0.0320586 0.08714432 0.2368828 0.6439142 ]
[0.0320586 0.08714431 0.23688279 0.64391416]
[4.44019]
| MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
The purpose of the dot-product is to 'focus attention' on some of the inputs. Dot now has entries appropriately scaled to enhance some values and reduce others. These are now applied to the $V$ entries.Figure 7: Applying Attention to $V$$V$ is of size (n_seq,n_v). Note the shading in the diagram. This is to draw attent... | def our_simple_attend(
q,
k=None,
v=None,
mask_fn=None,
q_info=None,
kv_info=None,
dropout=0.0,
rng=None,
verbose=False,
passthrough=False,
):
"""Dot-product attention, with masking, without optional chunking and/or.
Args:
q: Query vectors, shape [q_len, d_qk]
k: ... | Our attend dots (8, 8)
Our attend dots post softmax (8, 8) (8, 1)
Our attend out1 (8, 4)
Our attend out2 (8, 4)
[[0.5606324 0.7290605 0.5251243 0.47101074]
[0.5713517 0.71991956 0.5033342 0.46975708]
[0.5622886 0.7288458 0.52172124 0.46318397]
[0.5568317 0.72234154 0.542236 0.4699722 ]
[0.56504494 0.72274... | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Expected Output **Expected Output**```Our attend dots (8, 8)Our attend dots post softmax (8, 8) (8, 1)Our attend out1 (8, 4)Our attend out2 (8, 4)[[0.5606324 0.7290605 0.5251243 0.47101074] [0.5713517 0.71991956 0.5033342 0.46975708] [0.5622886 0.7288458 0.52172124 0.46318397] [0.5568317 0.72234154 0.54223... | class OurSelfAttention(tl.SelfAttention):
"""Our self-attention. Just the Forward Function."""
def forward_unbatched(
self, x, mask=None, *, weights, state, rng, update_state, verbose=False
):
print("ourSelfAttention:forward_unbatched")
del update_state
attend_rng, output_rn... | ourSelfAttention:forward_unbatched
x.shape,w_q.shape (8, 5) (5, 3)
Our attend dots (8, 8)
Our attend dots post softmax (8, 8) (8, 1)
Our attend out1 (8, 4)
Our attend out2 (8, 4)
ourSelfAttention:forward_unbatched
x.shape,w_q.shape (8, 5) (5, 3)
Our attend dots (8, 8)
Our attend dots post softmax (8, 8) (8, 1)
Our atte... | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Expected Output **Expected Output**Notice a few things:* the w_q (and w_k) matrices are applied to each row or each embedding on the input. This is similar to the filter operation in convolution* forward_unbatched is called 3 times. This is because we have 3 heads in this example.```ourSelfAttention:forward_unbatc... | def our_hash_vectors(vecs, rng, n_buckets, n_hashes, mask=None, verbose=False):
"""
Args:
vecs: tensor of at least 2 dimension,
rng: random number generator
n_buckets: number of buckets in each hash table
n_hashes: the number of hash tables
mask: None indicating no mask or a 1D boolean array... | random.rotations.shape (5, 3, 2)
random_rotations reshaped (5, 6)
rotated_vecs1 (8, 6)
rotated_vecs2 (8, 3, 2)
rotated_vecs3 (3, 8, 2)
rotated_vecs.shape (3, 8, 4)
buckets.shape (3, 8)
buckets ndarray<tf.Tensor(
[[3 3 3 3 3 3 3 3]
[3 3 3 3 3 3 3 3]
[3 3 3 3 3 3 3 3]], shape=(3, 8), dtype=int32)>
buckets with offsets ... | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Expected Output **Expected Values**```random.rotations.shape (5, 3, 2)random_rotations reshaped (5, 6)rotated_vecs1 (8, 6)rotated_vecs2 (8, 3, 2)rotated_vecs3 (3, 8, 2)rotated_vecs.shape (3, 8, 4)buckets.shape (3, 8)buckets ndarray<tf.Tensor([[3 3 3 3 3 3 3 3] [3 3 3 3 3 3 3 3] [3 3 3 3 3 3 3 3]], shape=(3, 8), dt... | def sort_buckets(buckets, q, v, n_buckets, n_hashes, seqlen, verbose=True):
"""
Args:
buckets: tensor of at least 2 dimension,
n_buckets: number of buckets in each hash table
n_hashes: the number of hash tables
"""
if verbose:
print("---sort_buckets--")
## Step 1
ticker =... | q
[[0. 0. 0.]
[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]
[0. 0. 0.]
[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]]
t_buckets: [0 1 2 3 0 1 2 3 4 5 6 7 4 5 6 7]
---sort_buckets--
ticker (16,) [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
buckets_and_t (16,) [ 0 9 18 27 4 13 22 31 32 41 50 59 36 45 54 63]
sbuckets_and_t (16,) [ ... | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Expected Output **Expected Values**```q [[0. 0. 0.] [1. 1. 1.] [2. 2. 2.] [3. 3. 3.] [0. 0. 0.] [1. 1. 1.] [2. 2. 2.] [3. 3. 3.]]t_buckets: [0 1 2 3 0 1 2 3 4 5 6 7 4 5 6 7]---sort_buckets--ticker (16,) [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]buckets_and_t (16,) [ 0 9 18 27 4 13 22 31 32 41 50 59 36 45... | a = np.arange(16 * 3).reshape((16, 3))
chunksize = 2
ar = np.reshape(
a, (-1, chunksize, a.shape[-1])
) # the -1 usage is very handy, see numpy reshape
print(ar.shape) | (8, 2, 3)
| MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
**Instructions****Step 1** Reshaping Q* np.reshape `sq` (sorted q) to be 3 dimensions. The middle dimension is the size of the 'chunk' specified by `kv_chunk_len`* np.swapaxes to perform a 'transpose' on the reshaped `sq`, *but only on the last two dimension** np.matmul the two values.**Step 2*** use our_softmax to per... | def dotandv(sq, sv, undo_sort, kv_chunk_len, n_hashes, seqlen, passthrough, verbose=False ):
# Step 1
rsq = np.reshape(sq,(-1, kv_chunk_len, sq.shape[-1]))
rsqt = np.swapaxes(rsq, -1, -2)
if verbose: print("rsq.shape,rsqt.shape: ", rsq.shape,rsqt.shape)
dotlike = np.matmul(rsq, rsqt)
if verbose... | rsq.shape,rsqt.shape: (8, 2, 3) (8, 3, 2)
dotlike
[[[ 0. 0.]
[ 0. 0.]]
[[ 3. 3.]
[ 3. 3.]]
[[12. 12.]
[12. 12.]]
[[27. 27.]
[27. 27.]]
[[ 0. 0.]
[ 0. 0.]]
[[ 3. 3.]
[ 3. 3.]]
[[12. 12.]
[12. 12.]]
[[27. 27.]
[27. 27.]]]
dotlike post softmax
[[[ 0. 0.]
[ 0. 0.]]
[[ 3. 3.]
... | MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Expected Output **Expected Values**```rsq.shape,rsqt.shape: (8, 2, 3) (8, 3, 2)dotlike [[[ 0. 0.] [ 0. 0.]] [[ 3. 3.] [ 3. 3.]] [[12. 12.] [12. 12.]] [[27. 27.] [27. 27.]] [[ 0. 0.] [ 0. 0.]] [[ 3. 3.] [ 3. 3.]] [[12. 12.] [12. 12.]] [[27. 27.] [27. 27.]]]dotlike post softmax [[[ 0. 0.] [ 0. 0.... | # original version from trax 1.3.4
def attend(
q,
k=None,
v=None,
q_chunk_len=None,
kv_chunk_len=None,
n_chunks_before=0,
n_chunks_after=0,
mask_fn=None,
q_info=None,
kv_info=None,
dropout=0.0,
rng=None,
):
"""Dot-product attention, with optional chunking and/or maski... | using jax
using jax
using jax
| MIT | Natural Language Processing Specialization/chatbot/C4_W4_Ungraded_Lab_Reformer_LSH.ipynb | aibenStunner/NLP-specialization |
Exercise 5 - Variational quantum eigensolver Historical backgroundDuring the last decade, quantum computers matured quickly and began to realize Feynman's initial dream of a computing system that could simulate the laws of nature in a quantum way. A 2014 paper first authored by Alberto Peruzzo introduced the **Variati... | from qiskit_nature.drivers import PySCFDriver
molecule = "H .0 .0 .0; H .0 .0 0.739"
driver = PySCFDriver(atom=molecule)
qmolecule = driver.run() | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
Tutorial questions 1 Look into the attributes of `qmolecule` and answer the questions below. 1. We need to know the basic characteristics of our molecule. What is the total number of electrons in your system?2. What is the number of molecular orbitals?3. What is the number of spin-orbitals?3. How many qubit... | from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver)
# Generate the second-quantized operators
second_q_ops = problem.second_q_ops()
# Hamiltonian
main_op = second_q_ops[0] | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
3. QubitConverterAllows to define the mapping that you will use in the simulation. You can try different mapping but we will stick to `JordanWignerMapper` as allows a simple correspondence: a qubit represents a spin-orbital in the molecule. | from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'JordanWignerMapper'
if mapper_type == 'ParityMapper':
mapper = Pa... | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
4. Initial stateAs we described in the Theory section, a good initial state in chemistry is the HF state (i.e. $|\Psi_{HF} \rangle = |0101 \rangle$). We can initialize it as follows: | from qiskit_nature.circuit.library import HartreeFock
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals
init_state = HartreeFock(num_spin_orbitals, num_particles, conver... | βββββ
q_0: β€ X β
βββββ
q_1: βββββ
βββββ
q_2: β€ X β
βββββ
q_3: βββββ
| Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
5. AnsatzOne of the most important choices is the quantum circuit that you choose to approximate your ground state.Here is the example of qiskit circuit library that contains many possibilities for making your own circuit. | from qiskit.circuit.library import TwoLocal
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
# Choose the ansatz
ansatz_type = "TwoLocal"
# Parameters for q-UCC antatze
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals... | βββββ ββββββββββββββββββββββββ ββββββββββββΒ»
q_0: ββββ€ X ββββββ€ RY(ΞΈ[0]) ββ€ RZ(ΞΈ[4]) ββββ βββββ ββββββββββ βββ€ RY(ΞΈ[8]) βΒ»
ββββ΄ββββ΄ββββββββββββββββ€βββββββββββββββ΄ββ β β ββββββββββββΒ»
q_1: β€ RY(ΞΈ[1]) ββ€ RZ(ΞΈ[5]) ββββββββββββββ€ X ββββΌβββββ βββββΌββββββββ ββββββΒ»
ββββ¬ββββ¬βββββββ... | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
6. BackendThis is where you specify the simulator or device where you want to run your algorithm.We will focus on the `statevector_simulator` in this challenge. | from qiskit import Aer
backend = Aer.get_backend('statevector_simulator') | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
7. OptimizerThe optimizer guides the evolution of the parameters of the ansatz so it is very important to investigate the energy convergence as it would define the number of measurements that have to be performed on the QPU.A clever choice might reduce drastically the number of needed energy evaluations. | from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
optimizer_type = 'COBYLA'
# You may want to tune the parameters
# of each optimizer, here the defaults are used
if optimizer_type == 'COBYLA':
optimizer = COBYLA(maxiter=500)
elif optimizer_type == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun=... | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
8. Exact eigensolverFor learning purposes, we can solve the problem exactly with the exact diagonalization of the Hamiltonian matrix so we know where to aim with VQE.Of course, the dimensions of this matrix scale exponentially in the number of molecular orbitals so you can try doing this for a large molecule of your c... | from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc ... | Exact electronic energy -1.8533636186720424
=== GROUND STATE ENERGY ===
* Electronic ground state energy (Hartree): -1.853363618672
- computed part: -1.853363618672
~ Nuclear repulsion energy (Hartree): 0.716072003951
> Total ground state energy (Hartree): -1.137291614721
=== MEASURED OBSERVABLES ===
0: ... | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
9. VQE and initial parameters for the ansatzNow we can import the VQE class and run the algorithm. | from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=T... | OrderedDict([ ('aux_operator_eigenvalues', None),
('cost_function_evals', 500),
( 'eigenstate',
array([ 1.72642837e-07+8.50403202e-06j, -1.78929971e-04-1.81951230e-05j,
-3.69523167e-06-1.34495890e-05j, -2.10924080e-04+1.77214969e-04j,
4.99046244e-06... | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
9. Scoring function We need to judge how good are your VQE simulations, your choice of ansatz/optimizer.For this, we implemented the following simple scoring function:$$ score = N_{CNOT}$$where $N_{CNOT}$ is the number of CNOTs. But you have to reach the chemical accuracy which is $\delta E_{chem} = 0.004$ Ha $= 4$ mH... | # Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
score = cnots
accuracy_t... | _____no_output_____ | Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
Tutorial questions 2 Experiment with all the parameters and then:1. Can you find your best (best score) heuristic ansatz (by modifying parameters of `TwoLocal` ansatz) and optimizer?2. Can you find your best q-UCC ansatz (choose among `UCCSD, PUCCD or SUCCD` ansatzes) and optimizer?3. In the cell where we define th... | from qiskit_nature.drivers import PySCFDriver
molecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474'
driver = PySCFDriver(atom=molecule)
qmolecule = driver.run()
from qiskit_nature.transformers import FreezeCoreTransformer, ActiveSpaceTransformer
from qiskit_nature.problems.second_quantization.electronic import ElectronicStr... | Submitting your answer for ex5. Please wait...
Success π! Your answer has been submitted.
| Apache-2.0 | solutions by participants/ex5/ex5-MichaelRollin-3cnot-?mHa-24params.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
Computer Vision Nanodegree Project: Image Captioning---In this notebook, you will learn how to load and pre-process data from the [COCO dataset](http://cocodataset.org/home). You will also design a CNN-RNN model for automatically generating image captions.Note that **any amendments that you make to this notebook will ... | import sys
sys.path.append('./cocoapi/PythonAPI')
from pycocotools.coco import COCO
!pip install nltk
import nltk
nltk.download('punkt')
from data_loader import get_loader
from torchvision import transforms
cocoapi_loc = '/mnt/data2/Project/Image-Captioning/'
# Define a transform to pre-process the training images.
t... | Requirement already satisfied: nltk in /home/hvlpr/anaconda3/lib/python3.7/site-packages (3.4.1)
Requirement already satisfied: six in /home/hvlpr/anaconda3/lib/python3.7/site-packages (from nltk) (1.12.0)
loading annotations into memory...
Done (t=0.46s)
creating index...
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
When you ran the code cell above, the data loader was stored in the variable `data_loader`. You can access the corresponding dataset as `data_loader.dataset`. This dataset is an instance of the `CoCoDataset` class in **data_loader.py**. If you are unfamiliar with data loaders and datasets, you are encouraged to revi... | sample_caption = 'A person doing a trick on a rail while riding a skateboard.' | _____no_output_____ | MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
In **`line 1`** of the code snippet, every letter in the caption is converted to lowercase, and the [`nltk.tokenize.word_tokenize`](http://www.nltk.org/) function is used to obtain a list of string-valued tokens. Run the next code cell to visualize the effect on `sample_caption`. | import nltk
sample_tokens = nltk.tokenize.word_tokenize(str(sample_caption).lower())
print(sample_tokens) | ['a', 'person', 'doing', 'a', 'trick', 'on', 'a', 'rail', 'while', 'riding', 'a', 'skateboard', '.']
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
In **`line 2`** and **`line 3`** we initialize an empty list and append an integer to mark the start of a caption. The [paper](https://arxiv.org/pdf/1411.4555.pdf) that you are encouraged to implement uses a special start word (and a special end word, which we'll examine below) to mark the beginning (and end) of a cap... | sample_caption = []
start_word = data_loader.dataset.vocab.start_word
print('Special start word:', start_word)
sample_caption.append(data_loader.dataset.vocab(start_word))
print(sample_caption) | Special start word: <start>
[0]
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
In **`line 4`**, we continue the list by adding integers that correspond to each of the tokens in the caption. | sample_caption.extend([data_loader.dataset.vocab(token) for token in sample_tokens])
print(sample_caption) | [0, 3, 98, 754, 3, 396, 39, 3, 1009, 207, 139, 3, 753, 18]
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
In **`line 5`**, we append a final integer to mark the end of the caption. Identical to the case of the special start word (above), the special end word (`""`) is decided when instantiating the data loader and is passed as a parameter (`end_word`). You are **required** to keep this parameter at its default value (`en... | end_word = data_loader.dataset.vocab.end_word
print('Special end word:', end_word)
sample_caption.append(data_loader.dataset.vocab(end_word))
print(sample_caption) | Special end word: <end>
[0, 3, 98, 754, 3, 396, 39, 3, 1009, 207, 139, 3, 753, 18, 1]
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
Finally, in **`line 6`**, we convert the list of integers to a PyTorch tensor and cast it to [long type](http://pytorch.org/docs/master/tensors.htmltorch.Tensor.long). You can read more about the different types of PyTorch tensors on the [website](http://pytorch.org/docs/master/tensors.html). | import torch
sample_caption = torch.Tensor(sample_caption).long()
print(sample_caption) | tensor([ 0, 3, 98, 754, 3, 396, 39, 3, 1009, 207, 139, 3,
753, 18, 1])
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
And that's it! In summary, any caption is converted to a list of tokens, with _special_ start and end tokens marking the beginning and end of the sentence:```[, 'a', 'person', 'doing', 'a', 'trick', 'while', 'riding', 'a', 'skateboard', '.', ]```This list of tokens is then turned into a list of integers, where every d... | # Preview the word2idx dictionary.
dict(list(data_loader.dataset.vocab.word2idx.items())[:10]) | _____no_output_____ | MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
We also print the total number of keys. | # Print the total number of keys in the word2idx dictionary.
print('Total number of tokens in vocabulary:', len(data_loader.dataset.vocab)) | Total number of tokens in vocabulary: 8856
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
As you will see if you examine the code in **vocabulary.py**, the `word2idx` dictionary is created by looping over the captions in the training dataset. If a token appears no less than `vocab_threshold` times in the training set, then it is added as a key to the dictionary and assigned a corresponding unique integer. ... | # Modify the minimum word count threshold.
vocab_threshold = 4
# Obtain the data loader.
data_loader = get_loader(transform=transform_train,
mode='train',
batch_size=batch_size,
vocab_threshold=vocab_threshold,
cocoapi_... | Total number of tokens in vocabulary: 9955
| MIT | 1_Preliminaries.ipynb | lanhhv84/Image-Captioning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.