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 |
|---|---|---|---|---|---|
Let's create an instance of MulticlassMetrics with this RDD: | metrics = MulticlassMetrics(predictions.rdd.map(tuple)) | _____no_output_____ | MIT | model-evaluation.ipynb | rh01/big-data-ml |
NOTE: the above command can take longer to execute than most Spark commands when first run in the notebook.The confusionMatrix() function returns a Spark Matrix, which we can convert to a Python Numpy array, and transpose to view: The confusionMatrix() function returns a Spark Matrix, which we can convert to a Python N... | metrics.confusionMatrix().toArray().transpose() | _____no_output_____ | MIT | model-evaluation.ipynb | rh01/big-data-ml |
**Q**Spark: In the last line of code in Step 4, the confusion matrix is printed out. If the “transpose()” is removed, the confusion matrix will be displayed as: | metrics.confusionMatrix().toArray()
| _____no_output_____ | MIT | model-evaluation.ipynb | rh01/big-data-ml |
Performance Analysis - Julia> Number of effective sequences implemented in Julia- toc: true- branch: master- badges: true- author: Donatas Repečka- categories: [performance] Introduction In [the previous post](https://donatasrep.github.io/donatas.repecka/performance/2021/04/27/Performance-comparison.html) I have com... | import Statistics
using NPZ
input_data = npzread(npz_file_path)
input_data = Int.(input_data) | _____no_output_____ | Apache-2.0 | _notebooks/2021-05-08-performance-julia.ipynb | donatasrep/donatas.repecka |
Algorithm | function get_nf_row(input_data)
dim1, dim2 = size(input_data)
pairwise_id = input_data[2:dim1,:] .== reshape(input_data[1,:], (1,dim2))
pairwise_id = Statistics.mean(pairwise_id, dims=2)
pairwise_id .> 0.8
end
function get_nf_julia(input_data)
n_seqs, seq_len = size(input_data)
is_same_cluster =... | _____no_output_____ | Apache-2.0 | _notebooks/2021-05-08-performance-julia.ipynb | donatasrep/donatas.repecka |
Computing native contacts with MDTrajUsing the definition from Best, Hummer, and Eaton, "Native contacts determine protein folding mechanisms in atomistic simulations" PNAS (2013) [10.1073/pnas.1311599110](http://dx.doi.org/10.1073/pnas.1311599110)Eq. (1) of the SI defines the expression for the fraction of native con... | import numpy as np
import mdtraj as md
from itertools import combinations
def best_hummer_q(traj, native):
"""Compute the fraction of native contacts according the definition from
Best, Hummer and Eaton [1]
Parameters
----------
traj : md.Trajectory
The trajectory to do the computation... | _____no_output_____ | CC-BY-4.0 | uci-pharmsci/lectures/cluster_and_visualize/MDTraj Examples/native-contact.ipynb | davidlmobley/drug-computing |
Create a Deployment Manifest | import sys
sys.path.append('../../../common')
from env_variables import *
# Manifest filenames
templateManifestFileName = "../../../common/deployment.lva_common.template.json"
deploymentManifestFileName = "../../../common/deployment.lva_yolov3_icpu.template.json" | _____no_output_____ | MIT | utilities/video-analysis/notebooks/Yolo/yolov3/yolov3-http-icpu-onnx/create_yolov3_icpu_deployment_manifest.ipynb | fvneerden/live-video-analytics |
Update Deployment Manifest Template The following cell will create a custom template based on this sample. It will copy the sample deployment manifest template and add a few more parameters to a new manifest template. | import json
with open(templateManifestFileName) as f:
data = json.load(f)
aiModule = data["modulesContent"]["$edgeAgent"]["properties.desired"]["modules"]["lvaExtension"]["settings"]["createOptions"]["HostConfig"]["runtime"]
aiModule = aiModule.replace("", "")
data["modulesContent"]["$edgeAgent"]["properties.desi... | _____no_output_____ | MIT | utilities/video-analysis/notebooks/Yolo/yolov3/yolov3-http-icpu-onnx/create_yolov3_icpu_deployment_manifest.ipynb | fvneerden/live-video-analytics |
Clone and install github repo | !git clone https://github.com/dmklee/nuro-arm.git
!pip install nuro-arm/ | Cloning into 'nuro-arm'...
remote: Enumerating objects: 2162, done.[K
remote: Counting objects: 100% (619/619), done.[K
remote: Compressing objects: 100% (440/440), done.[K
remote: Total 2162 (delta 377), reused 386 (delta 170), pack-reused 1543[K
Receiving objects: 100% (2162/2162), 35.12 MiB | 19.61 MiB/s, done.
... | MIT | nuro-arm-intro.ipynb | tw-ilson/nuro-arm |
Helper functions for visualization | import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
from IPython.display import HTML
def show_video(video):
fig = plt.figure()
im = plt.imshow(video[0])
plt.axis('off')
plt.tight_layout(pad=0)
plt.close()
def animate(i):
im.set_data(video[i])
anim = animation.FuncAni... | _____no_output_____ | MIT | nuro-arm-intro.ipynb | tw-ilson/nuro-arm |
Create simulated robot | # clear any existing simulators
import pybullet
try:
pybullet.disconnect()
except:
pass
from nuro_arm import RobotArm, Camera, Cube
robot = RobotArm('sim')
side_view_camera = Camera('sim', pose_mtx=side_view_pose_mtx)
camera = Camera('sim')
cube_size = 0.03
cube = Cube(pos=[0.15, 0.005, cube_size/2], size=cube_si... | _____no_output_____ | MIT | nuro-arm-intro.ipynb | tw-ilson/nuro-arm |
First, load the data, from the supplied data file | import tarfile
import json
import gzip
import pandas as pd
import botometer
from pandas.io.json import json_normalize
## VARIABLE INITIATION
tar = tarfile.open("../input/2017-09-22.tar.gz", "r:gz")
mashape_key = "QRraJnMT9KmshkpJ7iu74xKFN1jtp1IyBBijsnS5NGbEuwIX54"
twitter_app_auth = {
'consumer_key': 'sPzHpcj4jMit... | _____no_output_____ | MIT | 2nd_Assignment/iqbal/backup/botometer_data_generator.ipynb | indralukmana/twitter-brexit |
unused scriptonly for profillingxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxo | import pylab as pl
import numpy as np
from collections import Counter
x=Counter(data['created_at'].dt.strftime('%d%H'))
y=zip(map(int,x.keys()),x.values())
y.sort()
x=pd.DataFrame(y)
x
X = range(len(y))
pl.bar(X, x[1], align='center', width=1)
pl.xticks(X, x[0], rotation="vertical")
ymax = max(x[1]) + 1
pl.ylim(0, ym... | _____no_output_____ | MIT | 2nd_Assignment/iqbal/backup/botometer_data_generator.ipynb | indralukmana/twitter-brexit |
Wayne H Nixalo - 09 Aug 2017FADL2 L9: Generative Modelsneural-style-GPU.ipynb | %matplotlib inline
import importlib
import os, sys
sys.path.insert(1, os.path.join('../utils'))
from utils2 import *
from scipy.optimize import fmin_l_bfgs_b
from scipy.misc import imsave
from keras import metrics
from vgg16_avg import VGG16_Avg
limit_mem()
path = '../data/nst/'
# names = os.listdir(path)
# pkl_out =... | _____no_output_____ | MIT | FAI02_old/Lesson9/neural-style-GPU_weird-things.ipynb | WNoxchi/Kawkasos |
Content Recreation | # had to fix some compatibility issues w/ Keras 1 -> Keras 2
import vgg16_avg
importlib.reload(vgg16_avg)
from vgg16_avg import VGG16_Avg
model = VGG16_Avg(include_top=False)
# grabbing activations from near the end of the CNN model
layer = model.get_layer('block5_conv1').output
# calculating layer's target activations... | ../utils/vgg16_avg.py:56: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(64, (3, 3), activation="relu", name="block1_conv1", padding="same")`
x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv1')(img_input)
../utils/vgg16_avg.py:57: UserWarning: Update your `Conv2... | MIT | FAI02_old/Lesson9/neural-style-GPU_weird-things.ipynb | WNoxchi/Kawkasos |
In this implementation, need to define an object that'll allow us to separately access the loss function and gradients of a function, | class Evaluator(object):
def __init__(self, f, shp): self.f, self.shp = f, shp
def loss(self, x):
loss_, self.grad_values = self.f([x.reshape(self.shp)])
return loss_.astype(np.float64)
def grads(self, x): return self.grad_values.flatten().astype(np.float64)
# Define loss function... | _____no_output_____ | MIT | FAI02_old/Lesson9/neural-style-GPU_weird-things.ipynb | WNoxchi/Kawkasos |
jhu_data_us_t0 | ax = plt.gca()
plot_df = jhu_data_us_reduced[jhu_data_us_reduced['total']>0]
p=plot_df[plot_df['state'].isin(state_filter)].groupby('state').plot(x='date',
y='total',
... | _____no_output_____ | MIT | Coronavirus.ipynb | slstarnes/coronavirus-stats |
**OpenCV**---**OpenCV** (pour Open Computer Vision) est une bibliothèque graphique libre, initialement développée par Intel, spécialisée dans le traitement d'images en temps réel. La société de robotique Willow Garage et la société ItSeez se sont succédé au support de cette bibliothèque. Depuis 2016 et le rachat de I... | import cv2 # import de la biblio OpenCV
from google.colab.patches import cv2_imshow # import pour visualisation des image sous google_Colab ,
# Ne pas me demander pourquoi faire cette import dans collab sans lui pas d'affichage
image = ... | _____no_output_____ | MIT | Tuto_Visio_python_&_OpenCV.ipynb | JohnNuwan/TMP-Syst |
**Transformer une image en niveau de gris**Il est possible de transformer une image couleur en niveau de gris avec la ligne de code suivant : | # Transformation de l'image en Nuance de Gris
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2_imshow(gray) | _____no_output_____ | MIT | Tuto_Visio_python_&_OpenCV.ipynb | JohnNuwan/TMP-Syst |
**Qu'est ce que c'est la segmentation d'images?**La segmentation permet d’isoler les différents objets présents dans une image.Il existe différentes méthodes de segmentation : la classification, le clustering, les level-set, graph-cut, etc ....Mais la plus simple est le seuillage, c’est pourquoi je vais te parler uniq... | import numpy as np
ret,th=cv2.threshold(gray,150,255,cv2.THRESH_BINARY)
cv2_imshow(th)
cv2.waitKey(0)
cv2.destroyAllWindows() | _____no_output_____ | MIT | Tuto_Visio_python_&_OpenCV.ipynb | JohnNuwan/TMP-Syst |
Traçons un rectangle autour de la tête | import numpy as np
cv2.rectangle(image,(15,25),(200,250),(0,0,255),15)
cv2_imshow(image) | _____no_output_____ | MIT | Tuto_Visio_python_&_OpenCV.ipynb | JohnNuwan/TMP-Syst |
--- **Exemple Code Complet**Pour les personnes qui se demande a quoi cela peut servire je vous met si joint un code complet pour la detection de personne et d'objet ```! usr/bin/env Python3 |! -*- conding:utf-8 -*- | Usage : Python3.6 | Author : Azazel | ______... | _____no_output_____ | MIT | Tuto_Visio_python_&_OpenCV.ipynb | JohnNuwan/TMP-Syst | |
The Central Limit TheoremElements of Data Scienceby [Allen Downey](https://allendowney.com)[MIT License](https://opensource.org/licenses/MIT) | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
The Central Limit TheoremAccording to our friends at [Wikipedia](https://en.wikipedia.org/wiki/Central_limit_theorem):> The central limit theorem (CLT) establishes that, in some situations, when independent random variables are added, their properly normalized sum tends toward a normal distribution (informally a bell ... | def roll(size):
return np.random.randint(1, 7, size=size) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
If we roll it 1000 times, we expect each value to appear roughly the same number of times. | sample = roll(1000) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
Here's what the PMF looks like. | from empiricaldist import Pmf
pmf = Pmf.from_seq(sample)
pmf.bar()
plt.xlabel('Outcome')
plt.ylabel('Probability'); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
To simulate rolling two dice, I'll create an array with 1000 rows and 2 columns. | a = roll(size=(1000, 2))
a.shape | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
And then add up the columns. | sample2 = a.sum(axis=1)
sample2.shape | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
The result is a sample of 1000 sums of two dice. Here's what that PMF looks like. | pmf2 = Pmf.from_seq(sample2)
pmf2.bar()
plt.xlabel('Outcome')
plt.ylabel('Probability'); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
And here's what it looks like with three dice. | a = roll(size=(1000, 3))
sample3 = a.sum(axis=1)
pmf3 = Pmf.from_seq(sample3)
pmf3.bar()
plt.xlabel('Outcome')
plt.ylabel('Probability'); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
With one die, the distribution is uniform. With two dice, it's a triangle. With three dice, it starts to have the shape of a bell curve.Here are the three PMFs on the same axes, for comparison. | pmf.plot(label='1 die')
pmf2.plot(label='2 dice')
pmf3.plot(label='3 dice')
plt.xlabel('Outcome')
plt.ylabel('Probability')
plt.legend(); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
Gamma distributionsIn the previous section, we saw that the sum of values from a uniform distribution starts to look like a bell curve when we add up just a few values.Now let's do the same thing with values from a gamma distribution.NumPy provides a function to generate random values from a gamma distribution with a ... | mean = 2
gamma_sample = np.random.gamma(mean, size=1000) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
Here's what the distribution looks like, this time using a CDF. | from empiricaldist import Cdf
cdf1 = Cdf.from_seq(gamma_sample)
cdf1.plot()
plt.xlabel('Outcome')
plt.ylabel('CDF'); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
It doesn't look like like a normal distribution. To see the differences more clearly, we can plot the CDF of the data on top of a normal model with the same mean and standard deviation. | from scipy.stats import norm
def plot_normal_model(sample, **options):
"""Plot the CDF of a normal distribution with the
same mean and std of the sample.
sample: sequence of values
options: passed to plt.plot
"""
mean, std = np.mean(sample), np.std(sample)
xs = np.linspace(np.min(sampl... | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
Here's what that looks like for a gamma distribution with mean 2. | from empiricaldist import Cdf
plot_normal_model(gamma_sample, color='C0', label='Normal model')
cdf1.plot(label='Sample 1')
plt.xlabel('Outcome')
plt.ylabel('CDF'); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
There are clear differences between the data and the model. Let's see how that looks when we start adding up values.The following function computes the sum of gamma distributions with a given mean. | def sum_of_gammas(mean, num):
"""Sample the sum of gamma variates.
mean: mean of the gamma distribution
num: number of values to add up
"""
a = np.random.gamma(mean, size=(1000, num))
sample = a.sum(axis=1)
return sample | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
Here's what the sum of two gamma variates looks like: | gamma_sample2 = sum_of_gammas(2, 2)
cdf2 = Cdf.from_seq(gamma_sample2)
plot_normal_model(gamma_sample, color='C0')
cdf1.plot(label='Sum of 1 gamma')
plot_normal_model(gamma_sample2, color='C1')
cdf2.plot(label='Sum of 2 gamma')
plt.xlabel('Total')
plt.ylabel('CDF')
plt.legend(); | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
The normal model is a better fit for the sum of two gamma variates, but there are still evident differences. Let's see how big `num` has to be before it converges.First I'll wrap the previous example in a function. | def plot_gammas(mean, nums):
"""Plot the sum of gamma variates and a normal model.
mean: mean of the gamma distribution
nums: sequence of sizes
"""
for num in nums:
sample = sum_of_gammas(mean, num)
plot_normal_model(sample, color='gray')
Cdf.from_seq(sample).plot(label... | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
With `mean=2` it doesn't take long for the sum of gamma variates to approximate a normal distribution. | mean = 2
plot_gammas(mean, [2, 5, 10]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
However, that doesn't mean that all gamma distribution behave the same way. In general, the higher the variance, the longer it takes to converge.With a gamma distribution, smaller means lead to higher variance. With `mean=0.2`, the sum of 10 values is still not normal. | mean = 0.2
plot_gammas(mean, [2, 5, 10]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
We have to crank `num` up to 100 before the convergence looks good. | mean = 0.2
plot_gammas(mean, [20, 50, 100]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
With `mean=0.02`, we have to add up 1000 values before the distribution looks normal. | mean = 0.02
plot_gammas(mean, [200, 500, 1000]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
Pareto distributionsThe gamma distributions in the previous section have higher variance that the uniform distribution we started with, so we have to add up more values to get the distribution of the sum to look normal.The Pareto distribution is even more extreme. Depending on the parameter, `alpha`, the variance can... | def sum_of_paretos(alpha, num):
a = np.random.pareto(alpha, size=(1000, num))
sample = a.sum(axis=1)
return sample | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
And here's a function that plots the results. | def plot_paretos(mean, nums):
for num in nums:
sample = sum_of_paretos(mean, num)
plot_normal_model(sample, color='gray')
Cdf.from_seq(sample).plot(label=f'num = {num}')
plt.xlabel('Total')
plt.ylabel('CDF')
plt.legend() | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
With `alpha=3` the Pareto distribution is relatively well-behaved, and the sum converges to a normal distribution with a moderate number of values. | alpha = 3
plot_paretos(alpha, [10, 20, 50]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
With `alpha=2`, we don't get very good convergence even with 1000 values. | alpha = 2
plot_paretos(alpha, [200, 500, 1000]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
With `alpha=1.5`, it's even worse. | alpha = 1.5
plot_paretos(alpha, [2000, 5000, 10000]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
And with `alpha=1`, it's beyond hopeless. | alpha = 1
plot_paretos(alpha, [10000, 20000, 50000]) | _____no_output_____ | MIT | central_limit.ipynb | KwekuYamoah/ElementsOfDataScience |
**PINN eikonal solver using transfer learning for a smooth v(x,z) model** | from google.colab import drive
drive.mount('/content/gdrive')
cd "/content/gdrive/My Drive/Colab Notebooks/Codes/PINN_isotropic_eikonal"
!pip install sciann==0.4.6.2
!pip install tensorflow==2.2.0
!pip install keras==2.3.1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_gr... | GPU 0: Tesla P100-PCIE-16GB (UUID: GPU-b1896277-0760-d228-c7e3-e9e6f9e69c24)
| MIT | codes/script3.ipynb | geobook2015/PINNeikonal |
Qcodes example with Alazar ATS 9360 | # import all necessary things
%matplotlib nbagg
import qcodes as qc
import qcodes.instrument.parameter as parameter
import qcodes.instrument_drivers.AlazarTech.ATS9360 as ATSdriver
import qcodes.instrument_drivers.AlazarTech.ATS_acquisition_controllers as ats_contr
# Command to list all alazar boards connected to the ... | Started at 2017-11-09 18:08:04
DataSet:
location = 'data/2017-11-09/#005_AlazarTest_18-08-04'
<Type> | <array_id> | <array.name> | <array.shape>
Setpoint | dummy_set | dummy | (50,)
Measured | acquisition_controller_acquisition | acquisition | (50,)... | MIT | docs/examples/driver_examples/Qcodes example with Alazar 9360.ipynb | generalui/Qcodes-1 |
Notes Legal (ISO) gender types:* https://data.gov.uk/education-standards/sites/default/files/CL-Legal-Sex-Type-v2-0.pdf For data from 2010 and all stored as % * need to relax sum to 100%* Symbol Meaning * '-' Not Applicable * '-' No Entries (Table 3) * 0% Less than 0.5% * *** Fewer Than 5 Entrie... | # check focus subject (typically, but not necessarily, Computing) in list of subjects
checkFocusSubjectListed <-
function(awardFile, glimpseContent = FALSE, listSubjects = FALSE) {
awardData <- read_csv(awardFile, trim_ws = TRUE) %>% #, skip_empty_rows = T) # NOT skipping empty rows... :(
... | _____no_output_____ | MIT | code/r/base/it-402-dc-data_processing_error_checking-base.ipynb | aba-sah/sta-it402-dresscode |
Machine Translation and the Dataset:label:`sec_machine_translation`We have used RNNs to design language models,which are key to natural language processing.Another flagship benchmark is *machine translation*,a central problem domain for *sequence transduction* modelsthat transform input sequences into output sequences... | import os
import torch
from d2l import torch as d2l | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
[**Downloading and Preprocessing the Dataset**]To begin with,we download an English-French datasetthat consists of [bilingual sentence pairs from the Tatoeba Project](http://www.manythings.org/anki/).Each line in the datasetis a tab-delimited pairof an English text sequenceand the translated French text sequence.Note ... | #@save
d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
'94646ad1522d915e7b0f9296181140edcf86a4f5')
#@save
def read_data_nmt():
"""Load the English-French dataset."""
data_dir = d2l.download_extract('fra-eng')
with open(os.path.join(data_dir, 'fra.txt'), 'r') as f:
... | Go. Va !
Hi. Salut !
Run! Cours !
Run! Courez !
Who? Qui ?
Wow! Ça alors !
| MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
After downloading the dataset,we [**proceed with several preprocessing steps**]for the raw text data.For instance,we replace non-breaking space with space,convert uppercase letters to lowercase ones,and insert space between words and punctuation marks. | #@save
def preprocess_nmt(text):
"""Preprocess the English-French dataset."""
def no_space(char, prev_char):
return char in set(',.!?') and prev_char != ' '
# Replace non-breaking space with space, and convert uppercase letters to
# lowercase ones
text = text.replace('\u202f', ' ').replace(... | go . va !
hi . salut !
run ! cours !
run ! courez !
who ? qui ?
wow ! ça alors !
| MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
[**Tokenization**]Different from character-level tokenizationin :numref:`sec_language_model`,for machine translationwe prefer word-level tokenization here(state-of-the-art models may use more advanced tokenization techniques).The following `tokenize_nmt` functiontokenizes the the first `num_examples` text sequence pai... | #@save
def tokenize_nmt(text, num_examples=None):
"""Tokenize the English-French dataset."""
source, target = [], []
for i, line in enumerate(text.split('\n')):
if num_examples and i > num_examples:
break
parts = line.split('\t')
if len(parts) == 2:
source.app... | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
Let us [**plot the histogram of the number of tokens per text sequence.**]In this simple English-French dataset,most of the text sequences have fewer than 20 tokens. | #@save
def show_list_len_pair_hist(legend, xlabel, ylabel, xlist, ylist):
"""Plot the histogram for list length pairs."""
d2l.set_figsize()
_, _, patches = d2l.plt.hist(
[[len(l) for l in xlist], [len(l) for l in ylist]])
d2l.plt.xlabel(xlabel)
d2l.plt.ylabel(ylabel)
for patch in patches... | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
[**Vocabulary**]Since the machine translation datasetconsists of pairs of languages,we can build two vocabularies forboth the source language andthe target language separately.With word-level tokenization,the vocabulary size will be significantly largerthan that using character-level tokenization.To alleviate this,her... | src_vocab = d2l.Vocab(source, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
len(src_vocab) | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
Reading the Dataset:label:`subsec_mt_data_loading`Recall that in language modeling[**each sequence example**],either a segment of one sentenceor a span over multiple sentences,(**has a fixed length.**)This was specified by the `num_steps`(number of time steps or tokens) argument in :numref:`sec_language_model`.In mach... | #@save
def truncate_pad(line, num_steps, padding_token):
"""Truncate or pad sequences."""
if len(line) > num_steps:
return line[:num_steps] # Truncate
return line + [padding_token] * (num_steps - len(line)) # Pad
truncate_pad(src_vocab[source[0]], 10, src_vocab['<pad>']) | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
Now we define a function to [**transformtext sequences into minibatches for training.**]We append the special “<eos>” tokento the end of every sequence to indicate theend of the sequence.When a model is predictingbygenerating a sequence token after token,the generationof the “<eos>” tokencan suggest thatthe... | #@save
def build_array_nmt(lines, vocab, num_steps):
"""Transform text sequences of machine translation into minibatches."""
lines = [vocab[l] for l in lines]
lines = [l + [vocab['<eos>']] for l in lines]
array = torch.tensor([truncate_pad(
l, num_steps, vocab['<pad>']) for l in lines])
vali... | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
[**Putting All Things Together**]Finally, we define the `load_data_nmt` functionto return the data iterator, together withthe vocabularies for both the source language and the target language. | #@save
def load_data_nmt(batch_size, num_steps, num_examples=600):
"""Return the iterator and the vocabularies of the translation dataset."""
text = preprocess_nmt(read_data_nmt())
source, target = tokenize_nmt(text, num_examples)
src_vocab = d2l.Vocab(source, min_freq=2,
reser... | _____no_output_____ | MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
Let us [**read the first minibatch from the English-French dataset.**] | train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8)
for X, X_valid_len, Y, Y_valid_len in train_iter:
print('X:', X.type(torch.int32))
print('valid lengths for X:', X_valid_len)
print('Y:', Y.type(torch.int32))
print('valid lengths for Y:', Y_valid_len)
break | X: tensor([[6, 0, 4, 3, 1, 1, 1, 1],
[0, 4, 3, 1, 1, 1, 1, 1]], dtype=torch.int32)
valid lengths for X: tensor([4, 3])
Y: tensor([[6, 0, 4, 3, 1, 1, 1, 1],
[0, 4, 3, 1, 1, 1, 1, 1]], dtype=torch.int32)
valid lengths for Y: tensor([4, 3])
| MIT | d2l/pytorch/chapter_recurrent-modern/machine-translation-and-dataset.ipynb | nilesh-patil/dive-into-deeplearning |
Using BagIt to tag oceanographic data[`BagIt`](https://en.wikipedia.org/wiki/BagIt) is a packaging format that supports storage of arbitrary digital content. The "bag" consists of arbitrary content and "tags," the metadata files. `BagIt` packages can be used to facilitate data sharing with federal archive centers - th... | import os
import pandas as pd
fname = os.path.join('data', 'dsg', 'timeseriesProfile.csv')
df = pd.read_csv(fname, parse_dates=['time'])
df.head() | _____no_output_____ | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
Instead of "bagging" the `CSV` file we will use this create a metadata rich netCDF file.We can convert the table to a `DSG`, Discrete Sampling Geometry, using `pocean.dsg`. The first thing we need to do is to create a mapping from the data column names to the netCDF `axes`. | axes = {
't': 'time',
'x': 'lon',
'y': 'lat',
'z': 'depth'
} | _____no_output_____ | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
Now we can create a [Orthogonal Multidimensional Timeseries Profile](http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html_orthogonal_multidimensional_array_representation_of_time_series) object... | import os
import tempfile
from pocean.dsg import OrthogonalMultidimensionalTimeseriesProfile as omtsp
output_fp, output = tempfile.mkstemp()
os.close(output_fp)
ncd = omtsp.from_dataframe(
df.reset_index(),
output=output,
axes=axes,
mode='a'
) | _____no_output_____ | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
... And add some extra metadata before we close the file. | naming_authority = 'ioos'
st_id = 'Station1'
ncd.naming_authority = naming_authority
ncd.id = st_id
print(ncd)
ncd.close() | <class 'pocean.dsg.timeseriesProfile.om.OrthogonalMultidimensionalTimeseriesProfile'>
root group (NETCDF4 data model, file format HDF5):
Conventions: CF-1.6
date_created: 2017-11-27T15:11:00Z
featureType: timeSeriesProfile
cdm_data_type: TimeseriesProfile
naming_authority: ioos
id: Station1
... | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
Time to create the archive for the file with `BagIt`. We have to create a folder for the bag. | temp_bagit_folder = tempfile.mkdtemp()
temp_data_folder = os.path.join(temp_bagit_folder, 'data') | _____no_output_____ | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
Now we can create the bag and copy the netCDF file to a `data` sub-folder. | import bagit
import shutil
bag = bagit.make_bag(
temp_bagit_folder,
checksum=['sha256']
)
shutil.copy2(output, temp_data_folder + '/parameter1.nc') | _____no_output_____ | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
Last, but not least, we have to set bag metadata and update the existing bag with it. | urn = 'urn:ioos:station:{naming_authority}:{st_id}'.format(
naming_authority=naming_authority,
st_id=st_id
)
bag_meta = {
'Bag-Count': '1 of 1',
'Bag-Group-Identifier': 'ioos_bagit_testing',
'Contact-Name': 'Kyle Wilcox',
'Contact-Phone': '907-230-0304',
'Contact-Email': 'axiom+ncei@axiomda... | _____no_output_____ | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
That is it! Simple and efficient!!The cell below illustrates the bag directory tree.(Note that the commands below will not work on Windows and some \*nix systems may require the installation of the command `tree`, however, they are only need for this demonstration.) | !tree $temp_bagit_folder
!cat $temp_bagit_folder/manifest-sha256.txt | [01;34m/tmp/tmp5qrdn3qe[00m
├── bag-info.txt
├── bagit.txt
├── [01;34mdata[00m
│ └── parameter1.nc
├── manifest-sha256.txt
└── tagmanifest-sha256.txt
1 directory, 5 files
63d47afc3b8b227aac251a234ecbb9cfc6cc01d1dd1aa34c65969fdabf0740f1 data/parameter1.nc
| MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
We can add more files to the bag as needed. | shutil.copy2(output, temp_data_folder + '/parameter2.nc')
shutil.copy2(output, temp_data_folder + '/parameter3.nc')
shutil.copy2(output, temp_data_folder + '/parameter4.nc')
bag.save(manifests=True, processes=4)
!tree $temp_bagit_folder
!cat $temp_bagit_folder/manifest-sha256.txt | [01;34m/tmp/tmp5qrdn3qe[00m
├── bag-info.txt
├── bagit.txt
├── [01;34mdata[00m
│ ├── parameter1.nc
│ ├── parameter2.nc
│ ├── parameter3.nc
│ └── parameter4.nc
├── manifest-sha256.txt
└── tagmanifest-sha256.txt
1 directory, 8 files
63d47afc3b8b227aac251a234ecbb9cfc6cc01d1dd1aa34c65969fdabf0740f1 data/param... | MIT | notebooks/2017-11-01-Creating-Archives-Using-Bagit.ipynb | kellydesent/notebooks_demos |
Exercise 1 (5 points): Discrete Naive Bayes Classifier [Pen and Paper]In this exercise, we want to get a basic idea of the naive Bayes classifier by analysing a smallexample. Suppose we want to classify fruits based on the criteria length, sweetness and the colourof the fruit and we already spent days by categorizing 1... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn') # pretty matplotlib plots
plt.rcParams['figure.figsize'] = (12, 8) | _____no_output_____ | Apache-2.0 | PR/Assignment01/PRAssignment01.ipynb | jhinga-la-la/pattern-recognition-course |
Question 4.$\hat{x_0}$ = 0.1534 | #plot of likelihood function
#x
mu1 = 0
mu2 = 1
sigma = 1 / np.sqrt(2)
x = np.linspace(-3, 4, 100)
y1 = (1 / (np.sqrt(2 * np.pi * np.power(sigma, 2)))) * (np.power(np.e, -(np.power((x - mu1), 2) / (2 * np.power(sigma, 2))))) # P(x|w1)
y2 = (1 / (np.sqrt(2 * np.pi * np.power(sigma, 2)))) * (np.power(np.e, -(np.power((x... | _____no_output_____ | Apache-2.0 | PR/Assignment01/PRAssignment01.ipynb | jhinga-la-la/pattern-recognition-course |
Question 5.$\hat{x_0}$ = 0.7798 | #plot of likelihood with new threshold value
plt.plot(x, y1)
plt.plot(x, y2, color='Orange')
plt.axvline(x=0.7798, color='r', linestyle='--', ymin=0.05, ymax = 0.98)
plt.legend(('$p(x|\omega_1)$', '$p(x|\omega_2)$', 'Threshold'), loc=1)
#plot of loss functions
l1 = (2/3)*y2
l2 = (7/6)*y1
plt.plot(x, l1, color='Orange'... | _____no_output_____ | Apache-2.0 | PR/Assignment01/PRAssignment01.ipynb | jhinga-la-la/pattern-recognition-course |
Question 6$\hat{x_0}$ = 0.7798 No change in threshold becaue *p* is same and so is the ratio of the two penalty terms $\lambda_{12}$/$\lambda_{21}$ | #plot of likelihood with new threshold value
plt.plot(x, y1)
plt.plot(x, y2, color='Orange')
plt.axvline(x=0.7798, color='r', linestyle='--', ymin=0.05, ymax = 0.98)
plt.legend(('$p(x|\omega_1)$', '$p(x|\omega_2)$', 'Threshold'), loc=1)
#plot of loss functions
l1 = (2/3)*y2
l2 = (7/6)*y1
plt.plot(x, l1, color='Orange'... | _____no_output_____ | Apache-2.0 | PR/Assignment01/PRAssignment01.ipynb | jhinga-la-la/pattern-recognition-course |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 transiton and emission matrices respectively
test_corpus: a list containing a preprocessed corpus
best_probs: an ... | _____no_output_____ | MIT | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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... | # print(states)
# print(best_probs[3])
# print(prep[5])
print(best_paths[None,None])
# 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 word... | 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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
**Expected Output:** ```CPPThe prediction for prep[-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])
for prediction, y1 in zip(pred, y):
if len(y1.split()) == 2:
continue
print(y1.split()) | []
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]... | MIT | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
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 | week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-checkpoint.ipynb | aakar-mutha/NLP-C2-assignments |
Grayscaling Grayscaling is process by which an image is converted from a full color to shades of grey (black & white)In OpenCV, many functions grayscale images before processing. This is done because it simplifies the image, acting almost as a noise reduction and increasing processing time as there is less information... | import cv2
# Load our input image
image = cv2.imread('./images/input.jpg')
cv2.imshow('Original', image)
cv2.waitKey()
# We use cvtColor, to convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale', gray_image)
cv2.waitKey()
cv2.destroyAllWindows()
#Another method faster metho... | _____no_output_____ | MIT | LECTURES/Lecture 2.5 - Grayscaling.ipynb | PacktPublishing/Master-Computer-Vision-OpenCV3-in-Python-and-Machine-Learning |
RumbleDB sandbox This is a RumbleDB sandbox that allows you to play with simple JSONiq queries.It is a jupyter notebook that you can also download and execute on your own machine, but if you arrived here from the RumbleDB website, it is likely to be shown within Google's Colab environment.To get started, you first nee... | !pip install rumbledb
%load_ext rumbledb
%env RUMBLEDB_SERVER=http://public.rumbledb.org:9090/jsoniq | _____no_output_____ | Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
By default, this notebook uses a small public backend provided by us. Each query runs on just one machine that is very limited in CPU: one core and memory: 1GB, and with only the http scheme activated. This is sufficient to discover RumbleDB and play a bit, but of course is not intended for any production use. If you n... | %%jsoniq
let $stores :=
[
{ "store number" : 1, "state" : "MA" },
{ "store number" : 2, "state" : "MA" },
{ "store number" : 3, "state" : "CA" },
{ "store number" : 4, "state" : "CA" }
]
let $sales := [
{ "product" : "broiler", "store number" : 1, "quantity" : 20 },
{ "product" : "toaster", "store numbe... | Took: 0.1701183319091797 ms
[{"nb": 1, "state": "MA", "sold": "broiler"}, {"nb": 1, "state": "MA", "sold": "socks"}, {"nb": 2, "state": "MA", "sold": "toaster"}, {"nb": 2, "state": "MA", "sold": "toaster"}, {"nb": 2, "state": "MA", "sold": "socks"}, {"nb": 3, "state": "CA", "sold": "toaster"}, {"nb": 3, "state": "CA", ... | Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
And here you go Actually, you already knew some JSONiqThe first thing you need to know is that a well-formed JSON document is a JSONiq expression as well.This means that you can copy-and-paste any JSON document into a query. The following are JSONiq queries that are "idempotent" (they just output themselves): | %%jsoniq
{ "pi" : 3.14, "sq2" : 1.4 }
%%jsoniq
[ 2, 3, 5, 7, 11, 13 ]
%%jsoniq
{
"operations" : [
{ "binary" : [ "and", "or"] },
{ "unary" : ["not"] }
],
"bits" : [
0, 1
]
}
%%jsoniq
[ { "Question" : "Ultimate" }, ["Life", "the universe", "and everything"] ] | Took: 0.08156394958496094 ms
[{"Question": "Ultimate"}, ["Life", "the universe", "and everything"]]
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
This works with objects, arrays (even nested), strings, numbers, booleans, null.It also works the other way round: if your query outputs an object or an array, you can use it as a JSON document.JSONiq is a declarative language. This means that you only need to say what you want - the compiler will take care of the how.... | %%jsoniq
"Hello, World!" | Took: 0.05169677734375 ms
"Hello, World!"
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
Not surprisingly, it outputs the string "Hello, World!". Numbers and arithmetic operationsOkay, so, now, you might be thinking: "What is the use of this language if it just outputs what I put in?" Of course, JSONiq can more than that. And still in a declarative way. Here is how it works with numbers: | %%jsoniq
2 + 2
%%jsoniq
(38 + 2) div 2 + 11 * 2
| Took: 0.12616300582885742 ms
42
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
(mind the division operator which is the "div" keyword. The slash operator has different semantics).Like JSON, JSONiq works with decimals and doubles: | %%jsoniq
6.022e23 * 42 | Took: 0.06836986541748047 ms
2.52924e+25
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
Logical operationsJSONiq supports boolean operations. | %%jsoniq
true and false
%%jsoniq
(true or false) and (false or true) | Took: 0.007046222686767578 ms
true
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
The unary not is also available: | %%jsoniq
not true | Took: 0.006941080093383789 ms
false
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
StringsJSONiq is capable of manipulating strings as well, using functions: | %%jsoniq
concat("Hello ", "Captain ", "Kirk")
%%jsoniq
substring("Mister Spock", 8, 5) | Took: 0.00574493408203125 ms
"Spock"
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
JSONiq comes up with a rich string function library out of the box, inherited from its base language. These functions are listed [here](https://www.w3.org/TR/xpath-functions-30/) (actually, you will find many more for numbers, dates, etc). SequencesUntil now, we have only been working with single values (an object, an... | %%jsoniq
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
%%jsoniq
1, true, 4.2e1, "Life" | Took: 0.00654292106628418 ms
1
true
42
"Life"
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
The "to" operator is very convenient, too: | %%jsoniq
(1 to 100) | Took: 0.006345033645629883 ms
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
10... | Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
Some functions even work on sequences: | %%jsoniq
sum(1 to 100)
%%jsoniq
string-join(("These", "are", "some", "words"), "-")
%%jsoniq
count(10 to 20)
%%jsoniq
avg(1 to 100) | Took: 0.005938053131103516 ms
50.5
| Apache-2.0 | RumbleSandbox.ipynb | Sparksoniq/sparksoniq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.