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 |
|---|---|---|---|---|---|
Morpheus SandboxFirst test of actual morpheus being a thing. Preliminaries | import os
import sys
import numpy as np
from os.path import dirname
from networkx.drawing.nx_pydot import to_pydot
# Import morpheus
note_dir = os.getcwd()
root_dir = dirname(note_dir)
src_dir = os.path.join(root_dir, "src")
sys.path.append(src_dir)
import morpheus
from morpheus import Morpheus
from morpheus.tests... | _____no_output_____ | MIT | note/dev-1905/190502 - morpheus baby steps.ipynb | eliavw/morpheus |
FitHere, I test whether or not it can fit something. | m = Morpheus()
m.fit(data)
m.m_list[:2]
m.m_codes
m.g_list
m.g_list[3].nodes(data=True) | _____no_output_____ | MIT | note/dev-1905/190502 - morpheus baby steps.ipynb | eliavw/morpheus |
PredictNow testing our prediction functionalities. | q_code = np.array([0,0,0,0,0,0,0,1])
f_list = m.predict(data, q_code)
# show your work
q_grph = m.q_grph
fname = to_dot(q_grph, fname='q')
!dot -T png ./tmp/q.dot > ./tmp/q.png # Bash command (This can be done nicer, but is tricky)
display(Image('tmp/q.png'))
f_list['d-07'](data) | _____no_output_____ | MIT | note/dev-1905/190502 - morpheus baby steps.ipynb | eliavw/morpheus |
7. Регрессионный анализ```Ауд.: 345(330), 350(335), 405(383)Д/З: 346(331), 351(336), 406(384)``` Линейная регрессия$$ M[Y|x] = f(x) = \beta_{0} + \beta_{1} x $$$$ Y = \beta_{0} + \beta_{1} x + \varepsilon, $$$$ \varepsilon \sim N(0, \sigma^2 (неизв)) $$МНК-оценки:$$ \tilde{\beta_1} = \frac{Q_{xy}}{Q_{x}}, $$$$ Q_{xy}... | from scipy import stats
import numpy as np
alpha = 0.1
Qe = 6.199
Qx = 131.22
n = 9
beta1 = -1.057
beta0 = 20.34
q = stats.t(n-2).ppf(1 - alpha/2)
print(q)
s = np.sqrt(Qe / (n - 2))
delta_beta1 = q*s*np.sqrt(1 / Qx)
delta_beta0 = q*s*np.sqrt(865.63/n/Qx)
print('b1 +- {}'.format(delta_beta1))
print('b0 +- {}'.fo... | 1.89457860506
b1 +- 0.15564114248683683
b0 +- 1.526403330710377
| MIT | lessons/7.ipynb | BobNobrain/matstat-labs |
Криволинейная регрессия$$ M[Y|x] = \beta_0 + \beta_1 a_1(x) + ... + \beta_{k-1} a_{k-1}(x), $$где $a_i$ - известные функции.МНК-оценки параметров регрессии:$$Y = \begin{pmatrix}y_1 \\y_2 \\\dots \\y_n\end{pmatrix}$$$$A = \begin{pmatrix}1 & a_1(x_1) & \dots & a_{k-1}(x_1) \\1 & a_1(x_2) & \dots & a_{k-1}(x_2) \... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0, 2, 4, 6, 8, 10])
y = np.array([5, -1, -0.5, 1.5, 4.5, 8.5])
plt.scatter(x, y)
A = np.array([
[1, x_i, x_i ** 2] for x_i in x
])
beta = np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), y)
print(
np.around(
np.do... | [[ 0.821 0.321 0. -0.143 -0.107 0.107]
[-0.295 0.002 0.164 0.193 0.087 -0.152]
[ 0.022 -0.004 -0.018 -0.018 -0.004 0.022]]
[ 4. -2.16428571 0.26785714]
| MIT | lessons/7.ipynb | BobNobrain/matstat-labs |
Множественная линейная регрессия$$ y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \varepsilon_i $$$Q_y = \sum y_i^2 - \frac{\left( \sum y_i \right)^2}{n} $$Q_{x_j} = \sum_i x_{ji}^2 - \frac{\left( \sum x_{ji}^2 \right)^2}{n} $$Q_{x_jy} = \sum_i x_{ji} y_i - \frac{\left( \sum_i x_{ji} \right) \left( \sum y_{i} \righ... | import numpy as np
x1 = np.array([1, 4, 0, 5, -3, 3, -5, -1, 2, -2])
x2 = np.array([4, -6, 2, -4, 12, -2, 14, 6, 0, 8])
y = np.array([-4, -5, 4, -1, 4, 0, 5, 1, 2, 7])
n = len(y)
Qy = np.sum(y ** 2) - np.sum(y) ** 2 / n
Qx1 = np.sum(x1 ** 2) - np.sum(x1 ** 2) ** 2 / n
Qx2 = np.sum(x2 ** 2) - np.sum(x2 ** 2) ** 2 / n... | _____no_output_____ | MIT | lessons/7.ipynb | BobNobrain/matstat-labs |
!pip install -U sentence-transformers
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('bert-base-nli-mean-tokens')
sentences = ['This framework generates embeddings for each input sentence',
'Sentences are passed as a list of string.',
'The quick brown fox jumps over the lazy... | _____no_output_____ | Apache-2.0 | sentence_embeddings_examples.ipynb | alinaalborova/sentence-transformers | |
Overview Functionality implemented so far:1. Read excel files and plot raw traces of graphs2. Find & calculate responding cells `calc_response_rate`3. Graph max utp response for each slide3. Plot average values for control groups vs. L89A overexpressed groupsTODO's:** Please open an issue for anything that should be i... | # Import modules for working with excel sheets and for plotting
# matplotlib: module for plotting
# pandas: module for working with dataframe (can be imported from excel, csv, txt)
# %: ipython magic, to plot graphs in line
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
%m... | _____no_output_____ | MIT | code/20180913_calcium_imaging_analysis.ipynb | LienDNguyen/calcium_imaging |
Load DataThe following dataset is NOT on GitHub. Make sure your local directory structure is as follows: repository_directory / \ \ / \ \ code assets other files (.gitignore, README.md, LICENSE.txt, ...) ... | # Import excel file as a `pandas.ExcelFile' object (which basically has all sub-sheets in a big container!)
# also, only import 1302 rows
number_of_rows = 1302
ca_data = pd.ExcelFile('../assets/2018September11_23h49min14s_sorted_transformed_data.xlsx', nrows=number_of_rows) | _____no_output_____ | MIT | code/20180913_calcium_imaging_analysis.ipynb | LienDNguyen/calcium_imaging |
FunctionsThe following functions are used throughout this notebook to analyze and visualize data.The doc-string should provide enough information on how they work. They basically encapsulate commonly used commands to make re-use easier! | # plot every single trace after reading subsheets and alphabetically sorting them
def plot_traces(df, plot=False):
"""
this function takes a pandas.io.excel.ExcelFile object and iterates over all sheets
every column of every such sheet is interpreted as a 'trace' and plotted in a line plot
a new line pl... | _____no_output_____ | MIT | code/20180913_calcium_imaging_analysis.ipynb | LienDNguyen/calcium_imaging |
Exploratory Data Analysis (*EDA*) | # call the newly created `plot_traces' function (output is suppressed)
plot_traces(df=ca_data, plot=False)
# call the newly created `calc_response_rate' function (output is suppressed)
calc_response_rate(df=ca_data, threshold=1.2, utp_range=(40, 480), verbose=False, plot=False)
# Find max UTP response for each... | _____no_output_____ | MIT | code/20180913_calcium_imaging_analysis.ipynb | LienDNguyen/calcium_imaging |
! python3 "/content/drive/MyDrive/yolov4-pytorch-master/predict.py" | /content/drive/MyDrive/yolov4-pytorch-master/model_data/yolo4_weights.pth model, anchors, and classes loaded.
Input image filename:/content/sample_data/img/cap1.jpg
/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and... | MIT | YOLOV4.ipynb | AlexBzrc/bustag | |
Load Data | df_tweets = pd.read_csv("trump_tweets.csv", parse_dates = ['date'], index_col=7)
df_tweets.head()
df_tweets.tail()
df_doge = pd.read_csv("Daily-DOGE-USD.csv", parse_dates=['Date'], index_col=0)
df_doge.head()
df_doge.tail() | _____no_output_____ | MIT | Fall/OldLSTMtemp.ipynb | spewmaker/senior-capstone |
LSTM Application Function For Converting Time Series Data For Supervised Learning | # convert series to supervised learning
# developed in this blog post https://machinelearningmastery.com/convert-time-series-supervised-learning-problem-python/
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = pd.DataFrame(data)
cols, na... | _____no_output_____ | MIT | Fall/OldLSTMtemp.ipynb | spewmaker/senior-capstone |
Preparing Data | # Aligning Tweet Data with Doge Data
df_tweets = df_tweets.loc[(df_tweets.index > '2017-08-24')]
# Dropping ID column since it's unexpected to be useful
df_tweets = df_tweets.drop(columns=['id'], axis=1)
# Changing by the second data to by the day data
changed1 = df_tweets.groupby([df_tweets.index.date]).size().reset_... | _____no_output_____ | MIT | Fall/OldLSTMtemp.ipynb | spewmaker/senior-capstone |
Lambda School Data Science, Unit 2: Predictive Modeling Kaggle Challenge, Module 2 Assignment- [ ] Read [“Adopting a Hypothesis-Driven Workflow”](https://outline.com/5S5tsB), a blog post by a Lambda DS student about the Tanzania Waterpumps challenge.- [ ] Continue to participate in our Kaggle challenge.- [ ] Try Ordin... | import os, sys
in_colab = 'google.colab' in sys.modules
# If you're in Colab...
if in_colab:
# Pull files from Github repo
os.chdir('/content')
!git init .
!git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge.git
!git pull origin master
# Install required pytho... | _____no_output_____ | MIT | Vince_assignment_kaggle_challenge_2.ipynb | Vincent-Emma/DS-Unit-2-Kaggle-Challenge |
Write a pandas dataframe to disk as gunzip compressed csv- df.to_csv('dfsavename.csv.gz', compression='gzip') Read from disk- df = pd.read_csv('dfsavename.csv.gz', compression='gzip') Magic useful- %%timeit for the whole cell- %timeit for the specific line- %%latex to render the cell as a block of latex- %prun and %%p... | DATASET_PATH = '/media/rs/0E06CD1706CD0127/Kapok/WSDM/'
TRAIN_FILE = DATASET_PATH + 'all_train_withextra.csv'
TEST_FILE = DATASET_PATH + 'all_test_withextra.csv'
MEMBER_FILE = DATASET_PATH + 'members.csv'
SONG_FILE = DATASET_PATH + 'fix_songs.csv'
ALL_ARTIST = DATASET_PATH + 'all_artist_name.csv'
ALL_COMPOSER = DATASET... | _____no_output_____ | MIT | MusicRecommendation/TestXgboost.ipynb | HiKapok/KaggleCompetitions |
First and Second order random walksFirst and second order random walks are a node-sampling mechanism that can be employed in a large number of algorithms. In this notebook we will shortly show how to use Ensmallen to sample a large number of random walks from big graphs.To install the GraPE library run:```bashpip ins... | ! pip install -q ensmallen | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Retrieving a graph to run the sampling onIn this tutorial we will run samples on one of the graph from the ones available from the automatic graph retrieval of Ensmallen, namely the [Homo Sapiens graph from STRING](https://string-db.org/cgi/organisms). If you want to load a graph from an edge list, just follow the exa... | from ensmallen.datasets.string import HomoSapiens | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Retrieving and loading the graph | graph = HomoSapiens()
# We also create a version of the graph without edge weights
unweighted_graph = graph.remove_edge_weights() | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
We compute the graph report: | graph | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
and the unweighted graph report: | unweighted_graph | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Random walks are heavily parallelizedAll the algorithms to sample random walks provided by Ensmallen are heavily parallelized and therefore executing them on instances with a large amount amount of threads will lead to (obviously) better time performance. This notebook is being executed on a COLAB instance with only 2... | from multiprocessing import cpu_count
cpu_count() | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Unweighted first-order random walksComputation of first-order random walks ignoring the edge weights. | %%time
unweighted_graph.random_walks(
# We want random walks with length 100
walk_length=32,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 2 iterations from each node
iterations=2
)
%%time
unweighted_graph.complete_walks(
# We want random walks with l... | CPU times: user 2.85 s, sys: 13.2 ms, total: 2.86 s
Wall time: 1.54 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Weighted first-order random walksComputation of first-order random walks, biased using the edge weights. | %%time
graph.random_walks(
# We want random walks with length 100
walk_length=32,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 2 iterations from each node
iterations=2
) | CPU times: user 1.49 s, sys: 14.9 ms, total: 1.51 s
Wall time: 794 ms
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Similarly, to get random walks from all of the nodes in the graph (that are not singletons) it is possible to use: | %%time
graph.complete_walks(
# We want random walks with length 100
walk_length=100,
# We want 2 iterations from each node
iterations=2
) | CPU times: user 1min 33s, sys: 401 ms, total: 1min 34s
Wall time: 48 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Second-order random walksSecondly, we proceed to show the computation of second-order random walks, that is random walks that use [Node2Vec parameters](https://arxiv.org/abs/1607.00653) to bias the random walk towards a BFS or a DFS. | %%time
graph.random_walks(
# We want random walks with length 100
walk_length=32,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 2 iterations from each node
iterations=2,
return_weight=2.0,
explore_weight=2.0,
)
%%time
unweighted_graph.random_walks... | CPU times: user 46.2 s, sys: 149 ms, total: 46.4 s
Wall time: 23.6 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Approximated second-order random walksOn graphs that include nodes with extremely high node degrees, for instance above 50000, the computation of their transition weights can be a bottleneck. In those use-cases approximated random walks can help make the computation considerably faster, by randomly subsampling each no... | %%time
graph.random_walks(
# We want random walks with length 100
walk_length=32,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 2 iterations from each node
iterations=2,
return_weight=2.0,
explore_weight=2.0,
# We will subsample the neighbours... | CPU times: user 18.5 s, sys: 57.7 ms, total: 18.6 s
Wall time: 9.45 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Enabling the speedupsAs explained more in details in the tutorial [add reference to tutorial], there are numerous speed-ups time-memory tradeoffs available in Ensmallen. These speedups allow you to exchange to use more RAM and get faster computation. Generally speaking, these speedups on graphs that have less than a f... | graph.enable() | _____no_output_____ | MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Weighted first order random walks with speedupsThe first order random walks have about an order of magnitude speed increase. | %%time
graph.random_walks(
# We want random walks with length 100
walk_length=100,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 10 iterations from each node
iterations=2
)
%%time
graph.complete_walks(
# We want random walks with length 100
walk_l... | CPU times: user 7.66 s, sys: 41.8 ms, total: 7.7 s
Wall time: 3.99 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Second order random walks with speedups | %%time
graph.random_walks(
# We want random walks with length 100
walk_length=32,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 2 iterations from each node
iterations=2,
return_weight=2.0,
explore_weight=2.0,
)
%%time
graph.complete_walks(
# W... | CPU times: user 21.9 s, sys: 105 ms, total: 22 s
Wall time: 11.2 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Approximated second-order random walks with speedups | %%time
graph.random_walks(
# We want random walks with length 100
walk_length=32,
# We want to get random walks starting from 1000 random nodes
quantity=1000,
# We want 2 iterations from each node
iterations=2,
return_weight=2.0,
explore_weight=2.0,
# We will subsample the neighbours... | CPU times: user 6.3 s, sys: 22.7 ms, total: 6.33 s
Wall time: 3.23 s
| MIT | tutorials/First_and_Second_order_random_walks.ipynb | pnrobinson/grape |
Neural networks with PyTorchDeep learning networks tend to be massive with dozens or hundreds of layers, that's where the term "deep" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. PyTor... | # Import necessary packages
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import torch
import helper
import matplotlib.pyplot as plt | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Now we're going to build a larger network that can solve a (formerly) difficult problem, identifying text in an image. Here we'll use the MNIST dataset which consists of greyscale handwritten digits. Each image is 28x28 pixels, you can see a sample belowOur goal is to build a neural network that can take one of these i... | ### Run this cell
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
])
# Download and load the training data
trainset = datase... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. Later, we'll use this to loop through the dataset for training, like```pythonfor image, label in trainloader: do things with images and labels```You'll notice I created the `trainloader` with a batch size of 6... | dataiter = iter(trainloader)
images, labels = dataiter.next()
print(type(images))
print(images.shape)
print(labels.shape) | <class 'torch.Tensor'>
torch.Size([64, 1, 28, 28])
torch.Size([64])
| MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
This is what one of the images looks like. | plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r'); | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
First, let's try to build a simple network for this dataset using weight matrices and matrix multiplications. Then, we'll see how to do it using PyTorch's `nn` module which provides a much more convenient and powerful method for defining network architectures.The networks you've seen so far are called *fully-connected*... | ## Your solution
images = images.view(images.shape[0], -1)
W1 = torch.randn(784, 256)
B1 = torch.randn(1, 256)
W2 = torch.randn(256, 10)
B2 = torch.randn(1, 10)
def fn(x):
return 1 / (1 + torch.exp(-x))
# output of your network, should have shape (64,10)
h = fn(torch.mm(images, W1) + B1)
out = torch.mm(h, W2) +... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Now we have 10 outputs for our network. We want to pass in an image to our network and get out a probability distribution over the classes that tells us the likely class(es) the image belongs to. Something that looks like this:Here we see that the probability for each class is roughly the same. This is representing an ... | def softmax(x):
## TODO: Implement the softmax function here
denum = torch.sum(torch.exp(out), dim=1)
denum = denum.view(denum.shape[0], 1)
nomin = torch.exp(x)
return nomin / denum
# Here, out should be the output of the network in the previous excercise with shape (64,10)
probabilities ... | torch.Size([64, 10])
tensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0... | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Building networks with PyTorchPyTorch provides a module `nn` that makes building networks much simpler. Here I'll show you how to build the same one as above with 784 inputs, 256 hidden units, 10 output units and a softmax output. | from torch import nn
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(256, 10)
# De... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Let's go through this bit by bit.```pythonclass Network(nn.Module):```Here we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class... | # Create the network and look at it's text representation
model = Network()
model | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
You can define the network somewhat more concisely and clearly using the `torch.nn.functional` module. This is the most common way you'll see networks defined as many operations are simple element-wise functions. We normally import this module as `F`, `import torch.nn.functional as F`. | import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(256, 10)
def f... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Activation functionsSo far we've only been looking at the sigmoid activation function, but in general any function can be used as an activation function. The only requirement is that for a network to approximate a non-linear function, the activation functions must be non-linear. Here are a few more examples of common ... | ## Your solution here
class Netowrk(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 64)
self.output = nn.Linear(64, 10)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Initializing weights and biasesThe weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance. | print(model.fc1.weight)
print(model.fc1.bias) | Parameter containing:
tensor([[-0.0212, -0.0195, 0.0222, ..., -0.0317, -0.0309, -0.0017],
[-0.0099, 0.0313, -0.0179, ..., -0.0240, -0.0309, -0.0157],
[-0.0067, 0.0024, 0.0155, ..., -0.0145, -0.0326, 0.0130],
...,
[ 0.0105, -0.0156, 0.0041, ..., -0.0071, 0.0277, -0.0330],
... | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values. | # Set biases to all zeros
model.fc1.bias.data.fill_(0)
# sample from random normal with standard dev = 0.01
model.fc1.weight.data.normal_(std=0.01) | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Forward passNow that we have a network, let's see what happens when we pass in an image. | # Grab some data
dataiter = iter(trainloader)
images, labels = dataiter.next()
# Resize images into a 1D vector, new shape is (batch size, color channels, image pixels)
images.resize_(64, 1, 784)
# or images.resize_(images.shape[0], 1, 784) to automatically get batch size
# Forward pass through the network
img_idx ... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random! Using `nn.Sequential`PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](ht... | # Hyperparameters for our network
input_size = 784
hidden_sizes = [128, 64]
output_size = 10
# Build a feed-forward network
model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
nn.ReLU(),
nn.Linear(hidden_sizes[0], hidden_sizes[1]),
nn.ReLU(),
... | Sequential(
(0): Linear(in_features=784, out_features=128, bias=True)
(1): ReLU()
(2): Linear(in_features=128, out_features=64, bias=True)
(3): ReLU()
(4): Linear(in_features=64, out_features=10, bias=True)
(5): Softmax(dim=1)
)
| MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output.The operations are available by passing in the appropriate index. For example, if you want to get first Linear operation ... | print(model[0])
model[0].weight | Linear(in_features=784, out_features=128, bias=True)
| MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
You can also pass in an `OrderedDict` to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so _each operation must have a different name_. | from collections import OrderedDict
model = nn.Sequential(OrderedDict([
('fc1', nn.Linear(input_size, hidden_sizes[0])),
('relu1', nn.ReLU()),
('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])),
('relu2', nn.ReLU()),
... | _____no_output_____ | MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Now you can access layers either by integer or the name | print(model[0])
print(model.fc1) | Linear(in_features=784, out_features=128, bias=True)
Linear(in_features=784, out_features=128, bias=True)
| MIT | intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb | lucasshenv/deep-learning-v2-pytorch |
Regular Expressions | import re | _____no_output_____ | Apache-2.0 | scripts/Regular Expressions (Toy Data).ipynb | masiyua1/Python_tutorial |
example data | line = '{"usernameTweet": "Tom", "ID": "1176953905143590912", "text": "Cant agree more! RT:Masks + vaccines + boosters = best protection against #Omicron.When you wear a mask, you help protect yourself & others from #COVID19. Choose a mask with the best fit, protection, and comfort for you.", "url": "/CDCGOV/status/117... | ['Tom', 'CDCGOV']
| Apache-2.0 | scripts/Regular Expressions (Toy Data).ipynb | masiyua1/Python_tutorial |
Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE filedistributed with this work for additional informationregarding copyright ownership. The ASF licenses this fileto you under the Apache License, Version 2.0 (the"License"); you may not use this file exce... | import Orange
import numpy as np
import pandas as pd
df = pd.read_csv('results_ucr.csv', usecols=[6, 9, 10, 11, 12, 13])[:85]
ranks = np.array(df.rank(axis=1, method='min', ascending=False).mean())
names = df.columns
cd = Orange.evaluation.compute_CD(ranks, 85)
t = Orange.evaluation.graph_ranks(ranks, names, cd=cd, fil... | _____no_output_____ | Apache-2.0 | cd.ipynb | JinYang88/UnsupervisedScalableRepresentationLearningTimeSeries |
Dead Code | import random
dead_codes = [
'''
int main() {
int alpha;
}
''',
'''
int main() {
int alpha = 0;
int beta = 5;
int gamma = alpha + beta;
}
''',
'''
int main() {
const int ALPHA = 10;
const int BETA = 5;
}
''',
'''
int... | int main()
{
int n;
int i;
int shuzu[111];
int count1 = 0;
int count3 = 0;
int count2 = 0;
int alpha;
int count4 = 0;
scanf("%d", &n);
while (n >= 100)
{
n = n - 100;
count1++;
}
int alpha = 0;
int beta = 5;
int gamma = alpha + beta;
while (n >= 50)
{
n = n - 50;
count... | MIT | notebooks/.ipynb_checkpoints/transforms-checkpoint.ipynb | david-maine/astnn |
Variable Renaimg | import pickle
used_vars = pickle.load( open( "/home/david/projects/university/astnn/var_names.pkl", "rb" ) )
src = """
int main() {
int alpha;
alpha = 0;
scanf("%d",&n);
}
"""
ast = parser.parse(src)
print(ast)
print(generator.visit(ast))
import os
import sys
module_path = os.path.abspath(os.path.join('..'... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/transforms-checkpoint.ipynb | david-maine/astnn |
Restrict to sensible variable names | import numpy as np
def restrict_w2v(w2v, restricted_word_set):
new_vectors = []
new_vocab = {}
new_index2entity = []
new_vectors_norm = []
for i in range(len(w2v.vocab)):
word = w2v.index2entity[i]
vec = w2v.vectors[i]
vocab = w2v.vocab[word]
vec_norm = w2v.vectors_... | int main()
{
int tempi;
int win;
int ws = 0;
int ml = 0;
int cos = 0;
int sen = 0;
scanf("%d", &tempi);
while (tempi >= 100)
{
tempi = tempi - 100;
ws++;
}
while (tempi >= 50)
{
tempi = tempi - 50;
cos++;
}
while (tempi >= 20)
{
tempi = tempi - 20;
ml++;
}
wh... | MIT | notebooks/.ipynb_checkpoints/transforms-checkpoint.ipynb | david-maine/astnn |
Training Neural NetworksThe network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten ... | import torch
from torch import nn
import torch.nn.functional as F
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
])
# Downl... | _____no_output_____ | MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
NoteIf you haven't seen `nn.Sequential` yet, please finish the end of the Part 2 notebook. | # Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10))
# Define the loss
criterion = nn.CrossEntropyLoss()
# Get our data
dataiter = iter(trainloader)... | tensor(2.3003, grad_fn=<NllLossBackward>)
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.htmltorch.nn.LogSoftmax)). Then you can get the actual probabilities by taking the exponential `torch.exp(output)`. With a log-softmax output, y... | # TODO: Build a feed-forward network
model = nn.Sequential(nn.Linear(784,128),
nn.ReLU(),
nn.Linear(128,64),
nn.ReLU(),
nn.Linear(64,10),
nn.LogSoftmax(dim=1)
)
# TODO: Define the loss
cri... | tensor(2.3045, grad_fn=<NllLossBackward>)
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
AutogradNow that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operati... | x = torch.randn(2,2, requires_grad=True)
print(x)
y = x**2
print(y) | tensor([[7.1960e-03, 2.7573e-01],
[7.3863e-05, 1.3079e+00]], grad_fn=<PowBackward0>)
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
Below we can see the operation that created `y`, a power operation `PowBackward0`. | ## grad_fn shows the function that generated this variable
print(y.grad_fn) | <PowBackward0 object at 0x000001E5C27A9CD0>
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
The autograd module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean. | z = y.mean()
print(z) | tensor(0.3977, grad_fn=<MeanBackward0>)
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
You can check the gradients for `x` and `y` but they are empty currently. | print(x.grad) | None
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x`$$\frac{\partial z}{\partial x} = \frac{\partial}{\partial x}\left[\frac{1}{n}\sum_i^n x_i^2\right] = \frac{x}{2}$$ | z.backward()
print(x.grad)
print(x/2) | tensor([[-0.0424, 0.2625],
[-0.0043, 0.5718]])
tensor([[-0.0424, 0.2625],
[-0.0043, 0.5718]], grad_fn=<DivBackward0>)
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
These gradients calculations are particularly useful for neural networks. For training we need the gradients of the cost with respect to the weights. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the grad... | # Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10),
nn.LogSoftmax(dim=1))
criterion = nn.NLLLoss()
dataiter = iter(trainloader... | Before backward pass:
None
After backward pass:
tensor([[-0.0012, -0.0012, -0.0012, ..., -0.0012, -0.0012, -0.0012],
[-0.0002, -0.0002, -0.0002, ..., -0.0002, -0.0002, -0.0002],
[-0.0021, -0.0021, -0.0021, ..., -0.0021, -0.0021, -0.0021],
...,
[-0.0005, -0.0005, -0.0005, ..., -0.... | MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
Training the network!There's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to... | from torch import optim
# Optimizers require the parameters to optimize and a learning rate
optimizer = optim.SGD(model.parameters(), lr=0.01) | _____no_output_____ | MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch:* Make a forward pass through the network * Use the network output to calculate the loss* Perform a backward pass throug... | print('Initial weights - ', model[0].weight)
dataiter = iter(trainloader)
images, labels = next(dataiter)
images.resize_(64, 784)
# Clear the gradients, do this because gradients are accumulated
optimizer.zero_grad()
# Forward pass, then backward pass, then update weights
output = model(images)
loss = criterion(outp... | Updated weights - Parameter containing:
tensor([[ 0.0338, -0.0036, -0.0355, ..., 0.0301, -0.0247, 0.0167],
[-0.0321, 0.0066, 0.0354, ..., 0.0267, 0.0344, -0.0230],
[ 0.0110, -0.0167, -0.0310, ..., 0.0339, -0.0177, -0.0171],
...,
[ 0.0275, -0.0146, 0.0074, ..., -0.0061, 0.00... | MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
Training for realNow we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll doing a training pass where we calculate the l... | ## Your solution here
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10),
nn.LogSoftmax(dim=1))
criterion = nn.NLLLoss()
optimizer = optim.SGD(model.paramet... | Training loss: 1.946036617766057
Training loss: 0.8951423045541687
Training loss: 0.5485408180303919
Training loss: 0.4467467614519062
Training loss: 0.39703025616435356
| MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
With the network trained, we can check out it's predictions. | %matplotlib inline
import helper
dataiter = iter(trainloader)
images, labels = next(dataiter)
img = images[0].view(1, 784)
# Turn off gradients to speed up this part
with torch.no_grad():
logps = model(img)
# Output of the network are log-probabilities, need to take exponential for probabilities
ps = torch.exp(l... | _____no_output_____ | MIT | intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb | aliwajahat12/deep-learning-v2-pytorch-forked |
Классификация MNIST сверточной сетью | %matplotlib inline
import matplotlib.pyplot as plt
import cv2
import numpy as np
from tensorflow import keras
train = np.loadtxt('train.csv', delimiter=',', skiprows=1)
test = np.loadtxt('test.csv', delimiter=',', skiprows=1)
# сохраняем разметку в отдельную переменную
train_label = train[:, 0]
# приводим размерность ... | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Визуализируем исходные данные | fig = plt.figure(figsize=(20, 10))
for i, img in enumerate(train_img[0:5, :], 1):
subplot = fig.add_subplot(1, 5, i)
plt.imshow(img[:,:,0], cmap='gray');
subplot.set_title('%s' % train_label[i - 1]); | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Разбиваем выборку на обучение и валидацию | from sklearn.model_selection import train_test_split
y_train, y_val, x_train, x_val = train_test_split(
train_label, train_img, test_size=0.2, random_state=42) | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Собираем сверточную сеть для обучения | seed = 123457
kernek_initializer = keras.initializers.glorot_normal(seed=seed)
bias_initializer = keras.initializers.normal(stddev=1., seed=seed)
model = keras.models.Sequential()
model.add(keras.layers.Conv2D(6,
kernel_size=(5, 5),
padding='same',
... | WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/initializers.py:143: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argum... | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Выводим информацию о модели | model.summary() | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 28, 28, 6) 156
____________________________________... | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
One hot encoding разметки | y_train_labels = keras.utils.to_categorical(y_train)
y_train[:10]
y_train_labels[:10] | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Запускаем обучение | model.fit(x_train,
y_train_labels,
batch_size=32,
epochs=5,
validation_split=0.2) | Train on 26880 samples, validate on 6720 samples
Epoch 1/5
26880/26880 [==============================] - 19s 708us/sample - loss: 0.9753 - acc: 0.7766 - val_loss: 0.2560 - val_acc: 0.9298
Epoch 2/5
26880/26880 [==============================] - 21s 776us/sample - loss: 0.1949 - acc: 0.9466 - val_loss: 0.1530 - val_acc... | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Предсказываем класс объекта | pred_val = model.predict_classes(x_val)
pred_val[:10] | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Оцениваем качество решение на валидационной выборке | from sklearn.metrics import accuracy_score
print('Accuracy: %s' % accuracy_score(y_val, pred_val))
from sklearn.metrics import classification_report
print(classification_report(y_val, pred_val))
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_val, pred_val)) | [[801 0 2 1 0 1 2 0 0 9]
[ 0 897 5 1 1 0 0 2 0 3]
[ 0 4 831 3 3 0 1 1 1 2]
[ 1 0 3 915 0 1 1 5 4 7]
[ 1 1 2 0 805 0 4 1 3 22]
[ 1 1 0 11 2 668 3 3 3 10]
[ 4 2 1 0 0 3 769 0 4 2]
[ 1 0 11 6 ... | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Предсказания на тестовыйх данных | pred_test = model.predict_classes(test_img) | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Визуализируем предсказания | fig = plt.figure(figsize=(20, 10))
indices = np.random.choice(range(len(test_img)), 5)
img_prediction = zip(test_img[indices], pred_test[indices])
for i, (img, pred) in enumerate(img_prediction, 1):
subplot = fig.add_subplot(1, 5, i)
plt.imshow(img[...,0], cmap='gray');
subplot.set_title('%d' % pred); | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
Готовим файл для отправки | with open('submit.txt', 'w') as dst:
dst.write('ImageId,Label\n')
for i, p in enumerate(pred_test, 1):
dst.write('%s,%d\n' % (i, p))
# Your submission scored 0.9730952380952381 | _____no_output_____ | MIT | Lectures notebooks/(Lectures notebooks) netology Machine learning/15. Convolutional Neural Network (CNN)/005_cnn_mnist.ipynb | Alex110117/data_analysis |
prepared by Abuzer Yakaryilmaz (QLatvia) updated by Özlem Salehi | September 17, 2020 This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. $ \newcommand{\br... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_pairs = ['00','01','10','11']
#
# your code is here
#
| _____no_output_____ | Apache-2.0 | bronze/B50_Superdense_Coding.ipynb | KuantumTurkiye/bronze |
click for our solution Task 2 Verify each case by tracing the state vector (on paper). Task 3 [Extra]Can the above set-up be used by Balvis?Verify that the following modified protocol allows Balvis to send two classical bits by sending only his qubit.For each pair of $ (a,b) \in \left\{ (0,0), (0,1), (1,0),(1,1) \ri... | # import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_pairs = ['00','01','10','11']
#
# your code is here
#
| _____no_output_____ | Apache-2.0 | bronze/B50_Superdense_Coding.ipynb | KuantumTurkiye/bronze |
Project: Part of Speech Tagging with Hidden Markov Models --- IntroductionPart of speech tagging is the process of determining the syntactic category of a word from the words in its surrounding context. It is often used to help disambiguate natural language phrases because it can be done quickly with high accuracy. Ta... | # Jupyter "magic methods" -- only need to be run once per kernel restart
%load_ext autoreload
%aimport helpers, tests
%autoreload 1
# import python modules -- this cell needs to be run again if you make changes to any of the files
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.display import HTML... | _____no_output_____ | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Step 1: Read and preprocess the dataset---We'll start by reading in a text corpus and splitting it into a training and testing dataset. The data set is a copy of the [Brown corpus](https://en.wikipedia.org/wiki/Brown_Corpus) (originally from the [NLTK](https://www.nltk.org/) library) that has already been pre-processe... | data = Dataset("tags-universal.txt", "brown-universal.txt", train_test_split=0.8)
print("There are {} sentences in the corpus.".format(len(data)))
print("There are {} sentences in the training set.".format(len(data.training_set)))
print("There are {} sentences in the testing set.".format(len(data.testing_set)))
asser... | There are 57340 sentences in the corpus.
There are 45872 sentences in the training set.
There are 11468 sentences in the testing set.
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
The Dataset InterfaceYou can access (mostly) immutable references to the dataset through a simple interface provided through the `Dataset` class, which represents an iterable collection of sentences along with easy access to partitions of the data for training & testing. Review the reference below, then run and review... | key = 'b100-38532'
print("Sentence: {}".format(key))
print("words:\n\t{!s}".format(data.sentences[key].words))
print("tags:\n\t{!s}".format(data.sentences[key].tags)) | Sentence: b100-38532
words:
('Perhaps', 'it', 'was', 'right', ';', ';')
tags:
('ADV', 'PRON', 'VERB', 'ADJ', '.', '.')
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
**Note:** The underlying iterable sequence is **unordered** over the sentences in the corpus; it is not guaranteed to return the sentences in a consistent order between calls. Use `Dataset.stream()`, `Dataset.keys`, `Dataset.X`, or `Dataset.Y` attributes if you need ordered access to the data. Counting Unique ElementsY... | print("There are a total of {:,} samples of {:,} unique words in the corpus."
.format(data.N, len(data.vocab)))
print("There are {:,} samples of {:,} unique words in the training set."
.format(data.training_set.N, len(data.training_set.vocab)))
print("There are {:,} samples of {:,} unique words in the testi... | There are a total of 1,161,192 samples of 56,057 unique words in the corpus.
There are 928,458 samples of 50,536 unique words in the training set.
There are 232,734 samples of 25,112 unique words in the testing set.
There are 5,521 words in the test set that are missing in the training set.
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Accessing word and tag SequencesThe `Dataset.X` and `Dataset.Y` attributes provide access to ordered collections of matching word and tag sequences for each sentence in the dataset. | # accessing words with Dataset.X and tags with Dataset.Y
for i in range(2):
print("Sentence {}:".format(i + 1), data.X[i])
print()
print("Labels {}:".format(i + 1), data.Y[i])
print() | Sentence 1: ('Mr.', 'Podger', 'had', 'thanked', 'him', 'gravely', ',', 'and', 'now', 'he', 'made', 'use', 'of', 'the', 'advice', '.')
Labels 1: ('NOUN', 'NOUN', 'VERB', 'VERB', 'PRON', 'ADV', '.', 'CONJ', 'ADV', 'PRON', 'VERB', 'NOUN', 'ADP', 'DET', 'NOUN', '.')
Sentence 2: ('But', 'there', 'seemed', 'to', 'be', 'som... | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Accessing (word, tag) SamplesThe `Dataset.stream()` method returns an iterator that chains together every pair of (word, tag) entries across all sentences in the entire corpus. | # use Dataset.stream() (word, tag) samples for the entire corpus
print("\nStream (word, tag) pairs:\n")
for i, pair in enumerate(data.stream()):
print("\t", pair)
if i > 10: break |
Stream (word, tag) pairs:
('Mr.', 'NOUN')
('Podger', 'NOUN')
('had', 'VERB')
('thanked', 'VERB')
('him', 'PRON')
('gravely', 'ADV')
(',', '.')
('and', 'CONJ')
('now', 'ADV')
('he', 'PRON')
('made', 'VERB')
('use', 'NOUN')
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
For both our baseline tagger and the HMM model we'll build, we need to estimate the frequency of tags & words from the frequency counts of observations in the training corpus. In the next several cells you will complete functions to compute the counts of several sets of counts. Step 2: Build a Most Frequent Class tag... | def pair_counts(tags, words):
"""Return a dictionary keyed to each unique value in the first sequence list
that counts the number of occurrences of the corresponding value from the
second sequences list.
For example, if sequences_A is tags and sequences_B is the corresponding
words, then if 124... | 1275
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
IMPLEMENTATION: Most Frequent Class TaggerUse the `pair_counts()` function and the training dataset to find the most frequent class label for each word in the training data, and populate the `mfc_table` below. The table keys should be words, and the values should be the appropriate tag string.The `MFCTagger` class is ... | # Create a lookup table mfc_table where mfc_table[word] contains the tag label most frequently assigned to that word
from collections import namedtuple
FakeState = namedtuple("FakeState", "name")
class MFCTagger:
# NOTE: You should not need to modify this class or any of its methods
missing = FakeState(name="... | dict_keys(['ADV', 'NOUN', '.', 'VERB', 'ADP', 'ADJ', 'CONJ', 'DET', 'PRT', 'NUM', 'PRON', 'X'])
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Making Predictions with a ModelThe helper functions provided below interface with Pomegranate network models & the mocked MFCTagger to take advantage of the [missing value](http://pomegranate.readthedocs.io/en/latest/nan.html) functionality in Pomegranate through a simple sequence decoding function. Run these function... | def replace_unknown(sequence):
"""Return a copy of the input sequence where each unknown word is replaced
by the literal string value 'nan'. Pomegranate will ignore these values
during computation.
"""
return [w if w in data.training_set.vocab else 'nan' for w in sequence]
def simplify_decoding(X, ... | _____no_output_____ | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Example Decoding Sequences with MFC Tagger | for key in data.testing_set.keys[:3]:
print("Sentence Key: {}\n".format(key))
print("Predicted labels:\n-----------------")
print(simplify_decoding(data.sentences[key].words, mfc_model))
print()
print("Actual labels:\n--------------")
print(data.sentences[key].tags)
print("\n") | Sentence Key: b100-28144
Predicted labels:
-----------------
['CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN', '.', '.']
Actual labels:
--------------
('CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN... | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Evaluating Model AccuracyThe function below will evaluate the accuracy of the MFC tagger on the collection of all sentences from a text corpus. | def accuracy(X, Y, model):
"""Calculate the prediction accuracy by using the model to decode each sequence
in the input X and comparing the prediction with the true labels in Y.
The X should be an array whose first dimension is the number of sentences to test,
and each element of the array should b... | _____no_output_____ | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Evaluate the accuracy of the MFC taggerRun the next cell to evaluate the accuracy of the tagger on the training and test corpus. | mfc_training_acc = accuracy(data.training_set.X, data.training_set.Y, mfc_model)
print("training accuracy mfc_model: {:.2f}%".format(100 * mfc_training_acc))
mfc_testing_acc = accuracy(data.testing_set.X, data.testing_set.Y, mfc_model)
print("testing accuracy mfc_model: {:.2f}%".format(100 * mfc_testing_acc))
assert ... | training accuracy mfc_model: 95.72%
testing accuracy mfc_model: 93.02%
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Step 3: Build an HMM tagger---The HMM tagger has one hidden state for each possible tag, and parameterized by two distributions: the emission probabilties giving the conditional probability of observing a given **word** from each hidden state, and the transition probabilities giving the conditional probability of movi... | line_len = 60
print('data.training_set.X (WORDS)')
print('='*line_len)
max_display = 3
i = 1
for x in data.training_set.X:
print(x)
print('-'*line_len)
i += 1
if i >= max_display:
break
print('data.training_set.Y (TAGS)')
print('='*line_len)
i = 1
for x in data.training_set.Y:
... | {'ADV': 44877, 'NOUN': 220632, '.': 117757, 'VERB': 146161, 'ADP': 115808, 'ADJ': 66754, 'CONJ': 30537, 'DET': 109671, 'PRT': 23906, 'NUM': 11878, 'PRON': 39383, 'X': 1094}
928458
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
IMPLEMENTATION: Bigram CountsComplete the function below to estimate the co-occurrence frequency of each pair of symbols in each of the input sequences. These counts are used in the HMM model to estimate the bigram probability of two tags from the frequency counts according to the formula: $$P(tag_2|tag_1) = \frac{C(t... | def bigram_counts(tag_sequences):
"""Return a dictionary keyed to each unique PAIR of values in the input sequences
list that counts the number of occurrences of pair in the sequences list. The input
should be a 2-dimensional array.
For example, if the pair of tags (NOUN, VERB) appear 61582 times, ... | {'VERB VERB': 26957, 'PRON VERB': 27860, 'ADP NOUN': 29965, 'NOUN NOUN': 32990, 'NOUN VERB': 34972, 'ADJ NOUN': 43664, 'ADP DET': 52841, 'NOUN ADP': 53884, 'NOUN .': 62639, 'DET NOUN': 68785}
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
IMPLEMENTATION: Sequence Starting CountsComplete the code below to estimate the bigram probabilities of a sequence starting with each tag. | def starting_counts(tag_sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the beginning of
a sequence.
For example, if 8093 sequences start with NOUN, then you should return a
dictionary such th... | _____no_output_____ | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
IMPLEMENTATION: Sequence Ending CountsComplete the function below to estimate the bigram probabilities of a sequence ending with each tag. | def ending_counts(tag_sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the end of
a sequence.
For example, if 18 sequences end with DET, then you should return a
dictionary such that your_start... | {'.': 44936, 'NOUN': 722, 'NUM': 63, 'VERB': 75, 'ADJ': 25, 'ADV': 16, 'ADP': 7, 'DET': 14, 'CONJ': 2, 'PRON': 4, 'PRT': 7, 'X': 1}
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
IMPLEMENTATION: Basic HMM TaggerUse the tag unigrams and bigrams calculated above to construct a hidden Markov tagger.- Add one state per tag - The emission distribution at each state should be estimated with the formula: $P(w|t) = \frac{C(t, w)}{C(t)}$- Add an edge from the starting state `basic_model.start` to ea... | #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#>>> Emission Probabilities
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#states = list()
state_data = dict()
for tag in word_counts.keys():
emission_probabilities = dict()
#P(word|tag) = C(tag, word) / C(tag)
total_count = tag_unigrams[tag] #sum(word_counts[tag].values())
fo... | training accuracy basic hmm model: 97.54%
testing accuracy basic hmm model: 95.98%
| MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Example Decoding Sequences with the HMM Tagger | for key in data.testing_set.keys[:3]:
print("Sentence Key: {}\n".format(key))
print("Predicted labels:\n-----------------")
print(simplify_decoding(data.sentences[key].words, basic_model))
print()
print("Actual labels:\n--------------")
print(data.sentences[key].tags)
print("\n") | Sentence Key: b100-28144
Predicted labels:
-----------------
['CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN', '.', '.']
Actual labels:
--------------
('CONJ', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'NOUN', 'NUM', '.', 'CONJ', 'NOUN', 'NUM', '.', '.', 'NOUN... | MIT | HMM Tagger.ipynb | luiscberrocal/hmm-tagger |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.