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 Numpy array, and transpose to view: | 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 compared various languages and libraries in terms of their speed. This notebook contains the code of Julia implementation. I have struggled to make it run in parallel. I am also not sure if the code is actually optimal, but I include this for completion. Getting data | 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 = ones((n_seqs,n_seqs))
Threads.@threads for t in 1:24
for i in 1+t:24:n_seqs-1
out = get_nf_row(input_data[i:n_seqs, :])
is_same_cluster[i, i+1:n_seqs] =out
is_same_cluster[i+1:n_seqs, i] =out
end
end
s = 1.0./sum(is_same_cluster, dims=2)
sum(s)/(seq_len^0.5)
end
@time get_nf_julia(input_data) | _____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 contacts, $Q(X)$:$$Q(X) = \frac{1}{|S|} \sum_{(i,j) \in S} \frac{1}{1 + \exp[\beta(r_{ij}(X) - \lambda r_{ij}^0)]},$$where - $X$ is a conformation, - $r_{ij}(X)$ is the distance between atoms $i$ and $j$ in conformation $X$, - $r^0_{ij}$ is the distance from heavy atom i to j in the native state conformation, - $S$ is the set of all pairs of heavy atoms $(i,j)$ belonging to residues $\theta_i$ and $\theta_j$ such that $|\theta_i - \theta_j| > 3$ and $r^0_{i,} < 4.5 \unicode{x212B}$, - $\beta=5 \unicode{x212B}^{-1}$, - $\lambda=1.8$ for all-atom simulations | 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 for
native : md.Trajectory
The 'native state'. This can be an entire trajecory, or just a single frame.
Only the first conformation is used
Returns
-------
q : np.array, shape=(len(traj),)
The fraction of native contacts in each frame of `traj`
References
----------
..[1] Best, Hummer, and Eaton, "Native contacts determine protein folding
mechanisms in atomistic simulations" PNAS (2013)
"""
BETA_CONST = 50 # 1/nm
LAMBDA_CONST = 1.8
NATIVE_CUTOFF = 0.45 # nanometers
# get the indices of all of the heavy atoms
heavy = native.topology.select_atom_indices('heavy')
# get the pairs of heavy atoms which are farther than 3
# residues apart
heavy_pairs = np.array(
[(i,j) for (i,j) in combinations(heavy, 2)
if abs(native.topology.atom(i).residue.index - \
native.topology.atom(j).residue.index) > 3])
# compute the distances between these pairs in the native state
heavy_pairs_distances = md.compute_distances(native[0], heavy_pairs)[0]
# and get the pairs s.t. the distance is less than NATIVE_CUTOFF
native_contacts = heavy_pairs[heavy_pairs_distances < NATIVE_CUTOFF]
print("Number of native contacts", len(native_contacts))
# now compute these distances for the whole trajectory
r = md.compute_distances(traj, native_contacts)
# and recompute them for just the native state
r0 = md.compute_distances(native[0], native_contacts)
q = np.mean(1.0 / (1 + np.exp(BETA_CONST * (r - LAMBDA_CONST * r0))), axis=1)
return q
# pull a random protein from the PDB
# (The unitcell info happens to be wrong)
traj = md.load_pdb('http://www.rcsb.org/pdb/files/2MI7.pdb')
# just for example, use the first frame as the 'native' conformation
q = best_hummer_q(traj, traj[0])
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(q)
plt.xlabel('Frame', fontsize=14)
plt.ylabel('Q(X)', fontsize=14)
plt.show() | _____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.desired"]["modules"]["lvaExtension"]["settings"]["createOptions"]["HostConfig"]["runtime"] = aiModule
with open(deploymentManifestFileName, "w") as f:
json.dump(data, f, indent=4) | _____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.
Resolving deltas: 100% (1313/1313), done.
Processing ./nuro-arm
[33m DEPRECATION: A future pip version will change local packages to be built in-place without first copying to a temporary directory. We recommend you use --use-feature=in-tree-build to test your packages with this new behavior before it becomes the default.
pip 21.3 will remove support for this functionality. You can find discussion regarding this at https://github.com/pypa/pip/issues/7555.[0m
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from nuro-arm==0.0.1) (1.19.5)
Requirement already satisfied: opencv-contrib-python in /usr/local/lib/python3.7/dist-packages (from nuro-arm==0.0.1) (4.1.2.30)
Collecting pybullet==3.1.7
Downloading pybullet-3.1.7.tar.gz (79.0 MB)
[K |████████████████████████████████| 79.0 MB 33 kB/s
[?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from nuro-arm==0.0.1) (3.2.2)
Requirement already satisfied: sklearn in /usr/local/lib/python3.7/dist-packages (from nuro-arm==0.0.1) (0.0)
Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from nuro-arm==0.0.1) (1.4.1)
Requirement already satisfied: gym in /usr/local/lib/python3.7/dist-packages (from nuro-arm==0.0.1) (0.17.3)
Collecting easyhid
Downloading easyhid-0.0.10.tar.gz (5.0 kB)
Requirement already satisfied: cffi in /usr/local/lib/python3.7/dist-packages (from easyhid->nuro-arm==0.0.1) (1.14.6)
Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi->easyhid->nuro-arm==0.0.1) (2.20)
Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym->nuro-arm==0.0.1) (1.5.0)
Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym->nuro-arm==0.0.1) (1.3.0)
Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym->nuro-arm==0.0.1) (0.16.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->nuro-arm==0.0.1) (1.3.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->nuro-arm==0.0.1) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->nuro-arm==0.0.1) (0.10.0)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->nuro-arm==0.0.1) (2.8.2)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib->nuro-arm==0.0.1) (1.15.0)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from sklearn->nuro-arm==0.0.1) (0.22.2.post1)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->sklearn->nuro-arm==0.0.1) (1.0.1)
Building wheels for collected packages: nuro-arm, pybullet, easyhid
Building wheel for nuro-arm (setup.py) ... [?25l[?25hdone
Created wheel for nuro-arm: filename=nuro_arm-0.0.1-py3-none-any.whl size=3863148 sha256=f54a3c5eb44ac6acb5ceeff49361cd5e223d02c34c88acc77dd257287f077e4b
Stored in directory: /root/.cache/pip/wheels/10/03/f4/741a634e94648d97b14be760853bd353ef7beb7f96ccbb8578
Building wheel for pybullet (setup.py) ... [?25l[?25hdone
Created wheel for pybullet: filename=pybullet-3.1.7-cp37-cp37m-linux_x86_64.whl size=89751110 sha256=1b5cc4b9a0613c9c6a1d87d65fcdd4d5914149eb5f7e6c0c428e17a671d2412b
Stored in directory: /root/.cache/pip/wheels/70/1c/62/86c8b68885c24123d87c5392d6678aa2b68a1796c8113e1aa6
Building wheel for easyhid (setup.py) ... [?25l[?25hdone
Created wheel for easyhid: filename=easyhid-0.0.10-py3-none-any.whl size=5574 sha256=1eb0fb6a7a75115d6bd8502a1e22dd54c68ca21b386e99cd73ebefa4539f0361
Stored in directory: /root/.cache/pip/wheels/69/4b/32/e705c37967a4d9c004255ffb8b2c64674a6fb3019785d1adc7
Successfully built nuro-arm pybullet easyhid
Installing collected packages: pybullet, easyhid, nuro-arm
Successfully installed easyhid-0.0.10 nuro-arm-0.0.1 pybullet-3.1.7
| 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.FuncAnimation(fig, animate, frames=len(video), interval=50)
return HTML(anim.to_html5_video())
def show_image(image):
fig = plt.figure()
im = plt.imshow(image)
plt.axis('off')
plt.tight_layout(pad=0)
# pose matrix for camera that looks upon scene from side
side_view_pose_mtx = np.array([[-0.866, 0.3214,-0.3830, 0.3264],
[-0.5, -0.5567, 0.663, -0.351],
[-0, -0.766, -0.6428, 0.514],
[0, 0, 0, 1]]) | _____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_size, tag_id=0)
# visualize the scene
image = side_view_camera.get_image()
show_image(image)
# detect cube with aruco tag
detected_cube = camera.find_cubes(cube_size=cube_size, tag_size=0.75*cube_size)[0]
# show image with cube vertices highlighted
image = camera.get_image()
show_image(image)
pixel_vertices = camera.project_world_points(detected_cube.vertices)
for v in pixel_vertices:
plt.plot(*v, 'r.')
# picking up the cube
side_view_camera.start_recording(1)
robot.open_gripper()
robot.move_hand_to( detected_cube.pos )
# robot.move_hand_to( cube.get_position() )
robot.close_gripper()
robot.home()
video = side_view_camera.wait_for_recording()
show_video(video) | _____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': 'sPzHpcj4jMital75nY7dfd4zn',
'consumer_secret': 'rTGm68zdNmLvnTc22cBoFg4eVMf3jLVDSQLOwSqE9lXbVWLweI',
'access_token': '4258226113-4UnHbbbxoRPz10thy70q9MtEk9xXfJGOpAY12KW',
'access_token_secret': '549HdasMEW0q2uV05S5s4Uj5SdCeEWT8dNdLNPiAeeWoX',
}
bom = botometer.Botometer(wait_on_ratelimit=True,
mashape_key=mashape_key,
**twitter_app_auth)
count = 0
data = pd.DataFrame()
uname = pd.DataFrame()
#uname = []
for members in tar.getmembers():
if (None):
break
else:
f = tar.extractfile(members)
data = data.append(pd.read_json(f, lines=True))
#for memberx in data['user']:
#uname=uname.append(json_normalize(memberx)['screen_name'], ignore_index=True)
#uname.append('@'+str(json_normalize(memberx)['screen_name'].values[0]))
count = count + 1
data = pd.DataFrame()
uname = pd.DataFrame()
count=0
#uname = []
for members in tar.getmembers():
#if (None):
# break
#else:
if (count==13):
f = tar.extractfile(members)
data = data.append(pd.read_json(f, lines=True))
for memberx in data['user']:
uname=uname.append(json_normalize(memberx)['screen_name'], ignore_index=True)
#uname.append('@'+str(json_normalize(memberx)['screen_name'].values[0]))
count = count + 1
len(uname)
distinct_uname=[]
for i in uname.drop_duplicates().values:
distinct_uname.append((str('@'+i).replace("[u'","")).replace("']",''))
len(distinct_uname)
asu=distinct_uname[0:180]
botoresult = pd.DataFrame()
for screen_name, result in bom.check_accounts_in(asu):
botoresult=botoresult.append(result, ignore_index=True)
#bom.twitter_api.rate_limit_status()['resources']['application']['/application/rate_limit_status']['remaining']
output_bot=pd.concat([botoresult.user.apply(pd.Series), botoresult.scores.apply(pd.Series), botoresult.categories.apply(pd.Series)], axis=1)
len(botoresult)
output_bot.to_csv("outputbot.csv", sep=',', encoding='utf-8') | _____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, ymax)
pl.show() | _____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 = open('fnames.pkl','wb')
# pickle.dump(names, pkl_out)
# pkl_out.close()
fnames = pickle.load(open(path + 'fnames.pkl', 'rb'))
fnames = glob.glob(path+'**/*.JPG', recursive=True)
fn = fnames[0]
fn
img = Image.open(fn); img
# Subtracting mean and reversing color-channel order:
rn_mean = np.array([123.68,116.779,103.939], dtype=np.float32)
preproc = lambda x: (x - rn_mean)[:,:,:,::-1]
# later undoing preprocessing for image generation
deproc = lambda x,s: np.clip(x.reshape(s)[:,:,:,::-1] + rn_mean, 0, 255)
img_arr = preproc(np.expand_dims(np.array(img), 0))
shp = img_arr.shape | _____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
layer_model = Model(model.input, layer)
targ = K.variable(layer_model.predict(img_arr)) | ../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 `Conv2D` call to the Keras 2 API: `Conv2D(64, (3, 3), activation="relu", name="block1_conv2", padding="same")`
x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv2')(x)
../utils/vgg16_avg.py:61: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(128, (3, 3), activation="relu", name="block2_conv1", padding="same")`
x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv1')(x)
../utils/vgg16_avg.py:62: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(128, (3, 3), activation="relu", name="block2_conv2", padding="same")`
x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv2')(x)
../utils/vgg16_avg.py:66: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(256, (3, 3), activation="relu", name="block3_conv1", padding="same")`
x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv1')(x)
../utils/vgg16_avg.py:67: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(256, (3, 3), activation="relu", name="block3_conv2", padding="same")`
x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv2')(x)
../utils/vgg16_avg.py:68: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(256, (3, 3), activation="relu", name="block3_conv3", padding="same")`
x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv3')(x)
../utils/vgg16_avg.py:72: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(512, (3, 3), activation="relu", name="block4_conv1", padding="same")`
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv1')(x)
../utils/vgg16_avg.py:73: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(512, (3, 3), activation="relu", name="block4_conv2", padding="same")`
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv2')(x)
../utils/vgg16_avg.py:74: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(512, (3, 3), activation="relu", name="block4_conv3", padding="same")`
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv3')(x)
../utils/vgg16_avg.py:78: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(512, (3, 3), activation="relu", name="block5_conv1", padding="same")`
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv1')(x)
../utils/vgg16_avg.py:79: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(512, (3, 3), activation="relu", name="block5_conv2", padding="same")`
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv2')(x)
../utils/vgg16_avg.py:80: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(512, (3, 3), activation="relu", name="block5_conv3", padding="same")`
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv3')(x)
| 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 to calc MSE betwn the 2 outputs at specfd Conv layer
loss = metrics.mse(layer, targ)
grads = K.gradients(loss, model.input)
fn = K.function([model.input], [loss]+grads)
evaluator = Evaluator(fn, shp)
# optimize loss fn w/ deterministic approach using Line Search
def solve_image(eval_obj, niter, x):
for i in range(niter):
x, min_val, info = fmin_l_bfgs_b(eval_obj.loss, x.flatten(),
fprime=eval_obj.grads, maxfun=20)
x = np.clip(x, -127,127)
print('Current loss value:', min_val)
imsave(f'{path}/results/res_at_iteration_{i}.png', deproc(x.copy(), shp)[0])
return x
# generating a random image:
rand_img = lambda shape: np.random.uniform(-2.5,2.5,shape)/100
x = rand_img(shp)
plt.imshow(x[0])
iterations = 10
x = solve_image(evaluator, iterations, x)
Image.open(path + 'results/res_at_iteration_1.png')
# Looking at result for earlier Conv block (4):
layer = model.get_layer('block4_conv1').output
layer_model = Model(model.input, layer)
targ = K.variable(layer_model.predict(img_arr))
loss = metrics.mse(layer, targ)
grads = K.gradients(loss, model.input)
fn = K.function([model.input], [loss]+grads)
evaluator = Evaluator(fn, shp)
x = solve_image(evaluator, iterations, x)
Image.open(path + 'results/res_at_iteration_9.png') | _____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',
ax=ax, logy=True)
ax.figure.set_size_inches(12,6)
ax.legend(state_filter)
ax.set_xlabel('Days Since Cases = 1')
ax.set_ylabel('Total Confirmed Cases')
ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.0f}'));
state_abbr = pd.read_csv('https://raw.githubusercontent.com/jasonong/List-of-US-States/master/states.csv')
state_lookup = state_abbr.set_index('Abbreviation', drop=True).squeeze().to_dict()
covidtracking_reduced['state'] = covidtracking_reduced['state'].map(state_lookup)
covidtracking_reduced = covidtracking_reduced.groupby(['state', 'date']).max()['positive'].reset_index()
ax = plt.gca()
p=covidtracking_reduced[covidtracking_reduced['state'].isin(state_filter)].groupby('state').plot(x='date',
y='positive',
ax=ax, logy=True)
ax.figure.set_size_inches(12,6)
ax.legend(state_filter)
ax.set_xlabel('Days Since Cases = 1')
ax.set_ylabel('Total Confirmed Cases')
ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.0f}'))
top25_states = covidtracking_reduced.groupby('state').max()['total'].sort_values(ascending=False)[:25].keys()
fig = plt.figure(figsize=(20,20))
ax_list = fig.subplots(5, 5).flatten()
for ix, state in enumerate(top25_states):
if ix > 24:
continue
plot_data = covidtracking_reduced.query('state == @state').drop(columns='state').set_index('date')
plot_data.plot(ax=ax_list[ix],legend=False, title=state, logy=True) | _____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 ItSeez par Intel, le support est de nouveau assuré par Intel.Cette bibliothèque est distribuée sous licence BSD.NVidia a annoncé en septembre 2010 qu'il développerait des fonctions utilisant CUDA pour OpenCV7.--- **Fonctionnalités**La bibliothèque OpenCV met à disposition de nombreuses fonctionnalités très diversifiées permettant de créer des programmes en partant des données brutes pour aller jusqu'à la création d'interfaces graphiques basiques.--- **Traitement d'images**Elle propose la plupart des opérations classiques en traitement bas niveau des images 8:* lecture, écriture et affichage d’une image ;* calcul de l'histogramme des niveaux de gris ou d'histogrammes couleurs ;* lissage, filtrage ;* seuillage d'image (méthode d'Otsu, seuillage adaptatif)* segmentation (composantes connexes, GrabCut) ;* morphologie mathématique.--- **Traitement vidéos**Cette bibliothèque s'est imposée comme un standard dans le domaine de la recherche parce qu'elle propose un nombre important d'outils issus de l'état de l'art en vision des ordinateurs tels que :* lecture, écriture et affichage d’une vidéo (depuis un fichier ou une caméra)* détection de droites, de segment et de cercles par Transformée de Hough* détection de visages par la méthode de Viola et Jones* cascade de classifieurs boostés* détection de mouvement, historique du mouvement* poursuite d'objets par mean-shift ou Camshift* détection de points d'intérêts* estimation de flux optique (Méthode de Lucas–Kanade)* triangulation de Delaunay* diagramme de Voronoi* enveloppe convexe* ajustement d'une ellipse à un ensemble de points par la méthode des moindres carrés--- **Algorithmes d'apprentissages**Certains algorithmes classiques dans le domaine de l'apprentissage artificiel sont aussi disponibles :* K-means* AdaBoost et divers algorithmes de boosting* Réseau de neurones artificiels* Séparateur à vaste marge* Estimateur (statistique)* Les arbres de décision et les forêts aléatoires--- **Calculs Matriciels**Depuis la version 2.1 d'OpenCV l'accent a été mis sur les matrices et les opérations sur celles-ci. En effet, la structure de base est la matrice. Une image peut être considérée comme une matrice de pixel. Ainsi, toutes les opérations de bases des matrices sont disponibles, notamment:* la transposée* calcul du déterminant* inversion* multiplication (par une matrice ou un scalaire)* calcul des valeurs propres--- **Autres fonctionnalités**Elle met également à disposition quelques fonctions d'interfaces graphiques, comme les curseurs à glissière, les contrôles associés aux événements souris, ou bien l'incrustation de texte dans une image.--- **Source** : * https://fr.wikipedia.org/wiki/OpenCV **Site OpenCV** :* https://opencv.org--- **OpenCV Installation**--- **Windows** :L'installation d'openCV pour Windows est très simple. Pour commencer, télécharger le fichier qui correspond à votre architecture sur le liens suivant :http://www.lfd.uci.edu/~gohlke/pythonlibs/opencv(Profitez en pour jeter un coup d’œil sur toutes les librairies proposées) pour moi c'est le fichier : opencv_python-3.1.0-cp34-none-win_amd64.whl. Le cpXX correspond a votre version de python. Pour moi, cp34 signifie cPython version 3.4.Maintenant que vous avez récupéré le fichier qui nous intéresse , ouvrez une invite de commande en tant qu'administrateur. Pour cela lancer une recherche sur "cmd", faites un clic droit sur "Invite de commande" puis choisissez : "Exécuter en tant qu'administrateur"Préparez le terrain en installant numpy et matplotlib```pip3 install numpypip3 install matplotlib```ensuite le plat de résistance …```pip3 install opencv_python-3.1.0-cp34-none-win_amd64.whl```c'est tout. (moi j'aime bien quant ça s'installe sans douleur) --- Exemple :prise en main sur une photo pour montré ce que l'on peut faire avec OpenCV | 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 = cv2.imread('Eva_Green.jpg') # ouverture de l'image
cv2_imshow(image) # affichage de L'image
cv2.waitKey(0) # attente d'aucune touch pour fermer l'image
cv2.destroyAllWindows() # detruire le cache image sous windows | _____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 uniquement de celle-ci dans cette seconde partie.Le seuillage est une opération qui permet de transformer une image en niveau de gris en image binaire (noir et blanc),l'image obtenue est appelée masque binaire.Le schéma ci-dessous illustre bien ce concept.  Il existe 2 méthodes pour seuiller une image, le seuillage manuel et le seuillage automatique. **Seuillage manuel**Sur la l'illustration ci-dessus, trois formes sont présentes dans l’image originale.Les pixels du rond sont représentés par des étoiles, ceux du carré par des rectangles jaunes, ceux du triangle par des triangles verts et les cercles bleus correspondent au fond.Dans la figure, nous pouvons remarquer que tous les pixels correspondants du fond (rond bleu) ont une valeur supérieure à 175. Nous en déduisons que le seuil optimal est 175. En faisant cela, nous avons déterminé le seuil optimal manuellement.Pour utiliser le seuil manuel avec OpenCV, il suffit d’appeler la fonction thresold```ret,th=cv2.threshold(img, seuil,couleur, option)``` | 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 | __________________________________|----------------------------------------------------------------""" DocString: Visualisation OpenCV Note: Recherche avec OpenCV dans le cadre de créé une securité et la detection de D'objet. Objectife : Faire tourner sur un rasberry pi pour peut de consomation Why: Nous sommes le 31/10/2020 , Nous somme en confinement . Nous avons eu dans le monde Equestre Pas mal de soucie d'agression Parce que tous le monde peut aporté et crée une idée sans savoir codé. J'utilise le language Python car il est extrement compréhensible. Pas besoin d'etre Dev pour Lancer une idée et un POC."""---------------------------------------------------------------- import import cv2 Module OpenCV---------------------------------------------------------------- une vidéo etant composé d'images nous travaillerons en premiers sur une images fixe pour nos teste Chemin de L'imagepath_file = Eva_Green.jpg"----------------------------------------- Creation de l'ouverture de l'img Lecture imgimg = cv2.imread(path_file) creation capture videocap = cv2.VideoCapture(0) 0 Pour webcam integré 1,2,3... pour autre web cam Settingscap.set(3,648)cap.set(3,480) Creation de List Vide d'initclassNames = []classFile = 'coco.names' ouverture fichier with open (classFile , 'rt') as f: classNames = f.read().rstrip('\n').split('\n') Affichage de la listprint(classNames) affichage liste creation des path et import pour visualisation MLconfigPath = "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt"weightsPath = 'frozen_inference_graph.pb' Utilisation du resaux via doncifguration donner dans la Docnet = cv2.dnn_DetectionModel(weightsPath,configPath)net.setInputSize(320,320)net.setInputScale(1.0/127.5)net.setInputMean((127.5, 127.5,127.5))net.setInputSwapRB(True)while True: conf success, img = cap.read() classIds , confs, bbox = net.detect(img, confThreshold=0.5) bon bah gogole est ton amis code status: -1072875772 print(classIds, bbox) if len(classIds) !=0: configuration affichage rectangle dans l'image for classIds , confidence, box in zip(classIds.flatten(), confs.flatten(), bbox): Creation du rectangle et definition couleur epaisseur de traits cv2.rectangle(img,box, color=(0,255,0), thickness=2) creation du texte label avec definition de sont emplacement dans la page comme la creation graphique sous word ou autre cv2.putText(img, classNames[classIds-1].upper(),(box[0]+10,box[1]+30), cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2) Bon pour le moment par de webCam Exterieur Je sais plus ce que j'en est fait. visualisation cv2.imshow("Output", img) if cv2.waitKey(1) & 0xFF == ord('q'): breakcap.release()cv2.destroyAllWindows()``` ---**Un simple serveur de cache pour diffuser la vidéo aux clients**Vous pouvez les tester sur un ou plusieurs ordinateurs. Un pour la camera extern, tel que Raspberry Pi, ou toute plate-forme avec Python. Le code cache-server.py fera le gros du travail ici, car l'augmentation du nombre de threads demande plus de ressources au niveau du processeur. Il est donc préférable d'utiliser un PC multicœur pour la mise en œuvre du serveur de cache. Le PC côté client recevra la vidéo du serveur de cache. Il est supposé dans ce tutoriel que tous les appareils ont accès au réseau Wifi local. Pour connaître l'adresse IP de chaque pc, utilisez celle de l'adaptateur Wifi, la procédure pour différentes plateformes est ici: *Camera_Extern.py*```import socket, cv2, pickle, structimport imutilsimport cv2server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)host_name = socket.gethostname()host_ip = '192.168.79.102' Enter Camera IP addressprint('HOST IP:',host_ip)port = 9999socket_address = (host_ip,port)server_socket.bind(socket_address)server_socket.listen()print("Listening at",socket_address)def start_video_stream(): client_socket,addr = server_socket.accept() camera = True if camera == True: vid = cv2.VideoCapture(0) else: vid = cv2.VideoCapture('videos/boat.mp4') try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: while(vid.isOpened()): img,frame = vid.read() frame = imutils.resize(frame,width=320) a = pickle.dumps(frame) message = struct.pack("Q",len(a))+a client_socket.sendall(message) cv2.imshow("TRANSMITTING TO CACHE SERVER",frame) key = cv2.waitKey(1) & 0xFF if key ==ord('q'): client_socket.close() break except Exception as e: print(f"CACHE SERVER {addr} DISCONNECTED") passwhile True: start_video_stream()```` *cache-server.py*```import socket, cv2, pickle, structimport imutils pip install imutilsimport threadingimport cv2server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)host_name = socket.gethostname()host_ip = socket.gethostbyname(host_name)print('HOST IP:',host_ip)port = 9999socket_address = (host_ip,port)server_socket.bind(socket_address)server_socket.listen()print("Listening at",socket_address)global frameframe = Nonedef start_video_stream(): global frame client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_ip = '192.168.79.102' Here camera_extern IP port = 9999 client_socket.connect((host_ip,port)) data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) cv2.imshow("RECEIVING VIDEO FROM DRONE",frame) key = cv2.waitKey(1) & 0xFF print(data) if key == ord('q'): break client_socket.close() thread = threading.Thread(target=start_video_stream, args=())thread.start()def serve_client(addr,client_socket): global frame try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: while True: a = pickle.dumps(frame) message = struct.pack("Q",len(a))+a client_socket.sendall(message) except Exception as e: print(f"CLINET {addr} DISCONNECTED") pass while True: client_socket,addr = server_socket.accept() print(addr) thread = threading.Thread(target=serve_client, args=(addr,client_socket)) thread.start() print("TOTAL CLIENTS ",threading.activeCount() - 2) édité ici car un thread est déjà démarré avant``` *client.py*```import socket,cv2, pickle,struct create socketclient_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)host_ip = '192.168.124.15' Here Require CACHE Server IPport = 9999client_socket.connect((host_ip,port)) a tupledata = b""payload_size = struct.calcsize("Q")while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) cv2.imshow("RECEIVING VIDEO FROM CACHE SERVER",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): breakclient_socket.close() ``` --- **Transférer la vidéo sur les sockets de plusieurs clients**nous ferons la programmation de socket pour plusieurs clients et un seul serveur. Il s'agit de créer plusieurs sockets client et de transmettre leurs vidéos à un serveur en Python. Le client.py utilise OpenCv pour accéder aux images vidéo depuis la webcam en direct ou via la vidéo MP4. Le code côté serveur exécute le multi-threading pour afficher l'image vidéo de chaque client connecté. Requirements:```pip3 install opencv-contrib-pythonpip3 install pyshinepip3 install numpypip3 install imutils```Le côté client doit connaître l'adresse IP du serveur. Le serveur et le client doivent être connectés au même routeur wifi. *client.py*```import socket,cv2, pickle,structimport pyshine as ps pip install pyshineimport imutils pip install imutilscamera = Trueif camera == True: vid = cv2.VideoCapture(0)else: vid = cv2.VideoCapture('videos/mario.mp4')client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)host_ip = '192.168.1.11' port = 9999client_socket.connect((host_ip,port))if client_socket: while (vid.isOpened()): try: img, frame = vid.read() frame = imutils.resize(frame,width=380) a = pickle.dumps(frame) message = struct.pack("Q",len(a))+a client_socket.sendall(message) cv2.imshow(f"TO: {host_ip}",frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): client_socket.close() except: print('VIDEO FINISHED!') break``` *server.py*```import socket, cv2, pickle, structimport imutilsimport threadingimport pyshine as ps pip install pyshineimport cv2server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)host_name = socket.gethostname()host_ip = socket.gethostbyname(host_name)print('HOST IP:',host_ip)port = 9999socket_address = (host_ip,port)server_socket.bind(socket_address)server_socket.listen()print("Listening at",socket_address)def show_client(addr,client_socket): try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: if a client socket exists data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) text = f"CLIENT: {addr}" frame = ps.putBText(frame,text,10,10,vspace=10,hspace=1,font_scale=0.7, background_RGB=(255,0,0),text_RGB=(255,250,250)) cv2.imshow(f"FROM {addr}",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break client_socket.close() except Exception as e: print(f"CLINET {addr} DISCONNECTED") pass while True: client_socket,addr = server_socket.accept() thread = threading.Thread(target=show_client, args=(addr,client_socket)) thread.start() print("TOTAL CLIENTS ",threading.activeCount() - 1) ``` --- **Connectez la caméra Android à Python en utilisant OpenCV**tutoriel très court sur la façon de connecter la caméra de votre téléphone Android à OpenCV. Cela peut être très utile pour ceux qui envisagent de créer des applications de traitement d'image qui utiliseront une caméra Android comme support. J'utiliserai Python 3.6 sur une machine Ubuntu 18.04, mais ne vous inquiétez pas, mes amis utilisateurs de Windows, le processus sera également le même.|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||installez l'application IP Webcam sur vos téléphones mobiles. Cela sera utilisé pour établir une communication entre votre téléphone Android et votre PC.Après avoir installé l'application, assurez-vous que votre téléphone et votre PC sont connectés au même réseau. Exécutez l'application sur votre téléphone et cliquez sur Démarrer le serveur.Astuce: faites défiler vers le bas, c'est tout en bas.  Après cela, votre caméra s'ouvrira avec une adresse IP en bas.  Prenez note de ces URL car nous les utiliserons plus tard.Commençons à coder! ```import urllib.requestimport cv2import numpy as npimport timeURL = "http://192.168.43.1:8080"while True: img_arr = np.array(bytearray(urllib.request.urlopen(URL).read()),dtype=np.uint8) img = cv2.imdecode(img_arr,-1) cv2.imshow('IPWebcam',img) if cv2.waitKey(1): break``` Bien sûr, utilisez l'URL affichée dans l'interface de votre webcam IP, remplacez-la puis exécutez le code. Dans quelques instants, une fenêtre de CV apparaîtra et fera de la magie. Pour fermer la fenêtre, appuyez simplement sur n'importe quelle touche.C'est essentiellement comment connecter les téléphones Android à votre application Python. Les prochaines étapes seront pour vous. Cela peut impliquer une classification d'image en temps réel, une segmentation d'image, une détection d'objet ou une reconnaissance de visage, les possibilités sont presque illimitées. ------ **Reconnaisance Facial** :pour les utilisateur de windows l'installation de la lib Dlib est souvent une galère. a force de recherche et de teste j'ai trouver une solution dans le Bile des codeurs perdu Stackoverflow.la commande a rentré dans cotre terminal est la suivante :```pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whlmd5=b7330a5b2d46420343fbed5df69e6a3f```Créé un dossier "known_faces" qui sont les visages que vous connaissez , faire un dossier pour chaque personne que vous connaissé ou que vous savez l'identité.Créé un dossier unknown_faces, qui contiendra et archivera les visages non connue ```import face_recognitionimport osimport cv2KNOWN_FACES_DIR = 'known_faces'UNKNOWN_FACES_DIR = 'unknown_faces'TOLERANCE = 0.6FRAME_THICKNESS = 3FONT_THICKNESS = 2MODEL = 'cnn' default: 'hog', other one can be 'cnn' - CUDA accelerated (if available) deep-learning pretrained modelvideo = cv2.VideoCapture(0)def name_to_color(name): color = [(ord(c.lower())-97)*8 for c in name[:3]] return colorprint('Loading known faces...')known_faces = []known_names = []for name in os.listdir(KNOWN_FACES_DIR): for filename in os.listdir(f'{KNOWN_FACES_DIR}/{name}'): image = face_recognition.load_image_file(f'{KNOWN_FACES_DIR}/{name}/{filename}') encoding = face_recognition.face_encodings(image)[0] known_faces.append(encoding) known_names.append(name)print('Processing unknown faces...')while True: print(filename) ret, image = video.read() locations = face_recognition.face_locations(image, model=MODEL) encodings = face_recognition.face_encodings(image,) for face_encoding, face_location in zip(encodings, locations): results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE) match = None if True in results: match = known_names[results.index(True)] print(f' - {match} from {results}') print(f'Match Found : {match}') top_left = (face_location[3], face_location[0]) bottom_right = (face_location[1], face_location[2]) color = name_to_color(match) cv2.rectangle(image, top_left, bottom_right, color, FRAME_THICKNESS) top_left = (face_location[3], face_location[2]) bottom_right = (face_location[1], face_location[2] + 22) cv2.rectangle(image, top_left, bottom_right, color, cv2.FILLED) cv2.putText(image, match, (face_location[3] + 10, face_location[2] + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), FONT_THICKNESS) Show image cv2.imshow(filename, image) if cv2.waitKey(1) & 0xFF == ord("q"): break cv2.destroyWindow(filename)``` | _____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 curve) even if the original variables themselves are not normally distributed.This theorem is useful for two reasons:1. It offers an explanation for the ubiquity of normal distributions in the natural and engineered world. If you measure something that depends on the sum of many independent factors, the distribution of the measurements will often be approximately normal.2. In the context of mathematical statistics it provides a way to approximate the sampling distribution of many statistics, at least, as Wikipedia warns us, "in some situations".In this notebook, we'll explore those situations. Rolling diceI'll start by adding up the totals for 1, 2, and 3 dice.The following function simulates rolling a six-sided die. | 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 given mean. | 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(sample), np.max(sample))
ys = norm.cdf(xs, mean, std)
plt.plot(xs, ys, alpha=0.4, **options) | _____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=f'num = {num}')
plt.xlabel('Total')
plt.ylabel('CDF')
plt.legend() | _____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 be large, very large, or infinite.Here's a function that generates the sum of values from a Pareto distribution with a given parameter. | 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_grid1 import make_axes_locatable
import tensorflow as tf
from sciann import Functional, Variable, SciModel
from sciann.utils import *
import scipy.io
import time
import random
tf.config.threading.set_intra_op_parallelism_threads(1)
tf.config.threading.set_inter_op_parallelism_threads(1)
np.random.seed(123)
tf.random.set_seed(123)
#Model specifications
v0 = 2.; # Velocity at the origin of the model
vergrad = 1.; # Vertical gradient
horgrad = 0.5; # Horizontal gradient
zmin = 0.; zmax = 2.; deltaz = 0.02;
xmin = 0.; xmax = 2.; deltax = 0.02;
# Point-source location
sz = 0.3; sx = 1.4;
# Number of training points
num_tr_pts = 2000
# Creating grid, calculating refrence traveltimes, and prepare list of grid points for training (X_star)
z = np.arange(zmin,zmax+deltaz,deltaz)
nz = z.size
x = np.arange(xmin,xmax+deltax,deltax)
nx = x.size
Z,X = np.meshgrid(z,x,indexing='ij')
# Preparing velocity model
vs = v0 + vergrad*sz + horgrad*sx # Velocity at the source location
velmodel = vs + vergrad*(Z-sz) + horgrad*(X-sx);
# Traveltime solution
if vergrad==0 and horgrad==0:
# For homogeneous velocity model
T_data = np.sqrt((Z-sz)**2 + (X-sx)**2)/v0;
else:
# For velocity gradient model
T_data = np.arccosh(1.0+0.5*(1.0/velmodel)*(1/vs)*(vergrad**2 + horgrad**2)*((X-sx)**2 + (Z-sz)**2))/np.sqrt(vergrad**2 + horgrad**2)
X_star = [Z.reshape(-1,1), X.reshape(-1,1)] # Grid points for prediction
selected_pts = np.random.choice(np.arange(Z.size),num_tr_pts,replace=False)
Zf = Z.reshape(-1,1)[selected_pts]
Zf = np.append(Zf,sz)
Xf = X.reshape(-1,1)[selected_pts]
Xf = np.append(Xf,sx)
X_starf = [Zf.reshape(-1,1), Xf.reshape(-1,1)] # Grid points for training
# Plot the velocity model with the source location
plt.style.use('default')
plt.figure(figsize=(4,4))
ax = plt.gca()
im = ax.imshow(velmodel, extent=[xmin,xmax,zmax,zmin], aspect=1, cmap="jet")
ax.plot(sx,sz,'k*',markersize=8)
plt.xlabel('Offset (km)', fontsize=14)
plt.xticks(fontsize=10)
plt.ylabel('Depth (km)', fontsize=14)
plt.yticks(fontsize=10)
ax.xaxis.set_major_locator(plt.MultipleLocator(0.5))
ax.yaxis.set_major_locator(plt.MultipleLocator(0.5))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="6%", pad=0.15)
cbar = plt.colorbar(im, cax=cax)
cbar.set_label('km/s',size=10)
cbar.ax.tick_params(labelsize=10)
plt.savefig("./figs/vofz_transfer/velmodel.pdf", format='pdf', bbox_inches="tight")
# Analytical solution for the known traveltime part
vel = velmodel[int(round(sz/deltaz)),int(round(sx/deltax))] # Velocity at the source location
T0 = np.sqrt((Z-sz)**2 + (X-sx)**2)/vel;
px0 = np.divide(X-sx, T0*vel**2, out=np.zeros_like(T0), where=T0!=0)
pz0 = np.divide(Z-sz, T0*vel**2, out=np.zeros_like(T0), where=T0!=0)
# Find source location id in X_star
TOLX = 1e-6
TOLZ = 1e-6
sids,_ = np.where(np.logical_and(np.abs(X_starf[0]-sz)<TOLZ , np.abs(X_starf[1]-sx)<TOLX))
print(sids)
print(sids.shape)
print(X_starf[0][sids,0])
print(X_starf[1][sids,0])
# Preparing the Sciann model object
K.clear_session()
layers = [20]*10
# Appending source values
velmodelf = velmodel.reshape(-1,1)[selected_pts]; velmodelf = np.append(velmodelf,vs)
px0f = px0.reshape(-1,1)[selected_pts]; px0f = np.append(px0f,0.)
pz0f = pz0.reshape(-1,1)[selected_pts]; pz0f = np.append(pz0f,0.)
T0f = T0.reshape(-1,1)[selected_pts]; T0f = np.append(T0f,0.)
xt = Variable("xt",dtype='float64')
zt = Variable("zt",dtype='float64')
vt = Variable("vt",dtype='float64')
px0t = Variable("px0t",dtype='float64')
pz0t = Variable("pz0t",dtype='float64')
T0t = Variable("T0t",dtype='float64')
tau = Functional("tau", [zt, xt], layers, 'atan')
# Loss function based on the factored isotropic eikonal equation
L = (T0t*diff(tau, xt) + tau*px0t)**2 + (T0t*diff(tau, zt) + tau*pz0t)**2 - 1.0/vt**2
targets = [tau, L, (1-sign(tau*T0t))*abs(tau*T0t)]
target_vals = [(sids, np.ones(sids.shape).reshape(-1,1)), 'zeros', 'zeros']
model = SciModel(
[zt, xt, vt, pz0t, px0t, T0t],
targets,
load_weights_from='models/vofz_model-end.hdf5'
)
#Model training
start_time = time.time()
hist = model.train(
X_starf + [velmodelf,pz0f,px0f,T0f],
target_vals,
batch_size = X_starf[0].size,
epochs = 5000,
learning_rate = 0.0005,
verbose=0
)
elapsed = time.time() - start_time
print('Training time: %.2f minutes' %(elapsed/60.))
# Loading loss history and compute time for the pre-trained model
loss = np.load('models/loss_vofz.npy')
time_vofz = np.load('models/time_vofz.npy')
# Convergence history plot for verification
fig = plt.figure(figsize=(5,3))
ax = plt.axes()
ax.semilogy(loss,LineWidth=2,label='Random initial model')
ax.semilogy(hist.history['loss'],LineWidth=2,label='Pre-trained initial model')
ax.set_xlabel('Epochs',fontsize=14)
plt.xticks(fontsize=10)
ax.xaxis.set_major_locator(plt.MultipleLocator(5000))
ax.set_ylabel('Loss',fontsize=14)
plt.yticks(fontsize=10);
plt.grid()
plt.legend()
ax2 = ax.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(-time_vofz*.05, time_vofz*1.05)
ax2.set_xlabel('Time (s)',fontsize=14)
plt.savefig("./figs/vofz_transfer/loss.pdf", format='pdf', bbox_inches="tight")
# Predicting traveltime solution from the trained model
L_pred = L.eval(model, X_star + [velmodel,pz0,px0,T0])
tau_pred = tau.eval(model, X_star + [velmodel,pz0,px0,T0])
tau_pred = tau_pred.reshape(Z.shape)
T_pred = tau_pred*T0
print('Time at source: %.4f'%(tau_pred[int(round(sz/deltaz)),int(round(sx/deltax))]))
# Plot the PINN solution error
plt.style.use('default')
plt.figure(figsize=(4,4))
ax = plt.gca()
im = ax.imshow(np.abs(T_pred-T_data), extent=[xmin,xmax,zmax,zmin], aspect=1, cmap="jet")
plt.xlabel('Offset (km)', fontsize=14)
plt.xticks(fontsize=10)
plt.ylabel('Depth (km)', fontsize=14)
plt.yticks(fontsize=10)
ax.xaxis.set_major_locator(plt.MultipleLocator(0.5))
ax.yaxis.set_major_locator(plt.MultipleLocator(0.5))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="6%", pad=0.15)
cbar = plt.colorbar(im, cax=cax)
cbar.set_label('seconds',size=10)
cbar.ax.tick_params(labelsize=10)
plt.savefig("./figs/vofz_transfer/pinnerror.pdf", format='pdf', bbox_inches="tight")
# Loading fast marching solutions
# First order FMM solution
time_fmm1="data/fmm_or1_vofz_s(1.4,.3).txt"
T_fmm1 = pd.read_csv(time_fmm1, index_col=None, header=None)
T_fmm1 = np.reshape(np.array(T_fmm1), (nx, nz)).T
# Plot the first order FMM solution error
plt.style.use('default')
plt.figure(figsize=(4,4))
ax = plt.gca()
im = ax.imshow(np.abs(T_fmm1-T_data), extent=[xmin,xmax,zmax,zmin], aspect=1, cmap="jet")
plt.xlabel('Offset (km)', fontsize=14)
plt.xticks(fontsize=10)
plt.ylabel('Depth (km)', fontsize=14)
plt.yticks(fontsize=10)
ax.xaxis.set_major_locator(plt.MultipleLocator(0.5))
ax.yaxis.set_major_locator(plt.MultipleLocator(0.5))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="6%", pad=0.15)
cbar = plt.colorbar(im, cax=cax)
cbar.set_label('seconds',size=10)
cbar.ax.tick_params(labelsize=10)
plt.savefig("./figs/vofz_transfer/fmm1error.pdf", format='pdf', bbox_inches="tight")
# Traveltime contour plots
plt.figure(figsize=(5,5))
ax = plt.gca()
im1 = ax.contour(T_data, 6, extent=[xmin,xmax,zmin,zmax], colors='r')
im2 = ax.contour(T_pred, 6, extent=[xmin,xmax,zmin,zmax], colors='k',linestyles = 'dashed')
im3 = ax.contour(T_fmm1, 6, extent=[xmin,xmax,zmin,zmax], colors='b',linestyles = 'dotted')
ax.plot(sx,sz,'k*',markersize=8)
plt.xlabel('Offset (km)', fontsize=14)
plt.ylabel('Depth (km)', fontsize=14)
ax.tick_params(axis='both', which='major', labelsize=8)
plt.gca().invert_yaxis()
h1,_ = im1.legend_elements()
h2,_ = im2.legend_elements()
h3,_ = im3.legend_elements()
ax.legend([h1[0], h2[0], h3[0]], ['Analytical', 'PINN', 'Fast marching'],fontsize=12)
ax.xaxis.set_major_locator(plt.MultipleLocator(0.5))
ax.yaxis.set_major_locator(plt.MultipleLocator(0.5))
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
plt.savefig("./figs/vofz_transfer/contours.pdf", format='pdf', bbox_inches="tight")
print(np.linalg.norm(T_pred-T_data)/np.linalg.norm(T_data))
print(np.linalg.norm(T_pred-T_data))
!nvidia-smi -L | 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 system
ATSdriver.AlazarTech_ATS.find_boards()
# Create the ATS9870 instrument on the new server "alazar_server"
ats_inst = ATSdriver.AlazarTech_ATS9360(name='Alazar1')
# Print all information about this Alazar card
ats_inst.get_idn()
# Instantiate an acquisition controller (In this case we are doing a simple DFT) on the same server ("alazar_server") and
# provide the name of the name of the alazar card that this controller should control
acquisition_controller = ats_contr.Demodulation_AcquisitionController(name='acquisition_controller',
demodulation_frequency=10e6,
alazar_name='Alazar1')
# Configure all settings in the Alazar card
ats_inst.config(clock_source='INTERNAL_CLOCK',
sample_rate=1_000_000_000,
clock_edge='CLOCK_EDGE_RISING',
decimation=1,
coupling=['DC','DC'],
channel_range=[.4,.4],
impedance=[50,50],
trigger_operation='TRIG_ENGINE_OP_J',
trigger_engine1='TRIG_ENGINE_J',
trigger_source1='EXTERNAL',
trigger_slope1='TRIG_SLOPE_POSITIVE',
trigger_level1=160,
trigger_engine2='TRIG_ENGINE_K',
trigger_source2='DISABLE',
trigger_slope2='TRIG_SLOPE_POSITIVE',
trigger_level2=128,
external_trigger_coupling='DC',
external_trigger_range='ETR_2V5',
trigger_delay=0,
timeout_ticks=0,
aux_io_mode='AUX_IN_AUXILIARY', # AUX_IN_TRIGGER_ENABLE for seq mode on
aux_io_param='NONE' # TRIG_SLOPE_POSITIVE for seq mode on
)
# This command is specific to this acquisition controller. The kwargs provided here are being forwarded to ats_inst.acquire
# This way, it becomes easy to change acquisition specific settings from the ipython notebook
acquisition_controller.update_acquisitionkwargs(#mode='NPT',
samples_per_record=1024,
records_per_buffer=70,
buffers_per_acquisition=1,
#channel_selection='AB',
#transfer_offset=0,
#external_startcapture='ENABLED',
#enable_record_headers='DISABLED',
#alloc_buffers='DISABLED',
#fifo_only_streaming='DISABLED',
#interleave_samples='DISABLED',
#get_processed_data='DISABLED',
allocated_buffers=1,
#buffer_timeout=1000
)
# Getting the value of the parameter 'acquisition' of the instrument 'acquisition_controller' performes the entire acquisition
# protocol. This again depends on the specific implementation of the acquisition controller
acquisition_controller.acquisition()
# make a snapshot of the 'ats_inst' instrument
ats_inst.snapshot()
# Finally show that this instrument also works within a loop
dummy = parameter.ManualParameter(name="dummy")
data = qc.Loop(dummy[0:50:1]).each(acquisition_controller.acquisition).run(name='AlazarTest')
qc.MatPlot(data.acquisition_controller_acquisition) | 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,)
Finished at 2017-11-09 18:08:08
| 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 Entries Error Checking & Warnings* Ideally correct errors here and write out corrected csv to file with a note* TODO - log errors found and include error-checking code as part of pre-processing flow Errors to Watch ForPlease document as not found and/or what corrected, so can trace back to original. Update as needed and mirror in final docs submitted with project.* "Computing" (or "Computing Studies" or "Computing (New)") ... included in list of subjects * need to decide if files will be excluded or included with a flag to track changes in subjects offered* Each subject and grade listed only once per gender* proportions of male/female add up to 1Warning Only NeededNeed only document if triggered.* All values for a subject set to "-" or 0 (rare) -> translates to NAs if read in properly | # 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... :(
filter(rowSums(is.na(.)) != ncol(.)) %>%
suppressMessages
print(awardFile)
if (!exists("focus_subject") || is_null(focus_subject) || (str_trim(focus_subject) == "")) {
focus_subject <- "computing"
print(paste("No focus subject specified; defaulting to subjects containing: ", focus_subject))
} else
print(paste("Search on focus subject (containing term) '", focus_subject, "'", sep = ""))
if (glimpseContent)
print(glimpse(awardData))
result <- awardData %>%
select(Subject) %>%
filter(str_detect(Subject, regex(focus_subject, ignore_case = TRUE))) %>%
verify(nrow(.) > 0, error_fun = just_warn)
if (!listSubjects)
return(nrow(result)) # comment out this row to list subject names
else
return(result)
}
# check for data stored as percentages only
checkDataAsPercentageOnly <-
function(awardFile, glimpseContent = FALSE) {
awardData <- read_csv(awardFile, trim_ws = TRUE) %>% #, skip_empty_rows = T) # NOT skipping empty rows... :(
filter(rowSums(is.na(.)) != ncol(.)) %>%
suppressMessages
print(awardFile)
if (glimpseContent)
print(glimpse(awardData))
if (!exists("redundant_column_flags") || is.null(redundant_column_flags))
redundant_column_flags <- c("-percentage*", "-COMP", "-PassesUngradedCourses")
awardData %>%
select(-matches(c(redundant_column_flags, "all-Entries"))) %>% # "-percentage")) %>%
select(matches(c("male-", "female-", "all-"))) %>%
verify(ncol(.) > 0, error_fun = just_warn) %>%
#head(0) - comment in and next line out to list headers remaining
summarise(data_as_counts = (ncol(.) > 0))
}
# error checking - need to manually correct data if mismatch between breakdown by gender and totals found
# this case, if found, is relatively easy to fix
#TODO -include NotKnown and NA
checkDistributionByGenderErrors <-
function(awardFile, glimpseContent = FALSE) {
awardData <- read_csv(awardFile, trim_ws = TRUE) %>% #, skip_empty_rows = T) # NOT skipping empty rows... :(
filter(rowSums(is.na(.)) != ncol(.)) %>%
suppressMessages
print(awardFile)
if (glimpseContent)
print(glimpse(awardData))
if (awardData %>%
select(matches(gender_options)) %>%
verify(ncol(.) > 0, error_fun = just_warn) %>%
summarise(data_as_counts = (ncol(.) == 0)) == TRUE) {
awardData <- awardData %>%
select(-NumberOfCentres) %>%
pivot_longer(!c(Subject), names_to = "grade", values_to = "PercentageOfStudents") %>%
separate("grade", c("gender", "grade"), extra = "merge") %>%
mutate_at(c("gender", "grade"), as.factor) %>%
filter((gender %in% c("all")) & (grade %in% c("Entries")))
# building parallel structure
return(awardData %>%
group_by(Subject) %>%
mutate(total = -1) %>%
summarise(total = sum(total)) %>%
mutate(DataError = TRUE) # confirmation only - comment out to print al
)
}
awardData <- awardData %>%
mutate_at(vars(starts_with("male-") | starts_with("female-") | starts_with("all-")), as.character) %>%
mutate_at(vars(starts_with("male-") | starts_with("female-") | starts_with("all-")), parse_number) %>%
suppressWarnings
data_as_counts <- awardData %>%
select(-matches(redundant_column_flags)) %>% # "-percentage")) %>%
select(matches(c("male-", "female-"))) %>%
summarise(data_as_counts = (ncol(.) > 0)) %>%
as.logical
if (data_as_counts) {
awardData <- awardData %>%
select(-NumberOfCentres) %>%
mutate_at(vars(starts_with("male")), ~(. / `all-Entries`)) %>%
mutate_at(vars(starts_with("female")), ~(. / `all-Entries`)) %>%
select(-(starts_with("all") & !ends_with("-Entries"))) %>%
pivot_longer(!c(Subject), names_to = "grade", values_to = "PercentageOfStudents") %>%
separate("grade", c("gender", "grade"), extra = "merge") %>%
mutate_at(c("gender", "grade"), as.factor) %>%
filter(!(gender %in% c("all")) & (grade %in% c("Entries")))
} else { # dataAsPercentageOnly
awardData <- awardData %>%
select(Subject, ends_with("-percentage")) %>%
mutate_at(vars(ends_with("-percentage")), ~(. / 100)) %>%
pivot_longer(!c(Subject), names_to = "grade", values_to = "PercentageOfStudents") %>%
separate("grade", c("gender", "grade"), extra = "merge") %>%
mutate_at(c("gender", "grade"), as.factor)
} # end if-else - check for data capture approach
awardData %>%
group_by(Subject) %>%
summarise(total = sum(PercentageOfStudents, na.rm = TRUE)) %>%
verify((total == 1.0) | (total == 0), error_fun = just_warn) %>%
mutate(DataError = if_else(((total == 1.0) | (total == 0)), FALSE, TRUE)) %>%
filter(DataError == TRUE) %>% # confirmation only - comment out to print all
suppressMessages # ungrouping messages
}
# warning only - document if necessary
# double-check for subjects with values all NA - does this mean subject being excluded or no one took it?
checkSubjectsWithNoEntries <-
function(awardFile, glimpseContent = FALSE) {
awardData <- read_csv(awardFile, trim_ws = TRUE) %>% #, skip_empty_rows = T) # NOT skipping empty rows... :(
filter(rowSums(is.na(.)) != ncol(.)) %>%
suppressMessages
print(awardFile)
if (glimpseContent)
print(glimpse(awardData))
bind_cols(
awardData %>%
mutate(row_id = row_number()) %>%
select(row_id, Subject),
awardData %>%
select(-c(Subject, NumberOfCentres)) %>%
mutate_at(vars(starts_with("male-") | starts_with("female-") | starts_with("all-")), as.character) %>%
mutate_at(vars(starts_with("male-") | starts_with("female-") | starts_with("all-")), parse_number) %>%
suppressWarnings %>%
assert_rows(num_row_NAs,
within_bounds(0, length(colnames(.)), include.upper = F), everything(), error_fun = just_warn) %>%
# comment out just_warn to stop execution on fail
summarise(column_count = length(colnames(.)),
count_no_entries = num_row_NAs(.))
) %>% # end bind_cols
filter(count_no_entries == column_count) # comment out to print all
}
## call using any of the options below
## where files_to_verify is a vector containing (paths to) files to check
### checkFocusSubjectListed
#lapply(files_to_verify, checkFocusSubjectListed, listSubjects = TRUE)
#Map(checkFocusSubjectListed, files_to_verify, listSubjects = TRUE)
#as.data.frame(sapply(files_to_verify, checkFocusSubjectListed)) # call without as.data.frame if listing values
### checkDataAsPercentageOnly
#sapply(files_to_verify, checkDataAsPercentageOnly)
#Map(checkDataAsPercentageOnly, files_to_verify) #, T)
### checkDistributionByGenderErrors
#data.frame(sapply(files_to_verify, checkDistributionByGenderErrors))
### checkSubjectsWithNoEntries
#data.frame(sapply(files_to_verify, checkSubjectsWithNoEntries)) | _____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.Playing a crucial role in various modern AI applications,sequence transduction models will form the focus of the remainder of this chapterand :numref:`chap_attention`.To this end,this section introduces the machine translation problemand its dataset that will be used later.*Machine translation* refers to theautomatic translation of a sequencefrom one language to another.In fact, this fieldmay date back to 1940ssoon after digital computers were invented,especially by considering the use of computersfor cracking language codes in World War II.For decades,statistical approacheshad been dominant in this field :cite:`Brown.Cocke.Della-Pietra.ea.1988,Brown.Cocke.Della-Pietra.ea.1990`before the riseofend-to-end learning usingneural networks.The latteris often called*neural machine translation*to distinguish itself from*statistical machine translation*that involves statistical analysisin components such asthe translation model and the language model.Emphasizing end-to-end learning,this book will focus on neural machine translation methods.Different from our language model problemin :numref:`sec_language_model`whose corpus is in one single language,machine translation datasetsare composed of pairs of text sequencesthat are inthe source language and the target language, respectively.Thus,instead of reusing the preprocessing routinefor language modeling,we need a different way to preprocessmachine translation datasets.In the following,we show how toload the preprocessed datainto minibatches for training. | 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 that each text sequencecan be just one sentence or a paragraph of multiple sentences.In this machine translation problemwhere English is translated into French,English is the *source language*and French is the *target language*. | #@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:
return f.read()
raw_text = read_data_nmt()
print(raw_text[:75]) | 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('\xa0', ' ').lower()
# Insert space between words and punctuation marks
out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
for i, char in enumerate(text)]
return ''.join(out)
text = preprocess_nmt(raw_text)
print(text[:80]) | 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 pairs,whereeach token is either a word or a punctuation mark.This function returnstwo lists of token lists: `source` and `target`.Specifically,`source[i]` is a list of tokens from the$i^\mathrm{th}$ text sequence in the source language (English here) and `target[i]` is that in the target language (French here). | #@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.append(parts[0].split(' '))
target.append(parts[1].split(' '))
return source, target
source, target = tokenize_nmt(text)
source[:6], target[:6] | _____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[1].patches:
patch.set_hatch('/')
d2l.plt.legend(legend)
show_list_len_pair_hist(['source', 'target'], '# tokens per sequence',
'count', source, target); | _____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,here we treat infrequent tokensthat appear less than 2 timesas the same unknown ("<unk>") token.Besides that,we specify additional special tokenssuch as for padding ("<pad>") sequences to the same length in minibatches,and for marking the beginning ("<bos>") or end ("<eos>") of sequences.Such special tokens are commonly used innatural language processing tasks. | 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 machine translation, each example isa pair of source and target text sequences,where each text sequence may have different lengths.For computational efficiency,we can still process a minibatch of text sequencesat one time by *truncation* and *padding*.Suppose that every sequence in the same minibatchshould have the same length `num_steps`.If a text sequence has fewer than `num_steps` tokens,we will keep appending the special "<pad>" tokento its end until its length reaches `num_steps`.Otherwise,we will truncate the text sequenceby only taking its first `num_steps` tokensand discarding the remaining.In this way,every text sequencewill have the same lengthto be loaded in minibatches of the same shape.The following `truncate_pad` function(**truncates or pads text sequences**) as described before. | #@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 output sequence is complete.Besides,we also record the lengthof each text sequence excluding the padding tokens.This information will be needed bysome models thatwe will cover later. | #@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])
valid_len = (array != vocab['<pad>']).type(torch.int32).sum(1)
return array, valid_len | _____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,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
tgt_vocab = d2l.Vocab(target, min_freq=2,
reserved_tokens=['<pad>', '<bos>', '<eos>'])
src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
data_iter = d2l.load_array(data_arrays, batch_size)
return data_iter, src_vocab, tgt_vocab | _____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 - thus ensuring digital preservation of oceanographic datasets within IOOS and its regional associations. NOAA NCEI supports reading from a Web Accessible Folder (WAF) containing bagit archives. For an example please see: http://ncei.axiomdatascience.com/cencoos/On this notebook we will use the [python interface](http://libraryofcongress.github.io/bagit-python) for `BagIt` to create a "bag" of a time-series profile data. First let us load our data from a comma separated values file (`CSV`). | 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
dimensions(sizes): station(1), time(100), depth(4)
variables(dimensions): <class 'str'> [4mstation[0m(station), float64 [4mlat[0m(station), float64 [4mlon[0m(station), int32 [4mcrs[0m(), float64 [4mtime[0m(time), int32 [4mdepth[0m(depth), int32 [4mindex[0m(time,depth,station), float64 [4mhumidity[0m(time,depth,station), float64 [4mtemperature[0m(time,depth,station)
groups:
| 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@axiomdatascience.com',
'External-Identifier': urn,
'External-Description':
'Sensor data from station {}'.format(urn),
'Internal-Sender-Identifier': urn,
'Internal-Sender-Description':
'Station - URN:{}'.format(urn),
'Organization-address':
'1016 W 6th Ave, Ste. 105, Anchorage, AK 99501, USA',
'Source-Organization': 'Axiom Data Science',
}
bag.info.update(bag_meta)
bag.save(manifests=True, processes=4) | _____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/parameter1.nc
63d47afc3b8b227aac251a234ecbb9cfc6cc01d1dd1aa34c65969fdabf0740f1 data/parameter2.nc
63d47afc3b8b227aac251a234ecbb9cfc6cc01d1dd1aa34c65969fdabf0740f1 data/parameter3.nc
63d47afc3b8b227aac251a234ecbb9cfc6cc01d1dd1aa34c65969fdabf0740f1 data/parameter4.nc
| 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 1900 fruits. The results are summarized inthe following table.Length Sweetness ColourClass Short Medium Long Sweet Not Sweet Red Yellow Green TotalBanana 0 100 500 500 100 0 600 0 600Papaya 50 200 50 250 50 0 150 150 300Apple 900 100 0 800 200 600 100 300 1000Total 950 400 550 1550 350 600 850 450 1900 | %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 - mu2), 2) / (2 * np.power(sigma, 2))))) # P(x|w2)
plt.plot(x, y1)
plt.plot(x, y2, color='Orange')
plt.axvline(x=0.1534, 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*y2
l2 = y1
plt.plot(x, l1, color='Orange')
plt.plot(x, l2)
plt.axvline(x=0.1534, color='r', linestyle='--', ymin=0.05, ymax = 0.98)
plt.legend(('$l_1$', '$l_2$', 'Threshold'), loc=1) | _____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')
plt.plot(x, l2)
plt.axvline(x=0.7798, color='r', linestyle='--', ymin=0.05, ymax = 0.98)
plt.legend(('$l_1$', '$l_2$', 'Threshold'), loc=1) | _____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')
plt.plot(x, l2)
plt.axvline(x=0.7798, color='r', linestyle='--', ymin=0.05, ymax = 0.98)
plt.legend(('$l_1$', '$l_2$', 'Threshold'), loc=1) | _____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. Tagging is difficult because some words can represent more than one part of speech at different times. They are **Ambiguous**. Let's look at the following example: - The whole team played **well**. [adverb]- You are doing **well** for yourself. [adjective]- **Well**, this assignment took me forever to complete. [interjection]- The **well** is dry. [noun]- Tears were beginning to **well** in her eyes. [verb]Distinguishing the parts-of-speech of a word in a sentence will help you better understand the meaning of a sentence. This would be critically important in search queries. Identifying the proper noun, the organization, the stock symbol, or anything similar would greatly improve everything ranging from speech recognition to search. By completing this assignment, you will: - Learn how parts-of-speech tagging works- Compute the transition matrix A in a Hidden Markov Model- Compute the transition matrix B in a Hidden Markov Model- Compute the Viterbi algorithm - Compute the accuracy of your own model Outline- [0 Data Sources](0)- [1 POS Tagging](1) - [1.1 Training](1.1) - [Exercise 01](ex-01) - [1.2 Testing](1.2) - [Exercise 02](ex-02)- [2 Hidden Markov Models](2) - [2.1 Generating Matrices](2.1) - [Exercise 03](ex-03) - [Exercise 04](ex-04)- [3 Viterbi Algorithm](3) - [3.1 Initialization](3.1) - [Exercise 05](ex-05) - [3.2 Viterbi Forward](3.2) - [Exercise 06](ex-06) - [3.3 Viterbi Backward](3.3) - [Exercise 07](ex-07)- [4 Predicting on a data set](4) - [Exercise 08](ex-08) | # 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 letter tag and their meaning. - One data set (**WSJ-2_21.pos**) will be used for **training**.- The other (**WSJ-24.pos**) for **testing**. - The tagged training data has been preprocessed to form a vocabulary (**hmm_vocab.txt**). - The words in the vocabulary are words from the training set that were used two or more times. - The vocabulary is augmented with a set of 'unknown word tokens', described below. The training set will be used to create the emission, transmission and tag counts. The test set (WSJ-24.pos) is read in to create `y`. - This contains both the test text and the true tag. - The test set has also been preprocessed to remove the tags to form **test_words.txt**. - This is read in and further processed to identify the end of sentences and handle words not in the vocabulary using functions provided in **utils_pos.py**. - This forms the list `prep`, the preprocessed text used to test our POS taggers.A POS tagger will necessarily encounter words that are not in its datasets. - To improve accuracy, these words are further analyzed during preprocessing to extract available hints as to their appropriate tag. - For example, the suffix 'ize' is a hint that the word is a verb, as in 'final-ize' or 'character-ize'. - A set of unknown-tokens, such as '--unk-verb--' or '--unk-noun--' will replace the unknown words in both the training and test corpus and will appear in the emission, transmission and tag data structures. Implementation note: - For python 3.6 and beyond, dictionaries retain the insertion order. - Furthermore, their hash-based lookup makes them suitable for rapid membership tests. - If _di_ is a dictionary, `key in di` will return `True` if _di_ has a key _key_, else `False`. The dictionary `vocab` will utilize these features. | # 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().split('\n')
print("A few items of the vocabulary list")
print(voc_l[0:50])
print()
print("A few items at the end of the vocabulary list")
print(voc_l[-50:])
# vocab: dictionary that has the index of the corresponding words
vocab = {}
# Get the index of the corresponding words.
for i, word in enumerate(sorted(voc_l)):
vocab[word] = i
print("Vocabulary dictionary, key is the word, value is a unique integer")
cnt = 0
for k,v in vocab.items():
print(f"{k}:{v}")
cnt += 1
if cnt > 20:
break
# load in the test corpus
with open("WSJ_24.pos", 'r') as f:
y = f.readlines()
print("A sample of the test corpus")
print(y[0:10])
#corpus without tags, preprocessed
_, prep = preprocess(vocab, "test.words")
print('The length of the preprocessed test corpus: ', len(prep))
print('This is a sample of the test_corpus: ')
print(prep[0:10]) | 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$% of the token are unambiguous (meaning they have only one tag) - About $14\%$ are ambiguous (meaning that they have more than one tag)Before you start predicting the tags of each word, you will need to compute a few dictionaries that will help you to generate the tables. Transition counts- The first dictionary is the `transition_counts` dictionary which computes the number of times each tag happened next to another tag. This dictionary will be used to compute: $$P(t_i |t_{i-1}) \tag{1}$$This is the probability of a tag at position $i$ given the tag at position $i-1$.In order for you to compute equation 1, you will create a `transition_counts` dictionary where - The keys are `(prev_tag, tag)`- The values are the number of times those two tags appeared in that order. Emission countsThe second dictionary you will compute is the `emission_counts` dictionary. This dictionary will be used to compute:$$P(w_i|t_i)\tag{2}$$In other words, you will use it to compute the probability of a word given its tag. In order for you to compute equation 2, you will create an `emission_counts` dictionary where - The keys are `(tag, word)` - The values are the number of times that pair showed up in your training set. Tag countsThe last dictionary you will compute is the `tag_counts` dictionary. - The key is the tag - The value is the number of times each tag appeared. Exercise 01**Instructions:** Write a program that takes in the `training_corpus` and returns the three dictionaries mentioned above `transition_counts`, `emission_counts`, and `tag_counts`. - `emission_counts`: maps (tag, word) to the number of times it happened. - `transition_counts`: maps (prev_tag, tag) to the number of times it has appeared. - `tag_counts`: maps (tag) to the number of times it has occured. Implementation note: This routine utilises *defaultdict*, which is a subclass of *dict*. - A standard Python dictionary throws a *KeyError* if you try to access an item with a key that is not currently in the dictionary. - In contrast, the *defaultdict* will create an item of the type of the argument, in this case an integer with the default value of 0. - See [defaultdict](https://docs.python.org/3.3/library/collections.htmldefaultdict-objects). | # 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 index
Output:
emission_counts: a dictionary where the keys are (tag, word) and the values are the counts
transition_counts: a dictionary where the keys are (prev_tag, tag) and the values are the counts
tag_counts: a dictionary where the keys are the tags and the values are the counts
"""
# initialize the dictionaries using defaultdict
emission_counts = defaultdict(int)
transition_counts = defaultdict(int)
tag_counts = defaultdict(int)
# Initialize "prev_tag" (previous tag) with the start state, denoted by '--s--'
prev_tag = '--s--'
# use 'i' to track the line number in the corpus
i = 0
# Each item in the training corpus contains a word and its POS tag
# Go through each word and its tag in the training corpus
for word_tag in training_corpus:
# Increment the word_tag count
i += 1
# Every 50,000 words, print the word count
if i % 50000 == 0:
print(f"word count = {i}")
### START CODE HERE (Replace instances of 'None' with your code) ###
# get the word and tag using the get_word_tag helper function (imported from utils_pos.py)
word, tag = get_word_tag(word_tag, vocab)
# Increment the transition count for the previous word and tag
transition_counts[(prev_tag, tag)] += 1
# Increment the emission count for the tag and word
emission_counts[(tag, word)] += 1
# Increment the tag count
tag_counts[tag] += 1
# Set the previous tag to this tag (for the next iteration of the loop)
prev_tag = tag
### END CODE HERE ###
return emission_counts, transition_counts, tag_counts
emission_counts, transition_counts, tag_counts = create_dictionaries(training_corpus, vocab)
# get all the POS states
states = sorted(tag_counts.keys())
print(f"Number of POS tags (number of 'states'): {len(states)}")
print("View these POS tags (states)")
print(states) | 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', 'VBP', 'VBZ', 'WDT', 'WP', 'WP$', 'WRB', '``']
| 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', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP', 'WP$', 'WRB', '``']``` The 'states' are the Parts-of-speech designations found in the training data. They will also be referred to as 'tags' or POS in this assignment. - "NN" is noun, singular, - 'NNS' is noun, plural. - In addition, there are helpful tags like '--s--' which indicate a start of a sentence.- You can get a more complete description at [Penn Treebank II tag set](https://www.clips.uantwerpen.be/pages/mbsp-tags). | 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') 4
| 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', 'back') 4``` Part 1.2 - TestingNow you will test the accuracy of your parts-of-speech tagger using your `emission_counts` dictionary. - Given your preprocessed test corpus `prep`, you will assign a parts-of-speech tag to every word in that corpus. - Using the original tagged test corpus `y`, you will then compute what percent of the tags you got correct. Exercise 02**Instructions:** Implement `predict_pos` that computes the accuracy of your model. - This is a warm up exercise. - To assign a part of speech to a word, assign the most frequent POS for that word in the training set. - Then evaluate how well this approach works. Each time you predict based on the most frequent POS for the given word, check whether the actual POS of that word is the same. If so, the prediction was correct!- Calculate the accuracy as the number of correct predictions divided by the total number of words for which you predicted the POS tag. | # 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 consists of (word, POS)
emission_counts: a dictionary where the keys are (tag,word) tuples and the value is the count
vocab: a dictionary where keys are words in vocabulary and value is an index
states: a sorted list of all possible tags for this assignment
Output:
accuracy: Number of times you classified a word correctly
'''
# Initialize the number of correct predictions to zero
num_correct = 0
# Get the (tag, word) tuples, stored as a set
all_words = set(emission_counts.keys())
# Get the number of (word, POS) tuples in the corpus 'y'
total = len(y)
for word, y_tup in zip(prep, y):
# Split the (word, POS) string into a list of two items
y_tup_l = y_tup.split()
# Verify that y_tup contain both word and POS
if len(y_tup_l) == 2:
# Set the true POS label for this word
true_label = y_tup_l[1]
else:
# If the y_tup didn't contain word and POS, go to next word
continue
count_final = 0
pos_final = ''
# If the word is in the vocabulary...
if word in vocab:
for pos in states:
### START CODE HERE (Replace instances of 'None' with your code) ###
# define the key as the tuple containing the POS and word
key = (pos,word)
# check if the (pos, word) key exists in the emission_counts dictionary
if key in emission_counts.keys(): # complete this line
# get the emission count of the (pos,word) tuple
count = emission_counts[key]
# keep track of the POS with the largest count
if count > count_final: # complete this line
# update the final count (largest count)
count_final = count
# update the final POS
pos_final = pos
# If the final POS (with the largest count) matches the true POS:
if pos_final == true_label: # complete this line
# Update the number of correct predictions
num_correct += 1
### END CODE HERE ###
accuracy = num_correct / total
return accuracy
accuracy_predict_pos = predict_pos(prep, y, emission_counts, vocab, states)
print(f"Accuracy of prediction using predict_pos is {accuracy_predict_pos:.4f}") | 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 a Hidden Markov Model (HMM) with a Viterbi decoder- The HMM is one of the most commonly used algorithms in Natural Language Processing, and is a foundation to many deep learning techniques you will see in this specialization. - In addition to parts-of-speech tagging, HMM is used in speech recognition, speech synthesis, etc. - By completing this part of the assignment you will get a 95% accuracy on the same dataset you used in Part 1.The Markov Model contains a number of states and the probability of transition between those states. - In this case, the states are the parts-of-speech. - A Markov Model utilizes a transition matrix, `A`. - A Hidden Markov Model adds an observation or emission matrix `B` which describes the probability of a visible observation when we are in a particular state. - In this case, the emissions are the words in the corpus- The state, which is hidden, is the POS tag of that word. Part 2.1 Generating Matrices Creating the 'A' transition probabilities matrixNow that you have your `emission_counts`, `transition_counts`, and `tag_counts`, you will start implementing the Hidden Markov Model. This will allow you to quickly construct the - `A` transition probabilities matrix.- and the `B` emission probabilities matrix. You will also use some smoothing when computing these matrices. Here is an example of what the `A` transition matrix would look like (it is simplified to 5 tags for viewing. It is 46x46 in this assignment.):|**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-05 |1.722772e-05 |1.722772e-05 |0.000017 |1.722772e-05|...|**TO** |...|4.477336e-05 |4.472863e-08 |4.472863e-08 |0.000090 |4.477336e-05|...|**UH** |...|1.030439e-05 |1.030439e-05 |1.030439e-05 |0.061837 |3.092348e-02|...| ... |...| ... | ... | ... | ... | ... | ...Note that the matrix above was computed with smoothing. Each cell gives you the probability to go from one part of speech to another. - In other words, there is a 4.47e-8 chance of going from parts-of-speech `TO` to `RP`. - The sum of each row has to equal 1, because we assume that the next POS tag must be one of the available columns in the table.The smoothing was done as follows: $$ P(t_i | t_{i-1}) = \frac{C(t_{i-1}, t_{i}) + \alpha }{C(t_{i-1}) +\alpha * N}\tag{3}$$- $N$ is the total number of tags- $C(t_{i-1}, t_{i})$ is the count of the tuple (previous POS, current POS) in `transition_counts` dictionary.- $C(t_{i-1})$ is the count of the previous POS in the `tag_counts` dictionary.- $\alpha$ is a smoothing parameter. Exercise 03**Instructions:** Implement the `create_transition_matrix` below for all tags. Your task is to output a matrix that computes equation 3 for each cell in matrix `A`. | # 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: transition count for the previous word and tag
Output:
A: matrix of dimension (num_tags,num_tags)
'''
# Get a sorted list of unique POS tags
all_tags = sorted(tag_counts.keys())
# Count the number of unique POS tags
num_tags = len(all_tags)
# Initialize the transition matrix 'A'
A = np.zeros((num_tags,num_tags))
# Get the unique transition tuples (previous POS, current POS)
trans_keys = set(transition_counts.keys())
### START CODE HERE (Return instances of 'None' with your code) ###
# Go through each row of the transition matrix A
for i in range(num_tags):
# Go through each column of the transition matrix A
for j in range(num_tags):
# Initialize the count of the (prev POS, current POS) to zero
count = 0
# Define the tuple (prev POS, current POS)
# Get the tag at position i and tag at position j (from the all_tags list)
key = (all_tags[i],all_tags[j])
# Check if the (prev POS, current POS) tuple
# exists in the transition counts dictionaory
if key in transition_counts.keys(): #complete this line
# Get count from the transition_counts dictionary
# for the (prev POS, current POS) tuple
count = transition_counts[key]
# Get the count of the previous tag (index position i) from tag_counts
count_prev_tag = tag_counts[all_tags[i]]
# Apply smoothing using count of the tuple, alpha,
# count of previous tag, alpha, and number of total tags
A[i,j] = (count + alpha)/(count_prev_tag + alpha * num_tags )
### END CODE HERE ###
return A
alpha = 0.001
A = create_transition_matrix(alpha, tag_counts, transition_counts)
# Testing your function
print(f"A at row 0, col 0: {A[0,0]:.9f}")
print(f"A at row 3, col 1: {A[3,1]:.4f}")
print("View a subset of transition matrix A")
A_sub = pd.DataFrame(A[30:35,30:35], index=states[30:35], columns = states[30:35] )
print(A_sub) | 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-05 1.722772e-05 1.722772e-05 0.000017 1.722772e-05
TO 4.477336e-05 4.472863e-08 4.472863e-08 0.000090 4.477336e-05
UH 1.030439e-05 1.030439e-05 1.030439e-05 0.061837 3.092348e-02
| 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-07SYM 1.722772e-05 1.722772e-05 1.722772e-05 0.000017 1.722772e-05TO 4.477336e-05 4.472863e-08 4.472863e-08 0.000090 4.477336e-05UH 1.030439e-05 1.030439e-05 1.030439e-05 0.061837 3.092348e-02``` Create the 'B' emission probabilities matrixNow you will create the `B` transition matrix which computes the emission probability. You will use smoothing as defined below: $$P(w_i | t_i) = \frac{C(t_i, word_i)+ \alpha}{C(t_{i}) +\alpha * N}\tag{4}$$- $C(t_i, word_i)$ is the number of times $word_i$ was associated with $tag_i$ in the training data (stored in `emission_counts` dictionary).- $C(t_i)$ is the number of times $tag_i$ was in the training data (stored in `tag_counts` dictionary).- $N$ is the number of words in the vocabulary- $\alpha$ is a smoothing parameter. The matrix `B` is of dimension (num_tags, N), where num_tags is the number of possible parts-of-speech tags. Here is an example of the matrix, only a subset of tags and words are shown: B Emissions Probability Matrix (subset) |**B**| ...| 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.257091e-05**| ...||**NNS** | ...| 1.670013e-08 | 1.670013e-08 |**4.676203e-04** | 1.670013e-08 | 1.670013e-08| ...||**VB** | ...| 3.779036e-08 | 3.779036e-08 | 3.779036e-08 | 3.779036e-08 | 3.779036e-08| ...||**RB** | ...| 3.226454e-08 | **6.456135e-05** | 3.226454e-08 | 3.226454e-08 | 3.226454e-08| ...||**RP** | ...| 3.723317e-07 | 3.723317e-07 | 3.723317e-07 | **3.723317e-07** | 3.723317e-07| ...|| ... | ...| ... | ... | ... | ... | ... | ...| Exercise 04**Instructions:** Implement the `create_emission_matrix` below that computes the `B` emission probabilities matrix. Your function takes in $\alpha$, the smoothing parameter, `tag_counts`, which is a dictionary mapping each tag to its respective count, the `emission_counts` dictionary where the keys are (tag, word) and the values are the counts. Your task is to output a matrix that computes equation 4 for each cell in matrix `B`. | # 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
emission_counts: a dictionary where the keys are (tag, word) and the values are the counts
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
B: a matrix of dimension (num_tags, len(vocab))
'''
# get the number of POS tag
num_tags = len(tag_counts)
# Get a list of all POS tags
all_tags = sorted(tag_counts.keys())
# Get the total number of unique words in the vocabulary
num_words = len(vocab)
# Initialize the emission matrix B with places for
# tags in the rows and words in the columns
B = np.zeros((num_tags, num_words))
# Get a set of all (POS, word) tuples
# from the keys of the emission_counts dictionary
emis_keys = set(list(emission_counts.keys()))
### START CODE HERE (Replace instances of 'None' with your code) ###
# Go through each row (POS tags)
for i in range(num_tags): # complete this line
# Go through each column (words)
for j in range(num_words): # complete this line
# Initialize the emission count for the (POS tag, word) to zero
count = 0
# Define the (POS tag, word) tuple for this row and column
key = (all_tags[i],vocab[j])
# check if the (POS tag, word) tuple exists as a key in emission counts
if key in emis_keys: # complete this line
# Get the count of (POS tag, word) from the emission_counts d
count = emission_counts[key]
# Get the count of the POS tag
count_tag = tag_counts[key[0]]
# Apply smoothing and store the smoothed value
# into the emission matrix B for this row and column
B[i,j] = (count + alpha)/(count_tag + alpha * num_words )
### END CODE HERE ###
return B
# creating your emission probability matrix. this takes a few minutes to run.
B = create_emission_matrix(alpha, tag_counts, emission_counts, list(vocab))
print(f"View Matrix position at row 0, column 0: {B[0,0]:.9f}")
print(f"View Matrix position at row 3, column 1: {B[3,1]:.9f}")
# Try viewing emissions for a few words in a sample dataframe
cidx = ['725','adroitly','engineers', 'promoted', 'synergy']
# Get the integer ID for each word
cols = [vocab[a] for a in cidx]
# Choose POS tags to show in a sample dataframe
rvals =['CD','NN','NNS', 'VB','RB','RP']
# For each POS tag, get the row number from the 'states' list
rows = [states.index(a) for a in rvals]
# Get the emissions for the sample of words, and the sample of POS tags
B_sub = pd.DataFrame(B[np.ix_(rows,cols)], index=rvals, columns = cidx )
print(B_sub) | 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.257091e-05
NNS 1.670013e-08 1.670013e-08 4.676203e-04 1.670013e-08 1.670013e-08
VB 3.779036e-08 3.779036e-08 3.779036e-08 3.779036e-08 3.779036e-08
RB 3.226454e-08 6.456135e-05 3.226454e-08 3.226454e-08 3.226454e-08
RP 3.723317e-07 3.723317e-07 3.723317e-07 3.723317e-07 3.723317e-07
| 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.521128e-09 2.257091e-05NNS 1.670013e-08 1.670013e-08 4.676203e-04 1.670013e-08 1.670013e-08VB 3.779036e-08 3.779036e-08 3.779036e-08 3.779036e-08 3.779036e-08RB 3.226454e-08 6.456135e-05 3.226454e-08 3.226454e-08 3.226454e-08RP 3.723317e-07 3.723317e-07 3.723317e-07 3.723317e-07 3.723317e-07``` Part 3: Viterbi Algorithm and Dynamic ProgrammingIn this part of the assignment you will implement the Viterbi algorithm which makes use of dynamic programming. Specifically, you will use your two matrices, `A` and `B` to compute the Viterbi algorithm. We have decomposed this process into three main steps for you. * **Initialization** - In this part you initialize the `best_paths` and `best_probabilities` matrices that you will be populating in `feed_forward`.* **Feed forward** - At each step, you calculate the probability of each path happening and the best paths up to that point. * **Feed backward**: This allows you to find the best path with the highest probabilities. Part 3.1: Initialization You will start by initializing two matrices of the same dimension. - best_probs: Each cell contains the probability of going from one POS tag to a word in the corpus.- best_paths: A matrix that helps you trace through the best possible path in the corpus. Exercise 05**Instructions**: Write a program below that initializes the `best_probs` and the `best_paths` matrix. Both matrices will be initialized to zero except for column zero of `best_probs`. - Column zero of `best_probs` is initialized with the assumption that the first word of the corpus was preceded by a start token ("--s--"). - This allows you to reference the **A** matrix for the transition probabilityHere is how to initialize column 0 of `best_probs`:- The probability of the best path going from the start index to a given POS tag indexed by integer $i$ is denoted by $\textrm{best_probs}[s_{idx}, i]$.- This is estimated as the probability that the start tag transitions to the POS denoted by index $i$: $\mathbf{A}[s_{idx}, i]$ AND that the POS tag denoted by $i$ emits the first word of the given corpus, which is $\mathbf{B}[i, vocab[corpus[0]]]$.- Note that vocab[corpus[0]] refers to the first word of the corpus (the word at position 0 of the corpus). - **vocab** is a dictionary that returns the unique integer that refers to that particular word.Conceptually, it looks like this:$\textrm{best_probs}[s_{idx}, i] = \mathbf{A}[s_{idx}, i] \times \mathbf{B}[i, corpus[0] ]$In order to avoid multiplying and storing small values on the computer, we'll take the log of the product, which becomes the sum of two logs:$best\_probs[i,0] = log(A[s_{idx}, i]) + log(B[i, vocab[corpus[0]]$Also, to avoid taking the log of 0 (which is defined as negative infinity), the code itself will just set $best\_probs[i,0] = float('-inf')$ when $A[s_{idx}, i] == 0$So the implementation to initialize $best\_probs$ looks like this:$ if A[s_{idx}, i] 0 : best\_probs[i,0] = log(A[s_{idx}, i]) + log(B[i, vocab[corpus[0]]$$ if A[s_{idx}, i] == 0 : best\_probs[i,0] = float('-inf')$Please use [math.log](https://docs.python.org/3/library/math.html) to compute the natural logarithm. The example below shows the initialization assuming the corpus starts with the phrase "Loss tracks upward". Represent infinity and negative infinity like this:```CPPfloat('inf')float('-inf')``` | # 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 dimension (num_tags, num_tags)
B: Emission Matrix of dimension (num_tags, len(vocab))
corpus: a sequence of words whose POS is to be identified in a list
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
best_probs: matrix of dimension (num_tags, len(corpus)) of floats
best_paths: matrix of dimension (num_tags, len(corpus)) of integers
'''
# Get the total number of unique POS tags
num_tags = len(tag_counts)
# Initialize best_probs matrix
# POS tags in the rows, number of words in the corpus as the columns
best_probs = np.zeros((num_tags, len(corpus)))
# Initialize best_paths matrix
# POS tags in the rows, number of words in the corpus as columns
best_paths = np.zeros((num_tags, len(corpus)), dtype=int)
# Define the start token
s_idx = states.index("--s--")
### START CODE HERE (Replace instances of 'None' with your code) ###
# Go through each of the POS tags
for i in range(num_tags): # complete this line
# Handle the special case when the transition from start token to POS tag i is zero
if A[s_idx,i] == 0: # complete this line
# Initialize best_probs at POS tag 'i', column 0, to negative infinity
best_probs[i,0] = -inf
# For all other cases when transition from start token to POS tag i is non-zero:
else:
# Initialize best_probs at POS tag 'i', column 0
# Check the formula in the instructions above
best_probs[i,0] = np.log(A[s_idx,i]) + np.log(B[i, vocab[corpus[0]]])
### END CODE HERE ###
return best_probs, best_paths
best_probs, best_paths = initialize(states, tag_counts, A, B, prep, vocab)
# Test the function
print(f"best_probs[0,0]: {best_probs[0,0]:.4f}")
print(f"best_paths[2,3]: {best_paths[2,3]:.4f}") | 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 probability for each possible tag. - Unlike the previous algorithm `predict_pos` (the 'warm-up' exercise), this will include the path up to that (word,tag) combination. Here is an example with a three-word corpus "Loss tracks upward":- Note, in this example, only a subset of states (POS tags) are shown in the diagram below, for easier reading. - In the diagram below, the first word "Loss" is already initialized. - The algorithm will compute a probability for each of the potential tags in the second and future words. Compute the probability that the tag of the second work ('tracks') is a verb, 3rd person singular present (VBZ). - In the `best_probs` matrix, go to the column of the second word ('tracks'), and row 40 (VBZ), this cell is highlighted in light orange in the diagram below.- Examine each of the paths from the tags of the first word ('Loss') and choose the most likely path. - An example of the calculation for **one** of those paths is the path from ('Loss', NN) to ('tracks', VBZ).- The log of the probability of the path up to and including the first word 'Loss' having POS tag NN is $-14.32$. The `best_probs` matrix contains this value -14.32 in the column for 'Loss' and row for 'NN'.- Find the probability that NN transitions to VBZ. To find this probability, go to the `A` transition matrix, and go to the row for 'NN' and the column for 'VBZ'. The value is $4.37e-02$, which is circled in the diagram, so add $-14.32 + log(4.37e-02)$. - Find the log of the probability that the tag VBS would 'emit' the word 'tracks'. To find this, look at the 'B' emission matrix in row 'VBZ' and the column for the word 'tracks'. The value $4.61e-04$ is circled in the diagram below. So add $-14.32 + log(4.37e-02) + log(4.61e-04)$.- The sum of $-14.32 + log(4.37e-02) + log(4.61e-04)$ is $-25.13$. Store $-25.13$ in the `best_probs` matrix at row 'VBZ' and column 'tracks' (as seen in the cell that is highlighted in light orange in the diagram).- All other paths in best_probs are calculated. Notice that $-25.13$ is greater than all of the other values in column 'tracks' of matrix `best_probs`, and so the most likely path to 'VBZ' is from 'NN'. 'NN' is in row 20 of the `best_probs` matrix, so $20$ is the most likely path.- Store the most likely path $20$ in the `best_paths` table. This is highlighted in light orange in the diagram below. The formula to compute the probability and path for the $i^{th}$ word in the $corpus$, the prior word $i-1$ in the corpus, current POS tag $j$, and previous POS tag $k$ is:$\mathrm{prob} = \mathbf{best\_prob}_{k, i-1} + \mathrm{log}(\mathbf{A}_{k, j}) + \mathrm{log}(\mathbf{B}_{j, vocab(corpus_{i})})$where $corpus_{i}$ is the word in the corpus at index $i$, and $vocab$ is the dictionary that gets the unique integer that represents a given word.$\mathrm{path} = k$where $k$ is the integer representing the previous POS tag. Exercise 06Instructions: Implement the `viterbi_forward` algorithm and store the best_path and best_prob for every possible tag for each word in the matrices `best_probs` and `best_tags` using the pseudo code below.`for each word in the corpus for each POS tag type that this word may be for POS tag type that the previous word could be compute the probability that the previous word had a given POS tag, that the current word has a given POS tag, and that the POS tag would emit this current word. retain the highest probability computed for the current word set best_probs to this highest probability set best_paths to the index 'k', representing the POS tag of the previous word which produced the highest probability `Please use [math.log](https://docs.python.org/3/library/math.html) to compute the natural logarithm. Hints Remember that when accessing emission matrix B, the column index is the unique integer ID associated with the word. It can be accessed by using the 'vocab' dictionary, where the key is the word, and the value is the unique integer ID for that word. | # 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 initilized matrix of dimension (num_tags, len(corpus))
best_paths: an initilized matrix of dimension (num_tags, len(corpus))
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
best_probs: a completed matrix of dimension (num_tags, len(corpus))
best_paths: a completed matrix of dimension (num_tags, len(corpus))
'''
# Get the number of unique POS tags (which is the num of rows in best_probs)
num_tags = best_probs.shape[0]
# Go through every word in the corpus starting from word 1
# Recall that word 0 was initialized in `initialize()`
for i in range(1, len(test_corpus)):
# Print number of words processed, every 5000 words
if i % 5000 == 0:
print("Words processed: {:>8}".format(i))
### START CODE HERE (Replace instances of 'None' with your code EXCEPT the first 'best_path_i = None') ###
# For each unique POS tag that the current word can be
for j in range(num_tags): # complete this line
# Initialize best_prob for word i to negative infinity
best_prob_i = float("-inf")
# Initialize best_path for current word i to None
best_path_i = None
# For each POS tag that the previous word can be:
for k in range(num_tags): # complete this line
# Calculate the probability =
# best probs of POS tag k, previous word i-1 +
# log(prob of transition from POS k to POS j) +
# log(prob that emission of POS j is word i)
prob = best_probs[k,i-1] + np.log(A[k,j]) + np.log(B[j,vocab[test_corpus[i]]])
# check if this path's probability is greater than
# the best probability up to and before this point
if prob > best_prob_i: # complete this line
# Keep track of the best probability
best_prob_i = prob
# keep track of the POS tag of the previous word
# that is part of the best path.
# Save the index (integer) associated with
# that previous word's POS tag
best_path_i = k
# Save the best probability for the
# given current word's POS tag
# and the position of the current word inside the corpus
best_probs[j,i] = best_prob_i
# Save the unique integer ID of the previous POS tag
# into best_paths matrix, for the POS tag of the current word
# and the position of the current word inside the corpus.
best_paths[j,i] = best_path_i
### END CODE HERE ###
return best_probs, best_paths | _____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 below shows how to walk backwards through the best_paths matrix to get the POS tags of each word in the corpus. Recall that this example corpus has three words: "Loss tracks upward".POS tag for 'upward' is `RB`- Select the the most likely POS tag for the last word in the corpus, 'upward' in the `best_prob` table.- Look for the row in the column for 'upward' that has the largest probability.- Notice that in row 28 of `best_probs`, the estimated probability is -34.99, which is larger than the other values in the column. So the most likely POS tag for 'upward' is `RB` an adverb, at row 28 of `best_prob`. - The variable `z` is an array that stores the unique integer ID of the predicted POS tags for each word in the corpus. In array z, at position 2, store the value 28 to indicate that the word 'upward' (at index 2 in the corpus), most likely has the POS tag associated with unique ID 28 (which is `RB`).- The variable `pred` contains the POS tags in string form. So `pred` at index 2 stores the string `RB`.POS tag for 'tracks' is `VBZ`- The next step is to go backward one word in the corpus ('tracks'). Since the most likely POS tag for 'upward' is `RB`, which is uniquely identified by integer ID 28, go to the `best_paths` matrix in column 2, row 28. The value stored in `best_paths`, column 2, row 28 indicates the unique ID of the POS tag of the previous word. In this case, the value stored here is 40, which is the unique ID for POS tag `VBZ` (verb, 3rd person singular present).- So the previous word at index 1 of the corpus ('tracks'), most likely has the POS tag with unique ID 40, which is `VBZ`.- In array `z`, store the value 40 at position 1, and for array `pred`, store the string `VBZ` to indicate that the word 'tracks' most likely has POS tag `VBZ`.POS tag for 'Loss' is `NN`- In `best_paths` at column 1, the unique ID stored at row 40 is 20. 20 is the unique ID for POS tag `NN`.- In array `z` at position 0, store 20. In array `pred` at position 0, store `NN`. Exercise 07Implement the `viterbi_backward` algorithm, which returns a list of predicted POS tags for each word in the corpus.- Note that the numbering of the index positions starts at 0 and not 1. - `m` is the number of words in the corpus. - So the indexing into the corpus goes from `0` to `m - 1`. - Also, the columns in `best_probs` and `best_paths` are indexed from `0` to `m - 1`**In Step 1:** Loop through all the rows (POS tags) in the last entry of `best_probs` and find the row (POS tag) with the maximum value.Convert the unique integer ID to a tag (a string representation) using the dictionary `states`. Referring to the three-word corpus described above:- `z[2] = 28`: For the word 'upward' at position 2 in the corpus, the POS tag ID is 28. Store 28 in `z` at position 2.- states(28) is 'RB': The POS tag ID 28 refers to the POS tag 'RB'.- `pred[2] = 'RB'`: In array `pred`, store the POS tag for the word 'upward'.**In Step 2:** - Starting at the last column of best_paths, use `best_probs` to find the most likely POS tag for the last word in the corpus.- Then use `best_paths` to find the most likely POS tag for the previous word. - Update the POS tag for each word in `z` and in `preds`.Referring to the three-word example from above, read best_paths at column 2 and fill in z at position 1. `z[1] = best_paths[z[2],2]` The small test following the routine prints the last few words of the corpus and their states to aid in debug. | # 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 words in the corpus
# which is also the number of columns in best_probs, best_paths
m = best_paths.shape[1]
# Initialize array z, same length as the corpus
z = [None] * m
# Get the number of unique POS tags
num_tags = best_probs.shape[0]
# Initialize the best probability for the last word
best_prob_for_last_word = float('-inf')
# Initialize pred array, same length as corpus
pred = [None] * m
### START CODE HERE (Replace instances of 'None' with your code) ###
## Step 1 ##
# Go through each POS tag for the last word (last column of best_probs)
# in order to find the row (POS tag integer ID)
# with highest probability for the last word
for k in range(num_tags): # complete this line
# If the probability of POS tag at row k
# is better than the previosly best probability for the last word:
if best_probs[k,m-1] > best_prob_for_last_word: # complete this line
# Store the new best probability for the lsat word
best_prob_for_last_word = best_probs[k,m-1]
# Store the unique integer ID of the POS tag
# which is also the row number in best_probs
z[m - 1] = k
# Convert the last word's predicted POS tag
# from its unique integer ID into the string representation
# using the 'states' dictionary
# store this in the 'pred' array for the last word
pred[m - 1] = states[z[m-1]]
## Step 2 ##
# Find the best POS tags by walking backward through the be st_paths
# From the last word in the corpus to the 0th word in the corpus
for i in reversed(range(m-1)): # complete this line
# Retrieve the unique integer ID of
# the POS tag for the word at position 'i' in the corpus
pos_tag_for_word_i = z[i+1]
# In best_paths, go to the row representing the POS tag of word i
# and the column representing the word's position in the corpus
# to retrieve the predicted POS for the word at position i-1 in the corpus
z[i] = best_paths[pos_tag_for_word_i,i+1]
# Get the previous word's POS tag in string form
# Use the 'states' dictionary,
# where the key is the unique integer ID of the POS tag,
# and the value is the string representation of that POS tag
pred[i] = states[z[i]]
### END CODE HERE ###
return pred
print(y)
# Run and test your function
pred = viterbi_backward(best_probs, best_paths, prep, states)
m=len(pred)
print('The prediction for pred[-7:m-1] is: \n', prep[-7:m-1], "\n", pred[-7:m-1], "\n")
print('The prediction for pred[0:8] is: \n', pred[0:7], "\n", prep[0:7]) | 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 to compare the predicted labels to the true labels to evaluate your model on the accuracy metric! Part 4: Predicting on a data setCompute the accuracy of your prediction by comparing it with the true `y` labels. - `pred` is a list of predicted POS tags corresponding to the words of the `test_corpus`. | 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 = 0
total = 0
# Zip together the prediction and the labels
for prediction, y1 in zip(pred, y):
### START CODE HERE (Replace instances of 'None' with your code) ###
# Split the label into the word and the POS tag
word_tag_tuple = y1.split()
# Check that there is actually a word and a tag
# no more and no less than 2 items
if len(word_tag_tuple) == 2: # complete this line
# store the word and tag separately
word, tag = word_tag_tuple
# Check if the POS tag label matches the prediction
if tag == prediction: # complete this line
# count the number of times that the prediction
# and label match
num_correct += 1
# keep track of the total number of examples (that have valid labels)
total += 1
### END CODE HERE ###
return num_correct/total
print(f"Accuracy of the Viterbi algorithm is {compute_accuracy(pred, y):.4f}") | 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 in the image. Let convert our color image to greyscale | 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 method
img = cv2.imread('./images/input.jpg',0)
cv2.imshow('Grayscale', img)
cv2.waitKey()
cv2.destroyAllWindows() | _____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 need to execute the cell below to activate the RumbleDB magic (you do not need to understand what it does, this is just initialization Python code). | !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 need to use RumbleDB in production, you can use it with an installation of Spark either on your machine or on a cluster.This sandbox backend may occasionally break, especially if too many users use it at the same time, so please bear with us! The system is automatically restarted every day so, if it stops working, you can either try again in 24 hours or notify us. It is straightforward to execute your own RumbleDB server on your own Spark cluster (and then you can make full use of all the input file systems and file formats). In this case, just replace the above server with your own hostname and port. Note that if you run RumbleDB as a server locally, you will also need to download and use this notebook locally rather than in this Google Colab environment as, obviously, your personal computer cannot be accessed from the Web.Now we are all set! You can now start reading and executing the JSONiq queries as you go, and you can even edit them! JSONAs explained on the [official JSON Web site](http://www.json.org/), JSON is a lightweight data-interchange format designed for humans as well as for computers. It supports as values:- objects (string-to-value maps)- arrays (ordered sequences of values)- strings- numbers- booleans (true, false)- nullJSONiq provides declarative querying and updating capabilities on JSON data. Elevator PitchJSONiq is based on XQuery, which is a W3C standard (like XML and HTML). XQuery is a very powerful declarative language that originally manipulates XML data, but it turns out that it is also a very good fit for manipulating JSON natively.JSONiq, since it extends XQuery, is a very powerful general-purpose declarative programming language. Our experience is that, for the same task, you will probably write about 80% less code compared to imperative languages like JavaScript, Python or Ruby. Additionally, you get the benefits of strong type checking without actually having to write type declarations.Here is an appetizer before we start the tutorial from scratch. | %%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 number" : 2, "quantity" : 100 },
{ "product" : "toaster", "store number" : 2, "quantity" : 50 },
{ "product" : "toaster", "store number" : 3, "quantity" : 50 },
{ "product" : "blender", "store number" : 3, "quantity" : 100 },
{ "product" : "blender", "store number" : 3, "quantity" : 150 },
{ "product" : "socks", "store number" : 1, "quantity" : 500 },
{ "product" : "socks", "store number" : 2, "quantity" : 10 },
{ "product" : "shirt", "store number" : 3, "quantity" : 10 }
]
let $join :=
for $store in $stores[], $sale in $sales[]
where $store."store number" = $sale."store number"
return {
"nb" : $store."store number",
"state" : $store.state,
"sold" : $sale.product
}
return [$join]
| 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", "sold": "blender"}, {"nb": 3, "state": "CA", "sold": "blender"}, {"nb": 3, "state": "CA", "sold": "shirt"}]
| 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. In the above queries, you are basically saying: I want to output this JSON content, and here it is. JSONiq basics The real JSONiq Hello, World!Wondering what a hello world program looks like in JSONiq? Here it is: | %%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 array, a number, a string, a boolean). JSONiq supports sequences of values. You can build a sequence using commas: | %%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
100
| 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.