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
List the model files uploaded during the run:
print(best_run.get_file_names())
_____no_output_____
Apache-2.0
azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb
miguelusque/cloud-ml-examples
Register the folder (and all files in it) as a model named `train-rapids` under the workspace for deployment
# model = best_run.register_model(model_name='train-rapids', model_path='outputs/model-rapids.joblib')
_____no_output_____
Apache-2.0
azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb
miguelusque/cloud-ml-examples
Delete cluster
# delete the cluster # gpu_cluster.delete()
_____no_output_____
Apache-2.0
azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb
miguelusque/cloud-ml-examples
[Optional]: If you're using a Mac/Linux, you can check your environment with these commands:```!which pip3!which python3!ls -lah /usr/local/bin/python3```
!pip3 install -U pip !pip3 install torch==1.3.0 !pip3 install seaborn import torch torch.cuda.is_available() # IPython candies... from IPython.display import Image from IPython.core.display import HTML from IPython.display import clear_output %%html <style> table {float:left} </style>
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Perceptron=====**Perceptron** algorithm is a:> "*system that depends on **probabilistic** rather than deterministic principles for its operation, gains its reliability from the **properties of statistical measurements obtain from a large population of elements***"> \- Frank Rosenblatt (1957)Then the news:> "*[Perceptro...
##Image(url="perceptron.png", width=500) Image(url="https://ibin.co/4TyMU8AdpV4J.png", width=500)
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
(**Note:** Usually, we use $x_1$ as the bias and fix the input to 1) Perceptron as a Workflow Diagram----If you're familiar with [mermaid flowchart](https://mermaidjs.github.io)```.. mermaid:: graph LR subgraph Input x_1 x_i x_n end subgraph Perceptron n1((s))...
##Image(url="perceptron-mermaid.svg", width=500) Image(url="https://svgshare.com/i/AbJ.svg", width=500)
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Optimization Process====To learn the weights, $w$, we use an **optimizer** to find the best-fit (optimal) values for $w$ such that the inputs correct maps to the outputs.Typically, process performs the following 4 steps iteratively. **Initialization** - **Step 1**: Initialize weights vector **Forward Propagation** - ...
import math import numpy as np np.random.seed(0) def sigmoid(x): # Returns values that sums to one. return 1 / (1 + np.exp(-x)) def sigmoid_derivative(sx): # See https://math.stackexchange.com/a/1225116 # Hint: let sx = sigmoid(x) return sx * (1 - sx) sigmoid(np.array([2.5, 0.32, -1.42])) ...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Representing OR Boolean---Lets consider the problem of the OR boolean and apply the perceptron with simple gradient descent. | x2 | x3 | y | |:--:|:--:|:--:|| 0 | 0 | 0 || 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 |
X = or_input = np.array([[0,0], [0,1], [1,0], [1,1]]) Y = or_output = np.array([[0,1,1,1]]).T or_input or_output # Define the shape of the weight vector. num_data, input_dim = or_input.shape # Define the shape of the output vector. output_dim = len(or_output.T) print('Inputs\n======') print('no. of rows =', num_data) ...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Step 2a: Multiply the weights vector with the inputs, sum the products====To get the output of step 2a, - Itrate through each row of the data, `X` - For each column in each row, find the product of the value and the respective weights - For each row, compute the sum of the products
# If we write it imperatively: summation = [] for row in X: sum_wx = 0 for feature, weight in zip(row, W): sum_wx += feature * weight summation.append(sum_wx) print(np.array(summation)) # If we vectorize the process and use numpy. np.dot(X, W)
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Train the Single-Layer Model====
num_epochs = 10000 # No. of times to iterate. learning_rate = 0.03 # How large a step to take per iteration. # Lets standardize and call our inputs X and outputs Y X = or_input Y = or_output for _ in range(num_epochs): layer0 = X # Step 2a: Multiply the weights vector with the inputs, sum the products, i.e. ...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Lets try the XOR Boolean---Lets consider the problem of the OR boolean and apply the perceptron with simple gradient descent. | x2 | x3 | y | |:--:|:--:|:--:|| 0 | 0 | 0 || 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 |
X = xor_input = np.array([[0,0], [0,1], [1,0], [1,1]]) Y = xor_output = np.array([[0,1,1,0]]).T xor_input xor_output num_epochs = 10000 # No. of times to iterate. learning_rate = 0.003 # How large a step to take per iteration. # Lets drop the last row of data and use that as unseen test. X = xor_input Y = xor_output ...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
You can't represent XOR with simple perceptron !!!====No matter how you change the hyperparameters or data, the XOR function can't be represented by a single perceptron layer. There's no way you can get all four data points to get the correct outputs for the XOR boolean operation. Solving XOR (Add more layers)====
from itertools import chain import numpy as np np.random.seed(0) def sigmoid(x): # Returns values that sums to one. return 1 / (1 + np.exp(-x)) def sigmoid_derivative(sx): # See https://math.stackexchange.com/a/1225116 return sx * (1 - sx) # Cost functions. def cost(predicted, truth): return truth - ...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Now try adding another layer====Use the same process: 1. Initialize 2. Forward Propagate 3. Back Propagate 4. Update (aka step)
from itertools import chain import numpy as np np.random.seed(0) def sigmoid(x): # Returns values that sums to one. return 1 / (1 + np.exp(-x)) def sigmoid_derivative(sx): # See https://math.stackexchange.com/a/1225116 return sx * (1 - sx) # Cost functions. def cost(predicted, truth): return truth - ...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Now, lets do it with PyTorch First lets try a single perceptron and see that we can't train a model that can represent XOR.
from tqdm import tqdm import torch from torch import nn from torch.autograd import Variable from torch import FloatTensor from torch import optim use_cuda = torch.cuda.is_available() import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set_style("darkgrid") sns.set(rc={'figure.figsize':(15, 10...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
(**Note**: Personally, I strongely encourage you to go through the [University of Washington course of machine learning regression](https://www.coursera.org/learn/ml-regression) to better understand the fundamentals of (i) ***gradient***, (ii) ***loss*** and (iii) ***optimizer***. But given that you know how to code it...
num_epochs = 1000 # Step 1: Initialization. # Note: When using PyTorch a lot of the manual weights # initialization is done automatically when we define # the model (aka architecture) model = nn.Sequential( nn.Linear(input_dim, output_dim), nn.Sigmoid()) criterion = nn.MSELoss() l...
Input: [0, 0] Pred: 0 Ouput: 0 ###### Input: [0, 1] Pred: 0 Ouput: 1 ###### Input: [1, 0] Pred: 0 Ouput: 1 ###### Input: [1, 1] Pred: 0 Ouput: 0 ######
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Now, try again with 2 layers using PyTorch====
%%time hidden_dim = 5 num_data, input_dim = X_pt.shape num_data, output_dim = Y_pt.shape model = nn.Sequential(nn.Linear(input_dim, hidden_dim), nn.Sigmoid(), nn.Linear(hidden_dim, output_dim), nn.Sigmoid()) criterion = nn.MSELoss() learning_rate = 0...
Input: [0, 0] Pred: 0 Ouput: 0 ###### Input: [0, 1] Pred: 1 Ouput: 1 ###### Input: [1, 0] Pred: 1 Ouput: 1 ###### Input: [1, 1] Pred: 0 Ouput: 0 ######
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
MNIST: The "Hello World" of Neural Nets====Like any deep learning class, we ***must*** do the MNIST. The MNIST dataset is - is made up of handwritten digits - 60,000 examples training set - 10,000 examples test set
# We're going to install tensorflow here because their dataset access is simpler =) !pip3 install torchvision from torchvision import datasets, transforms mnist_train = datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([ tran...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Lets apply what we learn about multi-layered perceptron with PyTorch and apply it to the MNIST data.
X_mnist = mnist_train.data.float() Y_mnist = mnist_train.targets.float() X_mnist_test = mnist_test.data.float() Y_mnist_test = mnist_test.targets.float() Y_mnist.shape # Use FloatTensor.shape to get the shape of the matrix/tensor. num_data, *input_dim = X_mnist.shape print('No. of images:', num_data) print('Inputs Dim...
_____no_output_____
MIT
completed/Session 1 - Hello DL World.ipynb
tongni1975/tsundoku
Interpolation
df = pd.DataFrame( { 'name': ['A','A', 'B','B','B','B', 'C','C','C'], 'value': [1, np.nan, np.nan, 2, 3, 1, 3, np.nan, 3], } ) df df.fillna(method="pad") df['value'].interpolate() df['value'].interpolate(method="quadratic") # For cumsums df['value'].interpolate(method="pchip")
_____no_output_____
Apache-2.0
Time Series/Missing-values_Multistep_Multivariate.ipynb
AlexKH22/Finance
LSTM
from pandas import read_csv from datetime import datetime # load data def parse(x): return datetime.strptime(x, '%Y %m %d %H') dataset = read_csv('data/raw_pollution.csv', parse_dates = [['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse) dataset.drop('No', axis=1, inplace=True) # manually specify c...
(8760, 1, 8) (8760,) (35039, 1, 8) (35039,)
Apache-2.0
Time Series/Missing-values_Multistep_Multivariate.ipynb
AlexKH22/Finance
We will define the LSTM with 50 neurons in the first hidden layer and 1 neuron in the output layer for predicting pollution. The input shape will be 1 time step with 8 features.We will use the Mean Absolute Error (MAE) loss function and the efficient Adam version of stochastic gradient descent.
# design network model = Sequential() model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2]))) model.add(Dense(1)) model.compile(loss='mae', optimizer='adam') # fit network history = model.fit(train_X, train_y, epochs=50, batch_size=64, validation_data=(test_X, test_y), verbose=2, shuf...
_____no_output_____
Apache-2.0
Time Series/Missing-values_Multistep_Multivariate.ipynb
AlexKH22/Finance
N previous lags
# load dataset dataset = read_csv('data/pollution.csv', header=0, index_col=0) values = dataset.values # integer encode direction encoder = LabelEncoder() values[:,4] = encoder.fit_transform(values[:,4]) # ensure all data is float values = values.astype('float32') # normalize features scaler = MinMaxScaler(feature_rang...
(43797, 32)
Apache-2.0
Time Series/Missing-values_Multistep_Multivariate.ipynb
AlexKH22/Finance
Next, we need to be more careful in specifying the column for input and output.We have 3 * 8 + 8 columns in our framed dataset. We will take 3 * 8 or 24 columns as input for the obs of all features across the previous 3 hours. We will take just the pollution variable as output at the following hour, as follows:
# split into train and test sets values = reframed.values n_train_hours = 365 * 24 train = values[:n_train_hours] test = values[n_train_hours:] # split into input and outputs n_obs = n_hours * n_features train_X, train_y = train[:, :n_obs], train[:, -n_features] test_X, test_y = test[:, :n_obs], test[:, -n_features] p...
Test RMSE: 22.785
Apache-2.0
Time Series/Missing-values_Multistep_Multivariate.ipynb
AlexKH22/Finance
Notebook for creating complete HRDPS file for 2007 from 2007 data, for every variable, all at once. For a more polished notebook, see generalPredictions4c. This notebook has been superceded by that notebook. Importing Training Data | Description | HRDPS | CANRCM | | ----------- | ----------- | ----------- |...
variables = [['tair', 'tas', 'Near-Surface Air Temperature'], ['precip', 'pr', 'Precipitation'], ['atmpres', 'psl', 'Sea Level Pressure'], ['qair', 'huss', 'Near Surface Specific Humidity'], ['solar', 'rsds', 'Shortwave radiation'], ['therm_rad', 'rl...
_____no_output_____
Apache-2.0
notebooks/generalPredictions4b.ipynb
UBC-MOAD/analysis-armaan
PCA Functions
##transforms and concatenates two data sets def transform2(data1, data2): A_mat = transform(data1) B_mat = transform(data2) return np.concatenate((A_mat, B_mat), axis=0) ##inverse function of transform2 - splits data matrix and returns two data sets def reverse2(matrix, orig_shape): split4 = int( matri...
_____no_output_____
Apache-2.0
notebooks/generalPredictions4b.ipynb
UBC-MOAD/analysis-armaan
Multiple Linear Regression Functions
##functions that use multiple linear regression to fit eigenvectors ##takes CANRCM eigenvectors (x1, x2, x3, x4...) and HRDPS eigenvectors (y1, y2, y3...) ##For each y from 0:result_size, approximates yn = a0 + a1*x1 + a2*x2 + a3*x3 ... using num_vec x's ##getCoefs returns (coeficients, intercept) ##fit_modes returns e...
_____no_output_____
Apache-2.0
notebooks/generalPredictions4b.ipynb
UBC-MOAD/analysis-armaan
Projection Function
##scalar projection of u onto v - with extra 1/norm factor (for math reasons) ##projectData projects the data onto each principle conponent, at each time ##output is a set of eigenvectors def project(u, v): v_norm = np.sqrt(np.sum(v**2)) return np.dot(u, v)/v_norm**2 def projectData(data_mat, new_PCs, n...
_____no_output_____
Apache-2.0
notebooks/generalPredictions4b.ipynb
UBC-MOAD/analysis-armaan
Overall Function
def reconstruct(downscale_mat, mean, can_PCs, can_me, hr_PCs, hr_me, n, r, method = 'LS', EB = 'False'): coefs = getCoefs(can_me, n + 1, hr_me, r + 1, type = method) proj = np.concatenate((mean.reshape(1, -1), projectData(downscale_mat - mean, can_PCs, n)), axis = 0) pred_eigs = np.matmul(coefs[0], proj) +...
_____no_output_____
Apache-2.0
notebooks/generalPredictions4b.ipynb
UBC-MOAD/analysis-armaan
Reconstructing Data
data = () ##reconstructing u and v winds import_wind_data() ##PCA on CANRCM 2007 can07_mat = transform2(can07_u, can07_v) can07_PCs, can07_eigs, can07_mean = doPCA(100, can07_mat) ##PCA on HRDPS 2007 hr07_mat = transform2(hr07_u, hr07_v) hr07_PCs, hr07_eigs, hr07_mean = doPCA(100, hr07_mat) ## combining the eigenve...
_____no_output_____
Apache-2.0
notebooks/generalPredictions4b.ipynb
UBC-MOAD/analysis-armaan
DBSCAN without Libraries
import time import warnings import queue import numpy as np import pandas as pd from sklearn import cluster, datasets, mixture from sklearn.neighbors import kneighbors_graph from sklearn import datasets # from sklearn.datasets import make_blobs from sklearn.preprocessing import StandardScaler from scipy.stats import...
/Users/kiat/opt/anaconda3/lib/python3.8/site-packages/sklearn/utils/extmath.py:770: RuntimeWarning: invalid value encountered in true_divide updated_mean = (last_sum + new_sum) / updated_sample_count /Users/kiat/opt/anaconda3/lib/python3.8/site-packages/sklearn/utils/extmath.py:711: RuntimeWarning: Degrees of freedom...
MIT
Code-Example-023-DBSCAN.ipynb
waltsco059/Elements-of-Data-Analytics
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Transfer Learning Using Pretrained ConvNets Run in Google Colab View source on GitHub
from __future__ import absolute_import, division, print_function import tensorflow.compat.v2 as tf #nightly-gpu tf.enable_v2_behavior() import os import numpy as np import matplotlib.pyplot as plt from functools import partial tf.__version__
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Data preprocessing Data download
_URL = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" zip_file = tf.keras.utils.get_file(origin=_URL, fname="flower_photos.tgz", extract=True) base_dir = os.path.join(os.path.dirname(zip_file), 'flower_p...
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Create the base model from the pre-trained convnets
IMG_SHAPE = (IMAGE_SIZE, IMAGE_SIZE, 3) # Create the base model from the pre-trained model MobileNet V2 base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Feature extractionYou will freeze the convolutional base created from the previous step and use that as a feature extractor, add a classifier on top of it and train the top-level classifier.
base_model.trainable = False
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Add a classification head
model = tf.keras.Sequential([ base_model, tf.keras.layers.Conv2D(32, 3, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(5, activation='softmax') ])
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Compile the modelYou must compile the model before training it. Since there are two classes, use a binary cross-entropy loss.
model.compile(optimizer=tf.keras.optimizers.Adam(), loss='categorical_crossentropy', metrics=['accuracy']) model.summary()
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
The 2.5M parameters in MobileNet are frozen, but there are 1.2K _trainable_ parameters in the Dense layer. These are divided between two `tf.Variable` objects, the weights and biases.
len(model.trainable_variables) train_generator.labels
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Train the model
epochs = 10 history = model.fit(train_generator, epochs=epochs, validation_data=val_generator)
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Learning curvesLet's take a look at the learning curves of the training and validation accuracy/loss when using the MobileNet V2 base model as a fixed feature extractor.
acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.yl...
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Note: If you are wondering why the validation metrics are clearly better than the training metrics, the main factor is because layers like `tf.keras.layers.BatchNormalization` and `tf.keras.layers.Dropout` affect accuracy during training. They are turned off when calculating validation loss.To a lesser extent, it is al...
base_model.trainable = True # Let's take a look to see how many layers are in the base model print("Number of layers in the base model: ", len(base_model.layers)) # Fine tune from this layer onwards fine_tune_at = 100 # Freeze all the layers before the `fine_tune_at` layer for layer in base_model.layers[:fine_tune_at...
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Compile the modelCompile the model using a much lower training rate.
model.compile(loss='categorical_crossentropy', optimizer = tf.keras.optimizers.Adam(1e-5), metrics=['accuracy']) model.summary() len(model.trainable_variables)
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Continue Train the model If you trained to convergence earlier, this will get you a few percent more accuracy.
history_fine = model.fit(train_generator, epochs=5, validation_data=val_generator)
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Let's take a look at the learning curves of the training and validation accuracy/loss, when fine tuning the last few layers of the MobileNet V2 base model and training the classifier on top of it. The validation loss is much higher than the training loss, so you may get some overfitting.You may also get some overfittin...
saved_model_dir = 'save/fine_tuning' tf.saved_model.save(model, saved_model_dir) model = tf.saved_model.load(saved_model_dir) concrete_func = model.signatures[ tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY] concrete_func.inputs[0].set_shape([1, 224, 224, 3]) converter = tf.lite.TFLiteConverter.from_concrete_fun...
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
Download the converted model
from google.colab import files files.download('model.tflite') acc += history_fine.history['accuracy'] val_acc += history_fine.history['val_accuracy'] loss += history_fine.history['loss'] val_loss += history_fine.history['val_loss'] plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label='Training Accuracy...
_____no_output_____
Apache-2.0
community/en/tensorflow_for_poets_reboot.ipynb
surabhithakare2128/examples
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb) Spark NLP Basics and P...
import os # Install java ! apt-get update -qq ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"] ! java -version # Install pyspark ! pip install --ignore-installed -q pys...
openjdk version "1.8.0_275" OpenJDK Runtime Environment (build 1.8.0_275-8u275-b01-0ubuntu1~18.04-b01) OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode)  |████████████████████████████████| 215.7MB 70kB/s  |████████████████████████████████| 204kB 48.3MB/s [?25h Building wheel for pyspark (setup.p...
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
**How to prevent Google Colab from disconnecting?**Google Colab notebooks have an idle timeout of 90 minutes and absolute timeout of 12 hours. This means, if user does not interact with his Google Colab notebook for more than 90 minutes, its instance is automatically terminated. Also, maximum lifetime of a Colab insta...
''' function ConnectButton(){ console.log("Connect pushed"); document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click() } setInterval(ConnectButton,60000); '''
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
1. Start Spark Session
import sparknlp spark = sparknlp.start() # params =>> gpu=False, spark23=False (start with spark 2.3) print("Spark NLP version", sparknlp.version()) print("Apache Spark version:", spark.version) ! cd ~/.ivy2/cache/com.johnsnowlabs.nlp/spark-nlp_2.11/jars && ls -lt
total 39960 -rw-r--r-- 1 root root 40918604 Jan 8 21:03 spark-nlp_2.11-2.7.1.jar
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
if you want to work with Spark 2.3 ```import os Install java! apt-get update -qq! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null!wget -q https://archive.apache.org/dist/spark/spark-2.3.0/spark-2.3.0-bin-hadoop2.7.tgz!tar xf spark-2.3.0-bin-hadoop2.7.tgz!pip install -q findsparkos.environ["JAVA_HOME"] = "/u...
# https://github.com/JohnSnowLabs/spark-nlp/blob/master/python/sparknlp/__init__.py from pyspark.sql import SparkSession def start(gpu=False, spark23=False): current_version="2.5.4" maven_spark24 = "com.johnsnowlabs.nlp:spark-nlp_2.11:{}".format(current_version) maven_gpu_spark24 = "com.johnsnowlabs.nlp:s...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
If you want to start `SparkSession` with your own parameters or you need to load the required jars/packages from your local disk, or you have no internet connection (that would be needed to pull the required packages from internet), you can skip `sparknlp.start()` and start your session manually as shown below.
""" from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Spark NLP Enterprise 2.4.5") \ .master("local[8]") \ .config("spark.driver.memory","12G") \ .config("spark.driver.maxResultSize", "2G") \ .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") \ ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
CPU on Apache Spark 2.4.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-assembly-2.7.1.jarGPU on Apache Spark 2.4.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-gpu-assembly-2.7.1.jarCPU on Apache Spark 2.3.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nl...
from sparknlp.pretrained import PretrainedPipeline testDoc = ''' Peter is a very good persn. My life in Russia is very intersting. John and Peter are brothrs. However they don't support each other that much. Lucas Nogal Dunbercker is no longer happy. He has a good car though. Europe is very culture rich. There are huge...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Explain Document ML **Stages**- DocumentAssembler- SentenceDetector- Tokenizer- Lemmatizer- Stemmer- Part of Speech- SpellChecker (Norvig)
pipeline = PretrainedPipeline('explain_document_ml', lang='en') pipeline.model.stages # Load pretrained pipeline from local disk: pipeline_local = PretrainedPipeline.from_disk('/root/cache_pretrained/explain_document_ml_en_2.4.0_2.4_1580252705962') %%time result = pipeline.annotate(testDoc) result.keys() result['sen...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Explain Document DL **Stages**- DocumentAssembler- SentenceDetector- Tokenizer- NER (NER with GloVe 100D embeddings, CoNLL2003 dataset)- Lemmatizer- Stemmer- Part of Speech- SpellChecker (Norvig)
pipeline_dl = PretrainedPipeline('explain_document_dl', lang='en') pipeline_dl.model.stages pipeline_dl.model.stages[-2].getStorageRef() pipeline_dl.model.stages[-2].getClasses() %%time result = pipeline_dl.annotate(testDoc) result.keys() result.keys() result['entities'] df = pd.DataFrame({'token':result['token'], '...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Recognize Entities DL
recognize_entities = PretrainedPipeline('recognize_entities_dl', lang='en') recognize_entities.model.stages recognize_entities.model.stages[3].getStorageRef() recognize_entities.model.stages[4].getClasses() testDoc = ''' Peter is a very good persn. My life in Russia is very intersting. John and Peter are brothrs. Howe...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Clean Stop Words
clean_stop = PretrainedPipeline('clean_stop', lang='en') result = clean_stop.annotate(testDoc) result.keys() ' '.join(result['cleanTokens'])
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Clean Slang
clean_slang = PretrainedPipeline('clean_slang', lang='en') result = clean_slang.annotate(' Whatsup bro, call me ASAP') ' '.join(result['normal']) clean_slang.model.stages clean_slang.model.stages[-1]
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Spell Checker (Norvig Algo)ref: https://norvig.com/spell-correct.html
spell_checker = PretrainedPipeline('check_spelling', lang='en') testDoc = ''' Peter is a very good persn. My life in Russia is very intersting. John and Peter are brothrs. However they don't support each other that much. Lucas Nogal Dunbercker is no longer happy. He has a good car though. Europe is very culture rich. ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Spell Checker DLhttps://medium.com/spark-nlp/applying-context-aware-spell-checking-in-spark-nlp-3c29c46963bc
spell_checker_dl = PretrainedPipeline('check_spelling_dl', lang='en') text = 'We will go to swimming if the ueather is nice.' result = spell_checker_dl.annotate(text) list(zip(result['token'], result['checked'])) result.keys() # check for the different occurrences of the word "ueather" examples = ['We will go to swi...
[('We', 'We'), ('will', 'will'), ('go', 'go'), ('to', 'to'), ('swimming', 'swimming'), ('if', 'if'), ('the', 'the'), ('ueather', 'weather'), ('is', 'is'), ('nice', 'nice'), ('.', '.')] [('I', 'I'), ('have', 'have'), ('a', 'a'), ('black', 'black'), ('ueather', 'weather'), ('jacket', 'jacket'), (',', ','), ('so', 'so'), ...
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Parsing a list of texts
testDoc_list = ['French author who helped pioner the science-fiction genre.', 'Verne wrate about space, air, and underwater travel before navigable aircrast', 'Practical submarines were invented, and before any means of space travel had been devised.'] testDoc_list pipeline = PretrainedPipeline('explain_document_ml', ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Using fullAnnotate to get more details ```annotatorType: String, begin: Int, end: Int, result: String, (this is what annotate returns)metadata: Map[String, String], embeddings: Array[Float]```
text = 'Peter Parker is a nice guy and lives in New York' # pipeline_dl >> explain_document_dl detailed_result = pipeline_dl.fullAnnotate(text) detailed_result detailed_result[0]['entities'] detailed_result[0]['entities'][0].result chunks=[] entities=[] for n in detailed_result[0]['entities']: chunks.append...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Use pretrained match_chunk Pipeline for Individual Noun Phrase **Stages**- DocumentAssembler- SentenceDetector- Tokenizer- Part of Speech- ChunkerPipeline:- The pipeline uses regex `?*+`- which states that whenever the chunk finds an optional determiner (DT) followed by any number of adjectives (JJ) and then a noun (N...
pipeline = PretrainedPipeline('match_chunks', lang='en') pipeline.model.stages result = pipeline.annotate("The book has many chapters") # single noun phrase result result['chunk'] result = pipeline.annotate("the little yellow dog barked at the cat") #multiple noune phrases result result['chunk']
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Extract exact dates from referential date phrases
pipeline = PretrainedPipeline('match_datetime', lang='en') result = pipeline.annotate("I saw him yesterday and he told me that he will visit us next week") result detailed_result = pipeline.fullAnnotate("I saw him yesterday and he told me that he will visit us next week") detailed_result tuples = [] for x in detail...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Sentiment Analysis Vivek algopaper: `Fast and accurate sentiment classification using an enhanced Naive Bayes model`https://arxiv.org/abs/1305.6143code `https://github.com/vivekn/sentiment`
sentiment = PretrainedPipeline('analyze_sentiment', lang='en') result = sentiment.annotate("The movie I watched today was not a good one") result['sentiment']
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
DL version (trained on imdb)
sentiment_imdb = PretrainedPipeline('analyze_sentimentdl_use_imdb', lang='en') sentiment_imdb_glove = PretrainedPipeline('analyze_sentimentdl_glove_imdb', lang='en') comment = ''' It's a very scary film but what impressed me was how true the film sticks to the original's tricks; it isn't filled with loud in-your-face j...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb
HashamUlHaq/spark-nlp-workshop
Table of Contents1&nbsp;&nbsp;Preamble1.1&nbsp;&nbsp;Some general parameters1.2&nbsp;&nbsp;Functions1.2.0.1&nbsp;&nbsp;Create overlap1.2.0.2&nbsp;&nbsp;Activity representation2&nbsp;&nbsp;The example Preamble
import pprint import subprocess import sys sys.path.append('../') import numpy as np import scipy as sp import statsmodels.api as sm import matplotlib.pyplot as plt import matplotlib import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn as sns %matplotlib in...
_____no_output_____
MIT
jupyter/2018-09-20(Graph of non-orthogonal sequences example).ipynb
h-mayorquin/sequence_learning_paper
Some general parameters
epsilon = 10e-80 vmin = -3.0 remove = 0.010 strict_maximum = True dt = 0.001 tau_s = 0.010 tau_a = 0.250 g_I = 2.0 g_a = 2.0 G = 50.0 sns.set(font_scale=3.5) sns.set_style("whitegrid", {'axes.grid': False}) plt.rcParams['figure.figsize'] = (12, 8) lw = 10 ms = 22 alpha_graph = 0.3 colors = sns.color_palette()
_____no_output_____
MIT
jupyter/2018-09-20(Graph of non-orthogonal sequences example).ipynb
h-mayorquin/sequence_learning_paper
Functions Create overlap
from copy import deepcopy def create_overalaped_representation(manager, representation_overlap, sequence_overlap): x = deepcopy(manager.canonical_activity_representation) to_modify = int(representation_overlap * len(x[0])) sequence_size = int(0.5 * len(x)) sequence_overlap_size = int(sequence_overlap ...
_____no_output_____
MIT
jupyter/2018-09-20(Graph of non-orthogonal sequences example).ipynb
h-mayorquin/sequence_learning_paper
Activity representation
activity_representation = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], [10, 10, 10], [11, 11, 11], [2, 2, 12], [3, 3, 13], [14, 14, 14], [15, 15, 15]])
_____no_output_____
MIT
jupyter/2018-09-20(Graph of non-orthogonal sequences example).ipynb
h-mayorquin/sequence_learning_paper
The example
sigma_out = 0.0 tau_z_pre = 0.025 tau_z_post = 0.020 hypercolumns = 3 minicolumns = 20 n_patterns = 12 patterns_per_sequence = 6 representation_overlap = 0.75 sequence_overlap = 0.5 # Training protocol training_times_base = 0.100 training_times = [training_times_base for i in range(n_patterns)] ipi_base = 0.0 inter_p...
_____no_output_____
MIT
jupyter/2018-09-20(Graph of non-orthogonal sequences example).ipynb
h-mayorquin/sequence_learning_paper
Abstract - Goal: Learn python basics on Jupyter notebook.- Ref: - Python crash course (Google for it) - the [naming section](https://github.com/google/styleguide/blob/gh-pages/pyguide.md316-naming) of Google's python style guide Python on Jupyter notebook - ColabPython on Jupyter notebook allows one to perfor...
2 + 2 #Executing a Command
_____no_output_____
MIT
other/python_notebook.ipynb
nickwotton/MQP2019
Importing LibrariesThe vast majority of the time, you'll want to use functions from pre-built libraries. You can't import every library each time, but you can import most of the common scientific ones. Here I import numpy, pandas, and matplotlib, the most common and useful libraries. Notice that you can rename librari...
import numpy as np import pandas as pd import matplotlib.pyplot as plt
_____no_output_____
MIT
other/python_notebook.ipynb
nickwotton/MQP2019
Using numpy and matplotlib: A sampling example Let's use numpy to select 100 standard normal radom variables, and make a plot.
X = np.random.normal(0, 1, 100) plt.plot(X); plt.xlabel('Time') plt.ylabel('Returns') plt.show()
_____no_output_____
MIT
other/python_notebook.ipynb
nickwotton/MQP2019
Let's use `numpy` to take some simple statistics.
np.mean(X) np.std(X)
_____no_output_____
MIT
other/python_notebook.ipynb
nickwotton/MQP2019
BiDirectional LSTM classifier in keras Load dependencies
import keras from keras.datasets import imdb from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding, SpatialDropout1D, Dense, Flatten, Dropout, LSTM from keras.layers.wrappers import Bidirectional from keras.callbacks import ModelCheckpoint # new! ...
_____no_output_____
Apache-2.0
Deep Learning/NLP Tutorials/.ipynb_checkpoints/Conv_LSTM_Stack_in_keras-checkpoint.ipynb
surajch77/ML-Examples
Load data For a given data set: * the Keras text utilities [here](https://keras.io/preprocessing/text/) quickly preprocess natural language and convert it into an index* the `keras.preprocessing.text.Tokenizer` class may do everything you need in one line: * tokenize into words or characters * `num_words`: maxim...
(x_train, y_train), (x_valid, y_valid) = imdb.load_data(num_words=n_unique_words)
_____no_output_____
Apache-2.0
Deep Learning/NLP Tutorials/.ipynb_checkpoints/Conv_LSTM_Stack_in_keras-checkpoint.ipynb
surajch77/ML-Examples
Preprocess data
x_train = pad_sequences(x_train, maxlen=max_review_length, padding=pad_type, truncating=trunc_type, value=0) x_valid = pad_sequences(x_valid, maxlen=max_review_length, padding=pad_type, truncating=trunc_type, value=0) x_train[:6] for i in range(6): print len(x_train[i])
200 200 200 200 200 200
Apache-2.0
Deep Learning/NLP Tutorials/.ipynb_checkpoints/Conv_LSTM_Stack_in_keras-checkpoint.ipynb
surajch77/ML-Examples
Design neural network architecture
model = Sequential() model.add(Embedding(n_unique_words, n_dim, input_length=max_review_length)) model.add(SpatialDropout1D(drop_embed)) # model.add(Conv1D(n_conv, k_conv, activation='relu')) # model.add(Conv1D(n_conv, k_conv, activation='relu')) # model.add(GlobalMaxPooling1D()) # model.add(Dense(n_dense, activation=...
_____no_output_____
Apache-2.0
Deep Learning/NLP Tutorials/.ipynb_checkpoints/Conv_LSTM_Stack_in_keras-checkpoint.ipynb
surajch77/ML-Examples
Configure Model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) modelcheckpoint = ModelCheckpoint(filepath=output_dir+"/weights.{epoch:02d}.hdf5") if not os.path.exists(output_dir): os.makedirs(output_dir) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, vali...
Train on 25000 samples, validate on 25000 samples Epoch 1/6 25000/25000 [==============================] - 689s 28ms/step - loss: 0.5523 - acc: 0.7024 - val_loss: 0.3817 - val_acc: 0.8368 Epoch 2/6 640/25000 [..............................] - ETA: 7:21 - loss: 0.2883 - acc: 0.8953
Apache-2.0
Deep Learning/NLP Tutorials/.ipynb_checkpoints/Conv_LSTM_Stack_in_keras-checkpoint.ipynb
surajch77/ML-Examples
Evaluate
model.load_weights(output_dir+"/weights.01.hdf5") # zero-indexed y_hat = model.predict_proba(x_valid) len(y_hat) y_hat[0] plt.hist(y_hat) _ = plt.axvline(x=0.5, color='orange') pct_auc = roc_auc_score(y_valid, y_hat)*100.0 "{:0.2f}".format(pct_auc)
_____no_output_____
Apache-2.0
Deep Learning/NLP Tutorials/.ipynb_checkpoints/Conv_LSTM_Stack_in_keras-checkpoint.ipynb
surajch77/ML-Examples
Header1
df = pd.read_csv('../data/raw/yellow_tripdata_2015-12-sample.csv') df.head() df['delta_lon'] = df.pickup_longitude - df.dropoff_longitude df['delta_lat'] = df.pickup_latitude - df.dropoff_latitude def calculate_direction(d_lon, d_lat): result = np.zeros(len(d_lon)) l = np.sqrt(d_lon**2 + d_lat**2) result[d...
4.7793882127762615
Unlicense
notebooks/random_forest.ipynb
AshwathSalimath/amazon-lab
Homework (15 pts) - Classification
# Questions are based on the mouse cortex protein expression level dataset used in lecture. # The Data_Cortex_Nuclear.csv file is available in the same folder as this notebook # or at https://www.kaggle.com/ruslankl/mice-protein-expression import pandas as pd import numpy as np import matplotlib.pyplot as plt from skle...
_____no_output_____
Unlicense
homework/homework_classification.ipynb
sathwikiyer/NEU-365P-385L-Spring-2021
---1. (3 pts) Remove mice/samples with missing measurements from the dataframe. Store the result in the mice variable for use with subsequent questions.
mice.isnull().sum() mice = mice.dropna()
_____no_output_____
Unlicense
homework/homework_classification.ipynb
sathwikiyer/NEU-365P-385L-Spring-2021
---2. (3 pts) Use both logistic regression and a random forest to classify the mice as either memantine or saline treated based on their protein expression profiles. Contrast the overall accuracy of the two classifiers on a withheld test set. You can ignore any warnings similar to those seen in the lecture for the purp...
X = mice.loc[:,'DYRK1A_N':'CaNA_N'] # just protein expression levels y = mice['Treatment'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state = 1) model = LogisticRegression() model.fit(X_train, y_train) LogisticRegression() y_test_pred = model.predict(X_test) lr_treatment_accu...
Random forests are a better predictor
Unlicense
homework/homework_classification.ipynb
sathwikiyer/NEU-365P-385L-Spring-2021
---3. (3 pts) For the two classifiers trained in 2 above, contrast their confusion matrices based on predictions for a withheld test set.
cm = confusion_matrix(y_test, y_test_pred) lr_treatment_cmd = ConfusionMatrixDisplay(confusion_matrix = cm, display_labels = model.classes_) lr_treatment_cmd.plot(); cm = confusion_matrix(y_test, y_test_pred2) rf_treatment_cmd = ConfusionMatrixDisplay(confusion_matrix = cm, display_labels = model.classes_) rf_treatm...
_____no_output_____
Unlicense
homework/homework_classification.ipynb
sathwikiyer/NEU-365P-385L-Spring-2021
---4. (3 pts) For the two classifiers trained in 2 above, contrast their ROC curves based on predictions for Memantine treatment in withheld test set.
y_test_proba = model.predict_proba(X_test) fpr, tpr, thresholds = roc_curve(y_test, y_test_proba[:,1], pos_label = model.classes_[1]) plt.plot(fpr, tpr, color = 'r', label = model.classes_[0]) plt.plot([0, 1], [0, 1], color = 'k', linestyle = '--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt...
_____no_output_____
Unlicense
homework/homework_classification.ipynb
sathwikiyer/NEU-365P-385L-Spring-2021
---5. (3 pts) Use a random forest to classify the mice into each of the 8 classes defined by genotype, fear conditioning and treatment based on their protein expression profiles. Repeat this classification 77 separate times, where on the ith time you will use only the first i proteins. For example, the 1st time you wil...
proteins = X_train.shape[1] accuracies = np.zeros((proteins,)) rFor = RandomForestClassifier(n_estimators = 100, random_state = 1) for i in np.arange(proteins) + 1: pTrain = X_train.iloc[:, 0:i] pTest = X_test.iloc[:, 0:i] rFor.fit(pTrain, y_train) rForPred = rFor.predict(pTest) rForAcc = accuracy...
_____no_output_____
Unlicense
homework/homework_classification.ipynb
sathwikiyer/NEU-365P-385L-Spring-2021
Assignment 2: Parts-of-Speech Tagging (POS)Welcome to the second assignment of Course 2 in the Natural Language Processing specialization. This assignment will develop skills in part-of-speech (POS) tagging, the process of assigning a part-of-speech tag (Noun, Verb, Adjective...) to each word in an input text. Taggin...
# Importing packages and loading in the data set from utils_pos import get_word_tag, preprocess import pandas as pd from collections import defaultdict import math import numpy as np
_____no_output_____
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Part 0: Data SourcesThis assignment will use two tagged data sets collected from the **Wall Street Journal (WSJ)**. [Here](http://relearn.be/2015/training-common-sense/sources/software/pattern-2.6-critical-fork/docs/html/mbsp-tags.html) is an example 'tag-set' or Part of Speech designation describing the two or three ...
# load in the training corpus with open("WSJ_02-21.pos", 'r') as f: training_corpus = f.readlines() print(f"A few items of the training corpus list") print(training_corpus[0:5]) # read the vocabulary data, split by each line of text, and save the list with open("hmm_vocab.txt", 'r') as f: voc_l = f.read().spli...
The length of the preprocessed test corpus: 34199 This is a sample of the test_corpus: ['The', 'economy', "'s", 'temperature', 'will', 'be', 'taken', 'from', 'several', '--unk--']
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Part 1: Parts-of-speech tagging Part 1.1 - TrainingYou will start with the simplest possible parts-of-speech tagger and we will build up to the state of the art. In this section, you will find the words that are not ambiguous. - For example, the word `is` is a verb and it is not ambiguous. - In the `WSJ` corpus, $86$...
# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: create_dictionaries def create_dictionaries(training_corpus, vocab): """ Input: training_corpus: a corpus where each line has a word followed by its tag. vocab: a dictionary where keys are words in vocabulary and value is an inde...
Number of POS tags (number of 'states'): 46 View these POS tags (states) ['#', '$', "''", '(', ')', ',', '--s--', '.', ':', 'CC', 'CD', 'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNP', 'NNPS', 'NNS', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', 'VBN',...
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPNumber of POS tags (number of 'states'46View these states['', '$', "''", '(', ')', ',', '--s--', '.', ':', 'CC', 'CD', 'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNP', 'NNPS', 'NNS', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', '...
print("transition examples: ") for ex in list(transition_counts.items())[:3]: print(ex) print() print("emission examples: ") for ex in list(emission_counts.items())[200:203]: print (ex) print() print("ambiguous word example: ") for tup,cnt in emission_counts.items(): if tup[1] == 'back': print (tup, cnt)
transition examples: (('--s--', 'IN'), 5050) (('IN', 'DT'), 32364) (('DT', 'NNP'), 9044) emission examples: (('DT', 'any'), 721) (('NN', 'decrease'), 7) (('NN', 'insider-trading'), 5) ambiguous word example: ('RB', 'back') 304 ('VB', 'back') 20 ('RP', 'back') 84 ('JJ', 'back') 25 ('NN', 'back') 29 ('VBP', 'back') ...
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPtransition examples: (('--s--', 'IN'), 5050)(('IN', 'DT'), 32364)(('DT', 'NNP'), 9044)emission examples: (('DT', 'any'), 721)(('NN', 'decrease'), 7)(('NN', 'insider-trading'), 5)ambiguous word example: ('RB', 'back') 304('VB', 'back') 20('RP', 'back') 84('JJ', 'back') 25('NN', 'back') 29('VBP', 'b...
# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: predict_pos def predict_pos(prep, y, emission_counts, vocab, states): ''' Input: prep: a preprocessed version of 'y'. A list with the 'word' component of the tuples. y: a corpus composed of a list of tuples where each tuple cons...
Accuracy of prediction using predict_pos is 0.8889
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPAccuracy of prediction using predict_pos is 0.8889```88.9% is really good for this warm up exercise. With hidden markov models, you should be able to get **95% accuracy.** Part 2: Hidden Markov Models for POSNow you will build something more context specific. Concretely, you will be implementing ...
# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: create_transition_matrix def create_transition_matrix(alpha, tag_counts, transition_counts): ''' Input: alpha: number used for smoothing tag_counts: a dictionary mapping each tag to its respective count transition_counts...
A at row 0, col 0: 0.000007040 A at row 3, col 1: 0.1691 View a subset of transition matrix A RBS RP SYM TO UH RBS 2.217069e-06 2.217069e-06 2.217069e-06 0.008870 2.217069e-06 RP 3.756509e-07 7.516775e-04 3.756509e-07 0.051089 3.756509e-07 SYM 1.722772e-0...
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPA at row 0, col 0: 0.000007040A at row 3, col 1: 0.1691View a subset of transition matrix A RBS RP SYM TO UHRBS 2.217069e-06 2.217069e-06 2.217069e-06 0.008870 2.217069e-06RP 3.756509e-07 7.516775e-04 3.756509e-07 0.051089 3.756509e-07...
# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: create_emission_matrix def create_emission_matrix(alpha, tag_counts, emission_counts, vocab): ''' Input: alpha: tuning parameter used in smoothing tag_counts: a dictionary mapping each tag to its respective count emissi...
View Matrix position at row 0, column 0: 0.000006032 View Matrix position at row 3, column 1: 0.000000720 725 adroitly engineers promoted synergy CD 8.201296e-05 2.732854e-08 2.732854e-08 2.732854e-08 2.732854e-08 NN 7.521128e-09 7.521128e-09 7.521128e-09 7.521128e-09 2.257...
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPView Matrix position at row 0, column 0: 0.000006032View Matrix position at row 3, column 1: 0.000000720 725 adroitly engineers promoted synergyCD 8.201296e-05 2.732854e-08 2.732854e-08 2.732854e-08 2.732854e-08NN 7.521128e-09 7.521128e-09 7.521128e-09 7...
# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: initialize def initialize(states, tag_counts, A, B, corpus, vocab): ''' Input: states: a list of all possible parts-of-speech tag_counts: a dictionary mapping each tag to its respective count A: Transition Matrix of dimen...
best_probs[0,0]: -22.6098 best_paths[2,3]: 0.0000
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPbest_probs[0,0]: -22.6098best_paths[2,3]: 0.0000``` Part 3.2 Viterbi ForwardIn this part of the assignment, you will implement the `viterbi_forward` segment. In other words, you will populate your `best_probs` and `best_paths` matrices.- Walk forward through the corpus.- For each word, compute a ...
# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: viterbi_forward def viterbi_forward(A, B, test_corpus, best_probs, best_paths, vocab): ''' Input: A, B: The transition and emission matrices respectively test_corpus: a list containing a preprocessed corpus best_probs: an...
_____no_output_____
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Run the `viterbi_forward` function to fill in the `best_probs` and `best_paths` matrices.**Note** that this will take a few minutes to run. There are about 30,000 words to process.
# this will take a few minutes to run => processes ~ 30,000 words best_probs, best_paths = viterbi_forward(A, B, prep, best_probs, best_paths, vocab) # Test this function print(f"best_probs[0,1]: {best_probs[0,1]:.4f}") print(f"best_probs[0,4]: {best_probs[0,4]:.4f}")
best_probs[0,1]: -24.7822 best_probs[0,4]: -49.5601
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Expected Output```CPPbest_probs[0,1]: -24.7822best_probs[0,4]: -49.5601``` Part 3.3 Viterbi backwardNow you will implement the Viterbi backward algorithm.- The Viterbi backward algorithm gets the predictions of the POS tags for each word in the corpus using the `best_paths` and the `best_probs` matrices.The example b...
# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: viterbi_backward def viterbi_backward(best_probs, best_paths, corpus, states): ''' This function returns the best path. ''' # Get the number of words in the corpus # which is also the number of columns in best_probs, best_paths ...
The prediction for pred[-7:m-1] is: ['see', 'them', 'here', 'with', 'us', '.'] ['VB', 'PRP', 'RB', 'IN', 'PRP', '.'] The prediction for pred[0:8] is: ['DT', 'NN', 'POS', 'NN', 'MD', 'VB', 'VBN'] ['The', 'economy', "'s", 'temperature', 'will', 'be', 'taken']
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
**Expected Output:** ```CPPThe prediction for pred[-7:m-1] is: ['see', 'them', 'here', 'with', 'us', '.'] ['VB', 'PRP', 'RB', 'IN', 'PRP', '.'] The prediction for pred[0:8] is: ['DT', 'NN', 'POS', 'NN', 'MD', 'VB', 'VBN'] ['The', 'economy', "'s", 'temperature', 'will', 'be', 'taken'] ```Now you just have...
print('The third word is:', prep[3]) print('Your prediction is:', pred[3]) print('Your corresponding label y is: ', y[3])
The third word is: temperature Your prediction is: NN Your corresponding label y is: temperature NN
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Exercise 08Implement a function to compute the accuracy of the viterbi algorithm's POS tag predictions.- To split y into the word and its tag you can use `y.split()`.
# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT) # GRADED FUNCTION: compute_accuracy def compute_accuracy(pred, y): ''' Input: pred: a list of the predicted parts-of-speech y: a list of lines where each word is separated by a '\t' (i.e. word \t tag) Output: ''' num_correct ...
Accuracy of the Viterbi algorithm is 0.9531
MIT
Course 2 - Natural Language Processing with Probabilistic Models/Week 2/C2_W2_Assignment.ipynb
naveen-9697/Natural-Language-Specialisation---Coursera
Dependencies for this notebook:* pip install spacy, pandas, matplotlib* python -m spacy.en.download
from IPython.display import SVG, display import spacy import pandas as pd import matplotlib.pyplot as plt from datetime import datetime %matplotlib inline #encode some text as uncode text = u"I'm executing this code on an Apple Computer." #instantiate a language model #to download language model: python -m spacy.en.do...
_____no_output_____
MIT
spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb
peterwilliams97/spaCy_practice