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 |
|---|---|---|---|---|---|
Avarage node degree | avg_degree = n_edges/n_nodes
avg_degree | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Approach 2 Although, since we need the average in and out degree because our graph is directed, we could use an easy command nx.info as follow, in order to obtain the basic informations.First import the graph from the reduced file of the list of edges indicating with nx.DiGraph that what we want is an oriented graph. | graph = nx.read_edgelist("wiki-topcats-reduced.txt", delimiter="\t", create_using=nx.DiGraph())
print(nx.info(graph)) | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
**Is the graph dense?**With the following formula $D=\frac{E}{N(N-1)}$ we obtain a value that could go from 0 up to 1. It measure the probability that any pairs of vertex is connected, so technically if the density is close to 1 the number of edges is close to the maximal number of edges, viceversa if the density is cl... | nx.density(graph) | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
As we could expect, according to the number of nodes and edges that we already know, the density is very low, so it means that our graph is sparse. RQ2 Let's start creating a dictionary called categories where for every category taken from wiki-topcats-categories.txt file, we have the list of all its articles. But att... | C = open('wiki-topcats-categories.txt','r')
categories = {}
for line in C.readlines():
l = line.split(' ')
cat = l[0].replace("Category:","").replace(";", "")
art = l[1:]
art[-1] = art[-1].replace("\n","")
if len(art) >= 3500:
categories[cat]= set(art).intersection(set(V))
all_set = categ... | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Block Ranking Our scope now is, to take in input a category $C_0 = \{article_1, article_2, \dots \}$. Then we want to rank all of the nodes according to the following criterion:Obtain a block-ranking, where the blocks are represented by the categories.The first category of the rank, $C_0$, always corresponds to the i... | input_category = input()
def ShortestPath(c0, graph):
queue = []
queue.append(c0)
distanceDict = dict()
for node in graph:
distanceDict[node] = -1
distanceDict[c0] = 0
while queue:
vertex = queue.pop(0)
for i in graph[vertex]:
if distanceDict[i] == -1:
... | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Obtained the Ordered Dictionary rank we notice that there are some categories with median equal to -1. This means that these categories are not reachable from the input category and so the values of distance among their nodes and the input category ones didn't change its initial values -1 associated during the iniziali... | all_cat = list(categories.keys())
def in_edges(cat, graph):
n_cat = categories[cat]
d = {}
for n1 in tqdm(n_cat):
count = 0
for n2 in graph:
if n1 in graph[n2] and n2 in n_cat:
count += 1
d[n1] = count
d = sorted(d.items(), key=lambda x: x[1])
retu... | _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Here there is the indexing dictionary, that occurs to us to find the in_edge dictionary of a particular category, starting from its index. Here, as promised, we have the dictionary for the category 0 of our block ranking, or in other words, the category7 of our indexing.For convention we print just a portion of it, in ... | with open("cat"+str(7)+".p", 'rb') as handle:
dd7 = pickle.load(handle)
print(dd7[1600:1700])
| _____no_output_____ | MIT | homework_5.ipynb | pavanalikana/Visit-the-Wikipedia-hyperlinks-graph- |
Multi-wavelength mapsNew in version `0.2.1` is the ability for users to instantiate wavelength-dependent maps. Nearly all of the computational overhead in `starry` comes from computing rotation matrices and integrals of the Green's basis functions, which makes it **really** fast to compute light curves at different wa... | %matplotlib inline
from starry import Map
map = Map(lmax=2, nwav=3) | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
Recall that the map coefficients are now *vectors*. Here's what the coefficient *matrix* now looks like: | map.y | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
Each row corresponds to a given spherical harmonic, and each column to a given wavelength bin. Let's set the $Y_{1,0}$ coefficient: | map[1, 0] = [0.3, 0.4, 0.5] | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
Here's our new map vector: | map.y | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
To visualize the map, we can call `map.show()` as usual, but now we actually get an *animation* showing us what the map looks like at each wavelength. | map.show() | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
(*Caveat: the* `map.animate()` *routine is disabled for multi-wavelength maps.*) Let's set a few more coefficients: | map[1, -1] = [0, 0.1, -0.1]
map[2, -1] = [-0.1, -0.2, -0.1]
map[2, 2] = [0.3, 0.2, 0.1]
map.show() | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
OK, our map now has some interesting wavelength-dependent features. Let's compute some light curves! First, a simple phase curve: | import numpy as np
theta = np.linspace(0, 360, 1000)
map.axis = [0, 1, 0]
phase_curve = map.flux(theta=theta) | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
Let's plot it. The blue line is the first wavelength bin, the orange line is the second bin, and the green line is the third: | import matplotlib.pyplot as pl
%matplotlib inline
fig, ax = pl.subplots(1, figsize=(14, 6))
ax.plot(theta, phase_curve);
ax.set_xlabel(r'$\theta$ (degrees)', fontsize=16)
ax.set_ylabel('Flux', fontsize=16); | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
We can also compute an occultation light curve: | xo = np.linspace(-1.5, 1.5, 1000)
light_curve = map.flux(xo=xo, yo=0.2, ro=0.1) | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
Let's plot it. This time we normalize the light curve by the baseline for better plotting, since the map has a different total flux at each wavelength: | fig, ax = pl.subplots(1, figsize=(14, 6))
ax.plot(theta, light_curve / light_curve[0]);
ax.set_xlabel('Occultor position', fontsize=16)
ax.set_ylabel('Flux', fontsize=16); | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
As we mentioned above, there's not that much overhead to computing light curves in many different wavelength bins. Check it out: | import time
np.random.seed(1234)
def runtime(nwav, N=10):
total_time = 0
xo = np.linspace(-1.5, 1.5, 1000)
for n in range(N):
map = Map(lmax=2, nwav=nwav)
map[:, :] = np.random.randn(9, nwav)
tstart = time.time()
map.flux(xo=xo, yo=0.2, ro=0.1)
total_time += time.time... | _____no_output_____ | BSD-3-Clause | sparse/repos/rodluger/starry/binder/Basics 5 - Multi-wavelength maps.ipynb | yuvipanda/mybinder.org-analytics |
Machine Learning- Exoplanet Exploration Extensive Data Dictionary: https://exoplanetarchive.ipac.caltech.edu/docs/API_kepcandidate_columns.htmlHighlightable columns of note are:* kepoi_name: A KOI is a target identified by the Kepler Project that displays at least one transit-like sequence within Kepler time-series p... | # # Update sklearn to prevent version mismatches
# !pip install sklearn --upgrade
# # install joblib
# !pip install joblib | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Import Dependencies | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Hide warning messages in notebook
import warnings
warnings.filterwarnings('ignore') | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Read the CSV and Perform Basic Data Cleaning | # Read/Load CSV file
df = pd.read_csv("exoplanet_data.csv")
# Drop the null columns where all values are null
df = df.dropna(axis='columns', how='all')
# Drop the null rows
df = df.dropna()
df.head() | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Basic Statistic Details | df.describe() | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Select Features (columns)* Feature Selection: Removing irrelevant feature results in better performing model that is easeir to understands & model runs faster | target_names = df["koi_disposition"].unique()
#target_names
print(df["koi_disposition"].unique())
# Assign X (Independant data) and y (Dependant target)
# Set X equal to the entire data set, except for the first column
X = df.iloc[:, 1:]
# X.head()
# Set y equal to the first column
y = df.iloc[:,0].values.reshape(-1,... | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Create a Train Test Split | from sklearn.model_selection import train_test_split
# Split the data into smaller buckets for training and testing
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
X_train.head()
# X and y Train shape have 5243 rows (80% of data)
X_train.shape, y_train.shape
# X and y Test shape have 1748 row... | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Pre-processingScale the data using the MinMaxScalerMinMaxScaler: * A way to normalize the input features/variables * Features will be transformed into the range * Scales the range of fetures from 0 to 1 | from sklearn.preprocessing import MinMaxScaler
# Create a MinMaxScaler model and fit it to the training data
X_scaler = MinMaxScaler().fit(X_train)
# Transform the training and testing data using the X_scaler
X_train_scaled = X_scaler.transform(X_train)
X_test_scaled = X_scaler.transform(X_test)
#print(np.matrix(X_t... | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Train the Model * Used Random Forest Model | from sklearn.ensemble import RandomForestClassifier
# Create a Randome Forest Model
model = RandomForestClassifier(n_estimators=200)
# Train (Fit) the model to the data
model.fit(X_train_scaled, y_train)
# Score/Validate the model using the test data
print(f"Training Data Score: {'%.3f' % model.score (X_train_scale... | Training Data Score: 1.000
Testing Data Score: 0.891
| BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Model Accuracy | # Predicting the Test set results
y_predic = model.predict(X_test)
# Making the confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_predic)
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_predic)
print('Test Model Accurracy: %.3f' % (accuracy)) | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Prediction | predictions = model.predict(X_test_scaled)
# print(f"first 10 Predictions{predictions[:10].tolist()}")
# print(f"first 10 Actual{y_test[:10].tolist()}")
# Printing into a Dataframe (y_test can't be reshap on top)
df_pred = pd.DataFrame({"Actual":y_test, "Predicted":predictions})
df_pred.head() | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Hyperparameter TuningUse `GridSearchCV` to tune the model's parameters | # Check Random Forest Model parameters that can be used for Tuning
model = RandomForestClassifier()
model
from sklearn.model_selection import GridSearchCV
param_grid = {'max_depth': [1, 5, 15, 25, 35],
'n_estimators': [100, 300, 500, 700, 1000]}
grid = GridSearchCV(model, param_grid, verbose=3)
# Train... | precision recall f1-score support
CONFIRMED 0.82 0.72 0.77 404
FALSE POSITIVE 0.76 0.83 0.80 435
CANDIDATE 0.99 1.00 0.99 909
accuracy 0.89 1748
macro avg 0.86 0.85 ... | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Save the Model* Using joblib | import joblib
filename = 'RandomForestClassifier.sav'
joblib.dump(RandomForestClassifier, filename) | _____no_output_____ | BSD-4-Clause-UC | Models/random_forest.ipynb | fereshtehaghaei/Machine-Learning-Exoplanets |
Fingerprint Generators Creating and using a fingerprint generatorFingerprint generators can be created by using the functions that return the type of generator desired. | from rdkit import Chem
from rdkit.Chem import rdFingerprintGenerator
mol = Chem.MolFromSmiles('CC(O)C(O)(O)C')
generator = rdFingerprintGenerator.GetAtomPairGenerator()
fingerprint = generator.GetSparseCountFingerprint(mol)
non_zero = fingerprint.GetNonzeroElements()
print(non_zero) | {541731: 1, 574497: 1, 574498: 1, 590881: 1, 590882: 1, 590945: 1, 1590306: 3, 1590307: 3, 1590369: 1, 1590370: 2, 1590401: 2, 1590402: 1, 1592354: 1, 1592355: 2}
| BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
We can set the parameters for the fingerprint while creating the generator for it. | generator = rdFingerprintGenerator.GetAtomPairGenerator(minDistance = 1, maxDistance = 2, includeChirality = False)
fingerprint = generator.GetSparseCountFingerprint(mol)
non_zero = fingerprint.GetNonzeroElements()
print(non_zero) | {574497: 1, 574498: 1, 590881: 1, 590882: 1, 590945: 1, 1590306: 3, 1590369: 1, 1590370: 2, 1590401: 2, 1590402: 1, 1592354: 1}
| BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
We can provide the molecule dependent arguments while creating the fingerprint. | fingerprint = generator.GetSparseCountFingerprint(mol, fromAtoms = [1])
non_zero = fingerprint.GetNonzeroElements()
print(non_zero)
fingerprint = generator.GetSparseCountFingerprint(mol, ignoreAtoms = [1, 5])
non_zero = fingerprint.GetNonzeroElements()
print(non_zero) | {574497: 1, 574498: 1, 590945: 1, 1590369: 1, 1590370: 2}
{590881: 1, 590882: 1, 1590306: 2, 1590401: 1, 1590402: 1}
| BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
Types of fingerprint generatorsCurrently 4 fingerprint types are supported by fingerprint generators | generator = rdFingerprintGenerator.GetAtomPairGenerator()
fingerprint = generator.GetSparseCountFingerprint(mol)
non_zero = fingerprint.GetNonzeroElements()
print("Atom pair", non_zero)
generator = rdFingerprintGenerator.GetMorganGenerator(radius = 3)
fingerprint = generator.GetSparseCountFingerprint(mol)
non_zero = ... | Atom pair {541731: 1, 574497: 1, 574498: 1, 590881: 1, 590882: 1, 590945: 1, 1590306: 3, 1590307: 3, 1590369: 1, 1590370: 2, 1590401: 2, 1590402: 1, 1592354: 1, 1592355: 2}
Morgan {864662311: 3, 1542631284: 2, 1542633699: 1, 1741045729: 1, 2245273601: 1, 2245277810: 1, 2246728737: 2, 2782665878: 1, 2927183216: 1, 35371... | BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
Invariant generatorsIt is possible to use a custom invariant generators while creating fingerprints. Invariant generators provide values to be used as invariants for each atom or bond in the molecule and these values affect the generated fingerprint. | simpleMol = Chem.MolFromSmiles('CCC')
generator = rdFingerprintGenerator.GetRDKitFPGenerator()
fingerprint = generator.GetSparseCountFingerprint(simpleMol)
non_zero = fingerprint.GetNonzeroElements()
print("RDKitFingerprint", non_zero)
atomInvariantsGen = rdFingerprintGenerator.GetAtomPairAtomInvGen()
generator = r... | RDKitFingerprint {1940446997: 1, 4275705116: 2}
RDKitFingerprint {578931652: 1, 2298572045: 2}
| BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
Currently avaliable invariants generators are: | atomInvariantsGen = rdFingerprintGenerator.GetAtomPairAtomInvGen()
generator = rdFingerprintGenerator.GetMorganGenerator(radius = 3, atomInvariantsGenerator = atomInvariantsGen)
fingerprint = generator.GetSparseCountFingerprint(mol)
non_zero = fingerprint.GetNonzeroElements()
print("Morgan with AtomPairAtomInvGen", n... | Morgan with AtomPairAtomInvGen {33: 2, 35: 1, 36: 1, 97: 3, 523835848: 1, 618975071: 1, 2343097318: 1, 3205489706: 2, 3205489717: 1, 3205494725: 1, 3205494778: 1}
Morgan with MorganAtomInvGen {864662311: 3, 1542631284: 2, 1542633699: 1, 1741045729: 1, 2245273601: 1, 2245277810: 1, 2246728737: 2, 2782665878: 1, 29271832... | BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
Custom InvariantsIt is also possible to provide custom invariants instead of using a invariants generator |
generator = rdFingerprintGenerator.GetAtomPairGenerator()
fingerprint = generator.GetSparseCountFingerprint(simpleMol)
non_zero = fingerprint.GetNonzeroElements()
print(non_zero)
customAtomInvariants = [1, 1, 1]
fingerprint = generator.GetSparseCountFingerprint(simpleMol, customAtomInvariants = customAtomInvariants)... | {541730: 1, 558113: 2}
{16417: 2, 16418: 1}
| BSD-3-Clause | Docs/Notebooks/FingerprintGenerators.ipynb | hryknkgw/rdkit |
1. 数据读入 | import pandas as pd
df = pd.read_csv('50_Startups.csv')
df.head() | _____no_output_____ | MIT | .ipynb_checkpoints/R&D_Profit-checkpoint.ipynb | nwmsno1/tensorflow_base |
2. 数据归一化 | def normalize_feature(df):
return df.apply(lambda column: (column - column.mean())/column.std())
df = normalize_feature(df[['R&D Spend', 'Marketing Spend', 'Profit']])
df.head()
# 数据分析(3D)
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.set_xlab... | _____no_output_____ | MIT | .ipynb_checkpoints/R&D_Profit-checkpoint.ipynb | nwmsno1/tensorflow_base |
3. 数据处理 | import numpy as np
# 为了方便矩阵相乘,添加一列全为1的x0
ones = pd.DataFrame({'ones': np.ones(len(df))}) # ones是n行1列的数据框,表示x0恒为1
df = pd.concat([ones, df], axis=1) # 根据列合并数据
X_data = np.array(df[df.columns[0:3]])
Y_data = np.array(df[df.columns[-1]]).reshape(len(df), 1)
print(X_data.shape, type(X_data))
print(Y_data.shape, type(Y... | (50, 3) <class 'numpy.ndarray'>
(50, 1) <class 'numpy.ndarray'>
| MIT | .ipynb_checkpoints/R&D_Profit-checkpoint.ipynb | nwmsno1/tensorflow_base |
4. 创建线性回归模型(数据流图) | import tensorflow as tf
tf.reset_default_graph() # https://www.cnblogs.com/demo-deng/p/10365889.html
alpha = 0.01 # 学习率
epoch = 500 # 训练全量数据集的轮数
# 创建线性回归模型(数据流图)
# 输入X, 形状[50,3]
X = tf.placeholder(tf.float32, X_data.shape)
# 输入Y,形状[50,1]
Y = tf.placeholder(tf.float32, Y_data.shape)
# 权重变量W,形状[3,1]
# 存疑:tf.get_var... | C:\Users\nwmsn\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
| MIT | .ipynb_checkpoints/R&D_Profit-checkpoint.ipynb | nwmsno1/tensorflow_base |
5. 创建会话(运行环境) | # 创建会话(运行环境)
with tf.Session() as sess:
# 初始化全局变量
sess.run(tf.global_variables_initializer())
# 开始训练模型
# 因为训练集较小,所以不采用批梯度下降优化算法,每次都采用全量数据训练
for e in range(1, epoch+1):
sess.run(train_op, feed_dict={X: X_data, Y: Y_data})
if e % 10 == 0:
loss, w = sess.run([loss_op, W], fe... | Epoch 10 Loss=0.3661 Model: y = 0.08908x1 + 0.06728x2 + -8.941e-10
Epoch 20 Loss=0.2775 Model: y = 0.1656x1 + 0.1226x2 + -4.098e-10
Epoch 30 Loss=0.2139 Model: y = 0.2315x1 + 0.1679x2 + 1.08e-09
Epoch 40 Loss=0.1682 Model: y = 0.2885x1 + 0.2047x2 + -6.706e-10
Epoch 50 Loss=0.1352 Model: y = 0.3378x1... | MIT | .ipynb_checkpoints/R&D_Profit-checkpoint.ipynb | nwmsno1/tensorflow_base |
Part 3: Launch a Grid Network LocallyIn this tutorial, you'll learn how to deploy a grid network into a local machine and then interact with it using PySyft._WARNING: Grid nodes publish datasets online and are for EXPERIMENTAL use only. Deploy nodes at your own risk. Do not use OpenGrid with any data/models you wish t... | # General dependencies
import torch as th
import syft as sy
import grid as gr
hook = sy.TorchHook(th)
gateway = gr.GridNetwork("http://localhost:5000")
# WARNING: We should use the same id and port as the one used to start the app!!!
bob = gr.WebsocketGridClient(hook, id="bob", address="http://localhost:3000")
# If yo... | _____no_output_____ | Apache-2.0 | examples/Part 3 - Launch a Grid Network Locally.ipynb | joaolcaas/PyGrid |
Step 7: Use PySyft Like NormalNow you can simply use the worker you created like you would any other normal PySyft worker. For more on how PySyft works, please see the PySyft tutorials: https://github.com/OpenMined/PySyft/tree/dev/examples/tutorials | x = th.tensor([1,2,3,4]).send(bob)
x
y = x + x
y
y.get() | _____no_output_____ | Apache-2.0 | examples/Part 3 - Launch a Grid Network Locally.ipynb | joaolcaas/PyGrid |
Step 7: Perform operations on Grid NetworkSo far we haven't done anything different, but here is the magic: we can interact with the network to query general information about it. | x = th.tensor([1, 2, 3, 4, 5]).tag("#tensor").send(bob) | _____no_output_____ | Apache-2.0 | examples/Part 3 - Launch a Grid Network Locally.ipynb | joaolcaas/PyGrid |
We can search for a tensor in the entire network, and get pointers to all tensors. | gateway.search("#tensor")
y = th.tensor([1, 2, 3, 4, 5]).tag("#tensor").send(alice)
gateway.search("#tensor") | _____no_output_____ | Apache-2.0 | examples/Part 3 - Launch a Grid Network Locally.ipynb | joaolcaas/PyGrid |
Reactions processing with AQME - substrates + TS | # cell with import, system name and PATHs
import os, glob, subprocess
import shutil
from pathlib import Path
from aqme.csearch import csearch
from aqme.qprep import qprep
from aqme.qcorr import qcorr
from rdkit import Chem
import pandas as pd | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 1: Determining the constraints for SN2 TS | # Provide the TS smiles to detemine the numbering for constraints
smi = 'C(C)(F)C.[OH-]'
mol = Chem.MolFromSmiles(smi)
mol = Chem.AddHs(mol)
for i,atom in enumerate(mol.GetAtoms()):
atom.SetAtomMapNum(i)
smi_new = Chem.MolToSmiles(mol)
print(smi_new)
mol
# distance and angle to fix are
# constraits_dist = [[0,2,1.... | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 2: Create a CSV as follows | data = pd.read_csv('example2.csv')
data | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 3: Running CSEARCH on the CSV | # run CSEARCH conformational sampling, specifying:
# choose program for conformer sampling
# 1) RDKit ('rdkit'): Fast sampling, only works for systems with one molecule
# 2) CREST ('crest'): Slower sampling, works for noncovalent complexes and
# transition structures (see example of TS in the CSEARCH_CREST_TS.ipynb n... | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 4: Create input files using QPREP a. for TS with TS keywords b. for substrates with substrate keywords | # set SDF filenames and directory where the new com files will be created
sdf_rdkit_files = ['CSEARCH/crest/TS_SN2_crest.sdf']
# choose program for input file generation, with the corresponding keywords line, memory and processors:
# 1) Gaussian ('gaussian')
program = 'gaussian'
qm_input = 'B3LYP/6-31G(d) opt=(ts,calc... | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 5: Checking with QPREP for corrections | w_dir_main=os.getcwd()+'/QCALC'
# run the QCORR analyzer, with:
# 1) Working directory (w_dir_main=com_path)
# 2) Names of the QM output files (files='*.log')
# 3) Detect and fix calcs that converged during geometry optimization but didn't converge during frequency calcs (freq_conv='opt=(calcfc,maxstep=5)')
# 4) Type ... | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 6: creation of DLPNO input files for ORCA single-point energy calculations | # choose output files to get atoms and coordinates to generate inputs for single-point energy calculations
success_dir = os.getcwd()+'/QCALC/successful_QM_outputs'
qm_files = '*.log'
# choose program for input file generation with QPREP, with the corresponding keywords line, memory and processors:
# 1) ORCA ('orca')
... | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Step 7: Analysis with goodvibes | # track all the output files from Gaussian and ORCA
opt_files = glob.glob(f'{success_dir}/*.log')
spc_files = glob.glob(f'{success_dir}/*.out')
all_files = opt_files + spc_files
# move all the output files together to a folder called "GoodVibes_analysis" for simplicity
w_dir_main = Path(os.getcwd())
GV_folder = w_dir... | _____no_output_____ | MIT | Example_workflows/End-to-end_Workflows/end-to-end-2-sn2-pes/end-to-end-example-2.ipynb | jvalegre/RotaConfort |
Import all the necessary libraries | import cv2, time, pandas
from datetime import datetime | _____no_output_____ | MIT | Motion Detection with Webcam.ipynb | annmohankunnath/Motion-Detection-with-Webcam |
Initialize the variables | first = None # This variable holds the value of the first frame
status_list = [None,None] # This variable holds the list of statuses - if Python has come across a frame greater than 1000 pixels
times = [] # This variable holds the timestamps during which a motion that was detected started and ended
df = pandas.DataFram... | _____no_output_____ | MIT | Motion Detection with Webcam.ipynb | annmohankunnath/Motion-Detection-with-Webcam |
Capture the video | vid = cv2.VideoCapture(0) # To capture the video from the first camera of the device | _____no_output_____ | MIT | Motion Detection with Webcam.ipynb | annmohankunnath/Motion-Detection-with-Webcam |
Process the video | while True:
check, frame = vid.read() # To read frame by frame
status = 0
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# To convert the image to grayscale
gray_frame = cv2.GaussianBlur(gray_frame,(21,21),0) # To make the image blurry so that noise is reduced and accuracy is improved
... | _____no_output_____ | MIT | Motion Detection with Webcam.ipynb | annmohankunnath/Motion-Detection-with-Webcam |
Write the timestamps to a csv file | for i in range(0,len(times),2):
df=df.append({"Start":times[i],"End":times[i+1]},ignore_index=True) # To store the start and end times of when each motion was detected
df.to_csv("Times.csv") # To write to the Times.csv file | _____no_output_____ | MIT | Motion Detection with Webcam.ipynb | annmohankunnath/Motion-Detection-with-Webcam |
End the video processing | vid.release() # To stop the capturing device from capturing video
cv2.destroyAllWindows # To close the windows and deallocate associated memory usage | _____no_output_____ | MIT | Motion Detection with Webcam.ipynb | annmohankunnath/Motion-Detection-with-Webcam |
Install the required packages to download and unzip data | !pip install xtarfile
!pip install wget | Requirement already satisfied: wget in c:\users\rpals\anaconda3\lib\site-packages (3.2)
| Apache-2.0 | mnist.ipynb | rpalsaxena/1000daysofcode |
Download data and unzip it | import wget
wget.download('https://activeeon-public.s3.eu-west-2.amazonaws.com/datasets/MNIST.old.tar.gz')
import tarfile
filename = tarfile.open('MNIST.old.tar.gz')
filename.extractall('./data') # specify which folder to extract to
filename.close()
| _____no_output_____ | Apache-2.0 | mnist.ipynb | rpalsaxena/1000daysofcode |
Load MNIST data | import torch
import numpy as np
from torchvision import datasets
import torchvision.transforms as transforms
transform = transforms.ToTensor()
trainset = datasets.MNIST('./data/', download=False, train=True, transform=transform)
test_data = datasets.MNIST(root='./data', train=False,
... | _____no_output_____ | Apache-2.0 | mnist.ipynb | rpalsaxena/1000daysofcode |
Compare iterrows vs itertuples |
start = time.time()
# create graph and add metadata
G = nx.DiGraph()
G.add_nodes_from(case_metadata.index.tolist())
nx.set_node_attributes(G, 'date', case_metadata['date'].to_dict())
for index, edge in edgelist.iterrows():
ing = edge['citing']
ed = edge['cited']
G.add_edge(ing, ed)
end = time.time()
print... | pandas took 1 seconds to go though 250465 edges using itertuples
| MIT | explore/Iain/load_ig_chalkboard.ipynb | wethepeopleonline/law-net |
load into igraph | # create a dictonary that maps court listener ids to igraph ids
cl_to_ig_id = {}
cl_ids = case_metadata['id'].tolist()
for i in range(case_metadata['id'].size):
cl_to_ig_id[cl_ids[i]] = i
start = time.time()
V = case_metadata.shape[0]
g = ig.Graph(n=V, directed=True)
g.vs['date'] = case_metadata['date'].tolist()
g... | _____no_output_____ | MIT | explore/Iain/load_ig_chalkboard.ipynb | wethepeopleonline/law-net |
igraph find vs. select | start = time.time()
R = 1000
for i in range(R):
g.vs.find(name='92891')
end = time.time()
print 'g.vs.find took %E seconds per lookup' % ((end - start)/R)
start = time.time()
R = 1000
for i in range(R):
g.vs.select(name='92891')
end = time.time()
print 'g.vs.select took %E seconds per lookup' % ((end - start)/R... | _____no_output_____ | MIT | explore/Iain/load_ig_chalkboard.ipynb | wethepeopleonline/law-net |
Download and extract zip from web- Specifies the source link, destination url and file name to download and extract data files- Currently reading from external folder as github does not support large files - To rerun function for testing before submission - To add checks and conditions for the function- Link to ... | import zipfile
import urllib.request
import pandas as pd
import numpy as np
import pickle
from tqdm import tqdm
SOURCE = "https://s3-ap-southeast-1.amazonaws.com/grab-aiforsea-dataset/safety.zip"
OUTPUT_PATH = "../grab-ai-safety-data"
FILE_NAME = ""
class DownloadProgressBar(tqdm):
'''Class for tqdm progress bar.''... | _____no_output_____ | MIT | 1. Safety Challenge - Data reading and cleaning.ipynb | jtsw1990/grab-ai-safety |
Merge and drop duplicates- Join the feautres together with the labels- Get rid of any obvious duplicates in the features and response- No data cleaning or formatting to minimize data leakage | df_features = pd.concat(
[df1, df2, df3, df4, df5, df6, df7, df8, df9],
axis=0
).drop_duplicates(
keep=False
)
response = response.drop_duplicates(
subset="bookingID",
keep=False
)
df = pd.merge(
df_features,
response,
how="inner",
on="bookingID"
).sort_values(
["bookingID", "... | _____no_output_____ | MIT | 1. Safety Challenge - Data reading and cleaning.ipynb | jtsw1990/grab-ai-safety |
cube of fibonacci numbers | cube = lambda x: x ** 3
def fibonacci(n):
nums = [0, 1]
for i in range(2, n):
nums.append(nums[i - 1] + nums[i - 2])
return nums[:n]
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
| 5
[0, 1, 1, 8, 27]
| MIT | Python/14. python functionals/71. map and lambda fn.ipynb | faisalsanto007/Hakcerrank-problem-solving |
Linear classifier on sensor data with plot patterns and filtersHere decoding, a.k.a MVPA or supervised machine learning, is applied to M/EEGdata in sensor space. Fit a linear classifier with the LinearModel objectproviding topographical patterns which are more neurophysiologicallyinterpretable [1]_ than the classifier... | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Romain Trachel <trachelr@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import Vectorizer, get_coef... | _____no_output_____ | BSD-3-Clause | 0.17/_downloads/d1b18c3376911723f0257fe5003a8477/plot_linear_model_patterns.ipynb | drammock/mne-tools.github.io |
Set parameters | raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.4
event_id = dict(aud_l=1, vis_l=3)
# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(.5, 25, fir_design='firwi... | _____no_output_____ | BSD-3-Clause | 0.17/_downloads/d1b18c3376911723f0257fe5003a8477/plot_linear_model_patterns.ipynb | drammock/mne-tools.github.io |
Decoding in sensor space using a LogisticRegression classifier | clf = LogisticRegression(solver='lbfgs')
scaler = StandardScaler()
# create a linear model with LogisticRegression
model = LinearModel(clf)
# fit the classifier on MEG data
X = scaler.fit_transform(meg_data)
model.fit(X, labels)
# Extract and plot spatial filters and spatial patterns
for name, coef in (('patterns', ... | _____no_output_____ | BSD-3-Clause | 0.17/_downloads/d1b18c3376911723f0257fe5003a8477/plot_linear_model_patterns.ipynb | drammock/mne-tools.github.io |
Let's do the same on EEG data using a scikit-learn pipeline | X = epochs.pick_types(meg=False, eeg=True)
y = epochs.events[:, 2]
# Define a unique pipeline to sequentially:
clf = make_pipeline(
Vectorizer(), # 1) vectorize across time and channels
StandardScaler(), # 2) normalize features across trials
LinearModel(
Logi... | _____no_output_____ | BSD-3-Clause | 0.17/_downloads/d1b18c3376911723f0257fe5003a8477/plot_linear_model_patterns.ipynb | drammock/mne-tools.github.io |
Solving dual model using DSA with Entropy Prox TermInstantiating inner problem Solve battery of problems | # Setup
BENCHMARKS_PATH = './smpspy/benchmark_problems/2_caroe_schultz/'
n_S_exp = [10, 50, 100, 500]
N_STEPS = 200
GAMMA = 1.0
# First generate traditional DSA
inner_problems = {}
methods = {}
method_loggers = {}
for n_S in n_S_exp:
ip = TwoStage_SMPS_InnerProblem(BENCHMARKS_PATH+'caroe_schultz_{}'.format(n_S))... | _____no_output_____ | MIT | notebooks/1. Entropy Prox Term.ipynb | robin-vjc/smpspy |
Single run | ip = TwoStage_SMPS_InnerProblem('./smpspy/benchmark_problems/2_caroe_schultz/caroe_schultz_10') | Parsing nominal model information from ./smpspy/benchmark_problems/2_caroe_schultz/caroe_schultz_10.cor and .tim ...
Parsing stochastic information from ./smpspy/benchmark_problems/2_caroe_schultz/caroe_schultz_10.sto ...
Stochastic model is of type SCENARIOS DISCRETE
| MIT | notebooks/1. Entropy Prox Term.ipynb | robin-vjc/smpspy |
First solving it with DSA | GAMMA = 1.0
dsa = DSA(ip.oracle, ip.projection_function, dimension=ip.dimension, gamma=GAMMA)
logger_dsa = EnhancedDualMethodLogger(dsa)
for iteration in range(1000):
if not iteration%50:
print('Iteration: {}, d_k={}'.format(iteration, dsa.d_k))
dsa.dual_step() | Iteration: 0, d_k=-inf
Iteration: 50, d_k=-55.0159186353
Iteration: 100, d_k=-54.9786759617
Iteration: 150, d_k=-54.8958271191
Iteration: 200, d_k=-54.946123664
Iteration: 250, d_k=-54.9126206845
Iteration: 300, d_k=-54.8681531927
Iteration: 350, d_k=-54.8759044684
Iteration: 400, d_k=-54.83683095
Iteration: 450, d_k=-... | MIT | notebooks/1. Entropy Prox Term.ipynb | robin-vjc/smpspy |
Then get the required parameters (R is derived a posteriori) | R_a_posteriori = np.linalg.norm(dsa.lambda_k, ord=np.inf)
R_safe = R_a_posteriori*1.1
ip = TwoStage_SMPS_InnerProblem('./smpspy/benchmark_problems/2_caroe_schultz/caroe_schultz_10', R=R_safe)
print('A-posteriori R={}'.format(R_a_posteriori)) | Parsing nominal model information from ./smpspy/benchmark_problems/2_caroe_schultz/caroe_schultz_10.cor and .tim ...
Parsing stochastic information from ./smpspy/benchmark_problems/2_caroe_schultz/caroe_schultz_10.sto ...
Stochastic model is of type SCENARIOS DISCRETE
A-posteriori R=0.994113159479
| MIT | notebooks/1. Entropy Prox Term.ipynb | robin-vjc/smpspy |
Solve it using DSA with Entropy prox function. **Note that the only difference is that we pass in softmax projection function!** | dsa_entropy = DSA(ip.oracle, ip.softmax_projection, dimension=ip.dimension, gamma=GAMMA)
logger_dsa_entropy = EnhancedDualMethodLogger(dsa_entropy)
for iteration in range(1000):
if not iteration%50:
print('Iteration: {}, d_k={}'.format(iteration, dsa_entropy.d_k))
dsa_entropy.dual_step()
logger_dsa.lamb... | _____no_output_____ | MIT | notebooks/1. Entropy Prox Term.ipynb | robin-vjc/smpspy |
Learning Transformers with TensorFlow Here you can find all the theory and code for transformers. **What is transformer**A transformer model handles **variable-sized input using stacks of self-attention layers**.- Layer outputs can be calculated in parallel, instead of a series like an RNN. - Can learn long-range dep... | # Some downloads
!pip install tensorflow_datasets
!pip install -U tensorflow-text
# Imports
import collections
import logging
import os
import pathlib
import re
import string
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
import tensorflow_datasets as tfds
import tensorflow_text as text
i... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Downloading the datasets Testing the transformer on Portuguese-English translation dataset. This dataset contains approx 50000 training examples, 1100 validation examples and 2000 test examples. | examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True,
as_supervised=True)
train_examples, val_examples = examples['train'], examples['validation']
# Looking into the text examples
for pt_examples, en_examples in train_examples.batch(3).take(1):
for pt in pt_exam... | e quando melhoramos a procura , tiramos a única vantagem da impressão , que é a serendipidade .
mas e se estes fatores fossem ativos ?
mas eles não tinham a curiosidade de me testar .
and when you improve searchability , you actually take away the one advantage of print , which is serendipity .
but what if it were act... | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Text tokenization & detokenizatiion Here we will convert the text to some numeric representation, so now we will convert the text to sequences of token IDs, which are used as indices into an embedding. Downloading a saved model | model_name = "ted_hrlr_translate_pt_en_converter"
tf.keras.utils.get_file(
f"{model_name}.zip",
f"https://storage.googleapis.com/download.tensorflow.org/models/{model_name}.zip",
cache_dir='.', cache_subdir='', extract=True
)
# Loading the saved model
tokenizers = tf.saved_model.load(model_name)
| _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
The tokenizes contains two text tokenizers, one for english and one for portuguese. | print([item for item in dir(tokenizers) if not item.startswith('_')])
print([item for item in dir(tokenizers.en) if not item.startswith('_')])
print([item for item in dir(tokenizers.pt) if not item.startswith('_')]) | ['en', 'graph_debug_info', 'pt', 'signatures', 'tensorflow_git_version', 'tensorflow_version']
['detokenize', 'get_reserved_tokens', 'get_vocab_path', 'get_vocab_size', 'lookup', 'tokenize', 'tokenizer', 'vocab']
['detokenize', 'get_reserved_tokens', 'get_vocab_path', 'get_vocab_size', 'lookup', 'tokenize', 'tokenizer'... | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
- The `tokenize` method converts a batch of strings to a padded-batch of token IDs. - This method also splits punctuations, lowercases and unicode-normalizes the input before tokenizing. | # Printing out the english exampels
for en in en_examples.numpy():
print(en.decode('utf-8')) | and when you improve searchability , you actually take away the one advantage of print , which is serendipity .
but what if it were active ?
but they did n't test for curiosity .
| MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
The `detokenize` method attempts to convert these token IDs back to human readable text | # Tokenizing a text
encoded = tokenizers.en.tokenize(en_examples)
for row in encoded.to_list():
print(row)
# Detokenizing a text
round_trip = tokenizers.en.detokenize(encoded)
for line in round_trip.numpy():
print(line.decode('utf-8')) | and when you improve searchability , you actually take away the one advantage of print , which is serendipity .
but what if it were active ?
but they did n ' t test for curiosity .
| MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Lookup method converts from token-IDs to token text | tokens = tokenizers.en.lookup(encoded)
tokens | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Setup input pipeline Gotta apply some transformations in order to make the data suitable for Input pipeline. | # Preprocessing function and we can use while making the dataset
def tokenize_pairs(pt , en):
'''
pt -> portugese text
en -> english text
'''
pt = tokenizers.pt.tokenize(pt)
# Converting the ragged tensors to dense by padding with zero
pt = pt.to_tensor()
return pt , en
# Hyper parameters for batchin... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
**Positional Encoding** - Attention layers see the input as a set of vectors with no sequential order. - Like we know the transformers doesnt contain any recurrent or convolutional layers, so this means no reccurence available in the transformers. Thats why we need the help of a **positional encoding** and its added t... | # Getting the angles
def get_angles(pos , i , d_model):
angle_rates = 1 / np.power(1000 , (2 * (i // 2))) / np.float32(d_model) # 1 / 1000 (to the power 2i / d_model)
return pos * angle_rates # here we multiply by pos to make it complete
# Defining thhe whole positional encoding
def positional_encoding(positi... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
MaskingThe mask indicates where pad value 0 is present: it outputs a 1 at those locations, and a 0 otherwise. | # function to create padding
def create_padding(seq):
seq = tf.cast(tf.math.equal(seq , 0) , tf.float32)
# Add extra dimensions to add the padding (so we can add padding to our attention scores)
# mask + attention scores
return seq[: , tf.newaxis , tf.newaxis , :] # (batch_size , 1 , 1 , seq_len)
# Testing o... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
The look-ahead mask is used to mask the future token sequence. In other words, the mask indicates which entries should not be used.Zero attention scores for the token sequence | # Creating the look ahead matrix
def create_look_ahead_mask(size):
mask = 1 - tf.linalg.band_part(tf.ones(shape = (size , size)) , -1, 0)
return mask
# Applying dummy tensors
x = tf.random.uniform((1 , 3))
temp = create_look_ahead_mask(x.shape[1])
temp | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Scaled dot product attention Like we saw above the attention function used by the transformer takes namely three inputs, - Query (Q)- Key (K)- Value (V)The equation used to calculate the attention weights, `Attention(Q , K , V) = Softmax of [ (Query , key)T / square root of the depth of the keys `Dont worry much if i... | # Function for scaling the dot product attention
# That is passing in the query , key and value to our attention
def scaled_out_product_attention(q , k , v , mask):
'''
Calculate the attention weights
- q , k , v must have a matching leading dimensions
- k , v must have matching penultimate dimension, i.e... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
As the softmax normalization is done on K (keys), its values decide the amount of importance given to Q. The output represents the multiplication of the attention weights and the V vector. This ensures that the tokens you want to focus on are kept as-is and the irrelevant tokens are flushed out. | def print_out(q , k , v):
# Applying the above dot product function
temp_out , temp_attn = scaled_out_product_attention(q , k , v , None)
print(f'Attention weights are: {temp_attn}\n')
print(f'Output is (matmul of v and attention weights): {temp_out}\n')
# Using the above function visualizing our attention we... | Attention weights are: [[0. 1. 0. 0.]]
Output is (matmul of v and attention weights): [[10. 0.]]
| MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
**Multi-Head Attention** The multi-head attention consists of four parts, - Linear layers - Scaled dot-product attention - Final linear layer **Inputs of multi-head attention block:**- Each multi head attention block gets three inputs, [Query, Key, Value]. - Then these are put through (Dense) layers before the multi-h... | # Coding out the Multi-Head attention!!
class MultiHeadAttention(tf.keras.layers.Layer):
def __init__(self , d_model , num_heads ):
super(MultiHeadAttention , self).__init__()
self.num_heads = num_heads
self.d_model = d_model # the dimensions
assert d_model % self.num_heads == 0
self.dept... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Lets create a `MultiHeadAttention` layer to try out, wehre at each location in the sequeunce it runs all 8 attention heads across all other locations in the sequence, returning a new vector of the same length at each location. | # Dummy multi-head attention
temp_mha = MultiHeadAttention(d_model = 512 , num_heads = 8)
# Dummy input
y = tf.random.uniform((1 , 60 , 512)) # (batch_size , encoder_sequence , d_model)
out , attn = temp_mha(v = y , k = y , q = y , mask = None)
out.shape , attn.shape
out | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Point wise feed forward network It consists of two-fully connected layers with a ReLu activation in betwee. | # Creating a function for point wise forward network
def point_wise_feed_forward(d_model , dff):
return tf.keras.Sequential([
tf.keras.layers.Dense(dff , activation= 'relu') ,# (batch_size , seq_len , dff)
tf.keras.layers.Dense(d_model) # (batch_size , seq_len , d_model)
])
# Applying on a sample dat... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Encoder and Decoder - The input sentence is passed through `N` encoder layers that generates an output for each token in the sentence. - The decoder attends to encoders output and its own input (self-attention) to predict the next word. Encoder Layer Encoder layer consists of sublayers:- Multi-head attention (has pad... | # Building the encoder layer not the whole Encoder itself.
# This has the whole block of layer except the positional encoding
class EncoderLayer(tf.keras.layers.Layer):
def __init__(self , d_model , num_heads , dff , rate = 0.1 ):
super(EncoderLayer , self).__init__()
# Defining the sub-layers of the en... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Decoder Layer Each decoder layer consists of sublayers:- Masked multi-head attention (with look ahead mask and padding mask) - Multi-head attention with padding mask, - where value and key recieve the encoder output as inputs - query recieves the output from the masked multi-head attention sublayer. - Point wise fe... | # Building the Decoder layer
class DecoderLayer(tf.keras.layers.Layer):
def __init__(self , d_model , num_heads , dff , rate = 0.1 , **kwargs):
super(DecoderLayer , self).__init__(**kwargs)
# Two multi-head attention block in the Decoder
self.mha1 = MultiHeadAttention(d_model , num_heads)
self.mh... | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
So far we've been building the Encoder and Decoder Layers, now its time to build the whole Encoder and Decoder on whole by using the layers we've created. Encoder The `Encoder` consists of, - Input Embedding - Positional Encoding - N encoder layers (for n number of times)- The input is put through an embedding which ... | # Coding out the Encoder
class Encoder(tf.keras.layers.Layer):
def __init__(self , num_layers , d_model , num_heads , dff , input_vocab_size ,
maximum_position_encoding , rate = 0.1 ):
super(Encoder , self).__init__()
# Getting the dimensions
self.d_model = d_model
self.num_laye... | /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in true_divide
after removing the cwd from sys.path.
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:5: RuntimeWarning: invalid value encountered in multiply
"""
/usr/local/lib/python3.7/dist-pack... | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Decoder The `Decoder` consists of,- Output Embedding - Positional Encoding - N decoder layers - The target is put through an embedding which is summed with the positional encoding. - The output of the this summation is the input to the decoder layers.- The output of the decoder is the input to the final linear layer. | class Decoder(tf.keras.layers.Layer):
def __init__(self , num_layers , d_model , num_heads ,dff , target_vocab_size , maximum_position_encoding , rate = 0.1):
super(Decoder , self).__init__()
# Get the dimensions and number of layers
self.d_model = d_model
self.num_layers = num_layers
# Embedd... | /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in true_divide
after removing the cwd from sys.path.
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:5: RuntimeWarning: invalid value encountered in multiply
"""
/usr/local/lib/python3.7/dist-pack... | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Alright we have all the modules and layers required for creating the whole transformer model. Lets put them altogether and create a Model class called Transformer. Talking about the masks where encoder takes only one masks whereas decoders takes two of them, - Encoder -> Encoder padding mask - Decoder -> Decoder paddin... | # Coding out the entire Transformer class
class Transformer(tf.keras.Model):
def __init__(self , num_layers , d_model , num_heads , dff , input_vocab_size ,
target_vocab_size , pe_input , pe_target , rate = 0.1):
super().__init__()
# Initializing the Encoder and the Decoder + The file dens... | /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in true_divide
after removing the cwd from sys.path.
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:5: RuntimeWarning: invalid value encountered in multiply
"""
/usr/local/lib/python3.7/dist-pack... | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Setting the hyper parameters | num_layers = 4
d_model = 128
dff = 512
num_heads = 8
dropout_rate = 0.1 | _____no_output_____ | MIT | Learning_Transformers_with_TensorFlow.ipynb | ashikshafi08/Recipe1M |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.