text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
import numpy as np
import gym
import random
import time
from IPython.display import clear_output
# Initialise the basic environment
env = gym.make("FrozenLake-v0")
# Initialise the Q table
action_space_size = env.action_space.n
state_space_size = env.observation_space.n
q_table = np.zeros((state_space_size, action_space_size))
print(q_table)
# Parameters for learning
num_episodes = 10000
max_steps_per_episode = 100
learning_rate = 0.1
discount_rate = 0.99
exploration_rate = 1
max_exploration_rate = 1
min_exploration_rate = 0.01
exploration_decay_rate = 0.001
rewards_all_episodes = []
# Q-learning algorithm
for episode in range(num_episodes):
# Initialize new episode params
state = env.reset()
done = False
rewards_current_episode = 0
for step in range(max_steps_per_episode):
# Exploration-exploitation trade-off
exploration_rate_threshold = random.uniform(0, 1)
action = None
if exploration_rate_threshold > exploration_rate:
action = np.argmax(q_table[state,:])
else:
action = env.action_space.sample()
# Take new action
new_state, reward, done, info = env.step(action)
# Update Q-table
q_table[state, action] = q_table[state, action] * (1 - learning_rate) + \
learning_rate * (reward + discount_rate * np.max(q_table[new_state, :]))
# Set new state and add a reward
state = new_state
rewards_current_episode += reward
if done == True:
break
# Exploration rate decay
exploration_rate = min_exploration_rate + \
(max_exploration_rate - min_exploration_rate) * np.exp(-exploration_decay_rate*episode)
# Add current episode reward to total rewards list
rewards_all_episodes.append(rewards_current_episode)
print(q_table, rewards_all_episodes)
# Watch our agent play Frozen Lake by playing the best action
# from each state according to the Q-table
for episode in range(3):
# initialize new episode params
state = env.reset()
done = False
print("*****EPISODE ", episode+1, "*****\n\n\n\n")
time.sleep(1)
for step in range(max_steps_per_episode):
# Show current state of environment on screen
clear_output(wait=True)
env.render()
time.sleep(0.3)
# Choose action with highest Q-value for current state
action = np.argmax(q_table[state,:])
# Take new action
new_state, reward, done, info = env.step(action)
if done:
clear_output(wait=True)
env.render()
if reward == 1:
print("****You reached the goal!****")
time.sleep(3)
else:
print("****You fell through a hole!****")
time.sleep(3)
clear_output(wait=True)
break
state = new_state
env.close()
```
| github_jupyter |
RIHAD VARIAWA, Data Scientist - Who has fun LEARNING, EXPLORING & GROWING
<h1>Operations with numbers</h1>
```
21 * 21 #Returns int
21 * 21.0 #Returns float
21/3 #Returns float (division always returns float)
21//3 #Returns int
21//3.0 #Returns float
21//3.2 #Returns float whose value is the lower integer bound of 21//3.2
21%4 #Returns int (the remainder of dividing 21 by 4)
21%4.4 #Returns float (21 - 21//4.4)
21**4 #Returns int
21**4.2 #Returns float
```
<h1>String operations</h1>
<h3>Indexing</h3>
```
x = "Always take a banana to a party!"
x[3] #Returns the 4th (i+1)th character in x
x[-1] #Returns the last character in x
x[-2] #Returns the second last character in x
x[32] #IndexError. Out of range
len(x) #Returns the length of the string (an integer)
```
<h3>Slicing</h3>
```
x[7:11] #Returns the 8th to the 11th character (i.e., 11-7 characters)
x[7:] #Returns every character starting with location 7 (the 8th character) to the end of the string
#Omitting the endpoint defaults to the "rest of the string"
x[0::2] #returns a substring starting from 0, going to the end (omitted), 2 characters at a time
x[::-1] #Start from whatever makes sense as the start, go to whatever makes sense as the end,
#go backward one character at a time
#Here it makes sense to start at the end and go all the way to the beginning (because of the -1)
#Returns a reversed string
```
<h3>Searching</h3>
```
x.find('to') #Returns the location of the first 'to' found
x.find('hello') #Returns -1. I.e., the substring was not found in x
```
<h3>Immutability</h3>
```
x[3] = 'b' #TypeError. Can't change a string
x = "Hello"
y = x
print(id(x),id(y))
#x and y are the same string
x="Always take a banana to a party!"
print(id(x),id(y))
#x now points to a different string. y is still the same old string at the same old location!
```
<h3>Concatenation</h3>
```
#The plus operator concatenates two strings to give rise to a third string
x="Hello"
y="Dolly"
z=x+y
print(x,y,z,id(x),id(y),id(z)) #x, y and z are all different strings
#Since python doesn't understand that we need a space between Hello and Dolly, we need to add it ourselves
z = x + " " + y
print(z)
```
<h1>booleans</h1>
```
x=4
y=2
z=(x==y) #False because x and y are not the same
z=(x==x) #True because x and x are the same
z
#Comparison is by value
x = "Hello"
y = "Hello"
print(id(x),id(y)) #Different strings
print(x == y) #But they have the same value
x=8
m=0
print(x,bool(x),bool(m),m) #Non-zero numbers, strings with values are always True
x='' #Empty string
print(x,bool(x)) #Empty strings, 0 numbers are always False
```
<h3>Logical operators</h3>
```
x=4
y=5
print(x>2 and y>2) #True because both x and y are greater than 2
print(x>2 and y<2) #False because one is False
print(x<2 and y<2) #False because both are False
print(x>2 or y>2) #True because at least one is True
print(x<2 or y>2) #True because at least one is True
print(x<2 or y<2) #False because both are False
print(not(x>2 or y>2)) #False because x>2 or y>2 is True
print(x or y) #4 because x is True (non-zero) so no need to evaluate y. Value of x is returned
print(x and 0+3) #3 because x is non-zero but need to check the second operand as well. That evaluates to 3
```
<h1>Assignment</h1>
```
x = p + 10 #NameError! p is not defined
p = 7
x = p + 10 #This works
x,y = 3,4
print(x,y) #x is 3 and y is 4
x = 7
x += 4
print(x) #x is 11 because x += 4 is equivalent to x = x+4
```
| github_jupyter |
# Finding the maximum value of 2d function
Given equation:
\begin{align}
f(x, y) = 2xy + 2x - x^2 -2y^2
\end{align}
### Implementation of needed functions:
```
# Importing dependency functions and packages
from random import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np
%matplotlib notebook
# function
def f(x, y):
return 2*x*y + 2*x - x**2 - 2*y**2
# random search algorithm
def random_search(f, n, xl, xu, yl, yu):
# generate lists of random x and y values
x_cand = [xl + (xu - xl)*random() for _ in range(n)]
y_cand = [yl + (yu - yl)*random() for _ in range(n)]
# calculate appropriate to x and y values function values
poss_max = [f(x, y) for x, y in zip(x_cand, y_cand)]
# finding index of maximum value (argmax)
max_val = max(poss_max)
max_indexes = [i for i, j in enumerate(poss_max) if j == max_val]
# return maximum value of function and its parameters x, y
return max_val, x_cand[max_indexes[0]], y_cand[max_indexes[0]]
# simple rms error function
def rms_error(x_ref, y_ref, x, y):
return np.sqrt(((x_ref - x)/x_ref)**2 + ((y_ref - y)/y_ref)**2)
```
The problem is in guessing limits of parameters (x, y) for random number generation. The smaller limits are, the bigger accuracy we will get. Let's visualize function and judge from there.
```
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(1, 1, 1, projection='3d')
x = np.arange(-100, 100, 5)
y = np.arange(-100, 100, 5)
x, y = np.meshgrid(x, y)
z = f(x, y)
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=10)
plt.show()
```
From above 3D plot it is seen that solution lies between -50 and 50 for both parameters x, y.
```
f_ref, x_ref, y_ref = random_search(f, 10000000, -50, 50, -50, 50)
print('Using 10000000 random points and ranges between -50 and 50, it is found that maximum value of given function is:', f_ref)
```
The roots found using random search method using 10 million points and considered as reference roots and as ideal. This is done in order to determine root-mean-square error somehow and find dependency of error to number of random points. Since reference roots are found using 10 million random points, it is more accurate than roots found below for error plotting reasons.
```
error_list = []
for n in np.logspace(1, 6, num=20):
_, x, y = random_search(f, int(n), -50, 50, -50, 50)
error_list += [rms_error(x_ref, y_ref, x, y)]
plt.semilogx(np.logspace(1, 6, num=20), error_list, '-')
plt.grid(which='both')
plt.xlabel('Number of random points')
plt.ylabel('RMS error of x and y roots')
plt.show()
```
From error vs #of_points plot it is seen that line have linear dependency on number of random points (Exponential shape on log-scale). This confirms the fact that x and y values are generated uniformly and increased number of random points also increases accuracy linearly, distributing on 2d space equally.
| github_jupyter |
```
import tensorflow as tf
print(tf.__version__)
import numpy as np
import matplotlib.pyplot as plt
def plot_series(time, series, format="-", start=0, end=None):
plt.plot(time[start:end], series[start:end], format)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(True)
import csv
time_step = []
temps = []
with open('daily-min-temperatures.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader)
step=0
for row in reader:
temps.append(float(row[1]))
time_step.append(step)
step = step + 1
series = np.array(temps)
time = np.array(time_step)
plt.figure(figsize=(10, 6))
plot_series(time, series)
split_time = 2500
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
window_size = 30
batch_size = 32
shuffle_buffer_size = 1000
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
series = tf.expand_dims(series, axis=-1)
ds = tf.data.Dataset.from_tensor_slices(series)
ds = ds.window(window_size + 1, shift=1, drop_remainder=True)
ds = ds.flat_map(lambda w: w.batch(window_size + 1))
ds = ds.shuffle(shuffle_buffer)
ds = ds.map(lambda w: (w[:-1], w[1:]))
return ds.batch(batch_size).prefetch(1)
def model_forecast(model, series, window_size):
ds = tf.data.Dataset.from_tensor_slices(series)
ds = ds.window(window_size, shift=1, drop_remainder=True)
ds = ds.flat_map(lambda w: w.batch(window_size))
ds = ds.batch(32).prefetch(1)
forecast = model.predict(ds)
return forecast
tf.keras.backend.clear_session()
tf.random.set_seed(51)
np.random.seed(51)
window_size = 64
batch_size = 256
train_set = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
print(train_set)
print(x_train.shape)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=32, kernel_size=5,
strides=1, padding="causal",
activation="relu",
input_shape=[None, 1]),
tf.keras.layers.LSTM(64, return_sequences=True),
tf.keras.layers.LSTM(64, return_sequences=True),
tf.keras.layers.Dense(30, activation="relu"),
tf.keras.layers.Dense(10, activation="relu"),
tf.keras.layers.Dense(1),
tf.keras.layers.Lambda(lambda x: x * 400)
])
lr_schedule = tf.keras.callbacks.LearningRateScheduler(
lambda epoch: 1e-8 * 10**(epoch / 20))
optimizer = tf.keras.optimizers.SGD(lr=1e-8, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
plt.semilogx(history.history["lr"], history.history["loss"])
plt.axis([1e-8, 1e-4, 0, 60])
tf.keras.backend.clear_session()
tf.random.set_seed(51)
np.random.seed(51)
train_set = windowed_dataset(x_train, window_size=60, batch_size=100, shuffle_buffer=shuffle_buffer_size)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=60, kernel_size=5,
strides=1, padding="causal",
activation="relu",
input_shape=[None, 1]),
tf.keras.layers.LSTM(60, return_sequences=True),
tf.keras.layers.LSTM(60, return_sequences=True),
tf.keras.layers.Dense(30, activation="relu"),
tf.keras.layers.Dense(10, activation="relu"),
tf.keras.layers.Dense(1),
tf.keras.layers.Lambda(lambda x: x * 400)
])
optimizer = tf.keras.optimizers.SGD(lr=1e-5, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
history = model.fit(train_set,epochs=150)
rnn_forecast = model_forecast(model, series[..., np.newaxis], window_size)
rnn_forecast = rnn_forecast[split_time - window_size:-1, -1, 0]
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, rnn_forecast)
tf.keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()
print(rnn_forecast)
```
| github_jupyter |
# Medical Image Analysis workshop - IT-IST
## Image Filtering (edge preserving denoising, smoothing, etc.), Resampling and Segmentation
Lets load the image saved in previous notebook and view it.
```
import SimpleITK as sitk
import itk
import itkwidgets as itkw
from ipywidgets import interactive
import ipywidgets as widgets
import numpy as np
image_itk = itk.imread('./cT1wNeuro.nrrd')
image_sitk = sitk.ReadImage('./cT1wNeuro.nrrd')
itkw.view(image_itk, cmap='Grayscale', mode='x')
```
## Filters
### Curvature Anisotropic Diffusion Filter
The Curvature Anisotropic Diffusion Filter ([Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1CurvatureAnisotropicDiffusionImageFilter.html)) is widely used in medical images to denoise your image while preserving the edges.
Note 1: ITK/SimpleITK often poses restriction into the pixel/voxel type to execute some operations. In this case we can use the Cast Image filter to convert our image of type short into float. Be careful when performing the cast operation from higher to lower pixel/voxel types (rescaling may be required)
Note 2: There are several types of Anisotropic Diffusion Filters and another commonly used is the Gradient Anisotropic Diffusion filter (an example of that may be found on the Extras notebook).
```
image_sitk_float = sitk.Cast(image_sitk, sitk.sitkFloat32)
smooth_cadf_sitk = sitk.CurvatureAnisotropicDiffusion(image_sitk_float)
itkw.view(smooth_cadf_sitk, cmap='Grayscale', mode='x')
```
As previously mentioned, ITK is more verbose than SimpleITK but it more customizable and offers additional filters.
The same result that was achieved by with three lines requires the following in ITK
```
castImageFilter = itk.CastImageFilter[image_itk, itk.Image[itk.F,3]].New(image_itk)
castImageFilter.Update()
image_itk_float = castImageFilter.GetOutput()
curv_ani_dif_filter = itk.CurvatureAnisotropicDiffusionImageFilter[image_itk_float, itk.Image[itk.F,3]].New(image_itk_float)
curv_ani_dif_filter.Update()
smooth_cadf = curv_ani_dif_filter.GetOutput()
itkw.view(smooth_cadf, cmap='Grayscale', mode='x')
```
### Median Filter
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1MedianImageFilter.html)
```
# median_filter = sitk.MedianImageFilter()
# median_filter.SetRadius(2) # In pixels/voxels
# median_image = median_filter.Execute(image_sitk_float)
median_image = sitk.Median(image_sitk_float, [2, 2, 2])
itkw.view(median_image, cmap='Grayscale', mode='x')
```
### Sobel Filter
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1SobelEdgeDetectionImageFilter.html)
```
sobel_edge_image = sitk.SobelEdgeDetection(image_sitk_float)
itkw.view(sobel_edge_image, cmap='Grayscale', mode='x')
```
### Laplacian Sharpening Image Filter
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1LaplacianSharpeningImageFilter.html)
```
laplacian_sharped_image = sitk.LaplacianSharpening(image_sitk_float)
itkw.view(laplacian_sharped_image, cmap='Grayscale', mode='x')
```
You can also compare two images using the following command
```
itkw.checkerboard(median_image, laplacian_sharped_image, cmap='Grayscale', mode='x', pattern=5)
```
## Resampling an Image
This image is isotropic with voxels of size 1mm x 1mm x 1mm. Often images come with different voxel sizes, and depending on the analysis we may have to normalize the voxel size accross the dataset.
So lets learn how to change the voxel spacing/size from 1mm x 1mm x 1mm to 1.5mm x 2mm x 3mm.
```
resample = sitk.ResampleImageFilter()
resample.SetInterpolator = sitk.sitkBSpline
resample.SetOutputDirection(image_sitk_float.GetDirection())
resample.SetOutputOrigin(image_sitk_float.GetOrigin())
new_spacing = [1.5, 2, 5]
resample.SetOutputSpacing(new_spacing)
orig_size = np.array(image_sitk_float.GetSize(), dtype=np.int)
orig_spacing = np.array(image_sitk_float.GetSpacing(), dtype=np.float)
new_size = orig_size * (orig_spacing / new_spacing)
new_size = np.ceil(new_size).astype(np.int) # Image dimensions are in integers
new_size = [int(s) for s in new_size]
resample.SetSize(new_size)
resampled_image = resample.Execute(image_sitk_float)
print('Resample image spacing:', list(resampled_image.GetSpacing()))
print('Resample image size:', list(resampled_image.GetSize()))
print('Original image spacing:', list(image_sitk_float.GetSpacing()))
print('Original image size:', list(image_sitk_float.GetSize()))
```
## Segmentation Filters
Another common task on the medical image domain is the segmentation.
In this example we will work with a different image.
```
image_brainT1 = sitk.ReadImage('./brain_T1.nii.gz')
image_brainT1_mask_float = sitk.ReadImage('./brain_T1_mask.nii.gz')
# it is possible to force reading an image with a specific pixel/voxel type
image_brainT1_mask_uc = sitk.ReadImage('./brain_T1_mask.nii.gz', sitk.sitkUInt8)
itkw.view(image_brainT1, cmap='Grayscale', mode='z')
```
It is possible to observe that for this case we also have a binary mask corresponding to the brain.
Using the multiply filter we can obtain an image with just the brain.
```
brain_image = sitk.Multiply(image_brainT1, image_brainT1_mask_float)# image_atlas * image_atlas_mask
itkw.view(brain_image, cmap='Grayscale', mode='z')
```
NOTE: show multiplication by using *
### Thresholding Filters
#### Binary Threshold with lower and upper threshold
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1BinaryThresholdImageFilter.html)
```
binary_mask = sitk.BinaryThreshold(brain_image, lowerThreshold=300, upperThreshold=600, insideValue=1, outsideValue=0)
itkw.view(binary_mask, cmap='Grayscale', mode='z')
```
#### Interactively discretize your image using Otsu Multiple Threshold method
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1OtsuMultipleThresholdsImageFilter.html)
In this example you can see how to use SimpleITK and ipywidgets interactively change parameters of a filter (Otsu Multiple Thresholds) and check the results immediately!!
```
from ipywidgets import interactive
import ipywidgets as widgets
viewer_int = itkw.view(brain_image, cmap='Grayscale', mode='z', annotations=False)
# Create an itk smoother filter object. By re-using the object, output memory-reallocation is avoided
otsu_filter = sitk.OtsuMultipleThresholdsImageFilter() # [brain_image, itk.Image[itk.F,3]].New(brain_image)
otsu_filter.SetNumberOfHistogramBins(64)
def otsu_and_view(thresholds=2):
otsu_filter.SetNumberOfThresholds(thresholds)
# Execute and Update the image used in the viewer
viewer_int.image = otsu_filter.Execute(brain_image)
slider = interactive(otsu_and_view, thresholds=(1, 5, 1))
widgets.VBox([viewer_int, slider])
```
### Region Growing Filters
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1ConfidenceConnectedImageFilter.html)
These are a type filters that require a seed point to perform the segmentation. We will try to segment the white matter using the Confidence Connected algorithm but other implementations like the Connected Threshold and the Neighborhood Connected.
```
confidence_connected_filter = sitk.ConfidenceConnectedImageFilter()
confidence_connected_filter.SetMultiplier(1.80)
confidence_connected_filter.SetSeed([30, 61, 77])
confidence_connected_filter.SetNumberOfIterations( 10 );
confidence_connected_filter.SetReplaceValue( 255 );
confidence_connected_filter.SetInitialNeighborhoodRadius( 3 );
white_matter_image = confidence_connected_filter.Execute(brain_image)
itkw.view(white_matter_image, cmap='Grayscale', mode='z')
```
This segmentation is far from perfect. If we go back to the image, it is possible to observe that this MRI image was affected by bias field inhomogeneity. This artifact affects the performance of segmentation filters.
## Filtering MRI bias field inhomogeneity
<img src="bias_field_example.jpeg"> [Image Source](http://digitool.library.mcgill.ca/webclient/StreamGate?folder_id=0&dvs=1579874409466~728)
### N4 Bias Field Correction Image Filter
[Documentation SimpleITK](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1N4BiasFieldCorrectionImageFilter.html)
```
bias_field_filter = sitk.N4BiasFieldCorrectionImageFilter()
bias_field_filter.SetNumberOfControlPoints([4,4,4])
bias_corrected_image = bias_field_filter.Execute(sitk.Cast(brain_image,sitk.sitkFloat32), image_brainT1_mask_uc)
itkw.checkerboard(bias_corrected_image, brain_image, cmap='Grayscale', mode='z', pattern=4)
```
#### Let's now try to segment the white matter again using the same filter and parameters
```
confidence_connected_filter = sitk.ConfidenceConnectedImageFilter()
# confidence_connected_filter.SetInput(bias_corrected_image)
confidence_connected_filter.SetSeed([30, 61, 77])
confidence_connected_filter.SetMultiplier( 1.80 );
confidence_connected_filter.SetNumberOfIterations( 10 );
confidence_connected_filter.SetReplaceValue( 255 );
confidence_connected_filter.SetInitialNeighborhoodRadius( 3 );
white_matter_mask = confidence_connected_filter.Execute(bias_corrected_image)
itkw.view(white_matter_mask, cmap='Grayscale', mode='z')
```
#### Checkboard of Brain Image <-> White Matter Segmentation
```
white_matter_mask_float = sitk.Cast(white_matter_mask, sitk.sitkFloat32) * 5 ## * 5 -> bring the mask to an intensity ~ of the image
itkw.checkerboard(white_matter_mask_float, image_brainT1, cmap='Grayscale', mode='z', pattern=6)
```
## More Advanced Segmentation Filters
### Bayesian Classifier Image Filter Segmentation
This filter
This filter does not exist in SimpleITK, only in ITK. Using the numpy (python scientific computing package providing powerful N-dimensional array object) interface of both libraries we will recreate the bias field corrected simple itk images as an itk image.
The conversion of SimpleITK image to and ITK image will be your first exercise.
#### Exercise #1
Convert the bias_corrected_image, which is a SimpleITK image object to ITK image object called bias_corrected_itk_image.
##### Tips (functions required):
- sitk.GetArrayFromImage() - converts the SimpleITK image into a numpy array (physical properties of image like spacing, origin and direction are lost)
- itk.GetImageFromArray() - converts the numpy array into a SimpleITK image (physical properties of image like spacing, origin and direction are set to default values)
- bias_corrected_image.GetOrigin() - get SimpleITK image world coordinates origin vector
- bias_corrected_image.GetSpacing() - get SimpleITK image spacing vector
- bias_corrected_image.GetDirection() - get SimpleITK image direction vector
- bias_corrected_itk_image.SetOrigin(<vector_correct_origin>) - set the correct world coordinates origin using the values prodived in the vector
- bias_corrected_itk_image.SetSpacing(<vector_correct_spacing>) - set the correct spacing using the values prodived in the vector
- Set direction is a little bit trickier so here is the example of the code that you can use:
```python
# The interface for the direction is a little trickier
np_dir_vnl = itk.vnl_matrix_from_array(np.array(original_direction).reshape(3,3))
DirectionType = type(bias_corrected_itk_image.GetDirection())
direction = DirectionType(np_dir_vnl)
bias_corrected_itk_image.SetDirection(direction)
```
```
## use this code box to write your solution
bias_corrected_np_image = sitk.GetArrayFromImage(bias_corrected_image)
original_spacing = bias_corrected_image.GetSpacing()
original_origin = bias_corrected_image.GetOrigin()
original_direction = bias_corrected_image.GetDirection()
bias_corrected_itk_image = itk.GetImageFromArray(bias_corrected_np_image)
bias_corrected_itk_image.SetSpacing(original_spacing)
bias_corrected_itk_image.SetOrigin(original_origin)
# The interface for the direction is a little trickier
np_dir_vnl = itk.vnl_matrix_from_array(np.array(original_direction).reshape(3,3))
DirectionType = type(bias_corrected_itk_image.GetDirection())
direction = DirectionType(np_dir_vnl)
bias_corrected_itk_image.SetDirection(direction)
itkw.view(bias_corrected_itk_image, cmap='Grayscale', mode='z')
# The goal of this filter is to generate a membership image that indicates the membership of each pixel to each class.
# These membership images are fed as input to the Bayesian classifier filter.
# BayesianClassifierInitializationImageFilter runs K-means on the image to determine k Gaussian density functions centered
# around 'n' pixel intensity values. This is equivalent to generate Gaussian mixture model for the input image.
instance = itk.BayesianClassifierInitializationImageFilter[bias_corrected_itk_image, itk.F].New(bias_corrected_itk_image)
instance.SetNumberOfClasses(5)
instance.Update()
# The output to this filter is an itk::VectorImage that represents pixel memberships to 'n' classes.
image_bayesian_class = instance.GetOutput()
# Performs Bayesian Classification on an image using the membership Vector Image obtained by the itk.BayesianClassifierInitializationImageFilter.
bc = itk.BayesianClassifierImageFilter[image_bayesian_class, itk.SS, itk.F, itk.F].New(image_bayesian_class)
bc.Update()
labelled_bayesian = bc.GetOutput()
itkw.view(labelled_bayesian, cmap='Grayscale', mode='z')
```
### Gaussian Misture Models (GMMs) Segmentation
To execute this we will make use of the interface ITK <-> numpy and use scikit-learn use Gaussian Mixture Models (GMMs) to perform the segmentation.
We will start by getting some statistics of the image using the segmentation labels.
These will be used in the GMM.
```
import sklearn
from sklearn.mixture import GaussianMixture
## Copy of itk.Image to numpy.ndarray
np_copy = itk.array_from_image(bias_corrected_itk_image)
np_mask_copy = itk.array_from_image(labelled_bayesian)
middle_slice = int(np.floor(np_copy.shape[0]/2))
gmm = GaussianMixture(n_components = 4)
## Fit the GMM on a single slice of the MRI data
data = np_copy[middle_slice]
gmm.fit(np.reshape(data, (data.size, 1)))
## Classify the all images according to the GMM
for j in range(2):
im = np_copy[j]
cls = gmm.predict(im.reshape((im.size, 1)))
seg = np.zeros(np_copy[0].shape)
seg = cls.reshape(np_copy[0].shape)
np_mask_copy[j] = seg
## Copy of numpy.ndarray to itk.Image
mask_itk = itk.image_from_array(np_mask_copy)
## The conversion itk -> numpy -> itk will change axis orientation. Correct it with the following filter
flipFilter = itk.FlipImageFilter[itk.Image.SS3].New()
flipFilter.SetInput(mask_itk)
flipAxes = (False, True, False)
flipFilter.SetFlipAxes(flipAxes)
flipFilter.Update()
corrected_mask = flipFilter.GetOutput()
itkw.view(corrected_mask, cmap='Grayscale', mode='z')
```
#### Save mask for next notebook on Quantification
```
write_filter = itk.ImageFileWriter[labelled_bayesian].New(labelled_bayesian)
write_filter.SetFileName('bayesian_mask.nii.gz')
write_filter.Update()
```
| github_jupyter |
```
import numpy as np
import h5py
import json
import subprocess
from collections import OrderedDict
np.random.seed(0)
train_size = 0.85
answer_types = ['answer', 'rationale']
# 'sample' | 'mini'
size_type = 'orig'
def split_train_val(train_size, size_type):
with open('train-orig.jsonl', 'r') as f_in:
data = np.array([json.loads(s) for s in f_in])
data_grp_movies = OrderedDict()
for i in range(len(data)):
data_grp_movies.setdefault(data[i]['movie'], []).append(i)
movies = list(data_grp_movies.keys())
if 0. <= train_size <= 1.:
train_size = int(train_size*len(movies))
train_movie_ind = np.random.choice(range(len(movies)), size=train_size, replace=False)
val_movie_ind = np.setdiff1d(range(len(movies)), train_movie_ind)
print(len(train_movie_ind), len(val_movie_ind))
train, train_ind = [], []
for i in range(len(movies)):
if i in train_movie_ind:
train_ind.extend(data_grp_movies[movies[i]])
train.extend(data[data_grp_movies[movies[i]]])
val, val_ind = [], []
for i in range(len(movies)):
if i in val_movie_ind:
val_ind.extend(data_grp_movies[movies[i]])
val.extend(data[data_grp_movies[movies[i]]])
indices = {'train': train_ind, 'val': val_ind}
split_data_dict = {'train': train, 'val': val}
assert len(train) == len(train_ind)
assert len(val) == len(val_ind)
print(len(train_ind), len(val_ind))
for data_type in split_data_dict.keys():
with open('{}-{}.jsonl'.format(data_type, size_type), 'w') as f_out:
for line in split_data_dict[data_type]:
f_out.write(json.dumps(line)+'\n')
return train, val, indices
train, val, indices = split_train_val(train_size, size_type)
def create_embedding_split(answer_type, size_type, indices):
group_items = {'train': [], 'val': []}
data_folder = '../../data/'
with h5py.File('{}bert_da_{}_train_orig.h5'.format(data_folder, answer_type), 'r') as f:
for data_type in ['train', 'val']:
print(data_type)
for ind in indices[data_type]:
group_items[data_type].append({k: np.array(v, dtype=np.float16) \
for k, v in f[str(ind)].items()})
for data_type in ['train', 'val']:
print(data_type)
with h5py.File('{}bert_da_{}_{}_{}.h5'.format(data_folder, answer_type, data_type, size_type), 'w') as f:
for ind in range(len(group_items[data_type])):
group = f.create_group(str(ind))
for k, v in group_items[data_type][ind].items():
group.create_dataset(k, data=v)
for answer_type in answer_types:
print(answer_type)
create_embedding_split(answer_type, size_type, indices)
print()
data_folder = '../../data/'
answer_type = 'answer'
group_items1 = {'train': [], 'val': []}
for data_type in ['train', 'val']:
with h5py.File('{}bert_da_{}_{}_{}2.h5'.format(data_folder, answer_type, data_type, size_type), 'r') as f:
group_items1[data_type].append({k: np.array(v, dtype=np.float16) \
for k, v in f[str(0)].items()})
group_items2 = {'train': [], 'val': []}
with h5py.File('{}bert_da_{}_train_orig.h5'.format(data_folder, answer_type), 'r') as f:
for data_type in ['train', 'val']:
group_items2[data_type].append({k: np.array(v, dtype=np.float16) \
for k, v in f[str(indices[data_type][0])].items()})
for data_type in ['train', 'val']:
for k, v in group_items1[data_type][0].items():
assert np.all(v == group_items2[data_type][0][k])
```
| github_jupyter |
```
#import libraries
import gym
import numpy as np
import math
import tensorflow as tf
from matplotlib import pyplot as plt
from random import randint
from statistics import median, mean
env = gym.make('CartPole-v0')
no_states = env.observation_space.shape[0]
no_actions = env.action_space.n
#function to generate initial network parameters
def initial(run_test):
#initialize arrays
i_w = []
i_b = []
h_w = []
o_w = []
no_input_nodes = 8
no_hidden_nodes = 4
for r in range(run_test):
input_weight = np.random.rand(no_states, no_input_nodes)
input_bias = np.random.rand((no_input_nodes))
hidden_weight = np.random.rand(no_input_nodes,no_hidden_nodes)
output_weight = np.random.rand(no_hidden_nodes, no_actions)
i_w.append(input_weight)
i_b.append(input_bias)
h_w.append(hidden_weight)
o_w.append(output_weight)
chromosome =[i_w, i_b, h_w, o_w]
return chromosome
#function for deep neural network model
def nnmodel(observations, i_w, i_b, h_w, o_w):
alpha = 0.199
observations = observations/max(np.max(np.linalg.norm(observations)),1)
#apply relu on layers
funct1 = np.dot(observations, i_w)+ i_b.T
layer1= tf.nn.relu(funct1)-alpha*tf.nn.relu(-funct1)
funct2 = np.dot(layer1,h_w)
layer2 = tf.nn.relu(funct2) - alpha*tf.nn.relu(-funct2)
funct3 = np.dot(layer2, o_w)
layer3 = tf.nn.relu(funct3)-alpha*tf.nn.relu(-funct3)
#apply softmax
layer3 = np.exp(layer3)/np.sum(np.exp(layer3))
output = layer3.argsort().reshape(1,no_actions)
action = output[0][0]
return action
#function for getting the reward
def get_reward(env, i_w, i_b, h_w, o_w):
current_state = env.reset()
total_reward = 0
for step in range(300):
action = nnmodel(current_state, i_w, i_b, h_w, o_w)
next_state, reward, done, info = env.step(action)
total_reward += reward
current_state = next_state
if done:
break
return total_reward
#function for an initial run to get weights
def get_weights(env, run_test):
rewards = []
chromosomes = initial(run_test)
for trial in range(run_test):
i_w = chromosomes[0][trial]
i_b = chromosomes[1][trial]
h_w = chromosomes[2][trial]
o_w = chromosomes[3][trial]
total_reward = get_reward(env, i_w, i_b, h_w, o_w)
rewards = np.append(rewards, total_reward)
chromosome_weight = [chromosomes, rewards]
return chromosome_weight
#function for mutation:
def mutate(parent):
index = np.random.randint(0, len(parent))
if(0 < index < 10):
for idx in range(index):
n = np.random.randint(0, len(parent))
parent[n] = parent[n] + np.random.rand()
mutation = parent
return mutation
#function for cross-over
def crossover(list_chr):
gen_list = []
gen_list.append(list_chr[0])
gen_list.append(list_chr[1])
for i in range(10):
m = np.random.randint(0, len(list_chr[0]))
parent = np.append(list_chr[0][:m], list_chr[1][m:])
child = mutate(parent)
gen_list.append(child)
return gen_list
#function for a new generation of parameters
def generate_new_population(rewards, chromosomes):
#2 best reward indexes selected
best_reward_idx = rewards.argsort()[-2:][::-1]
list_chr = []
new_i_w =[]
new_i_b = []
new_h_w = []
new_o_w = []
new_rewards = []
#get current parameters
for ind in best_reward_idx:
weight1 = chromosomes[0][ind]
w1 = weight1.reshape(weight1.shape[1], -1)
bias1 = chromosomes[1][ind]
b1 = np.append(w1, bias1)
weight2 = chromosomes[2][ind]
w2 = np.append(b1, weight2.reshape(weight2.shape[1], -1))
weight3 = chromosomes[3][ind]
chr = np.append(w2, weight3)
#the 2 best parents are selected
list_chr.append(chr)
gen_list = crossover(list_chr)
for l in gen_list:
chromosome_w1 = np.array(l[:chromosomes[0][0].size])
new_input_weight = np.reshape(chromosome_w1,(-1,chromosomes[0][0].shape[1]))
new_input_bias = np.array([l[chromosome_w1.size:chromosome_w1.size+chromosomes[1][0].size]]).T
hidden = chromosome_w1.size + new_input_bias.size
chromosome_w2 = np.array([l[hidden:hidden + chromosomes[2][0].size]])
new_hidden_weight = np.reshape(chromosome_w2, (-1, chromosomes[2][0].shape[1]))
final = chromosome_w1.size+new_input_bias.size+chromosome_w2.size
new_output_weight = np.array([l[final:]]).T
new_output_weight = np.reshape(new_output_weight,(-1, chromosomes[3][0].shape[1]))
new_i_w.append(new_input_weight)
new_i_b.append(new_input_bias)
new_h_w.append(new_hidden_weight)
new_o_w.append(new_output_weight)
new_reward = get_reward(env, new_input_weight, new_input_bias, new_hidden_weight, new_output_weight)
new_rewards = np.append(new_rewards, new_reward)
generation = [new_i_w, new_i_b, new_h_w, new_o_w]
return generation, new_rewards
#function to print graphics
def graphics(act):
plt.plot(act)
plt.xlabel('No. of generations')
plt.ylabel('Rewards')
plt.grid()
print('Mean rewards:', mean(act))
return plt.show()
#run genetic algorithm
def ga_algo(env, run_test, no_gen):
weights = get_weights(env, run_test)
chrom = weights[0]
current_rewards = weights[1]
act = []
for n in range(no_gen):
gen, new_rewards = generate_new_population(current_rewards, chrom)
average = np.average(current_rewards)
new_average = np.average(new_rewards)
if average > new_average:
parameters = [chrom[0][0], chrom[1][0], chrom[2][0], chrom[3][0]]
else:
parameters = [gen[0][0], gen[1][0], gen[2][0], gen[3][0]]
chrom = gen
current_rewards = new_rewards
max_arg = np.amax(current_rewards)
print('Generation:{}, max reward:{}'.format(n+1, max_arg))
act = np.append(act, max_arg)
graphics(act)
return parameters
#function for outputting the initial parameters
def params(parameters):
i_w = parameters[0]
i_b = parameters[1]
h_w = parameters[2]
o_w = parameters[3]
return i_w,i_b,h_w,o_w
generations = []
no_gen = 50
run_test = 15
trial_length = 500
no_trials = 500
rewards = []
final_reward = 0
parameters = ga_algo(env, run_test, no_gen)
i_w, i_b, h_w, o_w = params(parameters)
for trial in range(no_trials):
current_state = env.reset()
total_reward = 0
for step in range(trial_length):
env.render()
action = nnmodel(current_state, i_w,i_b, h_w, o_w)
next_state,reward, done, info = env.step(action)
total_reward += reward
current_state = next_state
if done:
break
print('Trial:{}, total reward:{}'.format(trial, total_reward))
final_reward +=total_reward
print('Average reward:', final_reward/no_trials)
env.close()
```
| github_jupyter |
# Compound representation learning and property prediction
In this tuorial, we will go through how to run a Graph Neural Network (GNN) model for compound property prediction. In particular, we will demonstrate how to pretrain and finetune the model in the downstream tasks. If you are intersted in more details, please refer to the README for "[info graph](https://github.com/PaddlePaddle/PaddleHelix/apps/pretrained_compound/info_graph)" and "[pretrained GNN](https://github.com/PaddlePaddle/PaddleHelix/apps/pretrained_compound/pretrain_gnns)".
# Part I: Pretraining
In this part, we will show how to pretrain a compound GNN model. The pretraining skills here are adapted from the work of pretrain gnns, including attribute masking, context prediction and supervised pretraining.
Visit `pretrain_attrmask.py` and `pretrain_supervised.py` for more details.
```
import os
import numpy as np
import sys
sys.path.insert(0, os.getcwd() + "/..")
os.chdir("../apps/pretrained_compound/pretrain_gnns")
```
The Pahelix framework is build upon PaddlePaddle, which is a deep learning framework.
```
import paddle
import paddle.nn as nn
import pgl
from pahelix.model_zoo.pretrain_gnns_model import PretrainGNNModel, AttrmaskModel
from pahelix.datasets.zinc_dataset import load_zinc_dataset
from pahelix.utils.splitters import RandomSplitter
from pahelix.featurizers.pretrain_gnn_featurizer import AttrmaskTransformFn, AttrmaskCollateFn
from pahelix.utils import load_json_config
```
## Load configurations
Here, we use `compound_encoder_config`,`model_config` to hold the compound encoder and model configurations. `PretrainGNNModel` is the basic GNN Model used in pretrain gnns,`AttrmaskModel` is an unsupervised pretraining model which randomly masks the atom type of a node and then tries to predict the masked atom type. In the meanwhile, we use the Adam optimizer and set the learning rate to be 0.001.
```
compound_encoder_config = load_json_config("model_configs/pregnn_paper.json")
model_config = load_json_config("model_configs/pre_Attrmask.json")
compound_encoder = PretrainGNNModel(compound_encoder_config)
model = AttrmaskModel(model_config, compound_encoder)
opt = paddle.optimizer.Adam(0.001, parameters=model.parameters())
```
## Dataset loading and feature extraction
### Download the dataset using wget
First, we need to download a small dataset for this demo. If you do not have `wget` on your machine, you could also
copy the url below into your web browser to download the data. But remember to copy the data manually to the
path "../apps/pretrained_compound/pretrain_gnns/".
```
### Download a toy dataset for demonstration:
!wget "https://baidu-nlp.bj.bcebos.com/PaddleHelix%2Fdatasets%2Fcompound_datasets%2Fchem_dataset_small.tgz" --no-check-certificate
!tar -zxf "PaddleHelix%2Fdatasets%2Fcompound_datasets%2Fchem_dataset_small.tgz"
!ls "./chem_dataset_small"
### Download the full dataset as you want:
# !wget "http://snap.stanford.edu/gnn-pretrain/data/chem_dataset.zip" --no-check-certificate
# !unzip "chem_dataset.zip"
# !ls "./chem_dataset"
```
### Load the dataset and generate features
The Zinc dataset is used as the pretraining dataset.Here we use a toy dataset for demonstration,you can load the full dataset as you want.
`AttrmaskTransformFn` is used along with `AttrmaskModel`.It is used to generate features. The original features are processed into features available on the network, such as smiles strings into node and edge features.
```
### Load the first 1000 of the toy dataset for speed up
dataset = load_zinc_dataset("./chem_dataset_small/zinc_standard_agent/")
dataset = dataset[:1000]
print("dataset num: %s" % (len(dataset)))
transform_fn = AttrmaskTransformFn()
dataset.transform(transform_fn, num_workers=2)
```
## Start train
Now we train the attrmask model for 2 epochs for demostration purposes. Here we use `AttrmaskTransformFn` to aggregate multiple samples into a mini-batch.And the data loading process is accelerated with 4 processors.Then the pretrained model is saved to "./model/pretrain_attrmask", which will serve as the initial model of the downstream tasks.
```
def train(model, dataset, collate_fn, opt):
data_gen = dataset.get_data_loader(
batch_size=128,
num_workers=4,
shuffle=True,
collate_fn=collate_fn)
list_loss = []
model.train()
for graphs, masked_node_indice, masked_node_label in data_gen:
graphs = graphs.tensor()
masked_node_indice = paddle.to_tensor(masked_node_indice, 'int64')
masked_node_label = paddle.to_tensor(masked_node_label, 'int64')
loss = model(graphs, masked_node_indice, masked_node_label)
loss.backward()
opt.step()
opt.clear_grad()
list_loss.append(loss.numpy())
return np.mean(list_loss)
collate_fn = AttrmaskCollateFn(
atom_names=compound_encoder_config['atom_names'],
bond_names=compound_encoder_config['bond_names'],
mask_ratio=0.15)
for epoch_id in range(2):
train_loss = train(model, dataset, collate_fn, opt)
print("epoch:%d train/loss:%s" % (epoch_id, train_loss))
paddle.save(compound_encoder.state_dict(),
'./model/pretrain_attrmask/compound_encoder.pdparams')
```
The above is about the pretraining steps,you can adjust as needed.
# Part II: Downstream finetuning
Below we will introduce how to use the pretrained model for the finetuning of downstream tasks.
Visit `finetune.py` for more details.
```
from pahelix.utils.splitters import \
RandomSplitter, IndexSplitter, ScaffoldSplitter
from pahelix.datasets import *
from src.model import DownstreamModel
from src.featurizer import DownstreamTransformFn, DownstreamCollateFn
from src.utils import calc_rocauc_score, exempt_parameters
```
The downstream datasets are usually small and have different tasks. For example, the BBBP dataset is used for the predictions of the Blood-brain barrier permeability. The Tox21 dataset is used for the predictions of toxicity of compounds. Here we use the Tox21 dataset for demonstrations.
```
task_names = get_default_tox21_task_names()
print(task_names)
```
## Load configurations
Here, we use `compound_encoder_config` and `model_config` to hold the model configurations. Note that the configurations of the model architecture should align with that of the pretraining model, otherwise the loading will fail.
`DownstreamModel` is an supervised GNN model which predicts the tasks shown in `task_names`. Meanwhile, we use BCEloss as the criterion,Adam optimizer and set the lr to be 0.001.
```
compound_encoder_config = load_json_config("model_configs/pregnn_paper.json")
model_config = load_json_config("model_configs/down_linear.json")
model_config['num_tasks'] = len(task_names)
compound_encoder = PretrainGNNModel(compound_encoder_config)
model = DownstreamModel(model_config, compound_encoder)
criterion = nn.BCELoss(reduction='none')
opt = paddle.optimizer.Adam(0.001, parameters=model.parameters())
```
## Load pretrained models
Load the pretrained model in the pretraining phase. Here we load the model "pretrain_attrmask" as an example.
```
compound_encoder.set_state_dict(paddle.load('./model/pretrain_attrmask/compound_encoder.pdparams'))
```
## Dataset loading and feature extraction
`DownstreamTransformFn` is used along with `DownstreamModel`.It is used to generate features. The original features are processed into features available on the network, such as smiles strings into node and edge features.
The Tox21 dataset is used as the downstream dataset and we use `ScaffoldSplitter` to split the dataset into train/valid/test set. `ScaffoldSplitter` will firstly order the compounds according to Bemis-Murcko scaffold, then take the first `frac_train` proportion as the train set, the next `frac_valid` proportion as the valid set and the rest as the test set. `ScaffoldSplitter` can better evaluate the generalization ability of the model on out-of-distribution samples. Note that other splitters like `RandomSplitter`, `RandomScaffoldSplitter` and `IndexSplitter` is also available.
```
### Load the toy dataset:
dataset = load_tox21_dataset("./chem_dataset_small/tox21", task_names)
### Load the full dataset:
# dataset = load_tox21_dataset("./chem_dataset/tox21", task_names)
dataset.transform(DownstreamTransformFn(), num_workers=4)
# splitter = RandomSplitter()
splitter = ScaffoldSplitter()
train_dataset, valid_dataset, test_dataset = splitter.split(
dataset, frac_train=0.8, frac_valid=0.1, frac_test=0.1)
print("Train/Valid/Test num: %s/%s/%s" % (
len(train_dataset), len(valid_dataset), len(test_dataset)))
```
## Start train
Now we train the attrmask model for 4 epochs for demostration purposes.Here we use `DownstreamCollateFn` to aggregate multiple samples data into a mini-batch. Since each downstream task will contain more than one sub-task, the performance of the model is evaluated by the average roc-auc on all sub-tasks.
```
def train(model, train_dataset, collate_fn, criterion, opt):
data_gen = train_dataset.get_data_loader(
batch_size=128,
num_workers=4,
shuffle=True,
collate_fn=collate_fn)
list_loss = []
model.train()
for graphs, valids, labels in data_gen:
graphs = graphs.tensor()
labels = paddle.to_tensor(labels, 'float32')
valids = paddle.to_tensor(valids, 'float32')
preds = model(graphs)
loss = criterion(preds, labels)
loss = paddle.sum(loss * valids) / paddle.sum(valids)
loss.backward()
opt.step()
opt.clear_grad()
list_loss.append(loss.numpy())
return np.mean(list_loss)
def evaluate(model, test_dataset, collate_fn):
data_gen = test_dataset.get_data_loader(
batch_size=128,
num_workers=4,
shuffle=False,
collate_fn=collate_fn)
total_pred = []
total_label = []
total_valid = []
model.eval()
for graphs, valids, labels in data_gen:
graphs = graphs.tensor()
labels = paddle.to_tensor(labels, 'float32')
valids = paddle.to_tensor(valids, 'float32')
preds = model(graphs)
total_pred.append(preds.numpy())
total_valid.append(valids.numpy())
total_label.append(labels.numpy())
total_pred = np.concatenate(total_pred, 0)
total_label = np.concatenate(total_label, 0)
total_valid = np.concatenate(total_valid, 0)
return calc_rocauc_score(total_label, total_pred, total_valid)
collate_fn = DownstreamCollateFn(
atom_names=compound_encoder_config['atom_names'],
bond_names=compound_encoder_config['bond_names'])
for epoch_id in range(4):
train_loss = train(model, train_dataset, collate_fn, criterion, opt)
val_auc = evaluate(model, valid_dataset, collate_fn)
test_auc = evaluate(model, test_dataset, collate_fn)
print("epoch:%s train/loss:%s" % (epoch_id, train_loss))
print("epoch:%s val/auc:%s" % (epoch_id, val_auc))
print("epoch:%s test/auc:%s" % (epoch_id, test_auc))
paddle.save(model.state_dict(), './model/tox21/model.pdparams')
```
# Part III: Downstream Inference
In this part, we will briefly introduce how to use the trained downstream model to do inference on the given SMILES sequences.
## Load configurations
This part is the basically the same as the part II.
```
compound_encoder_config = load_json_config("model_configs/pregnn_paper.json")
model_config = load_json_config("model_configs/down_linear.json")
model_config['num_tasks'] = len(task_names)
compound_encoder = PretrainGNNModel(compound_encoder_config)
model = DownstreamModel(model_config, compound_encoder)
```
## Load finetuned models
Load the finetuned model from part II.
```
model.set_state_dict(paddle.load('./model/tox21/model.pdparams'))
```
## Start Inference
Do inference on the given SMILES sequence. We use directly call `DownstreamTransformFn` and `DownstreamCollateFn` to convert the raw SMILES sequence to the model input.
Using Tox21 dataset as an example, our finetuned downstream model can make predictions over 12 sub-tasks on Tox21.
```
SMILES="O=C1c2ccccc2C(=O)C1c1ccc2cc(S(=O)(=O)[O-])cc(S(=O)(=O)[O-])c2n1"
transform_fn = DownstreamTransformFn(is_inference=True)
collate_fn = DownstreamCollateFn(
atom_names=compound_encoder_config['atom_names'],
bond_names=compound_encoder_config['bond_names'],
is_inference=True)
graph = collate_fn([transform_fn({'smiles': SMILES})])
preds = model(graph.tensor()).numpy()[0]
print('SMILES:%s' % SMILES)
print('Predictions:')
for name, prob in zip(task_names, preds):
print(" %s:\t%s" % (name, prob))
```
| github_jupyter |
# Differential equations (symbolic)
This workbook uses symbolic computation to investigate the solutions of linear differential equations.
## First-order system
We consider a system governed by the differential equation
$$y(t) + RC \frac{dy(t)}{dt} = x(t)$$
where $x(t)$ is the input and $y(t)$ the output. We want to find the step response of this system, or in other words the output of the system when the input is the unit step $x(t) = u(t)$.
## Basic code functionality
The cell below sets up the environment for symbolic computation. The rest sets up the `display` function for a symbolic expression to make pretty output.
```
import sympy as sp
from IPython.display import display
sp.init_printing() # pretty printing
```
We define `imp` as the Dirac delta or unit impulse $\delta(t)$, and `ustep` as the unit (or Heaviside) step function. When the unit step is differentiated we get the unit impulse.
```
# Define impulse and unit step as functions of t
t = sp.symbols('t');
imp = sp.DiracDelta(t);
ustep = sp.Heaviside(t);
#ustep = sp.Piecewise( (0, t<1), (1, True)); # diff() doesn't give delta function?!
# Derivative of step is impulse
display(ustep);
display(sp.diff(ustep, t)); # derivative is dirac delta
#sp.plot(ustep, (t,-4,4)); # sympy plot() not numpy plot()!
```
The next block sets up variables and defines the differential equation. The `print` function on the symbolic expression gives the code representation of the relation, while `display` renders the result in a human friendly form.
```
# Setup differential equation
x = sp.Function('x'); y = sp.Function('y');
RC = sp.symbols('RC');#, real=True);
lp1de = sp.Eq(y(t) + RC*sp.diff(y(t), t), x(t));
print(lp1de); display(lp1de);
```
We can solve the differential equation for $y(t)$. Note the result has an undetermined symbolic constant $C_1$ in the expression. We will need to set its value based on an auxiliary constraint.
```
# Generic solution
y_sl0e = sp.dsolve(lp1de, y(t));
y_sl0r = y_sl0e.rhs # take only right hand side
display(y_sl0e); #display(y_sl0r);
```
To use the symbolic expresion above requirest specifying the value $C_1$. The code below defines an equation for the initial value constraint of the form $y(-1) = a_0$, where $a_0$ is a symbolic variable.
```
# Initial condition
a0 = sp.symbols('a0');
cnd1 = sp.Eq(y_sl0r.subs(t, -1), a0); # y(-1) = a0
#cnd2 = sy.Eq(y_sl0.diff(t).subs(t, 0), b0) # y'(0) = b0
print(cnd1); display(cnd1);
```
We want to solve the above expression for $C_1$ so that we can substitute back into our generic solution. The result is returned in a form useful later.
```
# Solve for C1: magic brackets in solve() returns result as dictionary
C1 = sp.symbols('C1') # generic constants
C1_sl = sp.solve([cnd1], (C1))
print(C1_sl); display(C1_sl);
```
Substituting the expression obtained into the generic solution gives the solution expressed in terms of the initial value $a_0$ based on the constraint $y(-1) = a_0$.
```
# Substitute back for solution in terms of a0
y_sl1 = y_sl0r.subs(C1_sl);
display(sp.Eq(y(t), y_sl1))
```
At this stage we're ready to substitute values and evaluate. This problem specified requires the step response, where the onset of the step occurs at $t=0$. We consider the case where the system was quiet before the step arrived, or an *initial rest* condition, so that $y(t)=0$ for $t<0$. This constraint meanst hat $y(-1) = 0$, so specifying $a_0=0$ for the constraint equation is appropriate. A value of $RC = 1$ is also assumed.
```
# Set values for constants
y_sl1s = y_sl1.subs({RC:1,a0:0}).doit()
display(sp.Eq(y(t), y_sl1s))
```
Finally we can make the substitution $x(t) = u(t)$ and evaluate the result. This provides the output of the system when the input is the unit step, and is thus the required step response.
```
# Set input function and solve
y_sl1sx = y_sl1s.subs({x(t):ustep}).doit()
print(sp.Eq(y(t), y_sl1sx)); display(sp.Eq(y(t), y_sl1sx))
sp.plot(y_sl1sx, (t,-4,8))
```
## Code
The script below combines all the steps above to find and plot the step response.
```
%run src/labX_preamble.py # For internal notebook functions
%%writefileexec src/lab_symdiffeq-1.py -s # dump cell to file before execute
import sympy as sp
from IPython.display import display
sp.init_printing() # pretty printing
# Define impulse and unit step as functions of t
t = sp.symbols('t');
imp = sp.DiracDelta(t);
ustep = sp.Heaviside(t);
#ustep = sp.Piecewise( (0, t<1), (1, True)); # diff() doesn't give delta function?!
# Setup differential equation
x = sp.Function('x'); y = sp.Function('y');
RC = sp.symbols('RC');#, real=True);
lp1de = sp.Eq(y(t) + RC*sp.diff(y(t), t), x(t));
#print(lp1de); display(lp1de);
# Generic solution
y_sl0e = sp.dsolve(lp1de, y(t));
y_sl0r = y_sl0e.rhs # take only right hand side
#print(y_sl0e); display(y_sl0e);
# Initial condition
a0 = sp.symbols('a0');
cnd1 = sp.Eq(y_sl0r.subs(t, -1), a0); # y(-1) = a0
#cnd2 = sp.Eq(y_sl0r.diff(t).subs(t, -1), b0) # y'(-1) = b0
#print(cnd1); display(cnd1);
# Solve for C1: magic brackets in solve() returns result as dictionary
C1 = sp.symbols('C1') # generic constants
C1_sl = sp.solve([cnd1], (C1))
#C1C2_sl = sp.solve([cnd1, cnd2], (C1, C2))
#print(C1_sl); display(C1_sl);
# Substitute back for solution in terms of a0
y_sl1 = y_sl0r.subs(C1_sl);
#print(sp.Eq(y(t), y_sl1)); display(sp.Eq(y(t), y_sl1));
# Set values for constants
y_sl1s = y_sl1.subs({RC:1,a0:0}).doit()
#print(sp.Eq(y(t), y_sl1s)); display(sp.Eq(y(t), y_sl1s));
# Set input function and solve
y_sl1sx = y_sl1s.subs({x(t):ustep}).doit()
print(sp.Eq(y(t), y_sl1sx)); display(sp.Eq(y(t), y_sl1sx))
# Plot output
sp.plot(y_sl1sx, (t,-4,8))
```
# Tasks
These tasks involve writing code, or modifying existing code, to meet the objectives described.
1. Find and plot the impulse responses of the first-order lowpass circuit for $RC = 1, 2, 4$ on the same set of axes and over the range $-4$ to 12.<br>
<br>
You should observe that the system reaches $1/e \approx 0.368$ of its initial value after time $\tau = RC$ has passed. This is called the *time constant* or sometimes the *RC time constant*$ of the circuit. A long time constant means that the circuit is slow to respond to changes, and involves a higher degree of lowpass filtering.<br><br>
2. Any linear constant coefficient differential equation corresponds to a linear time invariant system. Thus
$$y(t) - 0.1 \frac{dy(t)}{dt} = x(t)$$
is a valid system. It happens to correspond to a value of $RC=-0.1$ in the formulation above, so all the mathematics applies, although the system cannot be implemented with any real resistor and capacitor combination. Find the step response of this system under initial rest conditions, and plot it over the range $t=-4$ to $t=12$.<br>
<br>
In this case the differential equation corresponds to an unstable system: a bounded input can produce an unbounded output.<br><br>
3. The RLC circuit

is governed by the second-order differential equation
$$y(t) + \frac{L}{R} y'(t) + LC y''(t) = \frac{L}{R} x'(t).$$
On the same set of axes find and plot the step responses of the circuit over the range $t=-4$ to $t=12$ for $L=C=1$ and the cases $R=1/4$, $R=1/2$, and $R=1$. Use the auxiliary condition $y(-1)=0$ as before, along with the additional condition $y'(-1)=0$.<br>
<br>
The quantity $\omega_0 = 1/\sqrt{LC}$ is the *resonant frequency* of the system and $\alpha = 1/(2RC)$ is the *damping attenuation*. The three cases above respectively correspond to $\alpha>\omega_0$ (overdamped), $\alpha=\omega_0$ (critically damped), and $\alpha<\omega_0$ (underdamped).
| github_jupyter |
# Elliptical Trap Simulation
```
import numpy as np
import matplotlib.pyplot as plt
import src.analysis as src
from multiprocessing import Process, Queue
import pandas as pd
import time
from tqdm import tqdm
plt.gcf().subplots_adjust(bottom=0.15)
%load_ext autoreload
%autoreload 2
```
### 10 Particles
```
conf = src.config()
cutoff = 500
conf["directory"] = "elliptical_10_interacting"
conf["threads"] = 12
conf["numPart"] = 10
conf["numDim"] = 3
conf["numSteps"] = 2**20 + cutoff
conf["stepLength"] = 0.5
conf["importanceSampling"] = 1
conf["alpha"] = 0.5
conf["a"] = 0.0043
conf["InitialState"] = "HardshellInitial"
conf["Wavefunction"] = "EllipticalHardshellWavefunction"
conf["Hamiltonian"] = "EllipticalOscillator"
```
#### Gradient decent
```
mu = 0.01
for i in range(5):
src.runner(conf)
localEnergies, _, psiGrad, acceptanceRate = src.readData(conf)
gradient = src.calculateGradient(localEnergies, psiGrad)
conf["alpha"] -= mu*gradient
print(f"gradient: {gradient:.5f}. alpha: {conf['alpha']:.5f}. acceptance rate: {acceptanceRate[0]:.5f}.")
```
#### Using optimal alpha
```
conf["numSteps"] = 2**20 + cutoff
conf["alpha"] = 0.49752
src.runner(conf, verbose = True)
localEnergies, _, psiGrad, acceptanceRate = src.readData(conf, cutoff, readPos = False)
localEnergies = np.concatenate(localEnergies)
bins = np.linspace(0, 3, 200)
densityInteracting_10 = src.densityParallel(conf, bins)/conf["numSteps"]
conf["directory"] = "elliptical_10_noninteracting"
conf["a"] = 0
src.runner(conf, verbose = True)
bins = np.linspace(0, 3, 200)
densityNonInteracting = src.densityParallel(conf, bins)/conf["numSteps"]
```
#### Estimation of energy and uncertainty
```
E = np.mean(localEnergies)
Var = src.blocking(localEnergies, 18)
plt.plot(Var)
plt.show()
print(f"<E> = {E} +- {np.sqrt(Var[9])}")
```
#### Radial onebody density
```
fig = plt.figure()
plt.plot(bins, densityNonInteracting)
plt.plot(bins, densityInteracting_10, "--")
plt.xlabel("R")
plt.ylabel("number of particles per R")
plt.grid()
plt.show()
fig.savefig("figures/density10.pdf", bbox_inches = "tight")
```
### 50 particles
```
conf = src.config()
cutoff = 2000
conf["threads"] = 12
conf["numPart"] = 50
conf["numDim"] = 3
conf["numSteps"] = 2**20 + cutoff
conf["stepLength"] = 0.5
conf["importanceSampling"] = 1
conf["alpha"] = 0.49752
conf["a"] = 0.0043
conf["InitialState"] = "HardshellInitial"
conf["Wavefunction"] = "EllipticalHardshellWavefunction"
conf["Hamiltonian"] = "EllipticalOscillator"
mu = 0.001
for i in range(5):
src.runner(conf)
localEnergies, _, psiGrad, acceptanceRate = src.readData(conf, cutoff, readPos = False)
gradient = src.calculateGradient(localEnergies, psiGrad)
conf["alpha"] -= mu*gradient
print(f"gradient: {gradient:.5f}. alpha: {conf['alpha']:.5f}. acceptance rate: {acceptanceRate[0]:.5f}.")
```
#### Using optimal alpha
```
conf["directory"] = "elliptical_50_interacting"
conf["alpha"] = 0.48903
src.runner(conf, verbose = True)
localEnergies, _, psiGrad, acceptanceRate = src.readData(conf, cutoff, readPos = False)
localEnergies = np.concatenate(localEnergies)
bins = np.linspace(0, 3, 200)
conf["threads"] = 6 #downscale, to avoid using too much memory
densityInteracting_50 = src.densityParallel(conf, bins)/conf["numSteps"]
conf["directory"] = "elliptical_50_noninteracting"
conf["alpha"] = 0.48903
conf["a"] = 0
src.runner(conf, verbose = True)
bins = np.linspace(0, 3, 200)
densityNonInteracting = src.densityParallel(conf, bins)/conf["numSteps"]
```
#### Estimation of energy and uncertainty
```
E = np.mean(localEnergies)
Var = src.blocking(localEnergies, 18)
plt.plot(Var)
plt.show()
print(f"<E> = {E} +- {np.sqrt(Var[13])}")
```
#### Radial onebody density
```
fig = plt.figure()
plt.plot(bins, densityNonInteracting)
plt.plot(bins, densityInteracting_50, "--")
plt.xlabel("R")
plt.ylabel("number of particles per R")
plt.grid()
plt.show()
fig.savefig("figures/density50.pdf", bbox_inches = "tight")
```
### 100 Particles
```
conf = src.config()
cutoff = 2000
conf["threads"] = 12
conf["numPart"] = 100
conf["numDim"] = 3
conf["numSteps"] = 2**20 + cutoff
conf["stepLength"] = 0.5
conf["importanceSampling"] = 1
conf["alpha"] = 0.48903
conf["a"] = 0.0043
conf["InitialState"] = "HardshellInitial"
conf["Wavefunction"] = "EllipticalHardshellWavefunction"
conf["Hamiltonian"] = "EllipticalOscillator"
mu = 0.001
for i in range(5):
src.runner(conf)
localEnergies, _, psiGrad, acceptanceRate = src.readData(conf, cutoff, readPos = False)
gradient = src.calculateGradient(localEnergies, psiGrad)
conf["alpha"] -= mu*gradient
print(f"gradient: {gradient:.5f}. alpha: {conf['alpha']:.5f}. acceptance rate: {acceptanceRate[0]:.5f}.")
```
#### Using optimal alpha
```
conf["directory"] = "elliptical_100_interacting"
conf["alpha"] = 0.48160
src.runner(conf, verbose = True)
localEnergies, _, psiGrad, acceptanceRate = src.readData(conf, cutoff, readPos = False)
localEnergies = np.concatenate(localEnergies)
bins = np.linspace(0, 3, 200)
conf["threads"] = 3 #downscale, to avoid using too much memory
densityInteracting_100 = src.densityParallel(conf, bins)/conf["numSteps"]
conf["directory"] = "elliptical_100_noninteracting"
conf["alpha"] = 0.48160
conf["a"] = 0
src.runner(conf, verbose = True)
bins = np.linspace(0, 3, 200)
densityNonInteracting = src.densityParallel(conf, bins)/conf["numSteps"]
```
#### Estiamtion of Energy and Uncertainty
```
E = np.mean(localEnergies)
Var = src.blocking(localEnergies, 18)
plt.plot(Var)
print(f"<E> = {E} +- {np.sqrt(Var[15])}")
```
#### Radial Onebody Density
```
fig = plt.figure()
plt.plot(bins, densityNonInteracting)
plt.plot(bins, densityInteracting_100, "--")
plt.xlabel("R")
plt.ylabel("number of particles per R")
plt.grid()
plt.show()
fig.savefig("figures/density100.pdf", bbox_inches = "tight")
fig = plt.figure()
plt.plot(bins, densityNonInteracting/10)
plt.plot(bins, densityInteracting_10/10)
plt.plot(bins, densityInteracting_50/50)
plt.plot(bins, densityInteracting_100/100)
plt.xlabel("R")
plt.ylabel("scaled number of particles per R")
plt.legend(["Non-interacting", "10 particles", "50 particles", "100 particles"])
plt.grid()
plt.show()
fig.savefig("figures/density_all.pdf", bbox_inches = "tight")
```
| github_jupyter |
```
# NOTE: PLEASE MAKE SURE YOU ARE RUNNING THIS IN A PYTHON3 ENVIRONMENT
import tensorflow as tf
print(tf.__version__)
# This is needed for the iterator over the data
# But not necessary if you have TF 2.0 installed
#!pip install tensorflow==2.0.0-beta0
tf.enable_eager_execution()
# !pip install -q tensorflow-datasets
import tensorflow_datasets as tfds
imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True)
import numpy as np
train_data, test_data = imdb['train'], imdb['test']
training_sentences = []
training_labels = []
testing_sentences = []
testing_labels = []
# str(s.tonumpy()) is needed in Python3 instead of just s.numpy()
for s,l in train_data:
training_sentences.append(str(s.numpy()))
training_labels.append(l.numpy())
for s,l in test_data:
testing_sentences.append(str(s.numpy()))
testing_labels.append(l.numpy())
training_labels_final = np.array(training_labels)
testing_labels_final = np.array(testing_labels)
vocab_size = 10000
embedding_dim = 16
max_length = 120
trunc_type='post'
oov_tok = "<OOV>"
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(training_sentences)
word_index = tokenizer.word_index
sequences = tokenizer.texts_to_sequences(training_sentences)
padded = pad_sequences(sequences,maxlen=max_length, truncating=trunc_type)
testing_sequences = tokenizer.texts_to_sequences(testing_sentences)
testing_padded = pad_sequences(testing_sequences,maxlen=max_length)
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
def decode_review(text):
return ' '.join([reverse_word_index.get(i, '?') for i in text])
print(decode_review(padded[1]))
print(training_sentences[1])
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Bidirectional(tf.keras.layers.GRU(32)),
tf.keras.layers.Dense(6, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
model.summary()
num_epochs = 50
history = model.fit(padded, training_labels_final, epochs=num_epochs, validation_data=(testing_padded, testing_labels_final))
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.plot(history.history['val_'+string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.legend([string, 'val_'+string])
plt.show()
plot_graphs(history, 'accuracy')
plot_graphs(history, 'loss')
# Model Definition with LSTM
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(6, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
model.summary()
# Model Definition with Conv1D
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Conv1D(128, 5, activation='relu'),
tf.keras.layers.GlobalAveragePooling1D(),
tf.keras.layers.Dense(6, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
model.summary()
```
| github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#largest-number-of-fans-and-blotches" data-toc-modified-id="largest-number-of-fans-and-blotches-1"><span class="toc-item-num">1 </span>largest number of fans and blotches</a></span></li><li><span><a href="#parameter_scan" data-toc-modified-id="parameter_scan-2"><span class="toc-item-num">2 </span>parameter_scan</a></span></li><li><span><a href="#pipeline-examples" data-toc-modified-id="pipeline-examples-3"><span class="toc-item-num">3 </span>pipeline examples</a></span></li><li><span><a href="#ROIs-map" data-toc-modified-id="ROIs-map-4"><span class="toc-item-num">4 </span>ROIs map</a></span></li></ul></div>
```
from planet4 import plotting, catalog_production
rm = catalog_production.ReleaseManager('v1.0b4')
fans = rm.read_fan_file()
blotches = rm.read_blotch_file()
cols = ['angle', 'distance', 'tile_id', 'marking_id',
'obsid', 'spread',
'l_s', 'map_scale', 'north_azimuth',
'PlanetographicLatitude',
'PositiveEast360Longitude']
fans.head()
fans[cols].rename(dict(PlanetographicLatitude='Latitude',
PositiveEast360Longitude='Longitude'),
axis=1).head()
fans.columns
fan_counts = fans.groupby('tile_id').size()
blotch_counts = blotches.groupby('tile_id').size()
ids = fan_counts[fan_counts > 4][fan_counts < 10].index
pure_fans = list(set(ids) - set(blotches.tile_id))
len(ids)
len(pure_fans)
rm.savefolder
%matplotlib ipympl
plt.close('all')
from ipywidgets import interact
id_ = pure_fans[51]
def do_plot(i):
id_ = pure_fans[i]
plotting.plot_image_id_pipeline(id_, datapath=rm.savefolder, via_obsid=False,
save=True, figsize=(8,4),
saveroot='/Users/klay6683/Dropbox/src/p4_paper1/figures')
interact(do_plot, i=48)
from planet4 import markings
def do_plot(i=0):
plt.close('all')
fig, ax = plt.subplots()
markings.ImageID(pure_fans[i]).show_subframe(ax=ax)
ax.set_title(pure_fans[i])
interact(do_plot, i=(0,len(pure_fans),1))
markings.ImageID('6n3').image_name
from planet4 import markings
markings.ImageID(pure_fans[15]).image_name
plotting.plot_raw_fans(id_)
plotting.plot_finals(id_, datapath=rm.savefolder)
```
# largest number of fans and blotches
```
g_id = fans.groupby('tile_id')
g_id.size().sort_values(ascending=False).head()
blotches.groupby('tile_id').size().sort_values(ascending=False).head()
plotting.plot_finals('6mr', datapath=rm.savefolder)
plotting.plot_finals('7t9', datapath=rm.savefolder)
```
# parameter_scan
```
from planet4 import dbscan
db = dbscan.DBScanner()
import seaborn as sns
sns.set_context('paper')
db.parameter_scan(id_, 'fan', [0.13, 0.2], [10, 20, 30], size_to_scan='small')
```
# pipeline examples
```
plotting.plot_image_id_pipeline('bk7', datapath=rm.savefolder, via_obsid=False,
save=True, figsize=(8,4), do_title=False,
saveroot='/Users/klay6683/Dropbox/src/p4_paper1/figures')
plotting.plot_image_id_pipeline('ops', datapath=rm.savefolder, via_obsid=False,
save=True, figsize=(8,4), do_title=False,
saveroot='/Users/klay6683/Dropbox/src/p4_paper1/figures')
plotting.plot_image_id_pipeline('b0t', datapath=rm.savefolder, via_obsid=False,
save=True, figsize=(8,4), do_title=False,
saveroot='/Users/klay6683/Dropbox/src/p4_paper1/figures')
```
# ROIs map
```
from astropy.table import Table
tab = Table.read('/Users/klay6683/Dropbox/src/p4_paper1/rois_table.tex')
rois = tab.to_pandas()
rois.drop(0, inplace=True)
rois.head()
rois.columns = ['Latitude', 'Longitude', 'Informal Name', '# Images (MY29)', '# Images (MY30)']
rois.head()
rois.to_csv('/Users/klay6683/Dropbox/data/planet4/p4_analysis/rois.csv')
```
| github_jupyter |
# Politics and Social Sciences - Session 5 and 6
In this notebook we are going to look into the results of US presidential elections and test the Benford's law.
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Read the data
url = 'https://raw.githubusercontent.com/warwickdatasciencesociety/beginners-python/master/session-six/subject_questions/data/president_county_candidate.csv'
votes_df = pd.read_csv(url)
votes_df.head()
```
The above table (technically a dataframe) contains the results of US presidential elections grouped by each state, county and candidate. From this data set we extract two lists of numbers:
`biden_votes` - a list of total votes for Biden. Each number represents the total number of votes for Biden in a county
`trump_votes` - a list of total votes for Trump. Each number represents the total number of votes for Biden in a county
```
biden_votes = votes_df[votes_df['candidate'] == 'Joe Biden'].total_votes.to_list()
trump_votes = votes_df[votes_df['candidate'] == 'Donald Trump'].total_votes.to_list()
```
## Benford's law
The law of anomalous numbers, or the first-digit law, is an observation about the frequency distribution of leading digits in many real-life sets of numerical data. The law states that in many naturally occurring collections of numbers, the leading digit is likely to be small. In sets that obey the law, the number 1 appears as the leading significant digit about 30% of the time, while 9 appears as the leading significant digit less than 5% of the time.
[<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Rozklad_benforda.svg/2560px-Rozklad_benforda.svg.png">](http://google.com.au/)
We would like to test if the 2020 elections data follows the Benford's distribution. The first step is to write a function which given a number returns its first digit. Define this funciton as `get_first_digit()`
```
def get_first_digit(x):
return int(str(x)[0])
```
Now we need to write another function `count_first_digits()` which will calculate the distribution of first digits.
The input for this function is a list of integers $[x_1, x_2, ....., x_n]$ The function should return a new list $[y_0, y_1, ..., y_9]$ such that for each $i\in{0, 1, ..., 9}$, $y_i$ is the count of $x's$ such that the first digit of $x$ is equal to $i$.
Example input: $ x = [123, 2343, 6535, 123, 456, 678]$
Expected output: $ y = [0, 2, 1, 0, 0, 0, 6, 0, 0, 0]$
In the input list there are 2 numbers whose first digit is 6, therefore $y[6] = 2$
**HINT**: define a counter list of length 10 with every entry initially set to 0. Iterate through the input list and for each number in this list find its first digit and then increase the corresponding value in the counter list by one.
```
def count_first_digits(votes_ls):
digit_counter = [0 for i in range(0,10)]
for x in votes_ls:
first_digit = get_first_digit(x)
digit_counter[first_digit] += 1
return digit_counter
```
Use the `count_first_digits()` function to calculate the distribution of first digits for Biden and Trump votes. The Benford's law does not take into considaration 0's hence, truncate the lists to delete the first entry (which corresponds to the number of 0 votes for a candidate)
```
biden_1digits_count = count_first_digits(biden_votes)[1:]
trump_1digits_count = count_first_digits(trump_votes)[1:]
```
Create a function `calculate_percentages` which given a list of numbers returns a new list whose entries are the values of the input list divided by the total sum of the input list's entries and multiplied by 100. Apply this function to the `biden_1digits_count` and `trump_1digits_count`.
```
def calculate_percentages(ls):
sum_ls = sum(ls)
percentage_ls = []
for i in range(0,len(ls)):
percentage_ls.append(ls[i]/sum_ls * 100)
return percentage_ls
biden_1digits_pc = calculate_percentages(biden_1digits_count)
trump_1digits_pc = calculate_percentages(biden_1digits_count)
```
Run the cell below to generate the plots for distribution of first digits of Biden's and Trump's votes and compare it against the theoretical Benfords law distribution.
```
from math import log10
# generate theoretical Benfords distribution
benford = [log10(1 + 1/i)*100 for i in range(1, 10)]
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize = (20,10))
ax1.bar(x = list(range(1,10)), height = biden_1digits_pc, color = 'C0')
ax2.bar(x = list(range(1,10)), height = trump_1digits_pc, color = 'C3')
ax3.bar(x = list(range(1,10)), height = benford, color = 'C2')
ax1.set_title("Distribution of counts of first digits \n for Biden's votes per county")
ax2.set_title("Distribution of counts of first digits \n for Trump's votes per county")
ax3.set_title("Theoretical distribution of first digits \n according to Benford's law")
ax1.set_xticks(list(range(1,10)))
ax2.set_xticks(list(range(1,10)))
ax3.set_xticks(list(range(1,10)))
fig.show()
```
By visual inspection of the distribution plots we could suspect that the first digits law is applies. (To make this statement more rigorous we should run statistical tests to reject or confirm our hypothesis).
## Second-digit Benford's law
Walter Mebane, a political scientist and statistician at the University of Michigan, was the first to apply the **second-digit** Benford's law-test in election forensics. Such analyses are considered a simple, though not foolproof, method of identifying irregularities in election results and helping to detect electoral fraud.
In analogy to the previous exercise we would like to inspect now the distribution of second digits in the election results. Start by writing a function which given a number (you may assume that it has more than than 1 digit) returns its second digit. Define this funciton as `get_second_digit()`
```
def get_second_digit(x):
return int(str(x)[1])
```
Similarily as before define a function `count_first_digits()`.
**HINT** before applying the `get_second_digit()` function you need to make sure that the number which is currently under consideration is at least 10. If not, then this number should be omitted in the calculations. (Make use of the control flow statements)
```
def count_first_digits(votes_ls):
digit_counter = [0 for i in range(0,10)]
for x in votes_ls:
if x < 10:
continue
else:
second_digit = get_second_digit(x)
digit_counter[second_digit] += 1
return digit_counter
```
Use the `count_second_digits()` function to calculate the distribution of first digits for Biden and Trump votes. (There is no need to disregard 0's in the case of second digits case). Next apply the `calculate_percentages` functions the newly created lists.
```
trump_2digits_count = count_first_digits(trump_votes)
biden_2digits_count = count_first_digits(biden_votes)
biden_2digits_pc = calculate_percentages(biden_2digits_count)
trump_2digits_pc = calculate_percentages(trump_2digits_count)
```
Run the cell below to generate the plots for distribution of second digits for Biden's and Trump's votes.
```
#theoretical distribution of Benford second digits
benford_2 = [12, 11.4, 10.9, 10.4, 10.0, 9.7, 9.3, 9.0, 8.8, 8.5]
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize = (20,10))
ax1.bar(x = list(range(0,10)), height = biden_2digits_pc, color = 'C0')
ax2.bar(x = list(range(0,10)), height = trump_2digits_pc, color = 'C3')
ax3.bar(x = list(range(0,10)), height = benford_2, color = 'C2')
ax1.set_title("Distribution of counts of second digits \n for Biden's votes per county")
ax2.set_title("Distribution of counts of second digits \n for Trump's votes per county")
ax3.set_title("Theoretical distribution of second digits \n according to Benford's law")
ax1.set_xticks(list(range(0,10)))
ax2.set_xticks(list(range(0,10)))
ax3.set_xticks(list(range(0,10)))
fig.show()
```
The distributions still seem to be fairly similar to the theoretical distribution of second digits according to Benford's law. The two tests did not produce any striking results, there are no signs of irregularity in the officially declared vote counts.
| github_jupyter |
# Introduction
## Getting started with Jupyter notebooks
The majority of your work in this course will be done using Jupyter notebooks so we will here introduce some of the basics of the notebook system. If you are already comfortable using notebooks or just would rather get on with some coding feel free to [skip straight to the exercises below](#Exercises).
*Note: Jupyter notebooks are also known as IPython notebooks. The Jupyter system now supports languages other than Python [hence the name was changed to make it more language agnostic](https://ipython.org/#jupyter-and-the-future-of-ipython) however IPython notebook is still commonly used.*
### Jupyter basics: the server, dashboard and kernels
In launching this notebook you will have already come across two of the other key components of the Jupyter system - the notebook *server* and *dashboard* interface.
We began by starting a notebook server instance in the terminal by running
```
jupyter notebook
```
This will have begun printing a series of log messages to terminal output similar to
```
$ jupyter notebook
[I 08:58:24.417 NotebookApp] Serving notebooks from local directory: ~/mlpractical
[I 08:58:24.417 NotebookApp] 0 active kernels
[I 08:58:24.417 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/
```
The last message included here indicates the URL the application is being served at. The default behaviour of the `jupyter notebook` command is to open a tab in a web browser pointing to this address after the server has started up. The server can be launched without opening a browser window by running `jupyter notebook --no-browser`. This can be useful for example when running a notebook server on a remote machine over SSH. Descriptions of various other command options can be found by displaying the command help page using
```
juptyer notebook --help
```
While the notebook server is running it will continue printing log messages to terminal it was started from. Unless you detach the process from the terminal session you will need to keep the session open to keep the notebook server alive. If you want to close down a running server instance from the terminal you can use `Ctrl+C` - this will bring up a confirmation message asking you to confirm you wish to shut the server down. You can either enter `y` or skip the confirmation by hitting `Ctrl+C` again.
When the notebook application first opens in your browser you are taken to the notebook *dashboard*. This will appear something like this
<img src='res/jupyter-dashboard.png' />
The dashboard above is showing the `Files` tab, a list of files in the directory the notebook server was launched from. We can navigate in to a sub-directory by clicking on a directory name and back up to the parent directory by clicking the `..` link. An important point to note is that the top-most level that you will be able to navigate to is the directory you run the server from. This is a security feature and generally you should try to limit the access the server has by launching it in the highest level directory which gives you access to all the files you need to work with.
As well as allowing you to launch existing notebooks, the `Files` tab of the dashboard also allows new notebooks to be created using the `New` drop-down on the right. It can also perform basic file-management tasks such as renaming and deleting files (select a file by checking the box alongside it to bring up a context menu toolbar).
In addition to opening notebook files, we can also edit text files such as `.py` source files, directly in the browser by opening them from the dashboard. The in-built text-editor is less-featured than a full IDE but is useful for quick edits of source files and previewing data files.
The `Running` tab of the dashboard gives a list of the currently running notebook instances. This can be useful to keep track of which notebooks are still running and to shutdown (or reopen) old notebook processes when the corresponding tab has been closed.
### The notebook interface
The top of your notebook window should appear something like this:
<img src='res/jupyter-notebook-interface.png' />
The name of the current notebook is displayed at the top of the page and can be edited by clicking on the text of the name. Displayed alongside this is an indication of the last manual *checkpoint* of the notebook file. On-going changes are auto-saved at regular intervals; the check-point mechanism is mainly meant as a way to recover an earlier version of a notebook after making unwanted changes. Note the default system only currently supports storing a single previous checkpoint despite the `Revert to checkpoint` dropdown under the `File` menu perhaps suggesting otherwise.
As well as having options to save and revert to checkpoints, the `File` menu also allows new notebooks to be created in same directory as the current notebook, a copy of the current notebook to be made and the ability to export the current notebook to various formats.
The `Edit` menu contains standard clipboard functions as well as options for reorganising notebook *cells*. Cells are the basic units of notebooks, and can contain formatted text like the one you are reading at the moment or runnable code as we will see below. The `Edit` and `Insert` drop down menus offer various options for moving cells around the notebook, merging and splitting cells and inserting new ones, while the `Cell` menu allow running of code cells and changing cell types.
The `Kernel` menu offers some useful commands for managing the Python process (kernel) running in the notebook. In particular it provides options for interrupting a busy kernel (useful for example if you realise you have set a slow code cell running with incorrect parameters) and to restart the current kernel. This will cause all variables currently defined in the workspace to be lost but may be necessary to get the kernel back to a consistent state after polluting the namespace with lots of global variables or when trying to run code from an updated module and `reload` is failing to work.
To the far right of the menu toolbar is a kernel status indicator. When a dark filled circle is shown this means the kernel is currently busy and any further code cell run commands will be queued to happen after the currently running cell has completed. An open status circle indicates the kernel is currently idle.
The final row of the top notebook interface is the notebook toolbar which contains shortcut buttons to some common commands such as clipboard actions and cell / kernel management. If you are interested in learning more about the notebook user interface you may wish to run through the `User Interface Tour` under the `Help` menu drop down.
### Markdown cells: easy text formatting
This entire introduction has been written in what is termed a *Markdown* cell of a notebook. [Markdown](https://en.wikipedia.org/wiki/Markdown) is a lightweight markup language intended to be readable in plain-text. As you may wish to use Markdown cells to keep your own formatted notes in notebooks, a small sampling of the formatting syntax available is below (escaped mark-up on top and corresponding rendered output below that); there are many much more extensive syntax guides - for example [this cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
---
```
## Level 2 heading
### Level 3 heading
*Italicised* and **bold** text.
* bulleted
* lists
and
1. enumerated
2. lists
Inline maths $y = mx + c$ using [MathJax](https://www.mathjax.org/) as well as display style
$$ ax^2 + bx + c = 0 \qquad \Rightarrow \qquad x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
```
---
## Level 2 heading
### Level 3 heading
*Italicised* and **bold** text.
* bulleted
* lists
and
1. enumerated
2. lists
Inline maths $y = mx + c$ using [MathJax]() as well as display maths
$$ ax^2 + bx + c = 0 \qquad \Rightarrow \qquad x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
---
We can also directly use HTML tags in Markdown cells to embed rich content such as images and videos.
---
```
<img src="http://placehold.it/350x150" />
```
---
<img src="http://placehold.it/350x150" />
---
### Code cells: in browser code execution
Up to now we have not seen any runnable code. An example of a executable code cell is below. To run it first click on the cell so that it is highlighted, then either click the <i class="fa-step-forward fa"></i> button on the notebook toolbar, go to `Cell > Run Cells` or use the keyboard shortcut `Ctrl+Enter`.
```
from __future__ import print_function
import sys
print('Hello world!')
print('Alarming hello!', file=sys.stderr)
print('Hello again!')
'And again!'
```
This example shows the three main components of a code cell.
The most obvious is the input area. This (unsuprisingly) is used to enter the code to be run which will be automatically syntax highlighted.
To the immediate left of the input area is the execution indicator / counter. Before a code cell is first run this will display `In [ ]:`. After the cell is run this is updated to `In [n]:` where `n` is a number corresponding to the current execution counter which is incremented whenever any code cell in the notebook is run. This can therefore be used to keep track of the relative order in which cells were last run. There is no fundamental requirement to run cells in the order they are organised in the notebook, though things will usually be more readable if you keep things in roughly in order!
Immediately below the input area is the output area. This shows any output produced by the code in the cell. This is dealt with a little bit confusingly in the current Jupyter version. At the top any output to [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) is displayed. Immediately below that output to [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_.28stderr.29) is displayed. All of the output to `stdout` is displayed together even if there has been output to `stderr` between as shown by the suprising ordering in the output here.
The final part of the output area is the *display* area. By default this will just display the returned output of the last Python statement as would usually be the case in a (I)Python interpreter run in a terminal. What is displayed for a particular object is by default determined by its special `__repr__` method e.g. for a string it is just the quote enclosed value of the string itself.
### Useful keyboard shortcuts
There are a wealth of keyboard shortcuts available in the notebook interface. For an exhaustive list see the `Keyboard Shortcuts` option under the `Help` menu. We will cover a few of those we find most useful below.
Shortcuts come in two flavours: those applicable in *command mode*, active when no cell is currently being edited and indicated by a blue highlight around the current cell; those applicable in *edit mode* when the content of a cell is being edited, indicated by a green current cell highlight.
In edit mode of a code cell, two of the more generically useful keyboard shortcuts are offered by the `Tab` key.
* Pressing `Tab` a single time while editing code will bring up suggested completions of what you have typed so far. This is done in a scope aware manner so for example typing `a` + `[Tab]` in a code cell will come up with a list of objects beginning with `a` in the current global namespace, while typing `np.a` + `[Tab]` (assuming `import numpy as np` has been run already) will bring up a list of objects in the root NumPy namespace beginning with `a`.
* Pressing `Shift+Tab` once immediately after opening parenthesis of a function or method will cause a tool-tip to appear with the function signature (including argument names and defaults) and its docstring. Pressing `Shift+Tab` twice in succession will cause an expanded version of the same tooltip to appear, useful for longer docstrings. Pressing `Shift+Tab` four times in succession will cause the information to be instead displayed in a pager docked to bottom of the notebook interface which stays attached even when making further edits to the code cell and so can be useful for keeping documentation visible when editing e.g. to help remember the name of arguments to a function and their purposes.
A series of useful shortcuts available in both command and edit mode are `[modifier]+Enter` where `[modifier]` is one of `Ctrl` (run selected cell), `Shift` (run selected cell and select next) or `Alt` (run selected cell and insert a new cell after).
A useful command mode shortcut to know about is the ability to toggle line numbers on and off for a cell by pressing `L` which can be useful when trying to diagnose stack traces printed when an exception is raised or when referring someone else to a section of code.
### Magics
There are a range of *magic* commands in IPython notebooks, than provide helpful tools outside of the usual Python syntax. A full list of the inbuilt magic commands is given [here](http://ipython.readthedocs.io/en/stable/interactive/magics.html), however three that are particularly useful for this course:
* [`%%timeit`](http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=matplotlib#magic-timeit) Put at the beginning of a cell to time its execution and print the resulting timing statistics.
* [`%precision`](http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=matplotlib#magic-precision) Set the precision for pretty printing of floating point values and NumPy arrays.
* [`%debug`](http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=matplotlib#magic-debug) Activates the interactive debugger in a cell. Run after an exception has been occured to help diagnose the issue.
### Plotting with `matplotlib`
When setting up your environment one of the dependencies we asked you to install was `matplotlib`. This is an extensive plotting and data visualisation library which is tightly integrated with NumPy and Jupyter notebooks.
When using `matplotlib` in a notebook you should first run the [magic command](http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=matplotlib)
```
%matplotlib inline
```
This will cause all plots to be automatically displayed as images in the output area of the cell they are created in. Below we give a toy example of plotting two sinusoids using `matplotlib` to show case some of the basic plot options. To see the output produced select the cell and then run it.
```
# use the matplotlib magic to specify to display plots inline in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# generate a pair of sinusoids
x = np.linspace(0., 2. * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# produce a new figure object with a defined (width, height) in inches
fig = plt.figure(figsize=(8, 4))
# add a single axis to the figure
ax = fig.add_subplot(111)
# plot the two sinusoidal traces on the axis, adjusting the line width
# and adding LaTeX legend labels
ax.plot(x, y1, linewidth=2, label=r'$\sin(x)$')
ax.plot(x, y2, linewidth=2, label=r'$\cos(x)$')
# set the axis labels
ax.set_xlabel('$x$', fontsize=16)
ax.set_ylabel('$y$', fontsize=16)
# force the legend to be displayed
ax.legend()
# adjust the limits of the horizontal axis
ax.set_xlim(0., 2. * np.pi)
# make a grid be displayed in the axis background
ax.grid('on')
```
# Exercises
Today's exercises are meant to allow you to get some initial familiarisation with the `mlp` package and how data is provided to the learning functions. Next week onwards, we will follow with the material covered in lectures.
If you are new to Python and/or NumPy and are struggling to complete the exercises, you may find going through [this Stanford University tutorial](http://cs231n.github.io/python-numpy-tutorial/) by [Justin Johnson](http://cs.stanford.edu/people/jcjohns/) first helps. There is also a derived Jupyter notebook by [Volodymyr Kuleshov](http://web.stanford.edu/~kuleshov/) and [Isaac Caswell](https://symsys.stanford.edu/viewing/symsysaffiliate/21335) which you can download [from here](https://github.com/kuleshov/cs228-material/raw/master/tutorials/python/cs228-python-tutorial.ipynb) - if you save this in to your `mlpractical/notebooks` directory you should be able to open the notebook from the dashboard to run the examples.
## Data providers
Open (in the browser) the [`mlp.data_providers`](../../edit/mlp/data_providers.py) module. Have a look through the code and comments, then follow to the exercises.
### Exercise 1
The `MNISTDataProvider` iterates over input images and target classes (digit IDs) from the [MNIST database of handwritten digit images](http://yann.lecun.com/exdb/mnist/), a common supervised learning benchmark task. Using the data provider and `matplotlib` we can for example iterate over the first couple of images in the dataset and display them using the following code:
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import mlp.data_providers as data_providers
def show_single_image(img, fig_size=(2, 2)):
fig = plt.figure(figsize=fig_size)
ax = fig.add_subplot(111)
ax.imshow(img, cmap='Greys')
ax.axis('off')
plt.show()
return fig, ax
# An example for a single MNIST image
mnist_dp = data_providers.MNISTDataProvider(
which_set='valid', batch_size=1, max_num_batches=2, shuffle_order=True)
for inputs, target in mnist_dp:
show_single_image(inputs.reshape((28, 28)))
print('Image target: {0}'.format(target))
```
Generally we will want to deal with batches of multiple images i.e. `batch_size > 1`. As a first task:
* Using MNISTDataProvider, write code that iterates over the first 5 minibatches of size 100 data-points.
* Display each batch of MNIST digits in a $10\times10$ grid of images.
**Notes**:
* Images are returned from the provider as tuples of numpy arrays `(inputs, targets)`. The `inputs` matrix has shape `(batch_size, input_dim)` while the `targets` array is of shape `(batch_size,)`, where `batch_size` is the number of data points in a single batch and `input_dim` is dimensionality of the input features.
* Each input data-point (image) is stored as a 784 dimensional vector of pixel intensities normalised to $[0, 1]$ from inital integer values in $[0, 255]$. However, the original spatial domain is two dimensional, so before plotting you will need to reshape the one dimensional input arrays in to two dimensional arrays 2D (MNIST images have the same height and width dimensions).
```
def show_batch_of_images(img_batch, fig_size=(3, 3)):
fig = plt.figure(figsize=fig_size)
batch_size, im_height, im_width = img_batch.shape
# calculate no. columns per grid row to give square grid
grid_size = int(batch_size**0.5)
# intialise empty array to tile image grid into
tiled = np.empty((im_height * grid_size,
im_width * batch_size // grid_size))
# iterate over images in batch + indexes within batch
for i, img in enumerate(img_batch):
# calculate grid row and column indices
r, c = i % grid_size, i // grid_size
tiled[r * im_height:(r + 1) * im_height,
c * im_height:(c + 1) * im_height] = img
ax = fig.add_subplot(111)
ax.imshow(tiled, cmap='Greys')
ax.axis('off')
fig.tight_layout()
plt.show()
return fig, ax
batch_size = 100
num_batches = 5
mnist_dp = data_providers.MNISTDataProvider(
which_set='valid', batch_size=batch_size,
max_num_batches=num_batches, shuffle_order=True)
for inputs, target in mnist_dp:
# reshape inputs from batch of vectors to batch of 2D arrays (images)
_ = show_batch_of_images(inputs.reshape((batch_size, 28, 28)))
```
### Exercise 2
`MNISTDataProvider` as `targets` currently returns a vector of integers, each element in this vector represents an the integer ID of the class the corresponding data-point represents.
For training of neural networks a 1-of-K representation of multi-class targets is more useful. Instead of representing class identity by an integer ID, for each data point a vector of length equal to the number of classes is created, will all elements zero except for the element corresponding to the class ID.
For instance, given a batch of 5 integer targets `[2, 2, 0, 1, 0]` and assuming there are 3 different classes
the corresponding 1-of-K encoded targets would be
```
[[0, 0, 1],
[0, 0, 1],
[1, 0, 0],
[0, 1, 0],
[1, 0, 0]]
```
* Implement the `to_one_of_k` method of `MNISTDataProvider` class.
* Uncomment the overloaded `next` method, so the raw targets are converted to 1-of-K coding.
* Test your code by running the the cell below.
```
mnist_dp = data_providers.MNISTDataProvider(
which_set='valid', batch_size=5, max_num_batches=5, shuffle_order=False)
for inputs, targets in mnist_dp:
assert np.all(targets.sum(-1) == 1.)
assert np.all(targets >= 0.)
assert np.all(targets <= 1.)
print(targets)
```
### Exercise 3
Here you will write your own data provider `MetOfficeDataProvider` that wraps [weather data for south Scotland](http://www.metoffice.gov.uk/hadobs/hadukp/data/daily/HadSSP_daily_qc.txt). A previous version of this data has been stored in `data` directory for your convenience and skeleton code for the class provided in `mlp/data_providers.py`.
The data is organised in the text file as a table, with the first two columns indexing the year and month of the readings and the following 31 columns giving daily precipitation values for the corresponding month. As not all months have 31 days some of entries correspond to non-existing days. These values are indicated by a non-physical value of `-99.9`.
* You should read all of the data from the file ([`np.loadtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) may be useful for this) and then filter out the `-99.9` values and collapse the table to a one-dimensional array corresponding to a sequence of daily measurements for the whole period data is available for. [NumPy's boolean indexing feature](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays) could be helpful here.
* A common initial preprocessing step in machine learning tasks is to normalise data so that it has zero mean and a standard deviation of one. Normalise the data sequence so that its overall mean is zero and standard deviation one.
* Each data point in the data provider should correspond to a window of length specified in the `__init__` method as `window_size` of this contiguous data sequence, with the model inputs being the first `window_size - 1` elements of the window and the target output being the last element of the window. For example if the original data sequence was `[1, 2, 3, 4, 5, 6]` and `window_size=3` then `input, target` pairs iterated over by the data provider should be
```
[1, 2], 3
[4, 5], 6
```
* **Extension**: Have the data provider instead overlapping windows of the sequence so that more training data instances are produced. For example for the sequence `[1, 2, 3, 4, 5, 6]` the corresponding `input, target` pairs would be
```
[1, 2], 3
[2, 3], 4
[3, 4], 5
[4, 5], 6
```
* Test your code by running the cell below.
```
batch_size = 3
for window_size in [2, 5, 10]:
met_dp = data_providers.MetOfficeDataProvider(
window_size=window_size, batch_size=batch_size,
max_num_batches=1, shuffle_order=False)
fig = plt.figure(figsize=(6, 3))
ax = fig.add_subplot(111)
ax.set_title('Window size {0}'.format(window_size))
ax.set_xlabel('Day in window')
ax.set_ylabel('Normalised reading')
# iterate over data provider batches checking size and plotting
for inputs, targets in met_dp:
assert inputs.shape == (batch_size, window_size - 1)
assert targets.shape == (batch_size, )
ax.plot(np.c_[inputs, targets].T, '.-')
ax.plot([window_size - 1] * batch_size, targets, 'ko')
```
| github_jupyter |

<a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=notebook-basics.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a>
# Hackathon Challenges and Resources
These are notebooks and other resources to use as challenges for Callysto hackathons or related events. You're also welcome to use them for other non-commercial purposes.
Notebooks in this branch were tested on [Callysto Hub](https://hub.callysto.ca).
### Callysto Hub Basics
Callysto Hub is a free Jupyter notebook environment provided by [Cybera](https://www.cybera.ca/) and [PIMS](https://www.pims.math.ca/), and it's available at [hub.callysto.ca](https://hub.callysto.ca).
In order to log in to Callysto use a Google or Microsoft account.
Hackathon notebooks can be automatically copied to the Callysto Hub by clicking the "Open in Callysto" button at the top of the notebook.
Alternatively, to copy them manually:
- select `New` -> `Terminal` in the top right corner
- in the terminal window type `git clone https://github.com/callysto/hackathon -b jupyter`

### Open Notebooks in Callysto Hub
To open the hackathon notebooks on the Callysto Hub:
- Click on Jupyter logo in the top left corner - it will redirect you to the home screen.
- Open the `hackathon` folder and double-click the folder or notebook you are planning to work on.

To get started select the `Tutorials` folder and work through the prepatory notebooks. We suggest this order:
1. `Markdown basics`
2. `Python and pandas basics solutions`
3. `Matplotlib basics`
4. `Cufflinks basics`
## Some Jupyter Notebook Basics
### Run cell
In order to run a cell, select the cell of interest then:
- select `Cell` -> `Run Cells`
- or hit `Shift-Enter`
- or click the `Run` button above

### Create new cell
In order to create a new cell:
- select `Insert` -> `Insert Cell Above` or `Insert Cell Below`
- click on plus button in the top left corner

### Delete cell
In order to delete the cell:
- select the cell you are planning to delete
- click `Edit` -> `Delete Cells`
- or click on scisors button in the top left corner

### Undo deleting cells
If you accidentally deleted an incorrect cell, you can always bring it back:
- select `Edit` -> `Undo Delete Cells`

### Download notebook
If you want to download the notebook in ipynb format to your local machine:
- save the notebook first:
- Click on `Save and checkpoint` button in the top left corner
- select `File` -> `Download as` ->`Notebook(.ipynb)`

[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
| github_jupyter |
```
input_ultrasound_fullname = 'numpy_data/Stacked Arrays/Training/stacked_image_array.npy'
input_segmentationo_fullname = 'numpy_data/Stacked Arrays/Training/stacked_segmentation_array.npy'
test_ultrasound_fullname = 'numpy_data/Stacked Arrays/Test/test_image_array.npy'
test_segmentation_fullname = 'numpy_data/Stacked Arrays/Test/test_segmentation_array.npy'
output_ultrasound_fullname = 'numpy_data/Stacked Arrays/Training/stacked_image_64.npy'
output_segmentation_fullname = 'numpy_data/Stacked Arrays/Training/stacked_segmentation_64.npy'
output_test_ultrasound_fullname = 'numpy_data/Stacked Arrays/Test/test_image_64.npy'
output_test_segmentation_fullname = 'numpy_data/Stacked Arrays/Test/test_segmentation_64.npy'
output_size = 64
import numpy as np
import os
from scipy.ndimage import zoom
ultrasound_data = np.load(input_ultrasound_fullname)
segmentation_data = np.load(input_segmentationo_fullname)
test_ultrasound_data = np.load(test_ultrasound_fullname)
test_segmentation_data = np.load(test_segmentation_fullname)
num_ultrasound = ultrasound_data.shape[0]
num_segmentation = segmentation_data.shape[0]
num_test_ultrasound = test_ultrasound_data.shape[0]
num_test_segmentation = test_segmentation_data.shape[0]
print("Input ultrasound data shape: {}".format(ultrasound_data.shape))
print("Input segmentation data shape: {}".format(segmentation_data.shape))
print("Test ultrasound data shape: {}".format(test_ultrasound_data.shape))
print("Test segmentation data shape: {}".format(test_segmentation_data.shape))
print("")
print("Intensity range in input ultrasound: {} -- {}".format(ultrasound_data.min(), ultrasound_data.max()))
print("Intensity range in input segmentation: {} -- {}".format(segmentation_data.min(), segmentation_data.max()))
x_scale = output_size / ultrasound_data.shape[1]
y_scale = output_size / ultrasound_data.shape[2]
z_scale = output_size / ultrasound_data.shape[3]
print("Resize factors: {}, {}, {}".format(x_scale, y_scale, z_scale))
ultrasound_data_resized = zoom(ultrasound_data, (1, x_scale, y_scale, z_scale, 1), order=1)
segmentation_data_resized = zoom(segmentation_data, (1, x_scale, y_scale, z_scale, 1), order=0)
test_ultrasound_data_resized = zoom(test_ultrasound_data, (1, x_scale, y_scale, z_scale, 1), order=1)
test_segmentation_data_resized = zoom(test_segmentation_data, (1, x_scale, y_scale, z_scale, 1), order=0)
print("Output ultrasound data shape: {}".format(ultrasound_data_resized.shape))
print("Output segmentation data shape: {}".format(segmentation_data_resized.shape))
print("Output test ultrasound data shape: {}".format(test_ultrasound_data_resized.shape))
print("Output test segmentation data shape: {}".format(test_segmentation_data_resized.shape))
print("")
print("Intensity range of resized ultrasound: {} -- {}".format(
ultrasound_data_resized.min(), ultrasound_data_resized.max()))
print("Intensity range of resized segmentation: {} -- {}".format(
segmentation_data_resized.min(), segmentation_data_resized.max()))
np.save(output_ultrasound_fullname, ultrasound_data_resized)
np.save(output_segmentation_fullname, segmentation_data_resized)
np.save(output_test_ultrasound_fullname, test_ultrasound_data_resized)
np.save(output_test_segmentation_fullname, test_segmentation_data_resized)
print("Ultrasound saved to {}".format(output_ultrasound_fullname))
print("Segmentation saved to {}".format(output_segmentation_fullname))
print("Test ultrasound saved to {}".format(output_test_ultrasound_fullname))
print("Test segmentation saved to {}".format(output_test_segmentation_fullname))
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# ビジュアルアテンションを用いた画像キャプショニング
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/text/image_captioning">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png" />
View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/tutorials/text/image_captioning.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/tutorials/text/image_captioning.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/tutorials/text/image_captioning.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポジトリ[tensorflow/docs](https://github.com/tensorflow/docs)にプルリクエストをお送りください。 コミュニティによる翻訳やレビューに参加していただける方は、 [docs-ja@tensorflow.org メーリングリスト](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ja)にご連絡ください。
下記のような画像をもとに、"a surfer riding on a wave" のようなキャプションを生成することをめざします。

_[画像ソース](https://commons.wikimedia.org/wiki/Surfing#/media/File:Surfing_in_Hawaii.jpg); ライセンス: パブリックドメイン_
これを達成するため、アテンションベースのモデルを用います。これにより、キャプションを生成する際にモデルが画像のどの部分に焦点を当てているかを見ることができます。

モデルの構造は、[Show, Attend and Tell: Neural Image Caption Generation with Visual Attention](https://arxiv.org/abs/1502.03044) と類似のものです。
このノートブックには例として、一連の処理の最初から最後までが含まれています。このノートブックを実行すると、[MS-COCO](http://cocodataset.org/#home) データセットをダウンロードし、Inception V3 を使って画像のサブセットを前処理し、キャッシュします。その後、エンコーダー・デコーダーモデルを訓練し、訓練したモデルを使って新しい画像のキャプションを生成します。
この例では、比較的少量のデータ、およそ 20,000 枚の画像に対する最初の 30,000 のキャプションを使ってモデルを訓練します(データセットには 1 枚の画像あたり複数のキャプションがあるからです)。
```
import tensorflow as tf
# モデルがキャプション生成中に画像のどの部分に注目しているかを見るために
# アテンションのプロットを生成
import matplotlib.pyplot as plt
# Scikit-learn には役に立つさまざまなユーティリティが含まれる
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import re
import numpy as np
import os
import time
import json
from glob import glob
from PIL import Image
import pickle
```
## MS-COCO データセットのダウンロードと準備
モデルの訓練には [MS-COCO データセット](http://cocodataset.org/#home) を使用します。このデータセットには、82,000 枚以上の画像が含まれ、それぞれの画像には少なくとも 5 つの異なったキャプションがつけられています。下記のコードは自動的にデータセットをダウンロードして解凍します。
**Caution: 巨大ファイルのダウンロードあり** 訓練用のデータセットは、13GBのファイルです。
```
annotation_zip = tf.keras.utils.get_file('captions.zip',
cache_subdir=os.path.abspath('.'),
origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip',
extract = True)
annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'
name_of_zip = 'train2014.zip'
if not os.path.exists(os.path.abspath('.') + '/' + name_of_zip):
image_zip = tf.keras.utils.get_file(name_of_zip,
cache_subdir=os.path.abspath('.'),
origin = 'http://images.cocodataset.org/zips/train2014.zip',
extract = True)
PATH = os.path.dirname(image_zip)+'/train2014/'
else:
PATH = os.path.abspath('.')+'/train2014/'
```
## オプション: 訓練用データセットのサイズ制限
このチュートリアルの訓練をスピードアップするため、サブセットである 30,000 のキャプションと対応する画像を使ってモデルを訓練します。より多くのデータを使えばキャプションの品質が向上するでしょう。
```
# json ファイルの読み込み
with open(annotation_file, 'r') as f:
annotations = json.load(f)
# ベクトルにキャプションと画像の名前を格納
all_captions = []
all_img_name_vector = []
for annot in annotations['annotations']:
caption = '<start> ' + annot['caption'] + ' <end>'
image_id = annot['image_id']
full_coco_image_path = PATH + 'COCO_train2014_' + '%012d.jpg' % (image_id)
all_img_name_vector.append(full_coco_image_path)
all_captions.append(caption)
# captions と image_names を一緒にシャッフル
# random_state を設定
train_captions, img_name_vector = shuffle(all_captions,
all_img_name_vector,
random_state=1)
# シャッフルしたデータセットから最初の 30,000 のキャプションを選択
num_examples = 30000
train_captions = train_captions[:num_examples]
img_name_vector = img_name_vector[:num_examples]
len(train_captions), len(all_captions)
```
## InceptionV3 を使った画像の前処理
つぎに、(Imagenet を使って訓練済みの)InceptionV3をつかって、画像を分類します。最後の畳み込み層から特徴量を抽出します。
最初に、つぎのようにして画像を InceptionV3 が期待するフォーマットに変換します。
* 画像を 299 ピクセル × 299 ピクセルにリサイズ
* [preprocess_input](https://www.tensorflow.org/api_docs/python/tf/keras/applications/inception_v3/preprocess_input) メソッドをつかって画像を InceptionV3 の訓練用画像のフォーマットに合致した −1 から 1 の範囲のピクセルを持つ形式に標準化して[画像の前処理](https://cloud.google.com/tpu/docs/inception-v3-advanced#preprocessing_stage) を行う
```
def load_image(image_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, (299, 299))
img = tf.keras.applications.inception_v3.preprocess_input(img)
return img, image_path
```
## InceptionV3 を初期化し Imagenet で学習済みの重みをロードする
ここで、出力層が InceptionV3 アーキテクチャの最後の畳み込み層である tf.keras モデルを作成しましょう。このレイヤーの出力の shape は```8x8x2048``` です。
* 画像を 1 枚ずつネットワークに送り込み、処理結果のベクトルをディクショナリに保管します (image_name --> feature_vector)
* すべての画像をネットワークで処理したあと、ディクショナリを pickle 形式でディスクに書き出します
```
image_model = tf.keras.applications.InceptionV3(include_top=False,
weights='imagenet')
new_input = image_model.input
hidden_layer = image_model.layers[-1].output
image_features_extract_model = tf.keras.Model(new_input, hidden_layer)
```
## InceptionV3 から抽出した特徴量のキャッシング
それぞれの画像を InceptionV3 で前処理して出力をディスクにキャッシュします。出力を RAM にキャッシュすれば速くなりますが、画像 1 枚あたり 8 \* 8 \* 2048 個の浮動小数点数が必要で、メモリを大量に必要とします。これを書いている時点では、これは Colab のメモリ上限(現在は 12GB)を超えています。
より高度なキャッシング戦略(たとえば画像を分散保存しディスクのランダムアクセス入出力を低減するなど)を使えば性能は向上しますが、より多くのコーディングが必要となります。
このキャッシングは Colab で GPU を使った場合で約 10 分ほどかかります。プログレスバーを表示したければ次のようにします。
1. [tqdm](https://github.com/tqdm/tqdm) をインストールします:
`!pip install tqdm`
2. tqdm をインポートします:
`from tqdm import tqdm`
3. 下記の行を:
`for img, path in image_dataset:`
次のように変更します:
`for img, path in tqdm(image_dataset):`
```
# 重複のない画像を取得
encode_train = sorted(set(img_name_vector))
# batch_size はシステム構成に合わせて自由に変更可能
image_dataset = tf.data.Dataset.from_tensor_slices(encode_train)
image_dataset = image_dataset.map(
load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE).batch(16)
for img, path in image_dataset:
batch_features = image_features_extract_model(img)
batch_features = tf.reshape(batch_features,
(batch_features.shape[0], -1, batch_features.shape[3]))
for bf, p in zip(batch_features, path):
path_of_feature = p.numpy().decode("utf-8")
np.save(path_of_feature, bf.numpy())
```
## キャプションの前処理とトークン化
* まず最初に、キャプションをトークン化(たとえばスペースで区切るなど)します。これにより、データ中の重複しない単語のボキャブラリ(たとえば、"surfing"、"football" など)が得られます。
* つぎに、(メモリ節約のため)ボキャブラリのサイズを上位 5,000 語に制限します。それ以外の単語は "UNK" (不明)というトークンに置き換えます。
* 続いて、単語からインデックス、インデックスから単語への対応表を作成します。
* 最後に、すべてのシーケンスの長さを最長のものに合わせてパディングします。
```
# データセット中の一番長いキャプションの長さを検出
def calc_max_length(tensor):
return max(len(t) for t in tensor)
# ボキャブラリ中のトップ 5000 語を選択
top_k = 5000
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,
oov_token="<unk>",
filters='!"#$%&()*+.,-/:;=?@[\]^_`{|}~ ')
tokenizer.fit_on_texts(train_captions)
train_seqs = tokenizer.texts_to_sequences(train_captions)
tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'
# トークン化したベクトルを生成
train_seqs = tokenizer.texts_to_sequences(train_captions)
# キャプションの最大長に各ベクトルをパディング
# max_length を指定しない場合、pad_sequences は自動的に計算
cap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post')
# アテンションの重みを格納するために使われる max_length を計算
max_length = calc_max_length(train_seqs)
```
## データを訓練用とテスト用に分割
```
# 訓練用セットと検証用セットを 80-20 に分割して生成
img_name_train, img_name_val, cap_train, cap_val = train_test_split(img_name_vector,
cap_vector,
test_size=0.2,
random_state=0)
len(img_name_train), len(cap_train), len(img_name_val), len(cap_val)
```
## 訓練用の tf.data データセットの作成
画像とキャプションが用意できました。つぎは、モデルの訓練に使用する tf.data データセットを作成しましょう。
```
# これらのパラメータはシステム構成に合わせて自由に変更してください
BATCH_SIZE = 64
BUFFER_SIZE = 1000
embedding_dim = 256
units = 512
vocab_size = len(tokenizer.word_index) + 1
num_steps = len(img_name_train) // BATCH_SIZE
# InceptionV3 から抽出したベクトルの shape は (64, 2048)
# つぎの 2 つのパラメータはこのベクトルの shape を表す
features_shape = 2048
attention_features_shape = 64
# numpy ファイルをロード
def map_func(img_name, cap):
img_tensor = np.load(img_name.decode('utf-8')+'.npy')
return img_tensor, cap
dataset = tf.data.Dataset.from_tensor_slices((img_name_train, cap_train))
# numpy ファイルを並列に読み込むために map を使用
dataset = dataset.map(lambda item1, item2: tf.numpy_function(
map_func, [item1, item2], [tf.float32, tf.int32]),
num_parallel_calls=tf.data.experimental.AUTOTUNE)
# シャッフルとバッチ化
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
```
## モデル
興味深い事実:下記のデコーダは[Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb) の例のデコーダとまったく同一です。
このモデルのアーキテクチャは、[Show, Attend and Tell](https://arxiv.org/pdf/1502.03044.pdf) の論文にインスパイアされたものです。
* この例では、InceptionV3 の下層の畳込みレイヤーから特徴量を取り出します。得られるベクトルの shape は (8, 8, 2048) です。
* このベクトルを (64, 2048) に変形します。
* このベクトルは(1層の全結合層からなる)CNN エンコーダに渡されます。
* RNN(ここではGRU)が画像を介して次の単語を予測します。
```
class BahdanauAttention(tf.keras.Model):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def call(self, features, hidden):
# features(CNN_encoder output) shape == (batch_size, 64, embedding_dim)
# hidden shape == (batch_size, hidden_size)
# hidden_with_time_axis shape == (batch_size, 1, hidden_size)
hidden_with_time_axis = tf.expand_dims(hidden, 1)
# score shape == (batch_size, 64, hidden_size)
score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis))
# attention_weights shape == (batch_size, 64, 1)
# score を self.V に適用するので、最後の軸は 1 となる
attention_weights = tf.nn.softmax(self.V(score), axis=1)
# 合計をとったあとの context_vector の shpae == (batch_size, hidden_size)
context_vector = attention_weights * features
context_vector = tf.reduce_sum(context_vector, axis=1)
return context_vector, attention_weights
class CNN_Encoder(tf.keras.Model):
# すでに特徴量を抽出して pickle 形式でダンプしてあるので
# このエンコーダはそれらの特徴量を全結合層に渡して処理する
def __init__(self, embedding_dim):
super(CNN_Encoder, self).__init__()
# shape after fc == (batch_size, 64, embedding_dim)
self.fc = tf.keras.layers.Dense(embedding_dim)
def call(self, x):
x = self.fc(x)
x = tf.nn.relu(x)
return x
class RNN_Decoder(tf.keras.Model):
def __init__(self, embedding_dim, units, vocab_size):
super(RNN_Decoder, self).__init__()
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.keras.layers.GRU(self.units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
self.fc1 = tf.keras.layers.Dense(self.units)
self.fc2 = tf.keras.layers.Dense(vocab_size)
self.attention = BahdanauAttention(self.units)
def call(self, x, features, hidden):
# アテンションを別のモデルとして定義
context_vector, attention_weights = self.attention(features, hidden)
# embedding 層を通過したあとの x の shape == (batch_size, 1, embedding_dim)
x = self.embedding(x)
# 結合後の x の shape == (batch_size, 1, embedding_dim + hidden_size)
x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)
# 結合したベクトルを GRU に渡す
output, state = self.gru(x)
# shape == (batch_size, max_length, hidden_size)
x = self.fc1(output)
# x shape == (batch_size * max_length, hidden_size)
x = tf.reshape(x, (-1, x.shape[2]))
# output shape == (batch_size * max_length, vocab)
x = self.fc2(x)
return x, state, attention_weights
def reset_state(self, batch_size):
return tf.zeros((batch_size, self.units))
encoder = CNN_Encoder(embedding_dim)
decoder = RNN_Decoder(embedding_dim, units, vocab_size)
optimizer = tf.keras.optimizers.Adam()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction='none')
def loss_function(real, pred):
mask = tf.math.logical_not(tf.math.equal(real, 0))
loss_ = loss_object(real, pred)
mask = tf.cast(mask, dtype=loss_.dtype)
loss_ *= mask
return tf.reduce_mean(loss_)
```
## チェックポイント
```
checkpoint_path = "./checkpoints/train"
ckpt = tf.train.Checkpoint(encoder=encoder,
decoder=decoder,
optimizer = optimizer)
ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)
start_epoch = 0
if ckpt_manager.latest_checkpoint:
start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1])
```
## 訓練
* それぞれの `.npy` ファイルに保存されている特徴量を取り出し、エンコーダに渡す
* エンコーダの出力と(0 で初期化された)隠れ状態と、デコーダの入力(開始トークン)をデコーダに渡す
* デコーダは予測値とデコーダの隠れ状態を返す
* デコーダの隠れ状態はモデルに戻され、予測値をつかって損失を計算する
* デコーダの次の入力を決めるために teacher forcing を用いる
* Teacher forcing は、デコーダの次の入力として正解の単語を渡す手法である
* 最後のステップは、勾配を計算してそれをオプティマイザに適用し誤差逆伝播を行うことである
```
# 訓練用のセルを複数回実行すると loss_plot 配列がリセットされてしまうので
# 独立したセルとして追加
loss_plot = []
@tf.function
def train_step(img_tensor, target):
loss = 0
# バッチごとに隠れ状態を初期化
# 画像のキャプションはその前後の画像と無関係なため
hidden = decoder.reset_state(batch_size=target.shape[0])
dec_input = tf.expand_dims([tokenizer.word_index['<start>']] * target.shape[0], 1)
with tf.GradientTape() as tape:
features = encoder(img_tensor)
for i in range(1, target.shape[1]):
# 特徴量をデコーダに渡す
predictions, hidden, _ = decoder(dec_input, features, hidden)
loss += loss_function(target[:, i], predictions)
# teacher forcing を使用
dec_input = tf.expand_dims(target[:, i], 1)
total_loss = (loss / int(target.shape[1]))
trainable_variables = encoder.trainable_variables + decoder.trainable_variables
gradients = tape.gradient(loss, trainable_variables)
optimizer.apply_gradients(zip(gradients, trainable_variables))
return loss, total_loss
EPOCHS = 20
for epoch in range(start_epoch, EPOCHS):
start = time.time()
total_loss = 0
for (batch, (img_tensor, target)) in enumerate(dataset):
batch_loss, t_loss = train_step(img_tensor, target)
total_loss += t_loss
if batch % 100 == 0:
print ('Epoch {} Batch {} Loss {:.4f}'.format(
epoch + 1, batch, batch_loss.numpy() / int(target.shape[1])))
# 後ほどグラフ化するためにエポックごとに損失を保存
loss_plot.append(total_loss / num_steps)
if epoch % 5 == 0:
ckpt_manager.save()
print ('Epoch {} Loss {:.6f}'.format(epoch + 1,
total_loss/num_steps))
print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start))
plt.plot(loss_plot)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Loss Plot')
plt.show()
```
## キャプション!
* 評価関数は訓練ループとおなじだが、teacher forcing は使わない。タイムステップごとのデコーダへの入力は、隠れ状態とエンコーダの入力に加えて、一つ前の予測値である。
* モデルが終了トークンを予測したら、予測を終了する。
* それぞれのタイムステップごとに、アテンションの重みを保存する。
```
def evaluate(image):
attention_plot = np.zeros((max_length, attention_features_shape))
hidden = decoder.reset_state(batch_size=1)
temp_input = tf.expand_dims(load_image(image)[0], 0)
img_tensor_val = image_features_extract_model(temp_input)
img_tensor_val = tf.reshape(img_tensor_val, (img_tensor_val.shape[0], -1, img_tensor_val.shape[3]))
features = encoder(img_tensor_val)
dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0)
result = []
for i in range(max_length):
predictions, hidden, attention_weights = decoder(dec_input, features, hidden)
attention_plot[i] = tf.reshape(attention_weights, (-1, )).numpy()
predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy()
result.append(tokenizer.index_word[predicted_id])
if tokenizer.index_word[predicted_id] == '<end>':
return result, attention_plot
dec_input = tf.expand_dims([predicted_id], 0)
attention_plot = attention_plot[:len(result), :]
return result, attention_plot
def plot_attention(image, result, attention_plot):
temp_image = np.array(Image.open(image))
fig = plt.figure(figsize=(10, 10))
len_result = len(result)
for l in range(len_result):
temp_att = np.resize(attention_plot[l], (8, 8))
ax = fig.add_subplot(len_result//2, len_result//2, l+1)
ax.set_title(result[l])
img = ax.imshow(temp_image)
ax.imshow(temp_att, cmap='gray', alpha=0.6, extent=img.get_extent())
plt.tight_layout()
plt.show()
# 検証用セットのキャプション
rid = np.random.randint(0, len(img_name_val))
image = img_name_val[rid]
real_caption = ' '.join([tokenizer.index_word[i] for i in cap_val[rid] if i not in [0]])
result, attention_plot = evaluate(image)
print ('Real Caption:', real_caption)
print ('Prediction Caption:', ' '.join(result))
plot_attention(image, result, attention_plot)
```
## あなた独自の画像でためそう
お楽しみのために、訓練したばかりのモデルであなたの独自の画像を使うためのメソッドを下記に示します。比較的少量のデータで訓練していること、そして、あなたの画像は訓練データとは異なるであろうことを、心に留めておいてください(変な結果が出てくることを覚悟しておいてください)。
```
image_url = 'https://tensorflow.org/images/surf.jpg'
image_extension = image_url[-4:]
image_path = tf.keras.utils.get_file('image'+image_extension,
origin=image_url)
result, attention_plot = evaluate(image_path)
print ('Prediction Caption:', ' '.join(result))
plot_attention(image_path, result, attention_plot)
# 画像を開く
Image.open(image_path)
```
# 次のステップ
おめでとうございます!アテンション付きの画像キャプショニングモデルの訓練が終わりました。つぎは、この例 [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb) を御覧ください。これはおなじアーキテクチャをつかってスペイン語と英語の間の翻訳を行います。このノートブックのコードをつかって、別のデータセットで訓練を行うこともできます。
| github_jupyter |
## Getting started with pyscal
`pyscal` has three levels of objects. The fundamental one is [`Atom`](https://docs.pyscal.org/en/latest/pyscal.html#pyscal.catom.Atom) object which is used to store all properties that belong to an atom. The next object is [`System`](https://docs.pyscal.org/en/latest/pyscal.html#pyscal.core.System). `System` consists of multiple `Atom` objects and the simulation box. The final object is the [`Trajectory`](https://docs.pyscal.org/en/latest/pyscal.html#pyscal.trajectory.Timeslice) which stores a complete trajectory. In this example, we will look at `Atom` and `System`.
This example illustrates basic functionality of pyscal python library by setting up a system and the atoms.
```
import pyscal.core as pc
import numpy as np
```
### The ``System`` class
`System` is the basic class of pyscal and is required to be setup in order to perform any calculations. It can be set up as-
```
sys = pc.System()
```
`sys` is a `System` object. But at this point, it is completely empty. We have to provide the system with the following information-
* the simulation box dimensions
* the positions of individual atoms.
Let us try to set up a small system, which is the bcc unitcell of lattice constant 1. The simulation box dimensions of such a unit cell
would be [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]] where the first set correspond to the x axis, second to y axis and so on.
The unitcell has 2 atoms and their positions are [0,0,0] and [0.5, 0.5, 0.5].
```
sys.box = [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]]
```
We can easily check if everything worked by getting the box dimensions
```
sys.box
```
### The ``Atom`` class
The next part is assigning the atoms. This can be done using the `Atom` class. Here, we will only look at the basic properties of `Atom` class.
Now let us create two atoms.
```
atom1 = pc.Atom()
atom2 = pc.Atom()
```
Now two empty atom objects are created. The basic poperties of an atom are its positions and id. There are various other properties which can be set here. A detailed description can be found [here](https://docs.pyscal.org/en/latest/pyscal.html#pyscal.catom.Atom).
```
atom1.pos = [0., 0., 0.]
atom1.id = 0
atom2.pos = [0.5, 0.5, 0.5]
atom2.id = 1
```
Alternatively, atom objects can also be set up as
```
atom1 = pc.Atom(pos=[0., 0., 0.], id=0)
atom2 = pc.Atom(pos=[0.5, 0.5, 0.5], id=1)
```
We can check the details of the atom by querying it
```
atom1.pos
```
### Combining ``System`` and ``Atom``
Now that we have created the atoms, we can assign them to the system. We can also assign the same box we created before.
```
sys = pc.System()
sys.atoms = [atom1, atom2]
sys.box = [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]]
```
That sets up the system completely. It has both of it's constituents - atoms and the simulation box. We can check if everything works correctly.
```
sys.atoms
```
This returns all the atoms of the system. Alternatively a single atom can be accessed by,
```
atom = sys.get_atom(1)
```
The above call will fetch the atom at position 1 in the list of all atoms in the system. Due to Atom being a completely C++ class, it is necessary to use ``get_atom()`` and ``set_atom()`` to access individual atoms and set them back into the system object after modification. A list of all atoms however can be accessed directly by atoms.
Once you have all the atoms, you can modify any one and add it back to the list of all atoms in the system. The following statement will set the type of the first atom to 2.
```
atom = sys.atoms[0]
atom.type = 2
```
Lets verify if it was done properly
```
atom.type
```
Now we can push the atom back to the system with the new type
```
sys.set_atom(atom)
```
### Reading in an input file
We are all set! The `System` is ready for calculations. However, in most realistic simulation situations, we have many atoms and it can be difficult to set each of them
individually. In this situation we can read in input file directly. An example input file containing 500 atoms in a simulation box can be read in automatically. The file we use for this example is a file of the [lammps-dump](https://lammps.sandia.gov/doc/dump.html) format. ``pyscal`` can also read in POSCAR files. In principle, ``pyscal`` only needs the atom positions and simulation box size, so you can write a python function to process the input file, extract the details and pass to ``pyscal``.
```
sys = pc.System()
sys.read_inputfile('conf.dump')
```
Once again, lets check if the box dimensions are read in correctly
```
sys.box
```
Now we can get all atoms that belong to this system
```
len(sys.atoms)
```
We can see that all the atoms are read in correctly and there are 500 atoms in total. Once again, individual atom properties can be
accessed as before.
```
sys.atoms[0].pos
```
Thats it! Now we are ready for some calculations. You can find more in the examples section of the documentation.
| github_jupyter |
```
# useful to autoreload the module without restarting the kernel
%load_ext autoreload
%autoreload 2
from mppi import InputFiles as I
```
# Tutorial for the PwInput class
This tutorial describes the main features and the usage of the PwInput class that enables to create and
manage the input files for the QuantumESPRESSO computations
## Setting up an input from scratch
Create an empty input object from scratch. If not parameters are provided some keys are init from the _default_
data member of the class
```
inp = I.PwInput()
inp
```
The input object can be initialized passing arguments in the constuctor both using the kwargs syntax and/or passing a dictionary.
These operations override the _default_ dictionary
```
inp = I.PwInput(control = {'calculation' : 'nscf'})
inp
imp_dict = {'system' : {'ntyp' : 1}}
inp = I.PwInput(control = {'calculation' : 'scf'}, **imp_dict)
inp
```
The attribute of the object can be updated using the standard procedure for python dictionaries, for instance
```
inp['control'].update({'verbosity' : "'high'"})
inp
```
However it is more powerful to use the specific methods provided in the class (and other can be defined). For instance
```
inp = I.PwInput()
inp.set_scf()
inp.set_prefix('si_scf_pref')
inp.set_pseudo_dir(pseudo_dir='pseudos')
# specific methods for the cell have still to be added
inp.set_lattice(ibrav=2,celldm1=10.3)
# Set the atoms type and positions
inp.add_atom('Si','Si.pbe-mt_fhi.UPF')
# add other atoms if needed, then set the number of atoms in the cell.
# This method sets the ntyp variable equal to the number of atoms added
# with the add_atom method
inp.set_atoms_number(2)
inp.set_atomic_positions([['Si',[0.,0.,0.,]],['Si',[0.25,0.25,0.25]]])
# Set the sampling of kpoints
inp.set_kpoints(type='automatic',points=[4,4,4])
inp
```
The usage of the methods is described in the documentation and can be easily accessed as follows
```
inp.set_pseudo_dir?
inp.set_kpoints?
```
Once completed the input object can be converted to string with the correct format of the pw input files
```
inp_tostring = inp.convert_string()
print(inp_tostring)
```
and finally it can be written on file
```
inp.write('IO_files/pw_from-scratch.in')
```
## Build and input starting from an existing file
Consider a second example in which the input is initialized from an existing input file
```
inp = I.PwInput(file='IO_files/gaas_scf.in')
inp
```
The variables can be modified, for instance we can modify the input to perform a nscf computation with 12 bands and
a given k-path
```
G = [0.,0.,0.]
X = [1.,0.,0.]
L = [0.5,0.5,0.5]
W = [1.0,0.5,0.]
from mppi.Utilities import build_kpath
kpath = build_kpath(G,X,L,W,numstep=30)
kpath
inp.set_nscf(12)
inp.set_kpoints(type='tpiba_b',klist=kpath)
inp_tostring = inp.convert_string()
print(inp_tostring)
```
Finally a last example in which the lattice is specified through the 'cell_parameters' key
```
inp = I.PwInput(file='IO_files/graphene_nscf.in')
inp
print(inp.convert_string())
```
| github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import malaya_speech.train.model.conformer as conformer
import malaya_speech.train.model.transducer as transducer
import malaya_speech
import tensorflow as tf
import numpy as np
subwords = malaya_speech.subword.load('transducer.subword')
featurizer = malaya_speech.tf_featurization.STTFeaturizer(
normalize_per_feature = True
)
X = tf.compat.v1.placeholder(tf.float32, [None, None], name = 'X_placeholder')
X_len = tf.compat.v1.placeholder(tf.int32, [None], name = 'X_len_placeholder')
batch_size = tf.shape(X)[0]
features = tf.TensorArray(dtype = tf.float32, size = batch_size, dynamic_size = True, infer_shape = False)
features_len = tf.TensorArray(dtype = tf.int32, size = batch_size)
init_state = (0, features, features_len)
def condition(i, features, features_len):
return i < batch_size
def body(i, features, features_len):
f = featurizer(X[i, :X_len[i]])
f_len = tf.shape(f)[0]
return i + 1, features.write(i, f), features_len.write(i, f_len)
_, features, features_len = tf.while_loop(condition, body, init_state)
features_len = features_len.stack()
padded_features = tf.TensorArray(dtype = tf.float32, size = batch_size)
padded_lens = tf.TensorArray(dtype = tf.int32, size = batch_size)
maxlen = tf.reduce_max(features_len)
init_state = (0, padded_features, padded_lens)
def condition(i, padded_features, padded_lens):
return i < batch_size
def body(i, padded_features, padded_lens):
f = features.read(i)
len_f = tf.shape(f)[0]
f = tf.pad(f, [[0, maxlen - tf.shape(f)[0]], [0,0]])
return i + 1, padded_features.write(i, f), padded_lens.write(i, len_f)
_, padded_features, padded_lens = tf.while_loop(condition, body, init_state)
padded_features = padded_features.stack()
padded_lens = padded_lens.stack()
padded_lens.set_shape((None,))
padded_features.set_shape((None, None, 80))
padded_features = tf.expand_dims(padded_features, -1)
padded_features, padded_lens
padded_features = tf.identity(padded_features, name = 'padded_features')
padded_lens = tf.identity(padded_lens, name = 'padded_lens')
config = malaya_speech.config.conformer_large_encoder_config
config['dropout'] = 0.0
conformer_model = conformer.Model(**config)
decoder_config = malaya_speech.config.conformer_large_decoder_config
decoder_config['embed_dropout'] = 0.0
transducer_model = transducer.rnn.Model(
conformer_model, vocabulary_size = subwords.vocab_size, **decoder_config
)
p = tf.compat.v1.placeholder(tf.int32, [None, None])
z = tf.zeros((tf.shape(p)[0], 1),dtype=tf.int32)
c = tf.concat([z, p], axis = 1)
p_len = tf.compat.v1.placeholder(tf.int32, [None])
c
training = True
logits = transducer_model([padded_features, c, p_len], training = training)
logits
sess = tf.Session()
sess.run(tf.global_variables_initializer())
var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
saver = tf.train.Saver(var_list = var_list)
saver.restore(sess, 'asr-large-conformer-transducer-v2/model.ckpt-800000')
decoded = transducer_model.greedy_decoder(padded_features, padded_lens, training = training)
decoded = tf.identity(decoded, name = 'greedy_decoder')
decoded
encoded = transducer_model.encoder(padded_features, training = training)
encoded = tf.identity(encoded, name = 'encoded')
encoded_placeholder = tf.placeholder(tf.float32, [config['dmodel']], name = 'encoded_placeholder')
predicted_placeholder = tf.placeholder(tf.int32, None, name = 'predicted_placeholder')
t = transducer_model.predict_net.get_initial_state().shape
states_placeholder = tf.placeholder(tf.float32, [int(i) for i in t], name = 'states_placeholder')
ytu, new_states = transducer_model.decoder_inference(
encoded=encoded_placeholder,
predicted=predicted_placeholder,
states=states_placeholder,
training = training
)
ytu = tf.identity(ytu, name = 'ytu')
new_states = tf.identity(new_states, name = 'new_states')
ytu, new_states
initial_states = transducer_model.predict_net.get_initial_state()
initial_states = tf.identity(initial_states, name = 'initial_states')
# sess = tf.Session()
# sess.run(tf.global_variables_initializer())
# var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
# saver = tf.train.Saver(var_list = var_list)
# saver.restore(sess, 'asr-small-conformer-transducer/model.ckpt-325000')
files = [
'speech/record/savewav_2020-11-26_22-36-06_294832.wav',
'speech/record/savewav_2020-11-26_22-40-56_929661.wav',
'speech/record/675.wav',
'speech/record/664.wav',
'speech/example-speaker/husein-zolkepli.wav',
'speech/example-speaker/mas-aisyah.wav',
'speech/example-speaker/khalil-nooh.wav',
'speech/example-speaker/shafiqah-idayu.wav',
'speech/khutbah/wadi-annuar.wav',
]
front_pad = 200
back_pad = 2000
inputs = [malaya_speech.load(f)[0] for f in files]
padded, lens = malaya_speech.padding.sequence_1d(inputs, return_len = True)
back = np.zeros(shape = (len(inputs), back_pad))
front = np.zeros(shape = (len(inputs), front_pad))
padded = np.concatenate([front, padded, back], axis = -1)
lens = [l + front_pad + back_pad for l in lens]
import collections
import numpy as np
import tensorflow as tf
BeamHypothesis = collections.namedtuple(
'BeamHypothesis', ('score', 'prediction', 'states')
)
def transducer(
enc,
total,
initial_states,
encoded_placeholder,
predicted_placeholder,
states_placeholder,
ytu,
new_states,
sess,
beam_width = 10,
norm_score = True,
):
kept_hyps = [
BeamHypothesis(score = 0.0, prediction = [0], states = initial_states)
]
B = kept_hyps
for i in range(total):
A = B
B = []
while True:
y_hat = max(A, key = lambda x: x.score)
A.remove(y_hat)
ytu_, new_states_ = sess.run(
[ytu, new_states],
feed_dict = {
encoded_placeholder: enc[i],
predicted_placeholder: y_hat.prediction[-1],
states_placeholder: y_hat.states,
},
)
for k in range(ytu_.shape[0]):
beam_hyp = BeamHypothesis(
score = (y_hat.score + float(ytu_[k])),
prediction = y_hat.prediction,
states = y_hat.states,
)
if k == 0:
B.append(beam_hyp)
else:
beam_hyp = BeamHypothesis(
score = beam_hyp.score,
prediction = (beam_hyp.prediction + [int(k)]),
states = new_states_,
)
A.append(beam_hyp)
if len(B) > beam_width:
break
if norm_score:
kept_hyps = sorted(
B, key = lambda x: x.score / len(x.prediction), reverse = True
)[:beam_width]
else:
kept_hyps = sorted(B, key = lambda x: x.score, reverse = True)[
:beam_width
]
return kept_hyps[0].prediction
%%time
r = sess.run(decoded, feed_dict = {X: padded, X_len: lens})
for row in r:
print(malaya_speech.subword.decode(subwords, row[row > 0]))
%%time
encoded_, padded_lens_ = sess.run([encoded, padded_lens], feed_dict = {X: padded, X_len: lens})
padded_lens_ = padded_lens_ // conformer_model.conv_subsampling.time_reduction_factor
s = sess.run(initial_states)
for i in range(len(encoded_)):
r = transducer(
enc = encoded_[i],
total = padded_lens_[i],
initial_states = s,
encoded_placeholder = encoded_placeholder,
predicted_placeholder = predicted_placeholder,
states_placeholder = states_placeholder,
ytu = ytu,
new_states = new_states,
sess = sess,
beam_width = 1,
)
print(malaya_speech.subword.decode(subwords, r))
l = padded_lens // transducer_model.encoder.conv_subsampling.time_reduction_factor
encoded = transducer_model.encoder(padded_features, training = training)
g = transducer_model._perform_greedy(encoded[0], l[0],
tf.constant(0, dtype = tf.int32),
transducer_model.predict_net.get_initial_state())
g
indices = g.prediction
minus_one = -1 * tf.ones_like(indices, dtype=tf.int32)
blank_like = 0 * tf.ones_like(indices, dtype=tf.int32)
indices = tf.where(indices == minus_one, blank_like, indices)
num_samples = tf.cast(X_len[0], dtype=tf.float32)
total_time_reduction_factor = featurizer.frame_step
stime = tf.range(0, num_samples, delta=total_time_reduction_factor, dtype=tf.float32)
stime /= tf.cast(featurizer.sample_rate, dtype=tf.float32)
stime = stime[::tf.shape(stime)[0] // tf.shape(indices)[0]]
stime.set_shape((None,))
non_blank = tf.where(tf.not_equal(indices, 0))
non_blank_transcript = tf.gather_nd(indices, non_blank)
non_blank_stime = tf.gather_nd(stime, non_blank)
non_blank_transcript = tf.identity(non_blank_transcript, name = 'non_blank_transcript')
non_blank_stime = tf.identity(non_blank_stime, name = 'non_blank_stime')
%%time
r = sess.run([non_blank_transcript, non_blank_stime], feed_dict = {X: padded, X_len: lens})
words, indices = [], []
for no, ids in enumerate(r[0]):
w = subwords._id_to_subword(ids - 1)
if type(w) == bytes:
w = w.decode()
words.extend([w, None])
indices.extend([no, None])
import six
from malaya_speech.utils import text_encoder
def _trim_underscore_and_tell(token):
if token.endswith('_'):
return token[:-1], True
return token, False
def decode(ids):
ids = text_encoder.pad_decr(ids)
subword_ids = ids
del ids
subwords_ = []
prev_bytes = []
prev_ids = []
ids = []
def consume_prev_bytes():
if prev_bytes:
subwords_.extend(prev_bytes)
ids.extend(prev_ids)
return [], []
for no, subword_id in enumerate(subword_ids):
subword = subwords._id_to_subword(subword_id)
if isinstance(subword, six.binary_type):
# Byte-encoded
prev_bytes.append(subword.decode('utf-8', 'replace'))
if subword == b' ':
prev_ids.append(None)
else:
prev_ids.append(no)
else:
# If there were bytes previously, convert to unicode.
prev_bytes, prev_ids = consume_prev_bytes()
trimmed, add_space = _trim_underscore_and_tell(subword)
ids.append(no)
subwords_.append(trimmed)
if add_space:
subwords_.append(' ')
ids.append(None)
prev_bytes = consume_prev_bytes()
return subwords_, ids
words, indices = decode(r[0])
len(words), len(indices)
def combined_indices(subwords, ids, l, reduction_factor = 160, sample_rate = 16000):
result, temp_l, temp_r = [], [], []
for i in range(len(subwords)):
if ids[i] is not None:
temp_l.append(subwords[i])
temp_r.append(l[ids[i]])
else:
data = {'text': ''.join(temp_l),
'start': round(temp_r[0],4),
'end': round(temp_r[-1] + (reduction_factor / sample_rate), 4)}
result.append(data)
temp_l, temp_r = [], []
if len(temp_l):
data = {'text': ''.join(temp_l),
'start': round(temp_r[0],4),
'end': round(temp_r[-1] + (reduction_factor / sample_rate), 4)}
result.append(data)
return result
combined_indices(words, indices, r[1])
saver = tf.train.Saver()
saver.save(sess, 'output-large-conformer/model.ckpt')
strings = ','.join(
[
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('Variable' in n.op
or 'gather' in n.op.lower()
or 'placeholder' in n.name
or 'encoded' in n.name
or 'decoder' in n.name
or 'ytu' in n.name
or 'new_states' in n.name
or 'padded_' in n.name
or 'initial_states' in n.name
or 'non_blank' in n.name)
and 'adam' not in n.name
and 'global_step' not in n.name
and 'Assign' not in n.name
and 'ReadVariableOp' not in n.name
and 'Gather' not in n.name
]
)
strings.split(',')
def freeze_graph(model_dir, output_node_names):
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
'directory: %s' % model_dir
)
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + '/frozen_model.pb'
clear_devices = True
with tf.Session(graph = tf.Graph()) as sess:
saver = tf.train.import_meta_graph(
input_checkpoint + '.meta', clear_devices = clear_devices
)
saver.restore(sess, input_checkpoint)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
tf.get_default_graph().as_graph_def(),
output_node_names.split(','),
)
with tf.gfile.GFile(output_graph, 'wb') as f:
f.write(output_graph_def.SerializeToString())
print('%d ops in the final graph.' % len(output_graph_def.node))
freeze_graph('output-large-conformer', strings)
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
g = load_graph('output-large-conformer/frozen_model.pb')
input_nodes = [
'X_placeholder',
'X_len_placeholder',
'encoded_placeholder',
'predicted_placeholder',
'states_placeholder',
]
output_nodes = [
'greedy_decoder',
'encoded',
'ytu',
'new_states',
'padded_features',
'padded_lens',
'initial_states',
'non_blank_transcript',
'non_blank_stime'
]
inputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in input_nodes}
outputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}
test_sess = tf.Session(graph = g)
r = test_sess.run(outputs['greedy_decoder'], feed_dict = {inputs['X_placeholder']: padded,
inputs['X_len_placeholder']: lens})
for row in r:
print(malaya_speech.subword.decode(subwords, row[row > 0]))
encoded_, padded_lens_, s = test_sess.run([outputs['encoded'], outputs['padded_lens'], outputs['initial_states']],
feed_dict = {inputs['X_placeholder']: padded,
inputs['X_len_placeholder']: lens})
padded_lens_ = padded_lens_ // conformer_model.conv_subsampling.time_reduction_factor
i = 0
r = transducer(
enc = encoded_[i],
total = padded_lens_[i],
initial_states = s,
encoded_placeholder = inputs['encoded_placeholder'],
predicted_placeholder = inputs['predicted_placeholder'],
states_placeholder = inputs['states_placeholder'],
ytu = outputs['ytu'],
new_states = outputs['new_states'],
sess = test_sess,
beam_width = 1,
)
malaya_speech.subword.decode(subwords, r)
from tensorflow.tools.graph_transforms import TransformGraph
transforms = ['add_default_attributes',
'remove_nodes(op=Identity, op=CheckNumerics, op=Dropout)',
'fold_batch_norms',
'fold_old_batch_norms',
'quantize_weights(fallback_min=-10, fallback_max=10)',
'strip_unused_nodes',
'sort_by_execution_order']
input_nodes = [
'X_placeholder',
'X_len_placeholder',
'encoded_placeholder',
'predicted_placeholder',
'states_placeholder',
]
output_nodes = [
'greedy_decoder',
'encoded',
'ytu',
'new_states',
'padded_features',
'padded_lens',
'initial_states',
'non_blank_transcript',
'non_blank_stime'
]
pb = 'output-large-conformer/frozen_model.pb'
input_graph_def = tf.GraphDef()
with tf.gfile.FastGFile(pb, 'rb') as f:
input_graph_def.ParseFromString(f.read())
transformed_graph_def = TransformGraph(input_graph_def,
input_nodes,
output_nodes, transforms)
with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:
f.write(transformed_graph_def.SerializeToString())
g = load_graph('output-base-conformer/frozen_model.pb.quantized')
inputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in input_nodes}
outputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}
test_sess = tf.Session(graph = g)
r = test_sess.run(outputs['greedy_decoder'], feed_dict = {inputs['X_placeholder']: padded,
inputs['X_len_placeholder']: lens})
for row in r:
print(malaya_speech.subword.decode(subwords, row[row > 0]))
encoded_, padded_lens_, s = test_sess.run([outputs['encoded'], outputs['padded_lens'], outputs['initial_states']],
feed_dict = {inputs['X_placeholder']: padded,
inputs['X_len_placeholder']: lens})
padded_lens_ = padded_lens_ // conformer_model.conv_subsampling.time_reduction_factor
i = 0
r = transducer(
enc = encoded_[i],
total = padded_lens_[i],
initial_states = s,
encoded_placeholder = inputs['encoded_placeholder'],
predicted_placeholder = inputs['predicted_placeholder'],
states_placeholder = inputs['states_placeholder'],
ytu = outputs['ytu'],
new_states = outputs['new_states'],
sess = test_sess,
beam_width = 1,
)
malaya_speech.subword.decode(subwords, r)
```
| github_jupyter |
# Classificador Naive Bayes
Francisco Aparecido Rodrigues, francisco@icmc.usp.br.<br>
Universidade de São Paulo, São Carlos, Brasil.<br>
https://sites.icmc.usp.br/francisco <br>
Copyright: Creative Commons
<hr>
No classificador Naive Bayes, podemos assumir que os atributos são normalmente distribuídos.
```
import random
random.seed(42) # define the seed (important to reproduce the results)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#data = pd.read_csv('data/vertebralcolumn-3C.csv', header=(0))
data = pd.read_csv('data/Iris.csv', header=(0))
data = data.dropna(axis='rows') #remove NaN
# armazena os nomes das classes
classes = np.array(pd.unique(data[data.columns[-1]]), dtype=str)
print("Número de linhas e colunas na matriz de atributos:", data.shape)
attributes = list(data.columns)
data.head(10)
data = data.to_numpy()
nrow,ncol = data.shape
y = data[:,-1]
X = data[:,0:ncol-1]
```
Selecionando os conjuntos de treinamento e teste.
```
from sklearn.model_selection import train_test_split
p = 0.7 # fracao de elementos no conjunto de treinamento
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = p, random_state = 42)
```
### Classificação: implementação do método
Inicialmente, definimos uma função para calcular a densidade de probabilidade conjunta: $$p(\vec{x}|C_i) = \prod_{j=1}^d p(x_j|C_i), \quad i=1,\ldots, k$$
onde $C_i$ são as classes. Se a distribuição for normal, temos que cada atributo $X_j$ tem a seguinte função densidade de probabilidade associada, para cada classe:
$$
p(x_j|C_i) = \frac{1}{\sqrt{2\pi\sigma_{C_i}}}\exp \left[ -\frac{1}{2}\left( \frac{x_j-\mu_{C_i}}{\sigma_{C_i}}\right)^2 \right], \quad i=1,2,\ldots, k.
$$
Assim, definimos uma função para calcular a função de verossimilhança.
```
def likelyhood(y, Z):
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
prob = 1
for j in np.arange(0, Z.shape[1]):
m = np.mean(Z[:,j])
s = np.std(Z[:,j])
prob = prob*gaussian(y[j], m, s)
return prob
```
A seguir, realizamos a estimação para cada classe:
```
P = pd.DataFrame(data=np.zeros((X_test.shape[0], len(classes))), columns = classes)
for i in np.arange(0, len(classes)):
elements = tuple(np.where(y_train == classes[i]))
Z = X_train[elements,:][0]
for j in np.arange(0,X_test.shape[0]):
x = X_test[j,:]
pj = likelyhood(x,Z)
P[classes[i]][j] = pj*len(elements)/X_train.shape[0]
```
Para as observações no conjunto de teste, a probabilidade pertencer a cada classe:
```
P.head(10)
from sklearn.metrics import accuracy_score
y_pred = []
for i in np.arange(0, P.shape[0]):
c = np.argmax(np.array(P.iloc[[i]]))
y_pred.append(P.columns[c])
y_pred = np.array(y_pred, dtype=str)
score = accuracy_score(y_pred, y_test)
print('Accuracy:', score)
```
### Classificação: usando a biblioteca scikit-learn
Podemos realizar a classificação usando a função disponível na biblioteca scikit-learn.
```
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics
model = GaussianNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score = accuracy_score(y_pred, y_test)
print('Accuracy:', score)
```
Outra maneira de efetuarmos a classificação é assumirmos que os atributos possuem distribuição diferente da normal.
Uma possibilidade é assumirmos que os dados possuem distribuição de Bernoulli.
```
from sklearn.naive_bayes import BernoulliNB
model = BernoulliNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score = accuracy_score(y_pred, y_test)
print('Accuracy:', score)
```
Código completo.
```
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
random.seed(42)
data = pd.read_csv('data/Iris.csv', header=(0))
classes = np.array(pd.unique(data[data.columns[-1]]), dtype=str)
# Converte para matriz e vetor do numpy
data = data.to_numpy()
nrow,ncol = data.shape
y = data[:,-1]
X = data[:,0:ncol-1]
# Transforma os dados para terem media igual a zero e variancia igual a 1
#scaler = StandardScaler().fit(X)
#X = scaler.transform(X)
# Seleciona os conjuntos de treinamento e teste
p = 0.8 # fraction of elements in the test set
X_train, X_test, y_train, y_test = train_test_split(X, y,
train_size = p, random_state = 42)
# ajusta o classificador Naive-Bayes de acordo com os dados
model = GaussianNB()
model.fit(X_train, y_train)
# realiza a predicao
y_pred = model.predict(X_test)
# calcula a acuracia
score = accuracy_score(y_pred, y_test)
print('Acuracia:', score)
```
## Região de decisão
Selecionando dois atributos, podemos visualizar a região de decisão. Para graficar a região de separação, precisamos instalar a bibliteca mlxtend: http://rasbt.github.io/mlxtend/installation/<br>
Pode ser usado: conda install -c conda-forge mlxtend
Para o classificador Naive Bayes:
```
from mlxtend.plotting import plot_decision_regions
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
import sklearn.datasets as skdata
from matplotlib import pyplot
from pandas import DataFrame
# Gera os dados em duas dimensões
n_samples = 100 # número de observações
# centro dos grupos
centers = [(-4, 0), (0, 0), (3, 3)]
X, y = skdata.make_blobs(n_samples=100, n_features=2, cluster_std=1.0, centers=centers,
shuffle=False, random_state=42)
# monta a matrix de atributos
d = np.column_stack((X,np.transpose(y)))
# converte para o formato dataframe do Pandas
data = DataFrame(data = d, columns=['X1', 'X2', 'y'])
features_names = ['X1', 'X2']
class_labels = np.unique(y)
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
# mostra os dados e colori de acordo com as classes
colors = ['red', 'blue', 'green', 'black']
aux = 0
for c in class_labels:
ind = np.where(y == c)
plt.scatter(X[ind,0][0], X[ind,1][0], color = colors[aux], label = c)
aux = aux + 1
plt.legend()
plt.show()
# Training a classifier
model = GaussianNB()
model.fit(X, y)
# Plotting decision regions
plot_decision_regions(X, y, clf=model, legend=2)
plt.xlabel('X1')
plt.ylabel('X2')
plt.title('Decision Regions')
plt.show()
```
### Exercícios de fixação
1 - Repita todos os passos acima para a base de dados BreastCancer.
2 - Considere a base vertebralcolumn-3C e compare o classificadores: Naive Bayes, Classificador Bayesiano paramétrico e o classiificador Bayesiano não-paramétrico.
3 - Considerando a base de dados Vehicle, projete os dados em duas dimensões usando PCA e mostre as regiões de separação como feito acima.
4 - Faça a classificação dos dados gerados artificialmente com o código abaixo. Compare os resultados para os métodos Naive Bayes, Classificador Bayesiano paramétrico e o classiificador Bayesiano não-paramétrico.
```
from sklearn import datasets
plt.figure(figsize=(6,4))
n_samples = 1000
data = datasets.make_moons(n_samples=n_samples, noise=.05)
X = data[0]
y = data[1]
plt.scatter(X[:,0], X[:,1], c=y, cmap='viridis', s=50, alpha=0.7)
plt.show(True)
```
5 - Encontre a região de separação dos dados do exercício anterior usando o método Naive Bayes.
6 - (Facultativo) Escolha outras distribuições de probabilidade e implemente um algoritmo Naive Bayes geral. Ou seja, o algoritmo faz a classificação usando várias distribuições e obtém o melhor resultado, mostrando também qual a distribuição mais adequada.
7 - (Para pensar) É possível implementar o Naive Bayes heterogêneo, ou seja, com diferentes distribuições para cada atributo?
8 - (Desafio) Gere dados com diferentes níveis de correlação entre as variáveis e verifique se a perfomance do algoritmo muda com a correlação.
## Código completo
```
import random
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
random.seed(42)
data = pd.read_csv('data/Iris.csv', header=(0))
# classes: setosa, virginica e versicolor
classes = pd.unique(data[data.columns[-1]])
classes = np.array(classes, dtype=str)
# converte para matrizes do numpy
data = data.to_numpy()
nrow,ncol = data.shape
y = data[:,-1]
X = data[:,0:ncol-1]
# Seleciona o conjunto de teste e treinamento
p = 0.7
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = p)
# funcao para calcular a verossimilhanca
def likelyhood(y, Z):
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
prob = 1
for j in np.arange(0, Z.shape[1]):
m = np.mean(Z[:,j])
s = np.std(Z[:,j])
prob = prob*gaussian(y[j], m, s)
return prob
# matriz que armazena o produto da verossimilhanca pela priori
P = pd.DataFrame(data=np.zeros((X_test.shape[0], len(classes))), columns = classes)
for i in np.arange(0, len(classes)):
elements = tuple(np.where(y_train == classes[i]))
Z = X_train[elements,:][0]
for j in np.arange(0,X_test.shape[0]):
x = X_test[j,:]
pj = likelyhood(x,Z) #verossimilhanca
pc = len(elements)/X_train.shape[0] # priori
P[classes[i]][j] = pj*pc
# realiza a classificao seguindo a regra de Bayes
y_pred = []
for i in np.arange(0, P.shape[0]):
c = np.argmax(np.array(P.iloc[[i]]))
y_pred.append(P.columns[c])
y_pred = np.array(y_pred, dtype=str)
# calcula a acuracia na classificacao
score = accuracy_score(y_pred, y_test)
print('Accuracy:', score)
```
| github_jupyter |
# Wordle Notebook
This notebook is primarily intended as a coding demonstration of Python and Pandas for the filtering and processing of a set of string data. On a secondary basis, it also serves to simply the daily filtering and sorting of wordle-style puzzles, such as those found at https://www.nytimes.com/games/wordle/index.html
For the Python and Pandas coder, the example code includes:
1. Pulling text data out of a URL into a dataframe
2. Dynamic .assign statements using dictionaries
3. Method chaining filtering with Pandas
4. Logging statements within a method chain
5. Dynamically creating a variety of regex statements using list comprehensions, lambdas, and reduce
```
import pandas as pd
import re
import logging
from functools import reduce
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
df = pd.read_csv(
'https://raw.githubusercontent.com/tabatkins/wordle-list/main/words',
header=None,
names=['words']
)
df = df.assign(**{f'l{i+1}' : eval(f'lambda x: x.words.str[{i}]') for i in range(0,5)})
def pipe_logger(val, label):
logging.info(f'{label} : {val}')
return val
```
## Find today's word
```
# tries is a list of tuples, each containing 5 letters
# the first tuple is the submitted word
# the second tuple contains matches
# - Lower case = Yellow match
# - Upper case = Green match
tries = [
#'-----', '-----'
('takes', ' '),
# ('chino', ' n '),
]
# Generate remaining candidates out of the tries list of tuples
candidates = (
df
[
# match words not containing letters that failed matches
~df.words.str.contains(
pipe_logger(
''.join(
[r'['] +
[
re.sub(
'\.',
'',
reduce(
# iterate over the mask, replacing each space with the letter in word a
lambda a, b: ''.join([re.sub(' ', a[i], b[i]) for i in range(0,5)]),
[
t[0],
# create a mask for removing characters
re.sub('[A-Za-z]','.',t[1])
]
)
)
# iterate over tuples
for t in tries
] +
[']']
),
'Unmatched Regex',
),
regex=True,
)
# match words containing successful letter placement
& df.words.str.contains(
pipe_logger(
# create a regular expression to find exact matches
re.sub(
' ',
'.',
# reduce the list of successful letter finds to a single word
reduce(
# iterate over the letter, replacing spaces in word a with the letter in word b
lambda a, b: ''.join([re.sub(' ', b[i], a[i]) for i in range(0,5)]),
# select the Capital letters from the successful tries
[re.sub('[a-z]',' ',t[1]) for t in tries]
)
),
'Successful Placement Regex',
),
case=False,
regex=True
)
# match words that must contain characters but placement is unknown
& df.words.str.contains(
pipe_logger(
''.join(
['^'] +
[f'(?=.*{i}.*)' for i in set(sorted(''.join([re.sub('[A-Z ]','',t[1]) for t in tries])))] +
['.*$']
),
'Unknown Placement',
),
regex=True,
)
# match words that do not have incorrect placment of characters
& df.words.str.contains(
pipe_logger(
''.join([
# replace empty characters sets with '.'
re.sub(
r'\[\^\]',
r'.',
# drop spaces and build simple regex character set for 'not'
'[^' + re.sub(' ','',t) + ']'
)
for t in
# split list by every word attempt
re.findall(
'.' * len(tries),
# merge into a single string of characters
''.join(
# take the nth character from each incorrect placement result
[re.sub('[A-Z]',' ',t[1])[i] for i in range(0,5) for t in tries]
)
)
]),
'Incorrect Placement',
),
regex=True,
)
]
)
logging.info(f'Possible Candidates : {candidates.shape[0]}')
display(candidates)
# Calculate letter frequencies in remaining candidate words
freq = (
pd.concat(
[
candidates.l1.value_counts(),
candidates.l2.value_counts(),
candidates.l3.value_counts(),
candidates.l4.value_counts(),
candidates.l5.value_counts(),
],
axis = 1
)
.fillna(0)
.astype('int')
)
freq['total'] = freq.sum(axis=1)
display(freq.sort_values('total', ascending=False))
```
| github_jupyter |
# Ipyvuetify demo
See the [documentation](https://ipyvuetify.readthedocs.io/en/latest/index.html)
```
import micropip
await micropip.install('ipyvuetify==1.8.1')
import ipywidgets
import ipyvuetify as v
from threading import Timer
lorum_ipsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
count = 0
def on_click(widget, event, data):
global count
count += 1
button1.children=['button ' + str(count)]
button1 = v.Btn(children=['button'])
button1.on_event('click', on_click)
v.Layout(class_='pa-2', children=[button1])
```
## First template
```
import ipyvuetify as v
import traitlets
class FruitSelector(v.VuetifyTemplate):
fruits = traitlets.List(traitlets.Unicode(), default_value=['Apple', 'Pear']).tag(sync=True)
selected = traitlets.Unicode(default_value='', allow_none=True).tag(sync=True)
@traitlets.default('template')
def _template(self):
return '''
<template>
<div>
<v-select label="Fruits" :items="fruits" v-model="selected"/>
</div>
</template>
'''
fruits = FruitSelector()
fruits
fruits.selected
```
## Advanced template
```
import ipyvuetify as v
import traitlets
class FruitSelector(v.VuetifyTemplate):
fruits = traitlets.List(traitlets.Unicode(), default_value=['Apple', 'Pear']).tag(sync=True)
selected = traitlets.Unicode(default_value='', allow_none=True).tag(sync=True)
@traitlets.default('template')
def _template(self):
return '''
<template>
<div>
<v-select label="Fruits" :items="fruits" v-model="selected"/>
Available fruits
<table class="fruit-selector">
<tr v-for="(fruit, index) in fruits" :key="index" @click="selected = fruit">
<td>{{index}}</td>
<td>{{fruit}}</td>
<td>{{fruit == selected ? "selected" : ""}}</td>
</tr>
</table>
</div>
</template>
<style id="fruit-selector-style">
.fruit-selector td {
border: 1px solid black;
}
</style>
'''
fruits = FruitSelector(fruits=['Banana', 'Pear', 'Apple'])
fruits
```
## Template in vue files
Currenly local files can not be easily accessed in the kernel in `jupyterlite`. See this [issue](https://github.com/jupyterlite/jupyterlite/issues/119).
Here is a work around.
```
from js import fetch
async def _download_file(filename):
URL = f"https://raw.githubusercontent.com/jupyterlite/jupyterlite/main/examples/{filename}"
res = await fetch(URL)
text = await res.text()
with open(filename, 'w') as f:
f.write(text)
files = ['fruit-selector.vue','card.vue']
for filename in files:
print(f'Download {filename} from GH')
res = await _download_file(filename)
import ipyvuetify as v
import traitlets
import random
other_fruits = ['Pineapple', 'Kiwi', 'Cherry']
class FruitSelector(v.VuetifyTemplate):
template_file = 'fruit-selector.vue'
fruits = traitlets.List(traitlets.Unicode(), default_value=['Apple', 'Pear']).tag(sync=True)
selected = traitlets.Unicode(default_value='', allow_none=True).tag(sync=True)
can_add_from_python = traitlets.Bool(default_value=True).tag(sync=True)
def vue_add_fruit_python(self, data=None):
if other_fruits:
fruit = other_fruits.pop()
self.fruits = self.fruits + [fruit]
if not other_fruits:
self.can_add_from_python = False
fruits = FruitSelector(fruits=['Banana', 'Pear', 'Apple'])
fruits
import ipyvuetify as v
import traitlets
import random
class CardExample(v.VuetifyTemplate):
template_file = 'card.vue'
loading = traitlets.Bool(default_value=False).tag(sync=True)
selection = traitlets.Int(default_value=1, allow_none=True).tag(sync=True)
card = CardExample()
card
card.selection
card.selection = 3
```
| github_jupyter |
# Create and Query ML Lineage between SageMaker - Models, Inference Endpoints, Feature Store, Processing Jobs and Datasources
---
#### Note: Please set kernel to Python 3 (Data Science) and select instance to ml.t3.medium
<div class="alert alert-info"> 💡 <strong> Quick Start </strong>
ML Lineage racking from datasource to model endpoint, The challenge of reproducibility and lineage in machine learning (ML) is three-fold: code lineage, data lineage, and model lineage. Source version control is a standard for managing changes to code. For data lineage, most data storage services support versioning, which gives you the ability to track datasets at a given point in time. Model lineage combines code lineage, data lineage, and ML-specific information such as Docker containers used for training and deployment, model hyperparameters, and more.
<strong><a style="color: #0397a7 " href="https://aws.amazon.com/blogs/machine-learning/model-and-data-lineage-in-machine-learning-experimentation/">
<u>Click here for a comprehensive ML lineage concepts</u></a>
</strong>
</div>
Feature engineering is expensive and time-consuming, leading customers to adopt a feature store
for managing features across teams and models. Unfortunately, ML lineage solutions have yet to
adapt to this new concept of feature management. To achieve the full benefits of feature reuse,
customers need to be able to answer fundamental questions about features. For example, how
was this feature group built? What models are using this feature group? What features does my
model depend on? What features are built with this data source?
---
Amazon SageMaker ML Lineage Tracking creates and stores information about the steps of a machine learning (ML) workflow from data preparation to model deployment. With the tracking information you can reproduce the workflow steps, track model and dataset lineage, and establish model governance and audit standards.
<strong><a style="color: #0397a7 " href="https://aws.amazon.com/blogs/machine-learning/extend-model-lineage-to-include-ml-features-using-amazon-sagemaker-feature-store/">
<u>Read about ML Lineage tracking with Feature store</u></a>
</strong>
#### With SageMaker Lineage Tracking data and feature store, scientists and builders can do the following:
---
##### 1. Build confidence for reuse of existing features.
##### 2. Avoid re-inventing features that are based on the same raw data as existing features.
##### 3. Troubleshooting and auditing models and model predictions.
##### 4. Manage features proactively.
---
## Contents
1. [Notebook Preparation](#Notebook-Preparation)
1. [Imports](#Imports)
1. [Check git submodules](#Check-git-submodules)
1. [Check and update Sagemaker version](#Check-and-update-Sagemaker-version)
1. [Logging Settings](#Logging-Settings)
1. [Module Configurations](#Module-Configurations)
1. [Load peristed variables from previous modules](#Load-peristed-variables-from-previous-modules)
1. [ML Lineage Creation](#ML-Lineage-Creation)
1. [Create ML Lineage](#Create-ML-Lineage)
1. [Verify ML Lineage](#Verify-ML-Lineage)
1. [ML Lineage Graph](#ML-Lineage-Graph)
1. [ML Lineage Querying](#ML-Lineage-Querying)
1. [What ML lineage relationships can you infer from this model's endpoint?](#A.)
1. [What feature groups were used to train this model?](#B.)
1. [What models were trained using this feature group?](#C.)
1. [What feature groups were populated with data from this datasource?](#D.)
1. [What datasources were used to populate a feature group?](#E.)
## Notebook Preparation
#### Imports
```
import sagemaker
from sagemaker.feature_store.feature_group import FeatureGroup
from sagemaker import get_execution_role
import pandas as pd
import logging
import os
import json
import sys
from pathlib import Path
path = Path(os.path.abspath(os.getcwd()))
package_dir = f'{str(path.parent)}/ml-lineage-helper'
print(package_dir)
sys.path.append(package_dir)
```
#### Check git submodules
##### Check to confirm that the submodule ml-lineage-helper and all the files underneath are present as shown below. If not, please continue with the next instruction to update them.

---
##### Run the following command in a terminal under the [./amazon-sagemaker-feature-store-end-to-end-workshop] folder path to update the missing submodules.
git submodule update

```
%load_ext autoreload
%autoreload 2
from ml_lineage_helper import *
from ml_lineage_helper.query_lineage import QueryLineage
```
#### Check and update Sagemaker version
```
if sagemaker.__version__ < '2.48.1':
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'sagemaker==2.48.1'])
importlib.reload(sagemaker)
```
#### Logging Settings
```
logger = logging.getLogger('__name__')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger.info(f'Using SageMaker version: {sagemaker.__version__}')
logger.info(f'Using Pandas version: {pd.__version__}')
```
#### Module Configurations
```
# Sagemaker session
sess = sagemaker.Session()
# Sagemaker Region
region=sess.boto_region_name
print(region)
# IAM role for executing the processing job.
iam_role = sagemaker.get_execution_role()
```
#### Load peristed variables from previous modules
```
# Retreive Estimator parameters
%store -r training_jobName
print(training_jobName)
# Retreive FG names
%store -r customers_feature_group_name
print(customers_feature_group_name)
%store -r products_feature_group_name
print(products_feature_group_name)
%store -r orders_feature_group_name
print(orders_feature_group_name)
# Retreive Orders Datasource
%store -r orders_datasource
print(orders_datasource)
# Retreive Processing Job
%store -r processing_job_name
print(processing_job_name)
%store -r processing_job_description
print(processing_job_description)
# Retreive Endpoint Name
%store -r endpoint_name
print(endpoint_name)
# Retreive Query String
%store -r query_string
print(query_string)
```
---
## ML Lineage Creation
---
<div class="alert alert-info"> 💡 <strong> Why is feature lineage important? </strong>
<p>Lineage tracking can tie together a SageMaker Processing job, the raw data being processed, the processing code, the query you used against the Feature Store to fetch your training and test sets, the training and test data in S3, and the training code into a lineage represented as a DAG.</p>
</div>

##### Imagine trying to manually track all of this for a large team, or multiple teams or even multiple business units. Lineage tracking and querying helps make this more manageable and helps organizations move to ML at scale
<div class="alert alert-info"> 💡 <strong> What relationships are important to track? </strong>
<p>The diagram below shows a sample set of ML lifecycle steps, artifacts, and associations that are
typically needed for model lineage when using a feature store, including:</p>
</div>
---

---
#### Data source:
##### ML features depend on raw data sources like an operational data store, or a set of CSV files in Amazon S3.
#### Feature pipeline:
##### Production-worthy features are typically built using a feature pipeline that takes a set of raw data sources, performs feature transformations, and ingests resulting features into the feature store. Lineage tracking can help by associating those pipelines with their data sources and their target feature groups.
#### Feature sets:
##### Once features are in a feature store, data scientists query it to retrieve data for training and validation of a model. You can use lineage tracking to associate the feature store query with the produced dataset. This provides granular detail into which features were used and what feature history was selected across multiple feature groups.
#### Training job:
##### As the ML lifecycle matures to adopt the use of a feature store, model lineage can associate training with specific features and feature groups
#### Model:
##### In addition to relating models to hosting endpoints, they can be linked to their corresponding training job, and indirectly to feature groups.
#### Endpoint:
##### Lastly, for online models, specific endpoints can be associated with the models they are hosting, completing the end to end chain from data sources to endpoints providing predictions.
---
<div class="alert alert-info"> 💡 <strong>Tip</strong>
<p>An end-to-end lineage solution needs to give you the means to access information about parameters, versioning, data sourcess and their respective associations to understand all aspects that went in to training the model.</p>
</div>
#### Clear (Delete) existing ML Lineage
<div class="alert alert-warning"> 💡 <strong>Warning!!!</strong>
<p>Executing the <b>[delete_lineage_data()]</b> method will remove all Lineage among the associated artifacts used.</p>
<p>Please <b>DO NOT UNCOMMENT AND EXECUTE</b> the following code unless you absolutely understand of the consequences</p>
</div>
```
#sagemakersession = SageMakerSession(bucket_name=sess.default_bucket(),
# region=region,
# role_name=iam_role,
# aws_profile_name="default",
# )
#ml_lineage = MLLineageHelper(sagemaker_session=sagemakersession, sagemaker_model_name_or_model_s3_uri=endpoint_name)
#ml_lineage.delete_lineage_data()
```
#### Create ML Lineage
---
Lineage tracking can tie together a SageMaker Processing job, the raw data being processed, the processing code, the query you used against the Feature Store to fetch your training and test sets, the training and test data in S3, and the training code into a lineage represented as a DAG.
---
Many of the inputs are optional, but in this example we assume:
1. You started with a raw data source
2. You used SageMaker Data Wrangler to process the raw data and ingest it into the orders Feature Group.
3. You queried the Feature Store to create training and test datasets.
4. You trained a model in SageMaker on your training and test datasets.
```
# Model name is same as endpoint name in this example
ml_lineage = MLLineageHelper()
lineage = ml_lineage.create_ml_lineage(training_jobName, model_name=endpoint_name, query=query_string,
feature_group_names=[customers_feature_group_name,
products_feature_group_name,
orders_feature_group_name],
sagemaker_processing_job_description=processing_job_description
)
```
### Verify ML Lineage
```
# Print the ML Lineage
lineage
```
### ML Lineage Graph
<div class="alert alert-info"> 💡 <strong>Tip</strong>
<p>Given the number of components that are part of a model’s lineage, you may want to inspect the lineage of not only the model, but any object associated with the model, With a graph as the underlying data structure that supports lineage, you should have the flexibility to traverse an entity’s lineage from different focal points. You should be able to find the entire lineage of a model and all the components involved in creating it.</p>
</div>
```
# Visual Representation of the ML Lineage
ml_lineage.graph()
```
---
## ML Lineage Querying
---
<div class="alert alert-info"> 💡 <strong> What ML lineage relationships can you infer using this module? </strong>
<p>Feature mangement, auditing and trouble shooting</p>
</div>
---

---
##### A.
<div class="alert alert-info"> 💡 <strong>What ML lineage relationships can you infer from this model's endpoint?</strong>
<p>Query ML Lineage by SageMaker Model Name or SageMaker Inference Endpoint</p>
</div>
```
lineageObject = MLLineageHelper(sagemaker_model_name_or_model_s3_uri=endpoint_name)
lineageObject.df
```
---
##### B.
<div class="alert alert-info"> 💡 <strong>What feature groups were used to train this model?</strong>
<p>Given a SageMaker Model Name or artifact ARN, you can find associated Feature Groups</p>
</div>
```
query_lineage = QueryLineage()
query_lineage.get_feature_groups_from_model(endpoint_name)
```
---
##### C.
<div class="alert alert-info"> 💡 <strong>What models were trained using this feature group?</strong>
<p>Given a Feature Group ARN, and find associated SageMaker Models</p>
</div>
```
feature_group = FeatureGroup(name=orders_feature_group_name, sagemaker_session=sess)
query_lineage.get_models_from_feature_group(feature_group.describe()['FeatureGroupArn'])
```
---
##### D.
<div class="alert alert-info"> 💡 <strong>What feature groups were populated with data from this datasource?</strong>
<p>Given a data source's S3 URI or Artifact ARN, you can find associated SageMaker Feature Groups</p>
</div>
```
query_lineage.get_feature_groups_from_data_source(orders_datasource, 3)
```
---
##### E.
<div class="alert alert-info"> 💡 <strong>What datasources were used to populate a feature group?</strong>
<p>Given a Feature Group ARN, and find associated data sources</p>
</div>
```
orders_feature_group = FeatureGroup(name=orders_feature_group_name, sagemaker_session=sess)
orders_feature_group_arn = orders_feature_group.describe()['FeatureGroupArn']
print(orders_feature_group_arn)
query_lineage.get_data_sources_from_feature_group(orders_feature_group_arn, max_depth=2)
```
---
| github_jupyter |
##### Copyright 2020 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Introduction to graphs and tf.function
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/intro_to_graphs"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/intro_to_graphs.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/intro_to_graphs.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/intro_to_graphs.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Overview
This guide goes beneath the surface of TensorFlow and Keras to demonstrate how TensorFlow works. If you instead want to immediately get started with Keras, check out the [collection of Keras guides](https://www.tensorflow.org/guide/keras/).
In this guide, you'll learn how TensorFlow allows you to make simple changes to your code to get graphs, how graphs are stored and represented, and how you can use them to accelerate your models.
Note: For those of you who are only familiar with TensorFlow 1.x, this guide demonstrates a very different view of graphs.
**This is a big-picture overview that covers how `tf.function` allows you to switch from eager execution to graph execution.** For a more complete specification of `tf.function`, go to the [`tf.function` guide](function).
### What are graphs?
In the previous three guides, you ran TensorFlow **eagerly**. This means TensorFlow operations are executed by Python, operation by operation, and returning results back to Python.
While eager execution has several unique advantages, graph execution enables portability outside Python and tends to offer better performance. **Graph execution** means that tensor computations are executed as a *TensorFlow graph*, sometimes referred to as a `tf.Graph` or simply a "graph."
**Graphs are data structures that contain a set of `tf.Operation` objects, which represent units of computation; and `tf.Tensor` objects, which represent the units of data that flow between operations.** They are defined in a `tf.Graph` context. Since these graphs are data structures, they can be saved, run, and restored all without the original Python code.
This is what a TensorFlow graph representing a two-layer neural network looks like when visualized in TensorBoard.
<img alt="A simple TensorFlow graph" src="https://github.com/tensorflow/docs/blob/master/site/en/guide/images/intro_to_graphs/two-layer-network.png?raw=1">
### The benefits of graphs
With a graph, you have a great deal of flexibility. You can use your TensorFlow graph in environments that don't have a Python interpreter, like mobile applications, embedded devices, and backend servers. TensorFlow uses graphs as the format for [saved models](saved_model) when it exports them from Python.
Graphs are also easily optimized, allowing the compiler to do transformations like:
* Statically infer the value of tensors by folding constant nodes in your computation *("constant folding")*.
* Separate sub-parts of a computation that are independent and split them between threads or devices.
* Simplify arithmetic operations by eliminating common subexpressions.
There is an entire optimization system, [Grappler](./graph_optimization.ipynb), to perform this and other speedups.
In short, graphs are extremely useful and let your TensorFlow run **fast**, run **in parallel**, and run efficiently **on multiple devices**.
However, you still want to define your machine learning models (or other computations) in Python for convenience, and then automatically construct graphs when you need them.
## Setup
```
import tensorflow as tf
import timeit
from datetime import datetime
```
## Taking advantage of graphs
You create and run a graph in TensorFlow by using `tf.function`, either as a direct call or as a decorator. `tf.function` takes a regular function as input and returns a `Function`. **A `Function` is a Python callable that builds TensorFlow graphs from the Python function. You use a `Function` in the same way as its Python equivalent.**
```
# Define a Python function.
def a_regular_function(x, y, b):
x = tf.matmul(x, y)
x = x + b
return x
# `a_function_that_uses_a_graph` is a TensorFlow `Function`.
a_function_that_uses_a_graph = tf.function(a_regular_function)
# Make some tensors.
x1 = tf.constant([[1.0, 2.0]])
y1 = tf.constant([[2.0], [3.0]])
b1 = tf.constant(4.0)
orig_value = a_regular_function(x1, y1, b1).numpy()
# Call a `Function` like a Python function.
tf_function_value = a_function_that_uses_a_graph(x1, y1, b1).numpy()
assert(orig_value == tf_function_value)
```
On the outside, a `Function` looks like a regular function you write using TensorFlow operations. [Underneath](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/eager/def_function.py), however, it is *very different*. A `Function` **encapsulates [several `tf.Graph`s behind one API](#polymorphism_one_function_many_graphs).** That is how `Function` is able to give you the [benefits of graph execution](#the_benefits_of_graphs), like speed and deployability.
`tf.function` applies to a function *and all other functions it calls*:
```
def inner_function(x, y, b):
x = tf.matmul(x, y)
x = x + b
return x
# Use the decorator to make `outer_function` a `Function`.
@tf.function
def outer_function(x):
y = tf.constant([[2.0], [3.0]])
b = tf.constant(4.0)
return inner_function(x, y, b)
# Note that the callable will create a graph that
# includes `inner_function` as well as `outer_function`.
outer_function(tf.constant([[1.0, 2.0]])).numpy()
```
If you have used TensorFlow 1.x, you will notice that at no time did you need to define a `Placeholder` or `tf.Session`.
### Converting Python functions to graphs
Any function you write with TensorFlow will contain a mixture of built-in TF operations and Python logic, such as `if-then` clauses, loops, `break`, `return`, `continue`, and more. While TensorFlow operations are easily captured by a `tf.Graph`, Python-specific logic needs to undergo an extra step in order to become part of the graph. `tf.function` uses a library called AutoGraph (`tf.autograph`) to convert Python code into graph-generating code.
```
def simple_relu(x):
if tf.greater(x, 0):
return x
else:
return 0
# `tf_simple_relu` is a TensorFlow `Function` that wraps `simple_relu`.
tf_simple_relu = tf.function(simple_relu)
print("First branch, with graph:", tf_simple_relu(tf.constant(1)).numpy())
print("Second branch, with graph:", tf_simple_relu(tf.constant(-1)).numpy())
```
Though it is unlikely that you will need to view graphs directly, you can inspect the outputs to check the exact results. These are not easy to read, so no need to look too carefully!
```
# This is the graph-generating output of AutoGraph.
print(tf.autograph.to_code(simple_relu))
# This is the graph itself.
print(tf_simple_relu.get_concrete_function(tf.constant(1)).graph.as_graph_def())
```
Most of the time, `tf.function` will work without special considerations. However, there are some caveats, and the [tf.function guide](./function.ipynb) can help here, as well as the [complete AutoGraph reference](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/index.md)
### Polymorphism: one `Function`, many graphs
A `tf.Graph` is specialized to a specific type of inputs (for example, tensors with a specific [`dtype`](https://www.tensorflow.org/api_docs/python/tf/dtypes/DType) or objects with the same [`id()`](https://docs.python.org/3/library/functions.html#id])).
Each time you invoke a `Function` with new `dtypes` and shapes in its arguments, `Function` creates a new `tf.Graph` for the new arguments. The `dtypes` and shapes of a `tf.Graph`'s inputs are known as an **input signature** or just a **signature**.
The `Function` stores the `tf.Graph` corresponding to that signature in a `ConcreteFunction`. **A `ConcreteFunction` is a wrapper around a `tf.Graph`.**
```
@tf.function
def my_relu(x):
return tf.maximum(0., x)
# `my_relu` creates new graphs as it observes more signatures.
print(my_relu(tf.constant(5.5)))
print(my_relu([1, -1]))
print(my_relu(tf.constant([3., -3.])))
```
If the `Function` has already been called with that signature, `Function` does not create a new `tf.Graph`.
```
# These two calls do *not* create new graphs.
print(my_relu(tf.constant(-2.5))) # Signature matches `tf.constant(5.5)`.
print(my_relu(tf.constant([-1., 1.]))) # Signature matches `tf.constant([3., -3.])`.
```
Because it's backed by multiple graphs, a `Function` is **polymorphic**. That enables it to support more input types than a single `tf.Graph` could represent, as well as to optimize each `tf.Graph` for better performance.
```
# There are three `ConcreteFunction`s (one for each graph) in `my_relu`.
# The `ConcreteFunction` also knows the return type and shape!
print(my_relu.pretty_printed_concrete_signatures())
```
## Using `tf.function`
So far, you've learned how to convert a Python function into a graph simply by using `tf.function` as a decorator or wrapper. But in practice, getting `tf.function` to work correctly can be tricky! In the following sections, you'll learn how you can make your code work as expected with `tf.function`.
### Graph execution vs. eager execution
The code in a `Function` can be executed both eagerly and as a graph. By default, `Function` executes its code as a graph:
```
@tf.function
def get_MSE(y_true, y_pred):
sq_diff = tf.pow(y_true - y_pred, 2)
return tf.reduce_mean(sq_diff)
y_true = tf.random.uniform([5], maxval=10, dtype=tf.int32)
y_pred = tf.random.uniform([5], maxval=10, dtype=tf.int32)
print(y_true)
print(y_pred)
get_MSE(y_true, y_pred)
```
To verify that your `Function`'s graph is doing the same computation as its equivalent Python function, you can make it execute eagerly with `tf.config.run_functions_eagerly(True)`. This is a switch that **turns off `Function`'s ability to create and run graphs**, instead executing the code normally.
```
tf.config.run_functions_eagerly(True)
get_MSE(y_true, y_pred)
# Don't forget to set it back when you are done.
tf.config.run_functions_eagerly(False)
```
However, `Function` can behave differently under graph and eager execution. The Python [`print`](https://docs.python.org/3/library/functions.html#print) function is one example of how these two modes differ. Let's check out what happens when you insert a `print` statement to your function and call it repeatedly.
```
@tf.function
def get_MSE(y_true, y_pred):
print("Calculating MSE!")
sq_diff = tf.pow(y_true - y_pred, 2)
return tf.reduce_mean(sq_diff)
```
Observe what is printed:
```
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
```
Is the output surprising? **`get_MSE` only printed once even though it was called *three* times.**
To explain, the `print` statement is executed when `Function` runs the original code in order to create the graph in a process known as ["tracing"](function.ipynb#tracing). **Tracing captures the TensorFlow operations into a graph, and `print` is not captured in the graph.** That graph is then executed for all three calls **without ever running the Python code again**.
As a sanity check, let's turn off graph execution to compare:
```
# Now, globally set everything to run eagerly to force eager execution.
tf.config.run_functions_eagerly(True)
# Observe what is printed below.
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
tf.config.run_functions_eagerly(False)
```
`print` is a *Python side effect*, and there are other differences that you should be aware of when converting a function into a `Function`. Learn more in the _Limitations_ section of the [Better performance with tf.function](./function.ipynb#limitations) guide.
Note: If you would like to print values in both eager and graph execution, use `tf.print` instead.
### Non-strict execution
<a id="non-strict"></a>
Graph execution only executes the operations necessary to produce the observable effects, which includes:
- The return value of the function
- Documented well-known side-effects such as:
- Input/output operations, like `tf.print`
- Debugging operations, such as the assert functions in `tf.debugging`
- Mutations of `tf.Variable`
This behavior is usually known as "Non-strict execution", and differs from eager execution, which steps through all of the program operations, needed or not.
In particular, runtime error checking does not count as an observable effect. If an operation is skipped because it is unnecessary, it cannot raise any runtime errors.
In the following example, the "unnecessary" operation `tf.gather` is skipped during graph execution, so the runtime error `InvalidArgumentError` is not raised as it would be in eager execution. Do not rely on an error being raised while executing a graph.
```
def unused_return_eager(x):
# Get index 1 will fail when `len(x) == 1`
tf.gather(x, [1]) # unused
return x
try:
print(unused_return_eager(tf.constant([0.0])))
except tf.errors.InvalidArgumentError as e:
# All operations are run during eager execution so an error is raised.
print(f'{type(e).__name__}: {e}')
@tf.function
def unused_return_graph(x):
tf.gather(x, [1]) # unused
return x
# Only needed operations are run during graph exection. The error is not raised.
print(unused_return_graph(tf.constant([0.0])))
```
###`tf.function` best practices
It may take some time to get used to the behavior of `Function`. To get started quickly, first-time users should play around with decorating toy functions with `@tf.function` to get experience with going from eager to graph execution.
*Designing for `tf.function`* may be your best bet for writing graph-compatible TensorFlow programs. Here are some tips:
- Toggle between eager and graph execution early and often with `tf.config.run_functions_eagerly` to pinpoint if/ when the two modes diverge.
- Create `tf.Variable`s
outside the Python function and modify them on the inside. The same goes for objects that use `tf.Variable`, like `keras.layers`, `keras.Model`s and `tf.optimizers`.
- Avoid writing functions that [depend on outer Python variables](function#depending_on_python_global_and_free_variables), excluding `tf.Variable`s and Keras objects.
- Prefer to write functions which take tensors and other TensorFlow types as input. You can pass in other object types but [be careful](function#depending_on_python_objects)!
- Include as much computation as possible under a `tf.function` to maximize the performance gain. For example, decorate a whole training step or the entire training loop.
## Seeing the speed-up
`tf.function` usually improves the performance of your code, but the amount of speed-up depends on the kind of computation you run. Small computations can be dominated by the overhead of calling a graph. You can measure the difference in performance like so:
```
x = tf.random.uniform(shape=[10, 10], minval=-1, maxval=2, dtype=tf.dtypes.int32)
def power(x, y):
result = tf.eye(10, dtype=tf.dtypes.int32)
for _ in range(y):
result = tf.matmul(x, result)
return result
print("Eager execution:", timeit.timeit(lambda: power(x, 100), number=1000))
power_as_graph = tf.function(power)
print("Graph execution:", timeit.timeit(lambda: power_as_graph(x, 100), number=1000))
```
`tf.function` is commonly used to speed up training loops, and you can learn more about it in [Writing a training loop from scratch](https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch#speeding-up_your_training_step_with_tffunction) with Keras.
Note: You can also try [`tf.function(jit_compile=True)`](https://www.tensorflow.org/xla#explicit_compilation_with_tffunctionjit_compiletrue) for a more significant performance boost, especially if your code is heavy on TF control flow and uses many small tensors.
### Performance and trade-offs
Graphs can speed up your code, but the process of creating them has some overhead. For some functions, the creation of the graph takes more time than the execution of the graph. **This investment is usually quickly paid back with the performance boost of subsequent executions, but it's important to be aware that the first few steps of any large model training can be slower due to tracing.**
No matter how large your model, you want to avoid tracing frequently. The `tf.function` guide discusses [how to set input specifications and use tensor arguments](function#controlling_retracing) to avoid retracing. If you find you are getting unusually poor performance, it's a good idea to check if you are retracing accidentally.
## When is a `Function` tracing?
To figure out when your `Function` is tracing, add a `print` statement to its code. As a rule of thumb, `Function` will execute the `print` statement every time it traces.
```
@tf.function
def a_function_with_python_side_effect(x):
print("Tracing!") # An eager-only side effect.
return x * x + tf.constant(2)
# This is traced the first time.
print(a_function_with_python_side_effect(tf.constant(2)))
# The second time through, you won't see the side effect.
print(a_function_with_python_side_effect(tf.constant(3)))
# This retraces each time the Python argument changes,
# as a Python argument could be an epoch count or other
# hyperparameter.
print(a_function_with_python_side_effect(2))
print(a_function_with_python_side_effect(3))
```
New Python arguments always trigger the creation of a new graph, hence the extra tracing.
## Next steps
You can learn more about `tf.function` on the API reference page and by following the [Better performance with `tf.function`](function) guide.
| github_jupyter |
#### AMPEL intro
AMPEL is software framework designed for processing heterogeneous streamed data.
AMPEL was not developed to provide a specific scientific resource, but rather an environment where it is easy to ensure that a scientific program fulfills the strict requirement of the next generation real-time experiments: efficient and powerful analysis, where provenance and reproducibiltiy is paramount. In particular, to guarantee the last point requires algorithms (which make real-time deicsions) be separated from infrastructure (which will likely evolve with time and project phase).
An AMPEL _user_ constructs a configuration file which describes every step of how an incoming alert stream should be processed. This can be broken down into selecting which _units_ should be executed, and which _parameters_ each of these should be provided. An AMPEL _live instance_ executes these units, based on the input data, as requested and stores all intermediate and final data in a databse.
Provenance/reproducibility is ensured through multiple layers. First, each live instance is run from a container which can be retrieved later and together with a data archive replay the full stream. Second, AMPEL contains an extensive set of logs and a transient-specific _Journal_ which details all related actions/decisions. Finally, each unit and channel configuration file is drawn from a specific (tagged) github version.
The series of notebooks provided here gradually builds toward a sample full configration.
#### Sample science case
Each AMPEl _channel_ is designed with a science goal (or "hypothesis/test") in mind. A much discussed current topic is the origin of the extragalactic neutrino flux observed e.g. by IceCube, with one of the potential sources being supernovae interacting with circumstellar material (SNIIn). We here wish to investigate whether a particular subtype of these, SN2009ip-like SNe with recent previous outbursts, are regularly found within the uncertainty region of neutrino alerts.
The steps for this science program would be: Identify transients with optical lightcurves compatible with SN2009ip AND which coincide with neutrino alerts. For such targets, obtain follow-up spectroscopy to confirm classification (i.e. an external reaction).
#### This notebook - Tutorial 4
This notebook reproduces the results of Tutorial 3, but through using external configuration files. These work as "recipes" for a scientific program. Subsequent analysis verisons can be expressed through changes to these, and they can be conveniently distributed e.g. in publications. Versions of the same sample channel is provided both as `SAMPLE_CHANNEL.yml` in the `conf/ampel-contrib/sample/channel` dir and as two processes in the `conf/ampel-contrib/sample/process` dir. The content of `SAMPLE_CHANNEL.yml` is included the cell below. The generation of the core `ampel_config.yml` file included all of these.
At this stage the channel is ready to be included in a live AMPEL instance. This can either be used to process a large set of archive data, or for processing a real-time data stream. Simultaneously, the channel configuration and the unit algorithms serves to provide a full, referencable description of the science content of the channel.
As in Tutorial 2, this notebook thus assumes a mongod instance to be running and accessible through 27017. (The port can be changed through the mongo key of the ampel_config.yml file).
###### Content of SAMPLE_CHANNEL.yml
```
import os
%load_ext ampel_quick_import
%qi DevAmpelContext AmpelLogger T2Processor T3Processor ChannelModel AlertProcessor TarAlertLoader ChannelModel AbsAlertFilter ProcessModel AbsProcessorUnit DefaultProcessController
AMPEL_CONF = "../../ampel_config.yml"
ALERT_ARCHIVE = '../sample_data/ztfpub_200917_pruned.tar.gz'
# The operation context is created based on a setup configuration file.
# db_prefix sets the DB name to use
ctx = DevAmpelContext.load(
config_file_path = AMPEL_CONF,
db_prefix = "AmpelTutorial",
purge_db = True,
)
```
First the t0 selection/filter process will be run, as gathered from the 'process' folder:
```
process_name = "process.t0.sample_t0_process"
# A process model is determined and executed by a processor
pm = ProcessModel(**ctx.config.get(process_name))
ctx.loader.new_admin_unit(unit_model = pm.processor, context = ctx, process_name = pm.name).run()
```
Outcome is the same as previously. This process also created "tickets" for T2 calculations to do. These will now be executed:
```
process_name = "process.t2.DefaultT2Process"
pm = ProcessModel(**ctx.config.get(process_name))
ctx.loader.new_admin_unit(unit_model = pm.processor, context = ctx, process_name = pm.name).run()
process_name = "process.t3.sample_t3_process"
pm = ProcessModel(**ctx.config.get(process_name))
ctx.loader.new_admin_unit(unit_model = pm.processor, context = ctx, process_name = pm.name).run()
```
| github_jupyter |
```
import pickle
import math
import nltk
from nltk.corpus import wordnet as wn
import numpy as np
import string
import itertools
import datetime
import sys
import re
import os
import Stemmer
```
# Functions
### Similarity Metrics
#### Softcosine similarity function
$softcosine(a,b)=\frac{ \sum_{i}^{N}{ \sum_{j}^{N}{s_{ij} a_i b_j} } }{ \sqrt{ \sum{ \sum_{i,j}^{N}{s_{ij} a_i a_j} } } \sqrt{ \sum{ \sum_{i,j}^{N}{s_{ij} b_i b_j} } }} $
```
def soft_euclidean_norm(vect, ft_id2wn_id, term_sims):
"""Compute the soft euclidean norm given a vector <v> in dict format and a """
norm = 0.0
for token1_id in vect:
for token2_id in vect:
# Here me need to check if (a_i, a_j) is the same as (a_j, a_i)******************************
# The similarity between the same terms is 1
if token1_id == token2_id:
norm += vect[token1_id] * vect[token2_id]
else:
sims = []
for wn_id1 in ft_id2wn_id[token1_id]:
for wn_id2 in ft_id2wn_id[token2_id]:
sim_key = (wn_id1, wn_id2) if wn_id1 > wn_id2 else (wn_id2, wn_id1)
if sim_key in term_sims:
sims.append(term_sims[sim_key])
if len(sims) > 0:
norm += max(sims) * vect[token1_id] * vect[token2_id]
return math.sqrt(norm)
def softcosine(vect1, vect2, ft_id2wn_id, term_sims):
"""Compute the softcosine similarity given two vectors
<a> and <b> in a dictionary format, and the ."""
dot_prod = 0.0
det = soft_euclidean_norm(vect1, ft_id2wn_id, term_sims) * soft_euclidean_norm(vect2, ft_id2wn_id, term_sims)
if det == 0.0:
return 0.0
for token1_id in vect1:
for token2_id in vect2:
if token1_id == token2_id:
dot_prod += vect1[token1_id] * vect2[token2_id]
else:
sims = []
for wn_id1 in ft_id2wn_id[token1_id]:
for wn_id2 in ft_id2wn_id[token2_id]:
sim_key = (wn_id1, wn_id2) if wn_id1 > wn_id2 else (wn_id2, wn_id1)
if sim_key in term_sims:
sims.append(term_sims[sim_key])
if len(sims) > 0:
dot_prod += max(sims) * vect1[token1_id] * vect2[token2_id]
return dot_prod / det
```
#### Cosine similarity function
$cosine(a,b)=\frac{a \cdot b}{|a| |b|}=\frac{\sum_{i}^{N}{a_i b_i}}{\sqrt{ \sum_{i}^{N}{a_i^2} } \sqrt{ \sum_{i}^{N}{b_i^2} }}$
```
def euclidean_norm(vect):
norm = 0.0
for token_id in vect:
norm += vect[token_id]**2
return math.sqrt(norm)
def cosine(vect1, vect2):
dot_prod = 0.0
det = euclidean_norm(vect1) * euclidean_norm(vect2)
if det == 0.0:
return 0.0
for token_id in vect1:
if token_id in vect2:
dot_prod += vect1[token_id] * vect2[token_id]
return dot_prod / det
```
#### Stevenson similarity metric
Fernando, S. and Stevenson, M. (2008). **A semantic similarity approach to paraphrase detection**, *Computational Linguistics UK (CLUK 2008) 11th Annual Research Colloquium*
$stevenson\_sim(a,b)=\frac{a \cdot W \cdot b}{|a| |b|}=\frac{ \sum_{i}^{N}{ \sum_{j}^{N}{W_{ij} a_i b_j} } }{\sqrt{ \sum_{i}^{N}{a_i^2} } \sqrt{ \sum_{i}^{N}{b_i^2} }}$
```
def stevenson_sim(vect1, vect2, ft_id2wn_id, term_sims):
dot_prod = 0.0
det = euclidean_norm(vect1) * euclidean_norm(vect2)
if det == 0.0:
return 0.0
for token1_id in vect1:
for token2_id in vect2:
if token1_id == token2_id:
dot_prod += vect1[token1_id] * vect2[token2_id]
else:
sims = []
for wn_id1 in ft_id2wn_id[token1_id]:
for wn_id2 in ft_id2wn_id[token2_id]:
sim_key = (wn_id1, wn_id2) if wn_id1 > wn_id2 else (wn_id2, wn_id1)
if sim_key in term_sims:
sims.append(term_sims[sim_key])
if len(sims) > 0:
dot_prod += max(sims) * vect1[token1_id] * vect2[token2_id]
return dot_prod / det
```
#### Mihalcea's similarity method
```
def mihalcea_sim(vect1, vect2, ft_id2wn_id, ft_id2token_id, term_sims, idf, idf_median_value):
sum1 = 0.0
sum_idf1 = 0.0
for token1_id in vect1:
max_sim = 0.0
for token2_id in vect2:
if token1_id == token2_id:
max_sim = 1.0
break
for wn_id1 in ft_id2wn_id[token1_id]:
for wn_id2 in ft_id2wn_id[token2_id]:
sim_key = (wn_id1, wn_id2) if wn_id1 > wn_id2 else (wn_id2, wn_id1)
if sim_key in term_sims:
sval = term_sims[sim_key]
max_sim = sval if sval > max_sim else max_sim
#idf_val = idf.get(list(ft_id2token_id[token1_id])[0], idf_median_value)
idf_val = max([idf.get(x, idf_median_value) for x in ft_id2token_id[token1_id]])
sum1 += max_sim * (idf_val)
sum_idf1 += idf_val
sum2 = 0.0
sum_idf2 = 0.0
for token2_id in vect2:
max_sim = 0.0
for token1_id in vect1:
if token2_id == token1_id:
max_sim = 1.0
break
for wn_id2 in ft_id2wn_id[token2_id]:
for wn_id1 in ft_id2wn_id[token1_id]:
sim_key = (wn_id1, wn_id2) if wn_id1 > wn_id2 else (wn_id2, wn_id1)
if sim_key in term_sims:
sval = term_sims[sim_key]
max_sim = sval if sval > max_sim else max_sim
#idf_val = idf.get(list(ft_id2token_id[token2_id])[0], idf_median_value)
idf_val = max([idf.get(x, idf_median_value) for x in ft_id2token_id[token2_id]])
sum2 += max_sim * (idf_val)
sum_idf2 += idf_val
return 1/2 * (sum1/sum_idf1 + sum2/sum_idf2)
```
### Function to compute similarity metrics for all pairs in MSRPCorpus
Training instances
**TODO**
- Implement the tf-idf and log enthropy measures.
- Compute the the idf and enthropy over some of the existing corpora
- Implement Mihalcea's method
```
def compute_sims(pairs, vectors, feature, ft_id2wn_id, ft_id2token_id, metric="cosine",
weight_scheme="tf", term_sims={}, idf={}, idf_median_value=0.0):
res = []
for text_id1, text_id2 in pairs:
# Vectorization
if weight_scheme == "tf":
v1 = nltk.FreqDist([x[feature] for x in vectors[text_id1]])
v2 = nltk.FreqDist([x[feature] for x in vectors[text_id2]])
#v1 = nltk.FreqDist([eval(feature+"_id") for token_id, lemma_id, stem_id, lemmapos_id in vectors[text_id1]])
#v2 = nltk.FreqDist([eval(feature+"_id") for token_id, lemma_id, stem_id, lemmapos_id in vectors[text_id2]])
elif weight_scheme == "binary":
v1 = {}.fromkeys(set([x[feature] for x in vectors[text_id1]]), 1)
v2 = {}.fromkeys(set([x[feature] for x in vectors[text_id2]]), 1)
#v1 = {}.fromkeys(set([eval(feature+"_id") for token_id, lemma_id, stem_id, lemmapos_id in vectors[text_id1]]), 1)
#v2 = {}.fromkeys(set([eval(feature+"_id") for token_id, lemma_id, stem_id, lemmapos_id in vectors[text_id2]]), 1)
else:
print("Unrecognized weighting scheme")
raise
# Similarity computation
if metric == "softcosine":
res.append(softcosine(v1, v2, ft_id2wn_id, term_sims))
elif metric == "cosine":
res.append(cosine(v1, v2))
elif metric == "stevenson":
res.append(stevenson_sim(v1, v2, ft_id2wn_id, term_sims))
elif metric == "mihalcea":
res.append(mihalcea_sim(v1, v2, ft_id2wn_id, ft_id2token_id, term_sims, idf, idf_median_value))
else:
print("Unimplemented similarity metric")
raise
#break
return res
```
#### Optimizing the similarity threshold
```
def compute_scores(pair_sims, y, thresholds):
"""Receives a float between 0 and 1, or an iterable that returns such floats.
The function returns the <tuple>/<list of tuples> of scores
(threshold, accuracy, f_measure, precision, recall)"""
# (accuracy, f_measure, precision, recall)
if hasattr(thresholds, '__iter__'):
measures = []
for th in thresholds: #range(5, 101, 5):
results = [1 if val >= th else 0 for val in pair_sims]
measures.append((th,)+evaluate(results, y))
return measures
else:
results = [1 if val >= thresholds else 0 for val in pair_sims]
return (thresholds,)+evaluate(results, y)
```
### Preprocessing
#### Check if a token is made purely of punctuation symbols
```
def is_punct_token(token, puncts):
if sum([1 for c in token if c in puncts]) == len(token):
return True
return False
```
### Evaluation metrics
accuracy, f_measure, precision, recall
```
def evaluate(result, truth):
"""Receive the gold_standard and values returned by our system.
Return a tuple as (accuracy, f_measure, precision, recall)"""
tp, fp, tn, fn = 0, 0, 0, 0
for r, t in zip(result, truth):
if t == 1:
if r == 1:
tp += 1
else:
fn += 1
else:
if r == 1:
fp += 1
else:
tn += 1
accuracy = 0.0 if tp+tn+fp+fn == 0 else (tp+tn) / (tp+tn+fp+fn)
precision = 0.0 if tp+fp == 0 else tp / (tp+fp)
recall = 0.0 if (tp+fn) == 0 else tp / (tp+fn)
f_measure = (0 if precision + recall == 0 else
2*precision*recall/(precision+recall))
return accuracy, f_measure, precision, recall
```
### Normalization strategy for each WordNet metric
```
def normalize(term_sims, metric):
if metric == "path":
# Not need for normalization.
# Creating a copy of the similarity matrix
return dict(term_sims.items())
elif metric == "lch":
# MinMax normalization
data = np.array([val for (tkid1, tkid2), val in term_sims.items()])
_max = np.max(data)
_min = np.min(data)
res = {}
for key, val in term_sims.items():
res[key] = (val - _min)/(_max - _min)
return res
elif metric == "wup":
# Creating a copy of the similarity matrix
return dict(term_sims.items())
elif metric == "res":
# MinMax normalization except for extremly big values (WordNet Inf=1e300)
data = np.array([val for (tkid1, tkid2), val in term_sims.items() if val < 10000])
_max = np.max(data)
_min = np.min(data)
res = {}
for key, val in term_sims.items():
# Exception
if val > 10000:
res[key] = 1.0
else:
res[key] = (val - _min)/(_max - _min)
return res
elif metric == "jcn":
# MinMax normalization except for extremly big values (WordNet Inf=1e300)
data = np.array([val for (tkid1, tkid2), val in term_sims.items() if val < 10000])
_max = np.max(data)
_min = np.min(data)
res = {}
for key, val in term_sims.items():
# Exception
if val > 10000:
res[key] = 1.0
else:
res[key] = (val - _min)/(_max - _min)
return res
elif metric == "lin":
# Not need for normalization.
# Creating a copy of the similarity matrix
return dict(term_sims.items())
print("Unrecognize metric")
raise
```
# MAIN
#### Loading the parsed MSRPCorpus
```
[parsed_texts,
train_pairs,
train_y,
test_pairs,
test_y] = pickle.load(open("msrpc_parsed_20170821.pickle", 'rb'))
[vocab_tokens, token2index, index2token] = pickle.load(open("tokens_data_20170821.pickle", 'rb'))
[vocab_lemmas, lemma2index, index2lemma] = pickle.load(open("lemmas_data_20170821.pickle", 'rb'))
[vocab_stems, stem2index, index2stem] = pickle.load(open("stems_data_20170821.pickle", 'rb'))
[vocab_lemmapos, lemmapos2index, index2lemmapos] = pickle.load(open("lemmapos_data_20170821.pickle", 'rb'))
```
#### Loading WordNet similarity "matrix"
It is a dictionary (token1_id, token2_id): sim_value, where token1_id > token2_id
```
# PATH Similarity
path_all_tokens = pickle.load(open("path_all_tokens_20170821.pickle", 'rb'))
path_all_lemmas = pickle.load(open("path_all_lemmas_20170821.pickle", 'rb'))
path_all_lemmapos = pickle.load(open("path_all_lemmapos_20170821.pickle", 'rb'))
path_first_tokens = pickle.load(open("path_first_tokens_20170821.pickle", 'rb'))
path_first_lemmas = pickle.load(open("path_first_lemmas_20170821.pickle", 'rb'))
path_first_lemmapos = pickle.load(open("path_first_lemmapos_20170821.pickle", 'rb'))
# LCH Similarity
lch_all_tokens = pickle.load(open("lch_all_tokens_20170821.pickle", 'rb'))
lch_all_lemmas = pickle.load(open("lch_all_lemmas_20170821.pickle", 'rb'))
lch_all_lemmapos = pickle.load(open("lch_all_lemmapos_20170821.pickle", 'rb'))
lch_first_tokens = pickle.load(open("lch_first_tokens_20170821.pickle", 'rb'))
lch_first_lemmas = pickle.load(open("lch_first_lemmas_20170821.pickle", 'rb'))
lch_first_lemmapos = pickle.load(open("lch_first_lemmapos_20170821.pickle", 'rb'))
# WUP Similarity
wup_all_tokens = pickle.load(open("wup_all_tokens_20170821.pickle", 'rb'))
wup_all_lemmas = pickle.load(open("wup_all_lemmas_20170821.pickle", 'rb'))
wup_all_lemmapos = pickle.load(open("wup_all_lemmapos_20170821.pickle", 'rb'))
wup_first_tokens = pickle.load(open("wup_first_tokens_20170821.pickle", 'rb'))
wup_first_lemmas = pickle.load(open("wup_first_lemmas_20170821.pickle", 'rb'))
wup_first_lemmapos = pickle.load(open("wup_first_lemmapos_20170821.pickle", 'rb'))
# RES Similarity
res_all_tokens_bnc_ic_2007 = pickle.load(open("res_all_tokens_bnc_ic_2007_20170821.pickle", 'rb'))
res_all_tokens_bnc_ic_2000 = pickle.load(open("res_all_tokens_bnc_ic_2000_20170821.pickle", 'rb'))
res_all_tokens_semcor_ic = pickle.load(open("res_all_tokens_semcor_ic_20170821.pickle", 'rb'))
res_all_tokens_brown_ic = pickle.load(open("res_all_tokens_brown_ic_20170821.pickle", 'rb'))
res_all_lemmas_bnc_ic_2007 = pickle.load(open("res_all_lemmas_bnc_ic_2007_20170821.pickle", 'rb'))
res_all_lemmas_bnc_ic_2000 = pickle.load(open("res_all_lemmas_bnc_ic_2000_20170821.pickle", 'rb'))
res_all_lemmas_semcor_ic = pickle.load(open("res_all_lemmas_semcor_ic_20170821.pickle", 'rb'))
res_all_lemmas_brown_ic = pickle.load(open("res_all_lemmas_brown_ic_20170821.pickle", 'rb'))
res_all_lemmapos_bnc_ic_2007 = pickle.load(open("res_all_lemmapos_bnc_ic_2007_20170821.pickle", 'rb'))
res_all_lemmapos_bnc_ic_2000 = pickle.load(open("res_all_lemmapos_bnc_ic_2000_20170821.pickle", 'rb'))
res_all_lemmapos_semcor_ic = pickle.load(open("res_all_lemmapos_semcor_ic_20170821.pickle", 'rb'))
res_all_lemmapos_brown_ic = pickle.load(open("res_all_lemmapos_brown_ic_20170821.pickle", 'rb'))
res_first_tokens_bnc_ic_2007 = pickle.load(open("res_first_tokens_bnc_ic_2007_20170821.pickle", 'rb'))
res_first_tokens_bnc_ic_2000 = pickle.load(open("res_first_tokens_bnc_ic_2000_20170821.pickle", 'rb'))
res_first_tokens_semcor_ic = pickle.load(open("res_first_tokens_semcor_ic_20170821.pickle", 'rb'))
res_first_tokens_brown_ic = pickle.load(open("res_first_tokens_brown_ic_20170821.pickle", 'rb'))
res_first_lemmas_bnc_ic_2007 = pickle.load(open("res_first_lemmas_bnc_ic_2007_20170821.pickle", 'rb'))
res_first_lemmas_bnc_ic_2000 = pickle.load(open("res_first_lemmas_bnc_ic_2000_20170821.pickle", 'rb'))
res_first_lemmas_semcor_ic = pickle.load(open("res_first_lemmas_semcor_ic_20170821.pickle", 'rb'))
res_first_lemmas_brown_ic = pickle.load(open("res_first_lemmas_brown_ic_20170821.pickle", 'rb'))
res_first_lemmapos_bnc_ic_2007 = pickle.load(open("res_first_lemmapos_bnc_ic_2007_20170821.pickle", 'rb'))
res_first_lemmapos_bnc_ic_2000 = pickle.load(open("res_first_lemmapos_bnc_ic_2000_20170821.pickle", 'rb'))
res_first_lemmapos_semcor_ic = pickle.load(open("res_first_lemmapos_semcor_ic_20170821.pickle", 'rb'))
res_first_lemmapos_brown_ic = pickle.load(open("res_first_lemmapos_brown_ic_20170821.pickle", 'rb'))
# JCN Similarity
jcn_all_tokens_bnc_ic_2007 = pickle.load(open("jcn_all_tokens_bnc_ic_2007_20170821.pickle", 'rb'))
jcn_all_tokens_bnc_ic_2000 = pickle.load(open("jcn_all_tokens_bnc_ic_2000_20170821.pickle", 'rb'))
jcn_all_tokens_semcor_ic = pickle.load(open("jcn_all_tokens_semcor_ic_20170821.pickle", 'rb'))
jcn_all_tokens_brown_ic = pickle.load(open("jcn_all_tokens_brown_ic_20170821.pickle", 'rb'))
jcn_all_lemmas_bnc_ic_2007 = pickle.load(open("jcn_all_lemmas_bnc_ic_2007_20170821.pickle", 'rb'))
jcn_all_lemmas_bnc_ic_2000 = pickle.load(open("jcn_all_lemmas_bnc_ic_2000_20170821.pickle", 'rb'))
jcn_all_lemmas_semcor_ic = pickle.load(open("jcn_all_lemmas_semcor_ic_20170821.pickle", 'rb'))
jcn_all_lemmas_brown_ic = pickle.load(open("jcn_all_lemmas_brown_ic_20170821.pickle", 'rb'))
jcn_all_lemmapos_bnc_ic_2007 = pickle.load(open("jcn_all_lemmapos_bnc_ic_2007_20170821.pickle", 'rb'))
jcn_all_lemmapos_bnc_ic_2000 = pickle.load(open("jcn_all_lemmapos_bnc_ic_2000_20170821.pickle", 'rb'))
jcn_all_lemmapos_semcor_ic = pickle.load(open("jcn_all_lemmapos_semcor_ic_20170821.pickle", 'rb'))
jcn_all_lemmapos_brown_ic = pickle.load(open("jcn_all_lemmapos_brown_ic_20170821.pickle", 'rb'))
jcn_first_tokens_bnc_ic_2007 = pickle.load(open("jcn_first_tokens_bnc_ic_2007_20170821.pickle", 'rb'))
jcn_first_tokens_bnc_ic_2000 = pickle.load(open("jcn_first_tokens_bnc_ic_2000_20170821.pickle", 'rb'))
jcn_first_tokens_semcor_ic = pickle.load(open("jcn_first_tokens_semcor_ic_20170821.pickle", 'rb'))
jcn_first_tokens_brown_ic = pickle.load(open("jcn_first_tokens_brown_ic_20170821.pickle", 'rb'))
jcn_first_lemmas_bnc_ic_2007 = pickle.load(open("jcn_first_lemmas_bnc_ic_2007_20170821.pickle", 'rb'))
jcn_first_lemmas_bnc_ic_2000 = pickle.load(open("jcn_first_lemmas_bnc_ic_2000_20170821.pickle", 'rb'))
jcn_first_lemmas_semcor_ic = pickle.load(open("jcn_first_lemmas_semcor_ic_20170821.pickle", 'rb'))
jcn_first_lemmas_brown_ic = pickle.load(open("jcn_first_lemmas_brown_ic_20170821.pickle", 'rb'))
jcn_first_lemmapos_bnc_ic_2007 = pickle.load(open("jcn_first_lemmapos_bnc_ic_2007_20170821.pickle", 'rb'))
jcn_first_lemmapos_bnc_ic_2000 = pickle.load(open("jcn_first_lemmapos_bnc_ic_2000_20170821.pickle", 'rb'))
jcn_first_lemmapos_semcor_ic = pickle.load(open("jcn_first_lemmapos_semcor_ic_20170821.pickle", 'rb'))
jcn_first_lemmapos_brown_ic = pickle.load(open("jcn_first_lemmapos_brown_ic_20170821.pickle", 'rb'))
# LIN Similarity
lin_all_tokens_bnc_ic_2007 = pickle.load(open("lin_all_tokens_bnc_ic_2007_20170821.pickle", 'rb'))
lin_all_tokens_bnc_ic_2000 = pickle.load(open("lin_all_tokens_bnc_ic_2000_20170821.pickle", 'rb'))
lin_all_tokens_semcor_ic = pickle.load(open("lin_all_tokens_semcor_ic_20170821.pickle", 'rb'))
lin_all_tokens_brown_ic = pickle.load(open("lin_all_tokens_brown_ic_20170821.pickle", 'rb'))
lin_all_lemmas_bnc_ic_2007 = pickle.load(open("lin_all_lemmas_bnc_ic_2007_20170821.pickle", 'rb'))
lin_all_lemmas_bnc_ic_2000 = pickle.load(open("lin_all_lemmas_bnc_ic_2000_20170821.pickle", 'rb'))
lin_all_lemmas_semcor_ic = pickle.load(open("lin_all_lemmas_semcor_ic_20170821.pickle", 'rb'))
lin_all_lemmas_brown_ic = pickle.load(open("lin_all_lemmas_brown_ic_20170821.pickle", 'rb'))
lin_all_lemmapos_bnc_ic_2007 = pickle.load(open("lin_all_lemmapos_bnc_ic_2007_20170821.pickle", 'rb'))
lin_all_lemmapos_bnc_ic_2000 = pickle.load(open("lin_all_lemmapos_bnc_ic_2000_20170821.pickle", 'rb'))
lin_all_lemmapos_semcor_ic = pickle.load(open("lin_all_lemmapos_semcor_ic_20170821.pickle", 'rb'))
lin_all_lemmapos_brown_ic = pickle.load(open("lin_all_lemmapos_brown_ic_20170821.pickle", 'rb'))
lin_first_tokens_bnc_ic_2007 = pickle.load(open("lin_first_tokens_bnc_ic_2007_20170821.pickle", 'rb'))
lin_first_tokens_bnc_ic_2000 = pickle.load(open("lin_first_tokens_bnc_ic_2000_20170821.pickle", 'rb'))
lin_first_tokens_semcor_ic = pickle.load(open("lin_first_tokens_semcor_ic_20170821.pickle", 'rb'))
lin_first_tokens_brown_ic = pickle.load(open("lin_first_tokens_brown_ic_20170821.pickle", 'rb'))
lin_first_lemmas_bnc_ic_2007 = pickle.load(open("lin_first_lemmas_bnc_ic_2007_20170821.pickle", 'rb'))
lin_first_lemmas_bnc_ic_2000 = pickle.load(open("lin_first_lemmas_bnc_ic_2000_20170821.pickle", 'rb'))
lin_first_lemmas_semcor_ic = pickle.load(open("lin_first_lemmas_semcor_ic_20170821.pickle", 'rb'))
lin_first_lemmas_brown_ic = pickle.load(open("lin_first_lemmas_brown_ic_20170821.pickle", 'rb'))
lin_first_lemmapos_bnc_ic_2007 = pickle.load(open("lin_first_lemmapos_bnc_ic_2007_20170821.pickle", 'rb'))
lin_first_lemmapos_bnc_ic_2000 = pickle.load(open("lin_first_lemmapos_bnc_ic_2000_20170821.pickle", 'rb'))
lin_first_lemmapos_semcor_ic = pickle.load(open("lin_first_lemmapos_semcor_ic_20170821.pickle", 'rb'))
lin_first_lemmapos_brown_ic = pickle.load(open("lin_first_lemmapos_brown_ic_20170821.pickle", 'rb'))
idf = pickle.load(open("idf_bnc2007_20170810.pickle", 'rb'))
```
Possible Configurations TODO list
- Remove stopwords **Implemented!**
- Remove punctuation **Implemented!**
- Use binary or term frequency **Implemented!**
- Different kind of term_sims normalizations **Implemented!**
- Different WordNet term_sims **Implemented!**
- Softcosine or stevenson metric **Implemented!**
- Set as 0 all term similarity values below a given threshold **Implemented!**
#### Parameters
```
remove_stopwords_opt = [False, True]
remove_punctuation_opt = [False, True]
termsim_metric_opt = ["path", "lch", "wup", "res", "jcn", "lin"]
normalization_opt = [True, False]
termsim_threshold_opt = [0.0, 0.25, 0.5, 0.75]#np.linspace(0.0, 1.0, 21) # Every 5% # np.linspace(0.5, 1.0, 10)
synsets_taken_opt = ["all", "first"]
wscheme_opt = ["tf", "binary"]
sim_metric_opt = ["mihalcea", "softcosine", "stevenson"]
# This order should be kept given that it is used later
features_opt = ["token", "lemma", "stem", "lemmapos"]
synset_getter_opt = ["token", "lemma", "lemmapos"]
ic_data_opt = ["bnc_ic_2007", "bnc_ic_2000", "semcor_ic", "brown_ic"]
for x in synset_getter_opt:
print("vocab_"+x+ ('' if x[-1]=='s' else 's'))
```
# Running experiments with different combinations of parameters
#### Generating configurations
Generating the configurations trying to avoid any unnecessary repetition
configurations = list(itertools.product(remove_stopwords_opt,
remove_punctuation_opt,
termsim_metric_opt,
normalization_opt,
#termsim_threshold_opt,
synsets_taken_opt,
wscheme_opt,
sim_metric_opt))
```
# No normalization, No ic_data
configurations = list(itertools.product(remove_stopwords_opt,
[True], #remove_punctuation_opt,
["path", "wup"], # metrics
features_opt,
synset_getter_opt,
[None], # ic_data not needed
[False], # normalization not needed
termsim_threshold_opt,
synsets_taken_opt,
wscheme_opt,
sim_metric_opt))
# No normalization, Yes ic_data
configurations += list(itertools.product(remove_stopwords_opt,
[True], # remove_punctuation_opt,
["lin"], # metric
features_opt,
synset_getter_opt,
ic_data_opt, # ic_data needed
[False], # normalization not needed
termsim_threshold_opt,
synsets_taken_opt,
wscheme_opt,
sim_metric_opt))
# Yes normalization, No ic_data
configurations += list(itertools.product(remove_stopwords_opt,
[True], # remove_punctuation_opt,
["lch"], # metric
features_opt,
synset_getter_opt,
[None], # ic_data not needed
[True], # normalization needed
termsim_threshold_opt,
synsets_taken_opt,
wscheme_opt,
sim_metric_opt))
# Yes normalization, Yes ic_data
configurations += list(itertools.product(remove_stopwords_opt,
[True], # remove_punctuation_opt,
["jcn", "res"], # metrics
features_opt,
synset_getter_opt,
ic_data_opt, # ic_data needed
[True], # normalization needed
termsim_threshold_opt,
synsets_taken_opt,
wscheme_opt,
sim_metric_opt))
```
#### Converting from string to indexes given certain pre-processing options
Preprocessing options:
- Removing stopwords
- Removing punctuation
```
tags_mapping = {"NN":wn.NOUN, "VB":wn.VERB, "JJ":wn.ADJ, "RB":wn.ADV}
stopwords = set(nltk.corpus.stopwords.words("english"))
puncts = set(string.punctuation)
vectors_no_prep = {}
vectors_no_sw = {}
vectors_no_punct = {}
vectors_prep = {}
for idx in parsed_texts:
vectors_no_prep[idx] = [(token2index[token],
lemma2index[lemma],
stem2index[stem],
lemmapos2index[(lemma, tags_mapping.get(tag[:2], tag))])
for token, lemma, stem, tag in parsed_texts[idx]
]
vectors_no_sw[idx] = [(token2index[token],
lemma2index[lemma],
stem2index[stem],
lemmapos2index[(lemma, tags_mapping.get(tag[:2], tag))])
for token, lemma, stem, tag in parsed_texts[idx]
if token not in stopwords # Removing stopwords
]
vectors_no_punct[idx] = [(token2index[token],
lemma2index[lemma],
stem2index[stem],
lemmapos2index[(lemma, tags_mapping.get(tag[:2], tag))])
for token, lemma, stem, tag in parsed_texts[idx]
if not is_punct_token(token, puncts) # Removing punctuation
]
vectors_prep[idx] = [(token2index[token],
lemma2index[lemma],
stem2index[stem],
lemmapos2index[(lemma, tags_mapping.get(tag[:2], tag))])
for token, lemma, stem, tag in parsed_texts[idx]
if token not in stopwords # Removing stopwords
and not is_punct_token(token, puncts) # Removing punctuation
]
```
#### Mapping feature indexes to wordnet getter indexes
For the particular case of the MSRP Corpus
```
mappings = {}
for feature in features_opt:
for syngetter in synset_getter_opt:
comb_dict = {}
for idx in vectors_no_prep:
for token_id, lemma_id, stem_id, lemmapos_id in vectors_no_prep[idx]:
ft_idx = eval(feature+"_id")
wn_idx = eval(syngetter+"_id")
if ft_idx in comb_dict:
comb_dict[ft_idx].add(wn_idx)
else:
comb_dict[ft_idx] = set([wn_idx])
mappings[(feature, syngetter)] = comb_dict
```
#### Experiments with given configurations in the Training Corpus
```
idf_median_value = np.median(list(idf.values()))
idf_median_value
all_scores = {}
count = 0
total_configurations = len(configurations)
print("Progress ...")
for configuration in configurations:
(remove_stopwords,
remove_punctuation,
termsim_metric,
feature,
syngetter,
ic_data,
normalization,
termsim_th,
synsets_taken,
wscheme,
sim_metric) = configuration
# Converting from word vectors to index vectors from the vocabulary
vocab_syngetter = eval("vocab_"+syngetter+ ('' if syngetter[-1]=='s' else 's'))
syngetter2index = eval(syngetter+"2index")
index2syngetter = eval("index2"+syngetter)
vocab_feature = eval("vocab_"+feature+ ('' if feature[-1]=='s' else 's'))
feature2index = eval(feature+"2index")
index2feature = eval("index2"+feature)
# Choosing the appropiated preprocessed vecotrs
if remove_stopwords:
if remove_punctuation:
vectors = vectors_prep
else:
vectors = vectors_no_sw
else:
if remove_punctuation:
vectors = vectors_no_punct
else:
vectors = vectors_no_prep
# Choosing the term similarity matrix
if ic_data:
term_sims = eval(termsim_metric+"_"+synsets_taken+"_"+syngetter+('' if syngetter[-1]=='s' else 's')+"_"+ic_data)
else:
term_sims = eval(termsim_metric+"_"+synsets_taken+"_"+syngetter+('' if syngetter[-1]=='s' else 's'))
# Normalizing the term similarity matrix
if normalization:
term_sims = normalize(term_sims, termsim_metric)
# Setting to zero term similarities below termsim_th
term_sims = dict((key, value) for key, value in term_sims.items() if value >= termsim_th)
# Computing pair of texts similarities
sims = compute_sims(train_pairs,
vectors,
features_opt.index(feature),
mappings[(feature, syngetter)],
mappings[(feature, 'token')],
weight_scheme=wscheme,
metric=sim_metric,
term_sims=term_sims,
idf=idf,
idf_median_value=idf_median_value
)
#sims = compute_sims(test_pairs, vectors, weight_scheme=wscheme, metric=sim_metric, term_sims=term_sims)
# Computing scores
scores = np.array(compute_scores(sims, train_y, np.linspace(0.05, 1.0, 20))) # [x/100.0 for x in range(5, 101, 5)]))
#scores = np.array(compute_scores(sims, test_y, np.linspace(0.05, 1.0, 20))) # [x/100.0 for x in range(5, 101, 5)]))
all_scores[configuration] = scores[scores[:,1].argsort()[::-1]]
#print(configuration)
#print(all_scores[configuration][:3], "\n\n")
#break
sys.stdout.write('\r')
# the exact output you're looking for:
count += 1
i = count * 40.0 / total_configurations
sys.stdout.write("[{:40}] {:.0f}% {}/{}".format('='*int(i), int(2.5*i), count, total_configurations))
sys.stdout.flush()
```
##### Saving the results in HD
```
date_obj = datetime.date.today()
date_str = "{:04d}".format(date_obj.year) + "{:02d}".format(date_obj.month) + "{:02d}".format(date_obj.day)
date_str
pickle.dump(all_scores, open("results_"+date_str+"_simple_normalization.pickle", "wb"), protocol=pickle.HIGHEST_PROTOCOL)
```
#### Extracting best results
Configuration format
1. Removing stopwords flag : [True, False]
2. Removing punctuation flag : [True, False]
3. Wordnet similarity metrics : ["path", "lch", "wup", "res", "jcn", "lin"]
4. Features extracted to compute similarity : ["token", "lemma", "stem", "lemmapos"]
5. Features used to extract synsets : ["token", "lemma", "stem", "lemmapos"]
6. Information Content used in some WordNet metrics : ["bnc_ic_2007", "bnc_ic_2000", "semcor_ic", "brown_ic"]
7. Normalization flag : [True, False]
8. Term-Term similarity minimum threslhold : [0.0, 0.25, 0.5, 0.75]
9. Synsets selection strategy (all-vs-all, first) : ["all", "first"]
10. Features weighting scheme : ["tf", "binary"]
11. Text similarity method : ["mihalcea", "softcosine", "stevenson"]
```
# res = (threshold, accuracy, f_measure, precision, recall)
max([(conf, res[0][0], res[0][1], res[0][2])
for conf, res in all_scores.items()
#if conf[2] == "path"
]
, key=lambda x:x[3])
#[(conf, res[0][0], res[0][1]) for conf, res in all_scores.items()]
len(all_scores)
all_scores[(False, True, 'jcn', 'lemma', 'lemma', 'semcor_ic', True, 0.0, 'all', 'binary', 'stevenson')]
all_scores[(True, True, 'jcn', 'lemmapos', 'lemmapos', 'bnc_ic_2000', True, 0.0, 'all', 'tf', 'mihalcea')]
```
#### Serializing all results
### Evaluating best configuration for each WordNet metric on the test set
Best-k configurations
```
for metric in ["path", "lch", "wup", "res", "jcn", "lin"]:
print(metric)
# conf = (0-remove_stopwords, 1-remove_punctuation, 2-termsim_metric, 3-normalization,
# 4-termsim_th, 5-synsets_taken, 6-wscheme, 7-sim_metric)
#
# scores = (0-threshold, 1-accuracy, 2-f_measure, 3-precision, 4-recall)
#
for conf, score in sorted([(conf, scores[0,:])
for conf, scores in all_scores.items()
if conf[2] == metric],
key=lambda tup:tup[1][1], # tup=(conf, scores)
reverse=True)[:10]:
print(conf)
print(score, "\n")
print("\n\n")
#break
list(all_scores.items())[0][1][0,:]
options = [
(False, True, 'jcn', True, 0.0, 'all', 'binary', 'softcosine'),
(False, True, 'jcn', True, 0.0, 'all', 'binary', 'stevenson'),
(False, True, 'jcn', True, 0.0, 'all', 'binary', 'stevenson')
]
```
# Loading best configurations from training
```
test_configurations = pickle.load(open("test_configurations.pickle", "rb"))
```
# Evaluating best configurations
```
test_scores = {}
count = 0
total_configurations = len(test_configurations)
print("Progress ...")
for configuration in test_configurations:
(remove_stopwords,
remove_punctuation,
termsim_metric,
feature,
syngetter,
ic_data,
normalization,
termsim_th,
synsets_taken,
wscheme,
sim_metric) = configuration
# Converting from word vectors to index vectors from the vocabulary
vocab_syngetter = eval("vocab_"+syngetter+ ('' if syngetter[-1]=='s' else 's'))
syngetter2index = eval(syngetter+"2index")
index2syngetter = eval("index2"+syngetter)
vocab_feature = eval("vocab_"+feature+ ('' if feature[-1]=='s' else 's'))
feature2index = eval(feature+"2index")
index2feature = eval("index2"+feature)
# Choosing the appropiated preprocessed vecotrs
if remove_stopwords:
if remove_punctuation:
vectors = vectors_prep
else:
vectors = vectors_no_sw
else:
if remove_punctuation:
vectors = vectors_no_punct
else:
vectors = vectors_no_prep
# Choosing the term similarity matrix
if ic_data:
term_sims = eval(termsim_metric+"_"+synsets_taken+"_"+syngetter+('' if syngetter[-1]=='s' else 's')+"_"+ic_data)
else:
term_sims = eval(termsim_metric+"_"+synsets_taken+"_"+syngetter+('' if syngetter[-1]=='s' else 's'))
# Normalizing the term similarity matrix
if normalization:
term_sims = normalize(term_sims, termsim_metric)
# Setting to zero term similarities below termsim_th
term_sims = dict((key, value) for key, value in term_sims.items() if value >= termsim_th)
# Computing pair of texts similarities
sims = compute_sims(test_pairs,
vectors,
features_opt.index(feature),
mappings[(feature, syngetter)],
mappings[(feature, 'token')],
weight_scheme=wscheme,
metric=sim_metric,
term_sims=term_sims,
idf=idf,
idf_median_value=idf_median_value
)
#sims = compute_sims(test_pairs, vectors, weight_scheme=wscheme, metric=sim_metric, term_sims=term_sims)
# Computing scores
scores = np.array(compute_scores(sims, test_y, np.linspace(0.05, 1.0, 20))) # [x/100.0 for x in range(5, 101, 5)]))
test_scores[configuration] = scores[scores[:,1].argsort()[::-1]]
sys.stdout.write('\r')
# the exact output you're looking for:
count += 1
i = count * 40.0 / total_configurations
sys.stdout.write("[{:40}] {:.0f}% {}/{}".format('='*int(i), int(2.5*i), count, total_configurations))
sys.stdout.flush()
```
# Storing test results
```
with open("./Results/test_results_20180504.pickle", "wb") as fid:
pickle.dump(test_scores, fid)
```
| github_jupyter |
```
# default_exp core
```
# Utility functions
> A set of utility functions used throughout the library.
```
# export
import torch
import torch.nn.functional as F
import collections
import numpy as np
```
## General utils
```
# exports
def flatten_dict(nested, sep='/'):
"""Flatten dictionary and concatenate nested keys with separator."""
def rec(nest, prefix, into):
for k, v in nest.items():
if sep in k:
raise ValueError(f"separator '{sep}' not allowed to be in key '{k}'")
if isinstance(v, collections.Mapping):
rec(v, prefix + k + sep, into)
else:
into[prefix + k] = v
flat = {}
rec(nested, '', flat)
return flat
def stack_dicts(stats_dicts):
"""Stack the values of a dict."""
results = dict()
for k in stats_dicts[0]:
stats_list = [torch.flatten(d[k]) for d in stats_dicts]
results[k] = torch.stack(stats_list)
return results
def add_suffix(input_dict, suffix):
"""Add suffix to dict keys."""
return dict((k + suffix, v) for k,v in input_dict.items())
```
## Torch utils
```
# exports
def pad_to_size(tensor, size, dim=1, padding=50256):
"""Pad tensor to size."""
t_size = tensor.size()[dim]
if t_size==size:
return tensor
else:
return torch.nn.functional.pad(tensor, (0,size-t_size), 'constant', padding)
def logprobs_from_logits(logits, labels):
"""
See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591
"""
logp = F.log_softmax(logits, dim=2)
logpy = torch.gather(logp, 2, labels.unsqueeze(2)).squeeze(-1)
return logpy
def whiten(values, shift_mean=True):
"""Whiten values."""
mean, var = torch.mean(values), torch.var(values)
whitened = (values - mean) * torch.rsqrt(var + 1e-8)
if not shift_mean:
whitened += mean
return whitened
def clip_by_value(x, tensor_min, tensor_max):
"""
Tensor extenstion to torch.clamp
https://github.com/pytorch/pytorch/issues/2793#issuecomment-428784713
"""
clipped = torch.max(torch.min(x, tensor_max), tensor_min)
return clipped
def entropy_from_logits(logits):
"""Calculate entropy from logits."""
pd = torch.nn.functional.softmax(logits, dim=-1)
entropy = torch.logsumexp(logits, axis=-1) - torch.sum(pd*logits, axis=-1)
return entropy
def average_torch_dicts(list_of_dicts):
"""Average values of a list of dicts wiht torch tensors."""
average_dict = dict()
for key in list_of_dicts[0].keys():
average_dict[key] = torch.mean(torch.stack([d[key] for d in list_of_dicts]), axis=0)
return average_dict
def stats_to_np(stats_dict):
"""Cast all torch.tensors in dict to numpy arrays."""
new_dict = dict()
for k, v in stats_dict.items():
if isinstance(v, torch.Tensor):
new_dict[k] = v.detach().cpu().numpy()
else:
new_dict[k] = v
if np.isscalar(new_dict[k]):
new_dict[k] = float(new_dict[k])
return new_dict
```
## BERT utils
```
# exports
def build_bert_batch_from_txt(text_list, tokenizer, device):
"""Create token id and attention mask tensors from text list for BERT classification."""
# tokenize
tensors = [tokenizer.encode(txt, return_tensors="pt").to(device) for txt in text_list]
# find max length to pad to
max_len = max([t.size()[1] for t in tensors])
# get padded tensors and attention masks
# (attention masks make bert ignore padding)
padded_tensors = []
attention_masks = []
for tensor in tensors:
attention_mask = torch.ones(tensor.size(), device=device)
padded_tensors.append(pad_to_size(tensor, max_len, padding=0))
attention_masks.append(pad_to_size(attention_mask, max_len, padding=0))
# stack all tensors
padded_tensors = torch.cat(padded_tensors)
attention_masks = torch.cat(attention_masks)
return padded_tensors, attention_masks
```
| github_jupyter |
# Exploratory data analysis (EDA)
## Iris Flower dataset
* A simple dataset to learn the basics.
* 3 flowers of Iris species.
* 1936 by Ronald Fisher.
* Objective: Classify a new flower as belonging to one of the 3 classes given the 4 features.
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams.update({'font.size': 22})
```
## Reading the data with pandas
```
try:
iris = pd.read_csv("iris.csv") # iris is a pandas dataframe
except FileNotFoundError:
import requests
r = requests.get("https://raw.githubusercontent.com/aviralchharia/EDA-on-Iris-dataset/master/iris.csv.txt")
with open("iris.csv",'wb') as f:
f.write(r.content)
iris = pd.read_csv("iris.csv")
# iris
# iris.columns
# iris.head(2)
# iris.tail(2)
# iris.count()
# iris.shape
# iris.describe() # stats on features
# iris["species"].count() # counts all values
# iris["species"].value_counts() # counts distinct values - balanced data or not??
# iris.groupby(by="species").size()
# iris.groupby(by="species").mean() # mean of each col with distinct value of "species"
# iris.groupby(by="species").std()
# iris.groupby(by="species").count()
```
## 2-D Scatter Plot
```
#2-D scatter plot:
iris.plot(kind='scatter', x='sepal_length', y='sepal_width') ;
plt.show()
sns.FacetGrid(iris, hue="species", height=4)
# 2-D Scatter plot with color-coding for each flower type/class.
sns.set_style("whitegrid")
sns.FacetGrid(iris, hue="species", height=4) \
.map(plt.scatter, "sepal_length", "sepal_width") \
.add_legend()
plt.show()
```
**Observation(s):**
1. Using sepal_length and sepal_width features, we can distinguish Setosa flowers from others.
2. Seperating Versicolor from Viginica is much harder as they have considerable overlap.
## 3D Scatter plot
## Pair-plot
```
# pairwise scatter plot: Pair-Plot
plt.close();
sns.set_style("whitegrid");
sns.pairplot(iris, hue="species", height=5);
plt.show()
# NOTE: the diagonal elements are PDFs for each feature. PDFs are expalined below.
```
**Observations**
1. petal_length and petal_width are the most useful features to identify various flower types.
2. While Setosa can be easily identified (linearly seperable), Virnica and Versicolor have some overlap (almost linearly seperable).
3. We can find "lines" and "if-else" conditions to build a simple model to classify the flower types.
**Disadvantages**
- Can be used when number of features is not too large.
- Cannot visualize higher dimensional patterns in 3-D and 4-D.
- Only possible to view 2D patterns.
# Probability Density Function and Histogram
When the number of samples is too large, scatter plot is not good, instead we use PDF
```
# 1-D scatter plot of petal-length
import numpy as np
iris_setosa = iris.loc[iris["species"] == "setosa"]
iris_virginica = iris.loc[iris["species"] == "virginica"]
iris_versicolor = iris.loc[iris["species"] == "versicolor"]
#print(iris_setosa["petal_length"])
plt.plot(iris_setosa["petal_length"], np.zeros_like(iris_setosa['petal_length']), 'o')
plt.plot(iris_versicolor["petal_length"], np.zeros_like(iris_versicolor['petal_length']), 'o')
plt.plot(iris_virginica["petal_length"], np.zeros_like(iris_virginica['petal_length']), 'o')
plt.show()
# Disadvantages of 1-D scatter plot: Very hard to make sense as points are overlapping a lot.
sns.FacetGrid(iris, hue="species", height=5) \
.map(sns.distplot, "petal_length") \
.add_legend();
plt.show();
# map: petal_length, petal_width, sepal_length, sepal_width
# y[b] = (no of points falling in bin b)/((total no of points) * bin_width)
# pdf and not pmf
# Histograms and Probability Density Functions (PDF) using KDE
# Disadv of PDF: Can we say what percentage of versicolor points have a petal_length of less than 5?
# Do some of these plots look like a bell-curve you studied in under-grad?
# Gaussian/Normal distribution
# Need for Cumulative Distribution Function (CDF)
# We can visually see what percentage of versicolor flowers have a petal_length of less than 5?
#Plot CDF of petal_length
for species in ["setosa", "virginica", 'versicolor']:
data = iris.loc[iris["species"] == species]
counts, bin_edges = np.histogram(data['petal_length'], bins=10,
density = True)
pdf = counts
cdf = np.cumsum(pdf)
# plt.figure()
plt.plot(bin_edges[1:], pdf, label='pdf '+species)
plt.plot(bin_edges[1:], cdf, label='CDF '+species)
plt.legend(loc=(1.04,0))
plt.show()
```
| github_jupyter |
## 00:56:22 - Language model from scratch
* Going to learn how a recurrent neural network works.
## 00:56:52 - Question: are there model interpretabilty tools for language models?
* There are some, but won't be covered in this part of the course.
## 00:58:11 - Preparing the dataset: tokenisation and numericalisation
* Jeremy created a dataset called human numbers that contains first 10k numbers written out in English.
* Seems very few people create datasets, even though it's not particularly hard.
```
from fastai.text.all import *
from fastcore.foundation import L
path = untar_data(URLs.HUMAN_NUMBERS)
Path.BASE_PATH = path
path.ls()
lines = L()
with open(path/'train.txt') as f:
lines += L(*f.readlines())
with open(path/'valid.txt') as f:
lines += L(*f.readlines())
lines
```
* Concat them together and put a dot between them for tokenising.
```
text = ' . '.join([l.strip() for l in lines])
text[:100]
```
* Tokenise by splitting on spaces:
```
tokens = L(text.split(' '))
tokens[100:110]
```
* Create a vocab by getting unique tokens:
```
vocab = L(tokens).unique()
vocab, len(vocab)
```
* Convert tokens into numbers by looking up index of each word:
```
word2idx = {w: i for i,w in enumerate(vocab)}
nums = L(word2idx[i] for i in tokens)
tokens, nums
```
* That gives us a small easy dataset for building a language model.
## 01:01:31 - Language model from scratch
* Create a independent and dependent pair: first 3 words are input, next is dependent.
```
L((tokens[i:i+3], tokens[i+3]) for i in range(0, len(tokens)-4, 3))
```
* Same thing numericalised:
```
seqs = L((tensor(nums[i:i+3]), nums[i+3]) for i in range(0, len(nums)-4, 3))
seqs
```
* Can batch those with a `DataLoader` object
* Take first 80% as training, last 20% as validation.
```
bs = 64
cut = int(len(seqs) * 0.8)
dls = DataLoaders.from_dsets(seqs[:cut], seqs[:cut], bs=64, shuffle=False)
```
## 01:03:35 - Simple Language model
* 3 layer neural network.
* One linear layer that is reused 3 times.
* Each time the result is added to the embedding.
```
class LMModel(Module):
def __init__(self, vocab_sz, n_hidden):
self.input2hidden = nn.Embedding(vocab_sz, n_hidden)
self.hidden2hidden = nn.Linear(n_hidden, n_hidden)
self.hidden2output = nn.Linear(n_hidden, vocab_sz)
def forward(self, x):
hidden = self.input2hidden(x[:,0])
hidden = F.relu(self.hidden2hidden(hidden))
hidden = hidden + self.input2hidden(x[:,1])
hidden = F.relu(self.hidden2hidden(hidden))
hidden = hidden + self.input2hidden(x[:,2])
hidden = F.relu(self.hidden2hidden(hidden))
return self.hidden2output(hidden)
```
## 01:04:49 - Question: can you speed up fine-tuning the NLP model?
* Do something else while you wait or leave overnight.
## 01:05:44 - Simple Language model cont.
* 2 interesting happening:
* Some of the inputs are being fed into later layers, instead of just the first.
* The model is reusing hidden state throughout layers.
```
learn = Learner(dls, LMModel(len(vocab), 64), loss_func=F.cross_entropy, metrics=accuracy)
learn.fit_one_cycle(4, 1e-3)
```
* We can find out if that accuracy is good by making a simple model that predicts most common token:
```
c = Counter(tokens[cut:])
mc = c.most_common(5)
mc
mc[0][1]/len(tokens[cut:])
```
## 01:14:41 - Recurrent neural network
* We can refactor in Python using a for loop.
* Note that `hidden = 0` is being broadcast into the hidden state.
```
class LMModel2(Module):
def __init__(self, vocab_sz, n_hidden):
self.input2hidden = nn.Embedding(vocab_sz, n_hidden)
self.hidden2hidden = nn.Linear(n_hidden, n_hidden)
self.hidden2output = nn.Linear(n_hidden, vocab_sz)
def forward(self, x):
hidden = 0.
for i in range(3):
hidden = hidden + self.input2hidden(x[:,i])
hidden = F.relu(self.hidden2hidden(hidden))
return self.hidden2output(hidden)
learn = Learner(dls, LMModel2(len(vocab), 64), loss_func=F.cross_entropy, metrics=accuracy)
learn.fit_one_cycle(4, 1e-3)
```
* That's what a Recurrent Neural Network is!
## 01:18:39 - Improving the RNN
* Note that we're setting the previous state to 0.
* However, the hidden state from sequence to sequence contains useful information.
* We can rewrite to maintain state of RNN.
```
class LMModel3(Module):
def __init__(self, vocab_sz, n_hidden):
self.input2hidden = nn.Embedding(vocab_sz, n_hidden)
self.hidden2hidden = nn.Linear(n_hidden, n_hidden)
self.hidden2output = nn.Linear(n_hidden, vocab_sz)
self.hidden = 0.
def forward(self, x):
for i in range(3):
self.hidden = self.hidden + self.input2hidden(x[:,i])
self.hidden = F.relu(self.hidden2hidden(self.hidden))
output = self.hidden2output(self.hidden)
self.hidden = self.hidden.detach()
return output
def reset(self):
self.h = 0.
```
## 01:19:41 - Back propagation through time
* Note that we called `self.hidden.detach()` each forward pass to ensure we're not back propogating through all the previous forward passes.
* Known as Back propagation through time (BPTT)
## 01:22:19 - Ordered sequences and callbacks
* Samples must be seen in correct order - each batch needs to connect to previous batch.
* At the start of each epoch, we need to call reset.
```
def group_chunks(ds, bs):
m = len(ds) // bs
new_ds = L()
for i in range(m):
new_ds += L(ds[i + m*j] for j in range(bs))
return new_ds
cut = int(len(seqs) * 0.8)
dls = DataLoaders.from_dsets(
group_chunks(seqs[:cut], bs),
group_chunks(seqs[cut:], bs),
bs=bs, drop_last=True, shuffle=False
)
```
* At start of epoch, we call `reset`
* Last thing to add is little tweak of training model via a`Callback` called `ModelReseter`
```
from fastai.callback.rnn import ModelResetter
learn = Learner(dls, LMModel3(len(vocab), 64), loss_func=F.cross_entropy, metrics=accuracy, cbs=ModelResetter)
learn.fit_one_cycle(10, 3e-3)
```
* Training is doing a lot better now.
## 01:25:00 - Creating more signal
* Instead of putting output stage outside the loop, can put it in the loop.
* After every hidden state, we get a prediction.
* Can we change the data so dependant variable has each of the three words after each three input words.
```
sl = 16
seqs = L((tensor(nums[i:i+sl]), tensor(nums[i+1:i+sl+1]))
for i in range(0, len(nums) - sl - 1, sl))
cut = int(len(seqs) * 0.8)
dls = DataLoaders.from_dsets(group_chunks(seqs[:cut], bs),
group_chunks(seqs[cut:], bs),
bs=bs, drop_last=True, shuffle=False)
[L(vocab[o] for o in s) for s in seqs[0]]
```
* We can modify the model to return a list of outputs.
```
class LMModel4(Module):
def __init__(self, vocab_sz, n_hidden):
self.input2hidden = nn.Embedding(vocab_sz, n_hidden)
self.hidden2hidden = nn.Linear(n_hidden, n_hidden)
self.hidden2output = nn.Linear(n_hidden, vocab_sz)
self.hidden = 0.
def forward(self, x):
outputs = []
for i in range(sl):
self.hidden = self.hidden + self.input2hidden(x[:,i])
self.hidden = F.relu(self.hidden2hidden(self.hidden))
outputs.append(self.hidden2output(self.hidden))
self.hidden = self.hidden.detach()
return torch.stack(outputs, dim=1)
def reset(self):
self.h = 0.
```
* We have to write a custom loss function to flatten the outputs:
```
def loss_func(inp, targ):
return F.cross_entropy(inp.view(-1, len(vocab)), targ.view(-1))
learn = Learner(dls, LMModel4(len(vocab), 64), loss_func=loss_func, metrics=accuracy, cbs=ModelResetter)
learn.fit_one_cycle(15, 3e-3)
```
## 01:28:29 - Multilayer RNN
* Even though the RNN seemed to have a lot of layers, each layer is sharing the same weight matrix.
* Not that much better than a simple linear model.
* A multilayer RNN can stake multiple linear layers within the for loop.
* PyTorch provides the `nn.RNN` class for creating multilayers RNNs.
```
class LMModel5(Module):
def __init__(self, vocab_sz, n_hidden, n_layers):
self.input2hidden = nn.Embedding(vocab_sz, n_hidden)
self.rnn = nn.RNN(n_hidden, n_hidden, n_layers, batch_first=True)
self.hidden2output = nn.Linear(n_hidden, vocab_sz)
self.hidden = torch.zeros(n_layers, bs, n_hidden)
def forward(self, x):
res, h = self.rnn(self.input2hidden(x), self.hidden)
self.hidden = h.detach()
return self.hidden2output(res)
def reset(self):
self.hidden.zero_()
learn = Learner(dls, LMModel5(len(vocab), 64, 2), loss_func=loss_func, metrics=accuracy, cbs=ModelResetter)
learn.fit_one_cycle(15, 3e-3)
```
* The model seems to be doing worse. Validation loss appears to be really bad now.
## 01:32:39 - Exploding and vanishing gradients
* Very deep models can be hard to train due to exploding or vanishing gradients.
* Doing a lot of matrix multiplications across layers can give you very big or very small results.
* This can also cause gradients to grow.
* This is because numbers in a computer aren't stored precisely: they're stored as floating point numbers.
* Really big or small numbers become very close together and differences become practically 0.
* Lots of ways to deal with this:
* Batch norm.
* Smart initialisation.
* One simple technique is to use an RNN architecture called LSTM.
## 01:36:29 - LSTM
* Designed such that there's mini neural networks that decide how much previous state should be kept or discarded.
* Main detail: can replace matrix multiplication with LSTMCell sequence below:
```
class LSTMCell(nn.Module):
def __init__(self, num_inputs, num_hidden):
self.forget_gate = nn.Linear(num_inputs + num_hidden, num_hidden)
self.input_gate = nn.Linear(num_inputs + num_hidden, num_hidden)
self.cell_gate = nn.Linear(num_inputs + num_hidden, num_hidden)
self.output_gate = nn.Linear(num_inputs + num_hidden, num_hidden)
def forward(self, input, state):
h, c = state
h = torch.stack([h, input], dim=1)
forget = torch.sigmoid(self.forget_gate(h))
c = c * forget
inp = torch.sigmoid(self.input_gate(h))
cell = torch.tanh(self.cell_gate(h))
c = c + inp * cell
outgate = torch.sigmoid(self.output_gate(h))
h = outgate * torch.tanh(c)
return h, (h, c)
```
* RNN that uses LSTMCell is called `LSTM`
```
class LMModel6(Module):
def __init__(self, vocab_sz, n_hidden, n_layers):
self.input2hidden = nn.Embedding(vocab_sz, n_hidden)
self.rnn = nn.LSTM(n_hidden, n_hidden, n_layers, batch_first=True)
self.hidden2output = nn.Linear(n_hidden, vocab_sz)
self.hidden = [torch.zeros(n_layers, bs, n_hidden) for _ in range(2)]
def forward(self, x):
res, h = self.rnn(self.input2hidden(x), self.hidden)
self.hidden = [h_.detach() for h_ in h]
return self.hidden2output(res)
def reset(self):
for h in self.hidden:
h.zero_()
learn = Learner(dls, LMModel6(len(vocab), 64, 2), loss_func=loss_func, metrics=accuracy, cbs=ModelResetter)
learn.fit_one_cycle(15, 1e-2)
```
## 01:40:00 - Questions
* Can we use regularisation to make RNN params close to identity matrix?
* Will look at regularisation approaches.
* Can you check if activations are exploding or vanishing?
* Yes. You can output activations of each layer with print statements.
## 01:42:23 - Regularisation using Dropout
* Dropout is basically deleting activations at random.
* By removing activations at random, no single activations can become too "overspecialised"
* Dropout implementation:
```
class Dropout(nn.Module):
def __init__(self, p):
self.p = p
def forward(self, x):
if not self.training:
return x
mask = x.new(*x.shape).bernoulli_(1-p)
return x * mask.div_(1-p)
```
* A bermoulli random variable is a bunch of 1 and 0s with `1-p` probability of getting a 1.
* By multipying that by our input, we end up removing some layers.
## 01:47:16 - AR and TAR regularisation
* Jeremy has only seen in RNNs.
* AR (for activation regularisation)
* Similar to Weight Decay.
* Rather than adding a multiplier * sum of squares * weights.
* We add multiplier * sum of squares * activations.
* TAR (for temporal activation regularisation).
* TAR is used to calculate the difference of activations between each layer.
## 01:49:09 - Weight tying
* Since predicting the next word is about converting activations to English words.
* An embedding is about converting words to activations.
* Hypothesis: since they're roughly the same idea, can't they use the same weight matrix?
* Yes! This appears to work in practice.
```
class LMModel7(Module):
def __init__(self, vocab_sz, n_hidden, n_layers, p):
self.i_h = nn.Embedding(vocab_sz, n_hidden)
self.rnn = nn.LSTM(n_hidden, n_hidden, n_layers, batch_first=True)
self.drop = nn.Dropout(p)
self.h_o = nn.Linear(n_hidden, vocab_sz)
# This new line of code ensures that the weights of the embedding will always be the same as linear weights.
self.h_o.weight = self.i_h.weight
self.h = [torch.zeros(n_layers, bs, n_hidden) for _ in range(2)]
def forward(self, x):
raw, h = self.rnn(self.i_h(x), self.h)
out = self.drop(raw)
self.h = [h_.detach() for h_ in h]
return self.h_o(out), raw, out
def reset(self):
for h in self.h:
h.zero_()
```
## 01:51:00 - TextLearner
* We pass in `RNNRegularizer` callback:
```
learn = Learner(
dls,
LMModel7(len(vocab), 64, 2, 0.5),
loss_func=CrossEntropyLossFlat(),
metrics=accuracy, cbs=[ModelResetter, RNNRegularizer(alpha=2, beta=1)])
```
* Or use the `TextLearner` which passes it for us:
```
learn = TextLearner(
dls,
LMModel7(len(vocab), 64, 2, 0.5),
loss_func=CrossEntropyLossFlat(),
metrics=accuracy
)
learn.fit_one_cycle(15, 1e-2, wd=0.1)
```
* We've now reproduced everything in AWD LSTM, which was state of the art a few years ago.
## 01:52:48 - Conclusions
* Go idea to connect with other people in your community or forum who are along the learning journey.
| github_jupyter |
```
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import pyplot as plt
%matplotlib inline
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=10, shuffle=False)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
foreground_classes = {'plane', 'car', 'bird'}
#foreground_classes = {'bird', 'cat', 'deer'}
background_classes = {'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'}
#background_classes = {'plane', 'car', 'dog', 'frog', 'horse','ship', 'truck'}
fg1,fg2,fg3 = 0,1,2
dataiter = iter(trainloader)
background_data=[]
background_label=[]
foreground_data=[]
foreground_label=[]
batch_size=10
for i in range(5000):
images, labels = dataiter.next()
for j in range(batch_size):
if(classes[labels[j]] in background_classes):
img = images[j].tolist()
background_data.append(img)
background_label.append(labels[j])
else:
img = images[j].tolist()
foreground_data.append(img)
foreground_label.append(labels[j])
foreground_data = torch.tensor(foreground_data)
foreground_label = torch.tensor(foreground_label)
background_data = torch.tensor(background_data)
background_label = torch.tensor(background_label)
def create_mosaic_img(bg_idx,fg_idx,fg):
"""
bg_idx : list of indexes of background_data[] to be used as background images in mosaic
fg_idx : index of image to be used as foreground image from foreground data
fg : at what position/index foreground image has to be stored out of 0-8
"""
image_list=[]
j=0
for i in range(9):
if i != fg:
image_list.append(background_data[bg_idx[j]])#.type("torch.DoubleTensor"))
j+=1
else:
image_list.append(foreground_data[fg_idx])#.type("torch.DoubleTensor"))
label = foreground_label[fg_idx]-fg1 # minus 7 because our fore ground classes are 7,8,9 but we have to store it as 0,1,2
#image_list = np.concatenate(image_list ,axis=0)
image_list = torch.stack(image_list)
return image_list,label
desired_num = 30000
mosaic_list_of_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images
fore_idx =[] # list of indexes at which foreground image is present in a mosaic image i.e from 0 to 9
mosaic_label=[] # label of mosaic image = foreground class present in that mosaic
for i in range(desired_num):
np.random.seed(i)
bg_idx = np.random.randint(0,35000,8)
fg_idx = np.random.randint(0,15000)
fg = np.random.randint(0,9)
fore_idx.append(fg)
image_list,label = create_mosaic_img(bg_idx,fg_idx,fg)
mosaic_list_of_images.append(image_list)
mosaic_label.append(label)
class MosaicDataset(Dataset):
"""MosaicDataset dataset."""
def __init__(self, mosaic_list_of_images, mosaic_label, fore_idx):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.mosaic = mosaic_list_of_images
self.label = mosaic_label
self.fore_idx = fore_idx
def __len__(self):
return len(self.label)
def __getitem__(self, idx):
return self.mosaic[idx] , self.label[idx], self.fore_idx[idx]
batch = 250
msd = MosaicDataset(mosaic_list_of_images, mosaic_label , fore_idx)
train_loader = DataLoader( msd,batch_size= batch ,shuffle=False,num_workers=0,)
data,labels,fg_index = iter(train_loader).next()
bg = []
for i in range(120):
torch.manual_seed(i)
betag = torch.randn(250,9)#torch.ones((250,9))/9
a=bg.append( betag.requires_grad_() )
class Module2(nn.Module):
def __init__(self):
super(Module2, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.fc4 = nn.Linear(10,3)
def forward(self,y): #z batch of list of 9 images
y1 = self.pool(F.relu(self.conv1(y)))
y1 = self.pool(F.relu(self.conv2(y1)))
y1 = y1.view(-1, 16 * 5 * 5)
y1 = F.relu(self.fc1(y1))
y1 = F.relu(self.fc2(y1))
y1 = F.relu(self.fc3(y1))
y1 = self.fc4(y1)
return y1
torch.manual_seed(1234)
what_net = Module2().double()
#what_net.load_state_dict(torch.load("simultaneous_what.pt"))
what_net = what_net.to("cuda")
def attn_avg(x,beta):
y = torch.zeros([batch,3, 32,32], dtype=torch.float64)
y = y.to("cuda")
alpha = F.softmax(beta,dim=1) # alphas
for i in range(9):
alpha1 = alpha[:,i]
y = y + torch.mul(alpha1[:,None,None,None],x[:,i])
return y,alpha
def calculate_attn_loss(dataloader,what,criter):
what.eval()
r_loss = 0
alphas = []
lbls = []
pred = []
fidices = []
correct = 0
tot = 0
with torch.no_grad():
for i, data in enumerate(dataloader, 0):
inputs, labels,fidx= data
lbls.append(labels)
fidices.append(fidx)
inputs = inputs.double()
beta = bg[i] # alpha for ith batch
inputs, labels,beta = inputs.to("cuda"),labels.to("cuda"),beta.to("cuda")
avg,alpha = attn_avg(inputs,beta)
alpha = alpha.to("cuda")
outputs = what(avg)
_, predicted = torch.max(outputs.data, 1)
correct += sum(predicted == labels)
tot += len(predicted)
pred.append(predicted.cpu().numpy())
alphas.append(alpha.cpu().numpy())
loss = criter(outputs, labels)
r_loss += loss.item()
alphas = np.concatenate(alphas,axis=0)
pred = np.concatenate(pred,axis=0)
lbls = np.concatenate(lbls,axis=0)
fidices = np.concatenate(fidices,axis=0)
#print(alphas.shape,pred.shape,lbls.shape,fidices.shape)
analysis = analyse_data(alphas,lbls,pred,fidices)
return r_loss/i,analysis,correct.item(),tot,correct.item()/tot
# for param in what_net.parameters():
# param.requires_grad = False
def analyse_data(alphas,lbls,predicted,f_idx):
'''
analysis data is created here
'''
batch = len(predicted)
amth,alth,ftpt,ffpt,ftpf,ffpf = 0,0,0,0,0,0
for j in range (batch):
focus = np.argmax(alphas[j])
if(alphas[j][focus] >= 0.5):
amth +=1
else:
alth +=1
if(focus == f_idx[j] and predicted[j] == lbls[j]):
ftpt += 1
elif(focus != f_idx[j] and predicted[j] == lbls[j]):
ffpt +=1
elif(focus == f_idx[j] and predicted[j] != lbls[j]):
ftpf +=1
elif(focus != f_idx[j] and predicted[j] != lbls[j]):
ffpf +=1
#print(sum(predicted==lbls),ftpt+ffpt)
return [ftpt,ffpt,ftpf,ffpf,amth,alth]
optim1 = []
for i in range(120):
optim1.append(optim.RMSprop([bg[i]], lr=1))
# instantiate optimizer
optimizer_what = optim.RMSprop(what_net.parameters(), lr=0.001)#, momentum=0.9)#,nesterov=True)
criterion = nn.CrossEntropyLoss()
acti = []
analysis_data_tr = []
analysis_data_tst = []
loss_curi_tr = []
loss_curi_tst = []
epochs = 100
# calculate zeroth epoch loss and FTPT values
running_loss,anlys_data,correct,total,accuracy = calculate_attn_loss(train_loader,what_net,criterion)
print('training epoch: [%d ] loss: %.3f correct: %.3f, total: %.3f, accuracy: %.3f' %(0,running_loss,correct,total,accuracy))
loss_curi_tr.append(running_loss)
analysis_data_tr.append(anlys_data)
# training starts
for epoch in range(epochs): # loop over the dataset multiple times
ep_lossi = []
running_loss = 0.0
what_net.train()
for i, data in enumerate(train_loader, 0):
# get the inputs
inputs, labels,_ = data
inputs = inputs.double()
beta = bg[i] # alpha for ith batch
inputs, labels,beta = inputs.to("cuda"),labels.to("cuda"),beta.to("cuda")
# zero the parameter gradients
optimizer_what.zero_grad()
optim1[i].zero_grad()
# forward + backward + optimize
avg,alpha = attn_avg(inputs,beta)
outputs = what_net(avg)
loss = criterion(outputs, labels)
# print statistics
running_loss += loss.item()
#alpha.retain_grad()
loss.backward(retain_graph=False)
optimizer_what.step()
optim1[i].step()
running_loss_tr,anls_data,correct,total,accuracy = calculate_attn_loss(train_loader,what_net,criterion)
analysis_data_tr.append(anls_data)
loss_curi_tr.append(running_loss_tr) #loss per epoch
print('training epoch: [%d ] loss: %.3f correct: %.3f, total: %.3f, accuracy: %.3f' %(epoch+1,running_loss_tr,correct,total,accuracy))
if running_loss_tr<=0.08:
break
print('Finished Training run ')
analysis_data_tr = np.array(analysis_data_tr)
columns = ["epochs", "argmax > 0.5" ,"argmax < 0.5", "focus_true_pred_true", "focus_false_pred_true", "focus_true_pred_false", "focus_false_pred_false" ]
df_train = pd.DataFrame()
df_test = pd.DataFrame()
df_train[columns[0]] = np.arange(0,epoch+2)
df_train[columns[1]] = analysis_data_tr[:,-2]
df_train[columns[2]] = analysis_data_tr[:,-1]
df_train[columns[3]] = analysis_data_tr[:,0]
df_train[columns[4]] = analysis_data_tr[:,1]
df_train[columns[5]] = analysis_data_tr[:,2]
df_train[columns[6]] = analysis_data_tr[:,3]
df_train
fig= plt.figure(figsize=(12,12))
plt.plot(df_train[columns[0]],df_train[columns[3]]/300, label ="focus_true_pred_true ")
plt.plot(df_train[columns[0]],df_train[columns[4]]/300, label ="focus_false_pred_true ")
plt.plot(df_train[columns[0]],df_train[columns[5]]/300, label ="focus_true_pred_false ")
plt.plot(df_train[columns[0]],df_train[columns[6]]/300, label ="focus_false_pred_false ")
plt.title("On Train set")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.xlabel("epochs")
plt.ylabel("percentage of data")
#plt.vlines(vline_list,min(min(df_train[columns[3]]/300),min(df_train[columns[4]]/300),min(df_train[columns[5]]/300),min(df_train[columns[6]]/300)), max(max(df_train[columns[3]]/300),max(df_train[columns[4]]/300),max(df_train[columns[5]]/300),max(df_train[columns[6]]/300)),linestyles='dotted')
plt.show()
fig.savefig("train_analysis.pdf")
fig.savefig("train_analysis.png")
aph = []
for i in bg:
aph.append(F.softmax(i,dim=1).detach().numpy())
aph = np.concatenate(aph,axis=0)
torch.save({
'epoch': 500,
'model_state_dict': what_net.state_dict(),
#'optimizer_state_dict': optimizer_what.state_dict(),
"optimizer_alpha":optim1,
"FTPT_analysis":analysis_data_tr,
"alpha":aph
}, "cifar_what_net_500.pt")
aph
running_loss_tr,anls_data,correct,total,accuracy = calculate_attn_loss(train_loader,what_net,criterion)
print("argmax>0.5",anls_data[-2])
```
| github_jupyter |
### Abstract
We find histologies associated with tissues containing NF1 somatic mutations in the COSMIC database. There are 21. We find all other gene somatic mutations for those histologies. We assess the main predisposing gene to be the gene with the most mutation-sample pairs associated with the histology. We find that 4 histologies are primarily associated with NF1. We find that the mutation sites in NF1 observed to the 4 histologies each are associated with only a single histology. For MPNST, 3 genes are equally scored and Neurofibroma has a very high score for NF1. We find that each histology is associated with multiple mutation sites. For the NF1 mutation sites associated with each histology, we give FATHM score and PUBMED ID.
NOTE: All of the samples are taken from people with somatic mutations leading to cancer, so there is selection bias in the samples to that extent.
TODO: Program-based search for variant type, affected pathways and clinical significance from NCBI.
### Required packages
```
import os, re, time
import pandas as pd
import numpy as np
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
```
### Getting the COSMIC database of genome screens
For development purposes we have downloaded the COSMIC database from their website. We have also uploaded it as a ZIP file to private file syn20716008. It has license and sharing conditions and is 10GB in size, which makes it difficult to Dockerize. Let's assume you have downloaded the file and placed it in a folder, and that there is an environment variable NF2_DATA that points to that folder. This file, uncompressed, takes about an hour to read on a laptop PC with 16GB of RAM and 45GB of paging space. It takes about 10 minutes to read on a workstation with 32GB of RAM, Intel core i9 processor and solid state disk.
```
data_dir=os.getenv('NF2_DATA')
df=pd.read_csv(f'{data_dir}/CosmicGenomeScreensMutantExport.tsv', sep='\t')
df=df.loc[:,['Gene name','Mutation CDS', 'ID_sample', 'Primary histology']].dropna()
df.columns=['gene', 'mutation', 'sampleid', 'histology']
```
### We find histologies associated with tissues containing NF1 somatic mutations in the COSMIC database
#### Remove Not Sure histologies
```
df=df[df.histology != 'other']
df=df[df.histology != 'NS']
```
#### Make another dataframe for just NF1 mutations
```
nf1=df[df.gene=='NF1']
dd=nf1.to_dict()
nf1_histologies=set([y for x,y in dd['histology'].items()])
```
#### There are 21
```
len(nf1_histologies)
```
### We find all other gene somatic mutations for those histologies
#### Get the list of tissue samples studied for NF1
```
nf1_samples=set([y for x,y in dd['sampleid'].items()])
```
#### Restrict the set of all mutations to those concerning NF1-related histologies and samples
```
def strip_gene(x):
return x.split('_')[0] if '_' in x else x
df_nf1=df[df.histology.isin(nf1_histologies)]
df_nf1=df_nf1[df_nf1.sampleid.isin(nf1_samples)]
genes=df_nf1.gene.unique()
samples=df_nf1.sampleid.unique()
histologies=df_nf1.histology.unique()
M=df_nf1.values
f=np.vectorize(strip_gene)
M[:,0]=f(M[:,0])
W={histology:{} for gene, mutation, sample, histology in M}
for gene, mutation, sample, histology in M:
W[histology][gene]={}
for gene, mutation, sample, histology in M:
W[histology][gene][mutation]=set([])
for gene, mutation, sample, histology in M:
W[histology][gene][mutation].add(sample)
```
### We assess the main predisposing gene for each histology
#### Our scoring function is the gene with the most mutation-sample pairs associated with the histology
```
n=3
def score(mutation_samples):
return sum([len(mutation_samples[x]) for x in mutation_samples])
causative = []
not_causative = []
for histology in W:
TT=list(reversed(sorted([(score(W[histology][gene]),gene) for gene in W[histology]])))
total_mutations=sum([x for x,y in TT])
TT1=[(y,x/total_mutations) for x,y in TT]
genes=[x for x,y in TT1]
if 'NF1' in genes[0:n]:
i=[i for i,x in enumerate(genes[0:20]) if x=='NF1'][0]
if genes[0]=='NF1' or TT1[0][1]==TT1[i][1]:
causative.append((histology, [x for x in TT1 if x[1]==TT1[0][1]]))
else:
not_causative.append(histology)
else:
not_causative.append(histology)
```
#### 17 histologies do not score as causing NF1
```
pd.DataFrame(not_causative, columns=['Not caused by NF1'])
```
#### We find that 4 histologies are scored as causative for NF1
```
rows=[]
for histo,L in causative:
for (gene, score) in L:
rows.append((score, gene, histo))
rows.sort()
rows=list(reversed(rows))
nf1_histologies=[x for x,y in causative]
pd.DataFrame(nf1_histologies, columns=['histology'])
n_nf1_histologies=len(nf1_histologies)
n_nf1_histologies
```
### For MPNST, 3 genes are equally scored and Neurofibroma has a very high score for NF1
```
pd.DataFrame(rows, columns=['score', 'gene', 'histology'])
```
### Multiple NF1 mutation sites are associated with each histology
```
nf1_mutations={histology:[x for x in W[histology]['NF1']] for histology in nf1_histologies}
pd.DataFrame([(x, len(nf1_mutations[x]), ','.join(sorted(nf1_mutations[x]))) for x in nf1_mutations],
columns=['histology', 'n_mutations', 'mutations'])
```
### NF1 mutation sites are each observed for only a single histology
```
intersections=[]
for i in range(n_nf1_histologies):
hist_i=nf1_histologies[i]
W_i=nf1_mutations[hist_i]
for j in range(i+1,n_nf1_histologies):
hist_j=nf1_histologies[j]
W_j=nf1_mutations[hist_j]
intersection=[x for x in W_i if x in W_j]
intersections.append((hist_i,len(W_i), hist_j, len(W_j), len(intersection)))
pd.DataFrame(intersections, columns=['hist A', '# Mutations A', 'hist B', '# MutationsB', '# Intersections'])
```
## Information from COSMIC and NCBI on each NF1 mutation associated with a histology
For the NF1 mutation sites associated with each histology, we manually gather and present the variant type, affected pathways and clinical significance.
```
cosmic=pd.read_csv(f'{data_dir}/CosmicGenomeScreensMutantExport.tsv', sep='\t')
def nf1_hist_mutation_info(hist):
global cosmic, nf1_mutations
L=nf1_mutations[hist]
df = cosmic[cosmic['Primary histology']==hist]
df = df[df['Mutation CDS'].isin(L)]
df = df[['Mutation CDS',
'Mutation AA', 'Mutation Description', 'Mutation zygosity',
'Mutation strand', 'SNP',
'FATHMM prediction', 'FATHMM score',
'Pubmed_PMID']]
return df.drop_duplicates()
```
### malignant_peripheral_nerve_sheath_tumour
```
nf1_hist_mutation_info('malignant_peripheral_nerve_sheath_tumour')
```
### pheochromocytoma
```
nf1_hist_mutation_info('pheochromocytoma')
```
### neuroblastoma
```
nf1_hist_mutation_info('neuroblastoma')
```
### neurofibroma
```
nf1_hist_mutation_info('neuroblastoma')
```
| github_jupyter |
<a href="https://qworld.net" target="_blank" align="left"><img src="../qworld/images/header.jpg" align="left"></a>
$ \newcommand{\bra}[1]{\langle #1|} $
$ \newcommand{\ket}[1]{|#1\rangle} $
$ \newcommand{\braket}[2]{\langle #1|#2\rangle} $
$ \newcommand{\dot}[2]{ #1 \cdot #2} $
$ \newcommand{\biginner}[2]{\left\langle #1,#2\right\rangle} $
$ \newcommand{\mymatrix}[2]{\left( \begin{array}{#1} #2\end{array} \right)} $
$ \newcommand{\myvector}[1]{\mymatrix{c}{#1}} $
$ \newcommand{\myrvector}[1]{\mymatrix{r}{#1}} $
$ \newcommand{\mypar}[1]{\left( #1 \right)} $
$ \newcommand{\mybigpar}[1]{ \Big( #1 \Big)} $
$ \newcommand{\sqrttwo}{\frac{1}{\sqrt{2}}} $
$ \newcommand{\dsqrttwo}{\dfrac{1}{\sqrt{2}}} $
$ \newcommand{\onehalf}{\frac{1}{2}} $
$ \newcommand{\donehalf}{\dfrac{1}{2}} $
$ \newcommand{\hadamard}{ \mymatrix{rr}{ \sqrttwo & \sqrttwo \\ \sqrttwo & -\sqrttwo }} $
$ \newcommand{\vzero}{\myvector{1\\0}} $
$ \newcommand{\vone}{\myvector{0\\1}} $
$ \newcommand{\stateplus}{\myvector{ \sqrttwo \\ \sqrttwo } } $
$ \newcommand{\stateminus}{ \myrvector{ \sqrttwo \\ -\sqrttwo } } $
$ \newcommand{\myarray}[2]{ \begin{array}{#1}#2\end{array}} $
$ \newcommand{\X}{ \mymatrix{cc}{0 & 1 \\ 1 & 0} } $
$ \newcommand{\I}{ \mymatrix{rr}{1 & 0 \\ 0 & 1} } $
$ \newcommand{\Z}{ \mymatrix{rr}{1 & 0 \\ 0 & -1} } $
$ \newcommand{\Htwo}{ \mymatrix{rrrr}{ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} & \frac{1}{2} } } $
$ \newcommand{\CNOT}{ \mymatrix{cccc}{1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0} } $
$ \newcommand{\norm}[1]{ \left\lVert #1 \right\rVert } $
$ \newcommand{\pstate}[1]{ \lceil \mspace{-1mu} #1 \mspace{-1.5mu} \rfloor } $
$ \newcommand{\greenbit}[1] {\mathbf{{\color{green}#1}}} $
$ \newcommand{\bluebit}[1] {\mathbf{{\color{blue}#1}}} $
$ \newcommand{\redbit}[1] {\mathbf{{\color{red}#1}}} $
$ \newcommand{\brownbit}[1] {\mathbf{{\color{brown}#1}}} $
$ \newcommand{\blackbit}[1] {\mathbf{{\color{black}#1}}} $
<font style="font-size:28px;" align="left"><b> <font color="blue"> Solutions for </font>Two Qubits </b></font>
<br>
_prepared by Abuzer Yakaryilmaz_
<br><br>
<a id="task3"></a>
<h3> Task 3 </h3>
We define a quantum circuit with two qubits: $ q_0 $ and $ q_1 $. They are tensored as $ q_1 \otimes q_0 $ in Qiskit.
We apply the Hadamard operator to $q_1$.
```
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(1)
display(qc.draw(output='mpl',reverse_bits=True))
```
Then, the quantum operator applied to both qubits will be $ H \otimes I $.
Read the quantum operator of the above circuit by using 'unitary_simulator' and then verify that it is $ H \otimes I $.
<h3> Solution </h3>
$ H \otimes I = \hadamard \otimes \I = \mymatrix{c|c}{ \sqrttwo \I & \sqrttwo \I \\ \hline \sqrttwo \I & -\sqrttwo \I } = \mymatrix{rr|rr} { \sqrttwo & 0 & \sqrttwo & 0 \\ 0 & \sqrttwo & 0 & \sqrttwo \\ \hline \sqrttwo & 0 & -\sqrttwo & 0 \\ 0 & \sqrttwo & 0 & -\sqrttwo } $
```
from qiskit import execute, Aer
job = execute(qc, Aer.get_backend('unitary_simulator'),shots=1,optimization_level=0)
current_unitary = job.result().get_unitary(qc, decimals=3)
for row in current_unitary:
column = ""
for entry in row:
column = column + str(round(entry.real,3)) + " "
print(column)
```
<a id="task5"></a>
<h3> Task 5 </h3>
Create a quantum curcuit with $ n=5 $ qubits.
Set each qubit to $ \ket{1} $.
Repeat 4 times:
<ul>
<li>Randomly pick a pair of qubits, and apply cx-gate (CNOT operator) on the pair.</li>
</ul>
Draw your circuit, and execute your program 100 times.
Verify your measurement results by checking the diagram of the circuit.
<h3> Solution </h3>
```
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
n = 5
m = 4
states_of_qubits = [] # we trace the state of each qubit also by ourselves
q = QuantumRegister(n,"q") # quantum register with n qubits
c = ClassicalRegister(n,"c") # classical register with n bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# set each qubit to |1>
for i in range(n):
qc.x(q[i]) # apply x-gate (NOT operator)
states_of_qubits.append(1) # the state of each qubit is set to 1
# randomly pick m pairs of qubits
for i in range(m):
controller_qubit = randrange(n)
target_qubit = randrange(n)
# controller and target qubits should be different
while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again
target_qubit = randrange(n)
# print our picked qubits
print("the indices of the controller and target qubits are",controller_qubit,target_qubit)
# apply cx-gate (CNOT operator)
qc.cx(q[controller_qubit],q[target_qubit])
# we also trace the results
if states_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1,
states_of_qubits[target_qubit] = 1 - states_of_qubits[target_qubit] # then flips the value of the target qubit
# remark that 1-x gives the negation of x
# measure the quantum register
qc.barrier()
qc.measure(q,c)
# draw the circuit in reading order
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print("the measurument result is",counts)
our_result=""
for state in states_of_qubits:
our_result = str(state) + our_result
print("our result is",our_result)
```
<a id="task6"></a>
<h3>Task 6</h3>
Our task is to learn the behavior of the following quantum circuit by doing experiments.
Our circuit has two qubits: $ q_0 $ and $ q_1 $. They are tensored as $ q_1 \otimes q_0 $ in Qiskit.
<ul>
<li> Apply Hadamard to the both qubits.
<li> Apply CNOT($q_1$,$q_0$).
<li> Apply Hadamard to the both qubits.
<li> Measure the circuit.
</ul>
Iteratively initialize the qubits to $ \ket{00} $, $ \ket{01} $, $ \ket{10} $, and $ \ket{11} $.
Execute your program 100 times for each iteration, and then check the outcomes for each iteration.
Observe that the overall circuit implements CNOT($q_0$,$q_1$).
<h3> Solution </h3>
```
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
q = QuantumRegister(2,"q") # quantum register with 2 qubits
c = ClassicalRegister(2,"c") # classical register with 2 bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# initialize the inputs w.r.t the reading order of Qiskit
if input[0]=='1':
qc.x(q[1]) # set the state of the up qubit to |1>
if input[1]=='1':
qc.x(q[0]) # set the state of the down qubit to |1>
# apply h-gate to both qubits
qc.h(q[0])
qc.h(q[1])
# apply cx(up-qubit,down-qubit)
qc.cx(q[1],q[0])
# apply h-gate to both qubits
qc.h(q[0])
qc.h(q[1])
# measure both qubits
qc.barrier()
qc.measure(q,c)
# draw the circuit w.r.t the reading order of Qiskit
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print(input,"is mapped to",counts)
```
<a id="task7"></a>
<h3>Task 7</h3>
Our task is to learn the behavior of the following quantum circuit by doing experiments.
Our circuit has two qubits: $ q_0 $ and $ q_1 $. They are tensored as $ q_1 \otimes q_0 $ in Qiskit.
<ul>
<li> Apply CNOT($q_1$,$q_0$).
<li> Apply CNOT($q_0$,$q_1$).
<li> Apply CNOT($q_1$,$q_0$).
</ul>
Iteratively initialize the qubits to $ \ket{00} $, $ \ket{01} $, $ \ket{10} $, and $ \ket{11} $.
Execute your program 100 times for each iteration, and then check the outcomes for each iteration.
Observe that the overall circuit swaps the values of the first and second qubits:
<ul>
<li> $\ket{00} \rightarrow \ket{00} $ </li>
<li> $\ket{01} \rightarrow \ket{10} $ </li>
<li> $\ket{10} \rightarrow \ket{01} $ </li>
<li> $\ket{11} \rightarrow \ket{11} $ </li>
</ul>
<h3> Solution </h3>
```
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
q = QuantumRegister(2,"q") # quantum register with 2 qubits
c = ClassicalRegister(2,"c") # classical register with 2 bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
#initialize the inputs w.r.t the reading order of Qiskit
if input[0]=='1':
qc.x(q[1]) # set the state of the up qubit to |1>
if input[1]=='1':
qc.x(q[0]) # set the state of the down qubit to |1>
# apply cx(up-qubit,down-qubit)
qc.cx(q[1],q[0])
# apply cx(down-qubit,up-qubit)
qc.cx(q[0],q[1])
# apply cx(up-qubit,down-qubit)
qc.cx(q[1],q[0])
# measure both qubits
qc.barrier()
qc.measure(q,c)
# draw the circuit w.r.t the reading order of Qiskit
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print(input,"is mapped to",counts)
```
| github_jupyter |
# Figure 2 - supplement 4B
```
# required libraries
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%matplotlib inline
def plot_create():
#plt.title('Prediction of spinal cord outgrowth \n for different '+r'$\tau$'+' values', y=1.1, size=65)
exp_time = [0, 2, 3, 4, 6, 8]
exp_outgrowth = [0, 60, 160, 450, 1280, 2260]
exp_outgrowth_err = [0, 10, 20, 40, 60, 70]
# Experimental outgrowth
#ax.errorbar(exp_time , exp_outgrowth, yerr=exp_outgrowth_err, color='black',ecolor='black', fmt='o',markersize=11,elinewidth=3, label='Experiments')
ax.legend(loc='upper left', facecolor='white')
plt.xlabel('Time (days)')
plt.ylabel('Outgrowth' + ' (' + r'$\mu$'+'m)')
plt.xlim(-0.2,8.2)
plt.ylim(-50,2500)
fig.set_size_inches(18.5, 12.5)
plt.rcParams.update({'font.size': 32})
filename = "./" + "Fig_S2B.png"
fig.savefig(filename, dpi=300, bbox_inches='tight')
fig = plt.figure()
ax = fig.add_subplot(111)
n0_mean,n0_std = 196,2 # n0 mean and standar deviation
l_mean,l_std = 828,30 # lambda mean and standar deviation
tau_mean,tau_std = 85,12 # tau mean and standar deviation
root = "../main/simulations/"
model = 'outgrowth/'
parameters = 'n0='+str(n0_mean)+'\n'+'l='+str(l_mean)+'\n'+'tau='+str(tau_mean)+'/'
path = root+model+parameters
all_seeds = []
files = os.listdir(path)
for seed in files:
opened_file = open(path+seed)
data = pd.read_csv(opened_file, delimiter=',')
data.set_index(['time', 'id'], inplace=True)
outgrowth = data.groupby(level='time')['position'].max()
all_seeds.append(outgrowth)
all_seeds = pd.concat(all_seeds, ignore_index=True, axis=1)
outgrowth_mean = np.asarray(all_seeds.mean(axis=1))
outgrowth_mean = outgrowth_mean[np.logical_not(np.isnan(outgrowth_mean))]
outgrowth_std = np.asarray(all_seeds.std(axis=1))
outgrowth_std = outgrowth_std[np.logical_not(np.isnan(outgrowth_std))]
time = outgrowth.index/24
ax.plot(time, outgrowth_mean, color='royalblue',linewidth=7, label=r'$\lambda$'+' = 828 '+r'$\mu$'+'m (model best fit)')
ax.fill_between(time, outgrowth_mean-outgrowth_std, outgrowth_mean+outgrowth_std,linestyle='solid', facecolor='royalblue', alpha=0.2)
#################################
n0_mean,n0_std = 196,2 # n0 mean and standar deviation
l_mean = 1600 # lambda mean
tau_mean,tau_std = 85,12 # tau mean and standar deviation
root = "../main/simulations/"
model = 'outgrowth/'
parameters = 'n0='+str(n0_mean)+'\n'+'l='+str(l_mean)+'\n'+'tau='+str(tau_mean)+'/'
path = root+model+parameters
all_seeds = []
files = os.listdir(path)
for seed in files:
opened_file = open(path+seed)
data = pd.read_csv(opened_file, delimiter=',')
data.set_index(['time', 'id'], inplace=True)
outgrowth = data.groupby(level='time')['position'].max()
all_seeds.append(outgrowth)
all_seeds = pd.concat(all_seeds, ignore_index=True, axis=1)
outgrowth_mean = np.asarray(all_seeds.mean(axis=1))
outgrowth_mean = outgrowth_mean[np.logical_not(np.isnan(outgrowth_mean))]
outgrowth_std = np.asarray(all_seeds.std(axis=1))
outgrowth_std = outgrowth_std[np.logical_not(np.isnan(outgrowth_std))]
time = outgrowth.index/24
ax.plot(time, outgrowth_mean, color='saddlebrown',linewidth=7,linestyle='dotted', label=r'$\lambda$'+' = 1,600 '+r'$\mu$'+'m')
ax.fill_between(time, outgrowth_mean-outgrowth_std, outgrowth_mean+outgrowth_std, facecolor='saddlebrown', alpha=0.2)
#################################
n0_mean,n0_std = 196,2 # n0 mean and standar deviation
l_mean = 0 # lambda mean
tau_mean,tau_std = 85,12 # tau mean and standar deviation
root = "../main/simulations/"
model = 'outgrowth/'
parameters = 'n0='+str(n0_mean)+'\n'+'l='+str(l_mean)+'\n'+'tau='+str(tau_mean)+'/'
path = root+model+parameters
all_seeds = []
files = os.listdir(path)
for seed in files:
opened_file = open(path+seed)
data = pd.read_csv(opened_file, delimiter=',')
data.set_index(['time', 'id'], inplace=True)
outgrowth = data.groupby(level='time')['position'].max()
all_seeds.append(outgrowth)
all_seeds = pd.concat(all_seeds, ignore_index=True, axis=1)
outgrowth_mean = np.asarray(all_seeds.mean(axis=1))
outgrowth_mean = outgrowth_mean[np.logical_not(np.isnan(outgrowth_mean))]
outgrowth_std = np.asarray(all_seeds.std(axis=1))
outgrowth_std = outgrowth_std[np.logical_not(np.isnan(outgrowth_std))]
time = outgrowth.index/24
ax.plot(time, outgrowth_mean, color='r',linewidth=7,linestyle='dashed', label=r'$\lambda$'+' = 0 '+r'$\mu$'+'m')
ax.fill_between(time, outgrowth_mean-outgrowth_std, outgrowth_mean+outgrowth_std, facecolor='r', alpha=0.2)
##################################
plot_create()
```
| github_jupyter |
# Stock Value Prediction
In this Notebook, we will create the actual prediction system, by testing various approaches and accuracy against multiple time-horizons (target_days variable).
First we will load all libraries:
```
import pandas as pd
import numpy as np
import sys, os
from datetime import datetime
sys.path.insert(1, '..')
import recommender as rcmd
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline
# classification approaches
import tensorflow as tf
from sklearn.linear_model import LogisticRegression
from sklearn.multioutput import MultiOutputClassifier
from sklearn.mixture import GaussianMixture
from sklearn.svm import SVC
# regression approaches
from sklearn.linear_model import LinearRegression
# data handling and scoring
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import recall_score, precision_score, f1_score, mean_squared_error
```
Next, we create the input data pipelines for stock and statement data. Therefore we will have to split data into training and test sets. There are two options for doing that:
* Splitting the list of symbols
* Splitting the results list of training stock datapoints
We will use the first option in order ensure a clear split (since the generate data has overlapping time frames, the second options would generate data that might have been seen by the system beforehand).
```
# create cache object
cache = rcmd.stocks.Cache()
# load list of all available stocks and sample sub-list
stocks = cache.list_data('stock')
def train_test_data(back, ahead, xlim, split=0.3, count=2000, stocks=stocks, cache=cache):
'''Generetes a train test split'''
sample = np.random.choice(list(stocks.keys()), 2000)
# split the stock data
count_train = int((1-split) * count)
sample_train = sample[:count_train]
sample_test = sample[count_train:]
# generate sample data
df_train = rcmd.learning.preprocess.create_dataset(sample_train, stocks, cache, back, ahead, xlim)
df_test = rcmd.learning.preprocess.create_dataset(sample_test, stocks, cache, back, ahead, xlim)
return df_train, df_test
df_train, df_test = train_test_data(10, 22, (-.5, .5), split=0.2, count=4000)
print(df_train.shape)
df_train.head()
# shortcut: store / load created datasets
df_train.to_csv('../data/train.csv')
df_test.to_csv('../data/test.csv')
# load data
#df_train = pd.read_csv('../data/train.csv')
#df_test = pd.read_csv('../data/test.csv')
```
Now that we have loaded and split the data, we have to divide it into input and output data:
```
def divide_data(df, xlim, balance_mode=None, balance_weight=1):
'''Splits the data into 3 sets: input, ouput_classify, output_regression.
Note that this function will also sample the data if choosen to create a more balanced dataset. Options are:
`under`: Undersamples the data (takes lowest data sample and )
`over`: Oversamples data to the highest number of possible samples
`over_under`: takes the mean count and samples in both directions
Args:
df (DataFrame): DF to contain all relevant data
xlim (tuple): tuple of integers used to clip and scale regression values to a range of 0 to 1
balance_mode (str): Defines the balance mode of the data (options: 'over_under', 'under', 'over')
balance_weight (float): Defines how much the calculate sample count is weighted in comparision to the actual count (should be between 0 and 1)
Returns:
df_X: DataFrame with input values
df_y_cls: DataFrame with classification labels
df_y_reg: DataFrame with regression values
'''
# sample the data correctly
if balance_mode is not None:
if balance_mode == 'over_under':
# find median
num_samples = df['target_cat'].value_counts().median().astype('int')
elif balance_mode == 'over':
# find highest number
num_samples = df['target_cat'].value_counts().max()
elif balance_mode == 'under':
# find minimal number
num_samples = df['target_cat'].value_counts().min()
else:
raise ValueError('Unkown sample mode: {}'.format(balance_mode))
# sample categories
dfs = []
for cat in df['target_cat'].unique():
df_tmp = df[df['target_cat'] == cat]
cur_samples = int(balance_weight * num_samples + (1-balance_weight) * df_tmp.shape[0])
sample = df_tmp.sample(cur_samples, replace=cur_samples > df_tmp.shape[0])
dfs.append(sample)
# concat and shuffle the rows
df = pd.concat(dfs, axis=0).sample(frac=1)
# remove all target cols
df_X = df.drop(['target', 'target_cat', 'norm_price', 'symbol'], axis=1)
# convert to dummy classes
df_y_cls = pd.get_dummies(df['target_cat'], prefix='cat', dummy_na=False)
# clip values and scale to vals
df_y_reg = np.divide( np.subtract( df['target'].clip(xlim[0], xlim[1]), xlim[0] ), (xlim[1] - xlim[0]) )
return df, df_X, df_y_cls, df_y_reg
df_train_bm, X_train, y_ctrain, y_rtrain = divide_data(df_train, (-.5, .5), balance_mode='over_under', balance_weight=0.9)
df_test_bm, X_test, y_ctest, y_rtest = divide_data(df_test, (-.5, .5))
print(pd.concat([y_ctrain.sum(axis=0), y_ctest.sum(axis=0)], axis=1))
```
Before we create the actual prediction systems, we will have to define metrics, how we want to measure the success of the systems.
As we have two approaches (classification and regression) we will use two types metrics:
* Precision, Recall & Accuracy
* RMSE
```
def _metric_classifier(y_true, y_pred, avg=None):
p = precision_score(y_true, y_pred, average=avg)
r = recall_score(y_true, y_pred, average=avg)
f1 = f1_score(y_true, y_pred, average=avg)
return f1, p, r
def score_classifier(y_true, y_pred):
'''Calculates the relevant scores for a classifer and outputs. This should show predicitions per class.'''
f1, p, r = _metric_classifier(y_true, y_pred, avg='micro')
print("Model Performance: F1={:.4f} (P={:.4f} / R={:.4f})".format(f1, p, r))
# list scores of single classes
for i, c in enumerate(y_true.columns):
sf1, sp, sr = _metric_classifier(y_true.iloc[:, i], y_pred[:, i], avg='binary')
print(" {:10} F1={:.4f} (P={:.4f} / R={:.4f})".format(c + ":", sf1, sp, sr))
def score_regression(y_true, y_pred):
mse = mean_squared_error(y_true, y_pred)
print("Model Performance: MSE={:.4f}".format(mse))
```
## Classification
The first step is to create a baseline for both approaches (classification and regression). In case of regression our target value will be `target` and for classification it will be `target_cat` (which we might convert into a one-hot vector along the way).
Lets start with the simpler form of classification:
```
y_ctrain.sum(axis=0)
# scale input data to improve convergance (Note: scaler has to be used for other input data as well)
scaler = StandardScaler()
X_train_std = scaler.fit_transform(X_train)
X_test_std = scaler.transform(X_test)
# train element
classifier = MultiOutputClassifier(LogisticRegression(max_iter=500, solver='lbfgs'))
classifier.fit(X_train_std, y_ctrain)
# predict data
y_pred = classifier.predict(X_test_std)
score_classifier(y_ctest, y_pred)
```
We can see a strong bias in the system for `cat_3`, which also has the highest number of training samples. Future work might include oversampling or more target datapoint selection to reduce these biases.
Next, support vector machines:
```
classifier_svm = MultiOutputClassifier(SVC())
classifier_svm.fit(X_train_std, y_ctrain)
y_pred_svm = classifier_svm.predict(X_test_std)
score_classifier(y_ctest, y_pred_svm)
```
We can see the results improve
```
class TestCallback(tf.keras.callbacks.Callback):
def __init__(self, data=X_test_std):
self.data = data
def on_epoch_end(self, epoch, logs={}):
loss, acc = self.model.evaluate(self.data, df_test_bm['target_cat'].to_numpy(), verbose=0)
print('\nTesting loss: {}, acc: {}\n'.format(loss, acc))
# simple feed forward network
print(X_train.shape)
print(df_train.shape)
classifier_ffn = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(X_train_std.shape[1],)),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(256, activation=tf.nn.relu),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(y_ctrain.shape[1], activation=tf.nn.softmax)
])
classifier_ffn.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
classifier_ffn.fit(X_train.to_numpy(), df_train_bm['target_cat'].to_numpy(), epochs=100, callbacks=[TestCallback()])
y_pred_ffn = classifier_ffn.predict(X_test.to_numpy())
y_pred_ffn = pd.get_dummies(y_pred_ffn.argmax(axis=1))
print(y_pred_ffn.sum(axis=0))
score_classifier(y_ctest, y_pred_ffn.to_numpy())
```
It is noteworthy that the output of the model in the test data resembles the input distribution. Lets try to improve generalization with a more complex model
```
act = tf.keras.layers.PReLU
classifier_ffn = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(X_train_std.shape[1],)),
tf.keras.layers.Dense(32), act(),
tf.keras.layers.Dense(64), act(),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(128), act(),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(256), act(),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dropout(0.4),
tf.keras.layers.Dense(128), act(),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(64), act(),
tf.keras.layers.Dense(y_ctrain.shape[1], activation=tf.nn.softmax)
])
classifier_ffn.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
classifier_ffn.fit(X_train.to_numpy(), df_train_bm['target_cat'].to_numpy(), epochs=200, callbacks=[TestCallback(X_test.to_numpy())])
y_pred_ffn = classifier_ffn.predict(X_test.to_numpy())
print(y_pred_ffn)
y_pred_ffn = pd.get_dummies(y_pred_ffn.argmax(axis=1))
print(y_pred_ffn.sum(axis=0))
score_classifier(y_ctest, y_pred_ffn.to_numpy())
# save the model
classifier_ffn.save('../data/keras-model.h5')
```
## Regression
The other possible option is regression. We will test a linear regression against neural networks based on RMSE score to see how the predictions hold.
```
reg = LinearRegression()
reg.fit(X_train.iloc[:, :7].to_numpy(), y_rtrain)
y_pred_reg = reg.predict(X_test.iloc[:, :7].to_numpy())
score_regression(y_rtest, y_pred_reg)
```
Now the neural Network
```
classifier_reg = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(X_train_std.shape[1],)),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(256, activation=tf.nn.relu),
tf.keras.layers.Dense(256, activation=tf.nn.relu),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(1)
])
opt = tf.keras.optimizers.SGD(learning_rate=0.00000001, nesterov=False)
classifier_reg.compile(optimizer=opt, loss='mean_squared_error', metrics=['accuracy'])
classifier_reg.fit(X_train.to_numpy(), y_rtrain.to_numpy(), epochs=20)
y_pred_reg = classifier_reg.predict(X_test.to_numpy())
score_regression(y_rtest, y_pred_reg)
y_pred_reg
y_pred_reg.shape
y_pred_ffn = classifier_ffn.predict(X_test.to_numpy())
print(y_pred_ffn)
```
| github_jupyter |
```
#load the libraries
library(lme4)
library(nlme)
library(arm)
library(RCurl)#to directly download the rikz dataset
########################
# part 0 fitting GLMM #
# # # # # # #
#the example dataset we will use
rikz_link<-getURL("https://raw.githubusercontent.com/ranalytics/r-tutorials/master/Edition_2015/Data/RIKZ.txt")
data<-read.table(textConnection(rikz_link),head=TRUE,sep="\t",stringsAsFactors = FALSE)
#first a random intercept model
mod_lme1<-lme(Richness~NAP,data=data,random=~1|Beach)
mod_lmer1<-lmer(Richness~NAP+(1|Beach),data=data)
#then a random slope plus intercept model
# mod_lme2<-lme(Richness~NAP,data=data,random=NAP|Beach)
mod_lmer2<-lmer(Richness~NAP+(NAP|Beach),data=data)
# #Poisson model
# mod_glmer1<-glmer(Richness~NAP+(1|Beach),data=data,family="poisson")
# #nested and crossed random effect??
#factor variable with intercept only effect
#simulate data in a fixed effect way
x<-rnorm(120,0,1)
f<-gl(n=6,k=20)
modmat<-model.matrix(~x+f,data.frame(x=x,f=f))
betas<-c(1,2,0.3,-3,0.5,1.2,0.8)
y<-modmat%*%betas+rnorm(120,0,1)
#the fixed effect model
m_lm<-lm(y~x+f)
#the mixed effect model
m_lme<-lme(y~x,random=~1|f)
mod_lme1
#testing the random effect
#a first model
mod1<-lme(Richness~NAP+Exposure,data=data,random=~1|Beach,method="REML")
#a second model without the random term, gls is used because it also fit the model through REML
mod2<-gls(Richness~NAP+Exposure,data=data,method="REML")
#likelihood ratio test, not very precise for low sample size
anova(mod1,mod2)
# parameteric bootstrap
lrt.obs <- anova(mod1, mod2)$L.Ratio[2] # save the observed likelihood ratio test statistic
n.sim <- 1000 # use 1000 for a real data analysis
lrt.sim <- numeric(n.sim)
dattemp <- data
for(i in 1:n.sim){
dattemp$ysim <- simulate(lm(Richness ~ NAP+Exposure, data=dattemp))$sim_1 # simulate new observations from the null-model
modnullsim <- gls(ysim ~ NAP+Exposure, data=dattemp) # fit the null-model
modaltsim <-lme(ysim ~ NAP+Exposure, random=~1|Beach, data=dattemp) # fit the alternative model
lrt.sim[i] <- anova(modnullsim, modaltsim)$L.Ratio[2] # save the likelihood ratio test statistic
}
(sum(lrt.sim>=lrt.obs)+1)/(n.sim+1) # p-value
#testing the random effect
#a first model
mod1<-lme(Richness~NAP+Exposure,data=data,random=~1|Beach,method="REML")
#a second model without the random term, gls is used because it also fit the model through REML
mod2<-gls(Richness~NAP+Exposure,data=data,method="REML")
#likelihood ratio test, not very precise for low sample size
anova(mod1,mod2)
#plot
par(mfrow=c(1,1))
hist(lrt.sim, xlim=c(0, max(c(lrt.sim, lrt.obs))), col="blue", xlab="likelihood ratio test statistic", ylab="density", cex.lab=1.5, cex.axis=1.2)
abline(v=lrt.obs, col="orange", lwd=3)
```
| github_jupyter |
```
%pylab inline
import sklearn.datasets as datasets
```
# Datasets
There are three distinct kinds of dataset interfaces for different types of datasets. The simplest one is the interface for sample images, which is described below in the Sample images section.
The dataset generation functions and the svmlight loader share a simplistic interface, returning a tuple `(X, y)` consisting of a `n_samples * n_features` numpy array `X` and an array of length n_samples containing the targets `y`.
The toy datasets as well as the ‘real world’ datasets and the datasets fetched from mldata.org have more sophisticated structure. These functions return a dictionary-like object holding at least two items: an array of shape `n_samples * n_features` with key `data` (except for 20newsgroups) and a numpy array of length `n_samples`, containing the target values, with key `target`.
The datasets also contain a description in `DESCR` and some contain `feature_names` and `target_names`. See the dataset descriptions below for details.
## Sample Images
The scikit also embed a couple of sample JPEG images published under Creative Commons license by their authors. Those image can be useful to test algorithms and pipeline on 2D data.
```
# datasets.load_sample_images()
china = datasets.load_sample_image('china.jpg')
flower = datasets.load_sample_image('flower.jpg')
plt.imshow(china)
plt.imshow(flower)
flower.shape
```
## Sample Generators
In addition, scikit-learn includes various random sample generators that can be used to build artificial datasets of controlled size and complexity.
All of the generators are prefixed with the word `make`
```
datasets.make_blobs?
X, y = datasets.make_blobs()
X.shape, y.shape
```
## Toy and Fetched Datasets
Scikit-learn comes with a few small standard datasets that do not require to download any file from some external website.
These datasets are useful to quickly illustrate the behavior of the various algorithms implemented in the scikit. They are however often too small to be representative of real world machine learning tasks.
These datasets are prefixed with the `load` command.
```
data = datasets.load_boston()
data.keys()
data.data.shape, data.target.shape
data.feature_names
print data.DESCR
```
#### Fetched datasets
These are all somewhat unique with their own functions to fetch and load them. I'll go through a single one below. They are all prefixed with the word `fetch`
```
faces = datasets.fetch_olivetti_faces()
faces.keys()
faces.images.shape, faces.data.shape, faces.target.shape
```
| github_jupyter |
# अंश ३: उन्नत दूरस्थ निष्पादन उपकरण (Advanced Remote Execution Tools)
अंतिम खंड में हमने फेडरेटेड लर्निंग (Fedareted Learning) का उपयोग करके एक खिलौना मॉडल का प्रशिक्षण लिया। हमने अपने मॉडल पर .send() और .get() कॉल करके, इसे प्रशिक्षण डेटा के स्थान पर भेजकर, इसे अपडेट करके, और फिर इसे वापस लाया। हालांकि, उदाहरण के अंत में हमने महसूस किया कि हमें लोगों की गोपनीयता की रक्षा के लिए थोड़ा और आगे जाने की आवश्यकता है। अर्थात्, हम .get () कॉल करने से पहले ग्रेडिएंट को औसत (Average gredient) करना चाहते हैं। इस तरह, हम कभी किसी की सटीक ग्रेडिएंट (Gredient) नहीं देखेंगे (इस प्रकार उनकी गोपनीयता की रक्षा करना बेहतर है!!!)
लेकिन, ऐसा करने के लिए, हमें कुछ और खंड चाहिए:
- एक Tensor को सीधे किसी अन्य Worker को भेजने के लिए एक Pointer का उपयोग करें
और इसके अलावा, जब हम यहां हैं, तो हम कुछ और उन्नत tensor ऑपरेशंस के बारे में भी जानने वाले हैं, जो भविष्य में इस उदाहरण और कुछ अन्य चीज़ों में हमारी मदद करेंगे!
लेखक:
- Andrew Trask - Twitter: [@iamtrask](https://twitter.com/iamtrask)
अनुवादक:
- Arkadip Bhattacharya - Github: [@darkmatter18](https://github.com/darkmatter18)
```
import torch
import syft as sy
hook = sy.TorchHook(torch)
```
# अनुभाग 3.1 - Pointers से Pointers
जैसा कि आप जानते हैं, PointerTensor वस्तुएं सामान्य Tensor की तरह ही होती हैं। वास्तव में, वह इतनी Tensor जैसे होते हैं कि हम भी Pointers से Pointers कर सकते हैं। चलो पता करते हैं!
```
bob = sy.VirtualWorker(hook, id='bob')
alice = sy.VirtualWorker(hook, id='alice')
# this is a local tensor
x = torch.tensor([1,2,3,4])
x
# this sends the local tensor to Bob
x_ptr = x.send(bob)
# this is now a pointer
x_ptr
# now we can SEND THE POINTER to alice!!!
pointer_to_x_ptr = x_ptr.send(alice)
pointer_to_x_ptr
```
### क्या हुआ?
इसलिए, पिछले उदाहरण में, हमने `x` नामक एक Tensor बनाया और इसे Bob को भेजें, और हमारे स्थानीय मशीन (` x_ptr`) पर एक पॉइंटर बनाएं।
फिर, हमने `x_ptr.send (alice)` को कॉल किया, जिसने Alice को Pointer भेजा।
ध्यान दें, यह डेटा स्थानांतरित नहीं किया था! इसके बजाय, यह Pointer को डेटा में ले गया !!
```
# As you can see above, Bob still has the actual data (data is always stored in a LocalTensor type).
bob._objects
# Alice, on the other hand, has x_ptr!! (notice how it points at bob)
alice._objects
```
```
# and we can use .get() to get x_ptr back from Alice
x_ptr = pointer_to_x_ptr.get()
x_ptr
# and then we can use x_ptr to get x back from Bob!
x = x_ptr.get()
x
```
### Pointer -> Pointer -> Data Object पर अंकगणित (Arithmetic)
और सामान्य Pointers की तरह, हम इन Tensors के पार मनमाने ढंग से PyTorch संचालन कर सकते हैं
```
bob._objects
alice._objects
p2p2x = torch.tensor([1,2,3,4,5]).send(bob).send(alice)
y = p2p2x + p2p2x
bob._objects
alice._objects
y.get().get()
bob._objects
alice._objects
p2p2x.get().get()
bob._objects
alice._objects
```
# अनुभाग 3.2 - Pointer श्रृंखला संचालन
इसलिए अंतिम खंड में जब भी हम एक .send() या .get() ऑपरेशन कहते हैं, तो यह उस ऑपरेशन को सीधे हमारे स्थानीय मशीन पर Tensor पर कॉल करता है। हालाँकि, यदि आपके पास Pointers की एक श्रृंखला है, तो कभी-कभी आप चेन में अंतिम पॉइंटर पर .get () या .send () जैसे ऑपरेशन को कॉल करना चाहते हैं (जैसे कि एक कार्यकर्ता से दूसरे में डेटा सीधे भेजना)। इसे पूरा करने के लिए, आप उन फ़ंक्शन का उपयोग करना चाहते हैं जो विशेष रूप से इस गोपनीयता संरक्षण ऑपरेशन के लिए डिज़ाइन किए गए हैं।
ये ऑपरेशन हैं:
- `my_pointer2pointer.move(another_worker)`
```
# x is now a pointer to a pointer to the data which lives on Bob's machine
x = torch.tensor([1,2,3,4,5]).send(bob)
print(' bob:', bob._objects)
print('alice:',alice._objects)
x = x.move(alice)
print(' bob:', bob._objects)
print('alice:',alice._objects)
x
```
अति उत्कृष्ट! अब हम एक विश्वसनीय एग्रीगेटर (trusted aggregator) का उपयोग करके रिमोट ग्रेडिएंट औसत (remote gradient averaging) प्रदर्शन करने के लिए उपकरणों से लैस हैं!
# बधाई हो!!! - समुदाय में शामिल होने का समय!
इस नोटबुक ट्यूटोरियल को पूरा करने पर बधाई! यदि आपने इसका आनंद लिया है और एआई और एआई आपूर्ति श्रृंखला (डेटा) के विकेन्द्रीकृत स्वामित्व के संरक्षण की ओर आंदोलन में शामिल होना चाहते हैं, तो आप निम्न तरीकों से ऐसा कर सकते हैं!
### Pysyft को Github पर Star करें!
हमारे समुदाय की मदद करने का सबसे आसान तरीका GitHub repos अभिनीत है! यह हमारे द्वारा बनाए जा रहे कूल टूल्स के बारे में जागरूकता बढ़ाने में मदद करता है।
- [Star PySyft](https://github.com/OpenMined/PySyft)
### हमारी Slack में शामिल हों!
नवीनतम प्रगति पर अद्यतित रहने का सबसे अच्छा तरीका हमारे समुदाय में शामिल होना है! आप फॉर्म भरकर ऐसा कर सकते हैं। [http://slack.openmined.org](http://slack.openmined.org)
### एक कोड प्रोजेक्ट में शामिल हों!
हमारे समुदाय में योगदान करने का सबसे अच्छा तरीका एक कोड योगदानकर्ता बनना है! किसी भी समय आप PySyft GitHub Issues जारी करने वाले पृष्ठ पर जा सकते हैं और "प्रोजेक्ट्स" के लिए फ़िल्टर कर सकते हैं। यह आपको सभी शीर्ष स्तर के टिकट दिखाएगा कि आप किन परियोजनाओं में शामिल हो सकते हैं! यदि आप किसी परियोजना में शामिल नहीं होना चाहते हैं, लेकिन आप थोड़ी सी कोडिंग करना चाहते हैं, तो आप "अच्छा पहला अंक" चिह्नित गीथहब मुद्दों की खोज करके अधिक "वन ऑफ़" मिनी-प्रोजेक्ट्स की तलाश कर सकते हैं।
- [PySyft Projects](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3AProject)
- [Good First Issue Tickets](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
### दान करना
यदि आपके पास हमारे कोडबेस में योगदान करने का समय नहीं है, लेकिन फिर भी समर्थन उधार देना चाहते हैं, तो आप हमारे ओपन कलेक्टिव में भी एक बैकर बन सकते हैं। सभी दान हमारी वेब होस्टिंग और अन्य सामुदायिक खर्चों जैसे कि हैकाथॉन और मीटअप की ओर जाते हैं!
[OpenMined's Open Collective Page](https://opencollective.com/openmined)
| github_jupyter |
## Dependencies
```
import json, warnings, shutil
from tweet_utility_scripts import *
from tweet_utility_preprocess_roberta_scripts_text import *
from transformers import TFRobertaModel, RobertaConfig
from tokenizers import ByteLevelBPETokenizer
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers, metrics, losses, layers
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
SEED = 0
seed_everything(SEED)
warnings.filterwarnings("ignore")
class RectifiedAdam(tf.keras.optimizers.Optimizer):
"""Variant of the Adam optimizer whose adaptive learning rate is rectified
so as to have a consistent variance.
It implements the Rectified Adam (a.k.a. RAdam) proposed by
Liyuan Liu et al. in [On The Variance Of The Adaptive Learning Rate
And Beyond](https://arxiv.org/pdf/1908.03265v1.pdf).
Example of usage:
```python
opt = tfa.optimizers.RectifiedAdam(lr=1e-3)
```
Note: `amsgrad` is not described in the original paper. Use it with
caution.
RAdam is not a placement of the heuristic warmup, the settings should be
kept if warmup has already been employed and tuned in the baseline method.
You can enable warmup by setting `total_steps` and `warmup_proportion`:
```python
opt = tfa.optimizers.RectifiedAdam(
lr=1e-3,
total_steps=10000,
warmup_proportion=0.1,
min_lr=1e-5,
)
```
In the above example, the learning rate will increase linearly
from 0 to `lr` in 1000 steps, then decrease linearly from `lr` to `min_lr`
in 9000 steps.
Lookahead, proposed by Michael R. Zhang et.al in the paper
[Lookahead Optimizer: k steps forward, 1 step back]
(https://arxiv.org/abs/1907.08610v1), can be integrated with RAdam,
which is announced by Less Wright and the new combined optimizer can also
be called "Ranger". The mechanism can be enabled by using the lookahead
wrapper. For example:
```python
radam = tfa.optimizers.RectifiedAdam()
ranger = tfa.optimizers.Lookahead(radam, sync_period=6, slow_step_size=0.5)
```
"""
def __init__(self,
learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-7,
weight_decay=0.,
amsgrad=False,
sma_threshold=5.0,
total_steps=0,
warmup_proportion=0.1,
min_lr=0.,
name='RectifiedAdam',
**kwargs):
r"""Construct a new RAdam optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. or a schedule
that is a `tf.keras.optimizers.schedules.LearningRateSchedule`
The learning rate.
beta_1: A float value or a constant float tensor.
The exponential decay rate for the 1st moment estimates.
beta_2: A float value or a constant float tensor.
The exponential decay rate for the 2nd moment estimates.
epsilon: A small constant for numerical stability.
weight_decay: A floating point value. Weight decay for each param.
amsgrad: boolean. Whether to apply AMSGrad variant of this
algorithm from the paper "On the Convergence of Adam and
beyond".
sma_threshold. A float value.
The threshold for simple mean average.
total_steps: An integer. Total number of training steps.
Enable warmup by setting a positive value.
warmup_proportion: A floating point value.
The proportion of increasing steps.
min_lr: A floating point value. Minimum learning rate after warmup.
name: Optional name for the operations created when applying
gradients. Defaults to "RectifiedAdam".
**kwargs: keyword arguments. Allowed to be {`clipnorm`,
`clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients
by norm; `clipvalue` is clip gradients by value, `decay` is
included for backward compatibility to allow time inverse
decay of learning rate. `lr` is included for backward
compatibility, recommended to use `learning_rate` instead.
"""
super(RectifiedAdam, self).__init__(name, **kwargs)
self._set_hyper('learning_rate', kwargs.get('lr', learning_rate))
self._set_hyper('beta_1', beta_1)
self._set_hyper('beta_2', beta_2)
self._set_hyper('decay', self._initial_decay)
self._set_hyper('weight_decay', weight_decay)
self._set_hyper('sma_threshold', sma_threshold)
self._set_hyper('total_steps', float(total_steps))
self._set_hyper('warmup_proportion', warmup_proportion)
self._set_hyper('min_lr', min_lr)
self.epsilon = epsilon or tf.keras.backend.epsilon()
self.amsgrad = amsgrad
self._initial_weight_decay = weight_decay
self._initial_total_steps = total_steps
def _create_slots(self, var_list):
for var in var_list:
self.add_slot(var, 'm')
for var in var_list:
self.add_slot(var, 'v')
if self.amsgrad:
for var in var_list:
self.add_slot(var, 'vhat')
def set_weights(self, weights):
params = self.weights
num_vars = int((len(params) - 1) / 2)
if len(weights) == 3 * num_vars + 1:
weights = weights[:len(params)]
super(RectifiedAdam, self).set_weights(weights)
def _resource_apply_dense(self, grad, var):
var_dtype = var.dtype.base_dtype
lr_t = self._decayed_lr(var_dtype)
m = self.get_slot(var, 'm')
v = self.get_slot(var, 'v')
beta_1_t = self._get_hyper('beta_1', var_dtype)
beta_2_t = self._get_hyper('beta_2', var_dtype)
epsilon_t = tf.convert_to_tensor(self.epsilon, var_dtype)
local_step = tf.cast(self.iterations + 1, var_dtype)
beta_1_power = tf.pow(beta_1_t, local_step)
beta_2_power = tf.pow(beta_2_t, local_step)
if self._initial_total_steps > 0:
total_steps = self._get_hyper('total_steps', var_dtype)
warmup_steps = total_steps *\
self._get_hyper('warmup_proportion', var_dtype)
min_lr = self._get_hyper('min_lr', var_dtype)
decay_steps = tf.maximum(total_steps - warmup_steps, 1)
decay_rate = (min_lr - lr_t) / decay_steps
lr_t = tf.where(
local_step <= warmup_steps,
lr_t * (local_step / warmup_steps),
lr_t + decay_rate * tf.minimum(local_step - warmup_steps,
decay_steps),
)
sma_inf = 2.0 / (1.0 - beta_2_t) - 1.0
sma_t = sma_inf - 2.0 * local_step * beta_2_power / (
1.0 - beta_2_power)
m_t = m.assign(
beta_1_t * m + (1.0 - beta_1_t) * grad,
use_locking=self._use_locking)
m_corr_t = m_t / (1.0 - beta_1_power)
v_t = v.assign(
beta_2_t * v + (1.0 - beta_2_t) * tf.square(grad),
use_locking=self._use_locking)
if self.amsgrad:
vhat = self.get_slot(var, 'vhat')
vhat_t = vhat.assign(
tf.maximum(vhat, v_t), use_locking=self._use_locking)
v_corr_t = tf.sqrt(vhat_t / (1.0 - beta_2_power))
else:
vhat_t = None
v_corr_t = tf.sqrt(v_t / (1.0 - beta_2_power))
r_t = tf.sqrt((sma_t - 4.0) / (sma_inf - 4.0) * (sma_t - 2.0) /
(sma_inf - 2.0) * sma_inf / sma_t)
sma_threshold = self._get_hyper('sma_threshold', var_dtype)
var_t = tf.where(sma_t >= sma_threshold,
r_t * m_corr_t / (v_corr_t + epsilon_t), m_corr_t)
if self._initial_weight_decay > 0.0:
var_t += self._get_hyper('weight_decay', var_dtype) * var
var_update = var.assign_sub(
lr_t * var_t, use_locking=self._use_locking)
updates = [var_update, m_t, v_t]
if self.amsgrad:
updates.append(vhat_t)
return tf.group(*updates)
def _resource_apply_sparse(self, grad, var, indices):
var_dtype = var.dtype.base_dtype
lr_t = self._decayed_lr(var_dtype)
beta_1_t = self._get_hyper('beta_1', var_dtype)
beta_2_t = self._get_hyper('beta_2', var_dtype)
epsilon_t = tf.convert_to_tensor(self.epsilon, var_dtype)
local_step = tf.cast(self.iterations + 1, var_dtype)
beta_1_power = tf.pow(beta_1_t, local_step)
beta_2_power = tf.pow(beta_2_t, local_step)
if self._initial_total_steps > 0:
total_steps = self._get_hyper('total_steps', var_dtype)
warmup_steps = total_steps *\
self._get_hyper('warmup_proportion', var_dtype)
min_lr = self._get_hyper('min_lr', var_dtype)
decay_steps = tf.maximum(total_steps - warmup_steps, 1)
decay_rate = (min_lr - lr_t) / decay_steps
lr_t = tf.where(
local_step <= warmup_steps,
lr_t * (local_step / warmup_steps),
lr_t + decay_rate * tf.minimum(local_step - warmup_steps,
decay_steps),
)
sma_inf = 2.0 / (1.0 - beta_2_t) - 1.0
sma_t = sma_inf - 2.0 * local_step * beta_2_power / (
1.0 - beta_2_power)
m = self.get_slot(var, 'm')
m_scaled_g_values = grad * (1 - beta_1_t)
m_t = m.assign(m * beta_1_t, use_locking=self._use_locking)
with tf.control_dependencies([m_t]):
m_t = self._resource_scatter_add(m, indices, m_scaled_g_values)
m_corr_t = m_t / (1.0 - beta_1_power)
v = self.get_slot(var, 'v')
v_scaled_g_values = (grad * grad) * (1 - beta_2_t)
v_t = v.assign(v * beta_2_t, use_locking=self._use_locking)
with tf.control_dependencies([v_t]):
v_t = self._resource_scatter_add(v, indices, v_scaled_g_values)
if self.amsgrad:
vhat = self.get_slot(var, 'vhat')
vhat_t = vhat.assign(
tf.maximum(vhat, v_t), use_locking=self._use_locking)
v_corr_t = tf.sqrt(vhat_t / (1.0 - beta_2_power))
else:
vhat_t = None
v_corr_t = tf.sqrt(v_t / (1.0 - beta_2_power))
r_t = tf.sqrt((sma_t - 4.0) / (sma_inf - 4.0) * (sma_t - 2.0) /
(sma_inf - 2.0) * sma_inf / sma_t)
sma_threshold = self._get_hyper('sma_threshold', var_dtype)
var_t = tf.where(sma_t >= sma_threshold,
r_t * m_corr_t / (v_corr_t + epsilon_t), m_corr_t)
if self._initial_weight_decay > 0.0:
var_t += self._get_hyper('weight_decay', var_dtype) * var
with tf.control_dependencies([var_t]):
var_update = self._resource_scatter_add(
var, indices, tf.gather(-lr_t * var_t, indices))
updates = [var_update, m_t, v_t]
if self.amsgrad:
updates.append(vhat_t)
return tf.group(*updates)
def get_config(self):
config = super(RectifiedAdam, self).get_config()
config.update({
'learning_rate':
self._serialize_hyperparameter('learning_rate'),
'beta_1':
self._serialize_hyperparameter('beta_1'),
'beta_2':
self._serialize_hyperparameter('beta_2'),
'decay':
self._serialize_hyperparameter('decay'),
'weight_decay':
self._serialize_hyperparameter('weight_decay'),
'sma_threshold':
self._serialize_hyperparameter('sma_threshold'),
'epsilon':
self.epsilon,
'amsgrad':
self.amsgrad,
'total_steps':
self._serialize_hyperparameter('total_steps'),
'warmup_proportion':
self._serialize_hyperparameter('warmup_proportion'),
'min_lr':
self._serialize_hyperparameter('min_lr'),
})
return config
```
# Load data
```
database_base_path = '/kaggle/input/tweet-dataset-split-roberta-base-96-text/'
k_fold = pd.read_csv(database_base_path + '5-fold.csv')
display(k_fold.head())
# Unzip files
!tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96-text/fold_1.tar.gz
# !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96-text/fold_2.tar.gz
# !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96-text/fold_3.tar.gz
# !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96-text/fold_4.tar.gz
# !tar -xvf /kaggle/input/tweet-dataset-split-roberta-base-96-text/fold_5.tar.gz
```
# Model parameters
```
vocab_path = database_base_path + 'vocab.json'
merges_path = database_base_path + 'merges.txt'
base_path = '/kaggle/input/qa-transformers/roberta/'
config = {
"MAX_LEN": 96,
"BATCH_SIZE": 32,
"EPOCHS": 6,
"LEARNING_RATE": 3e-5,
"ES_PATIENCE": 1,
"N_FOLDS": 1,
"base_model_path": base_path + 'roberta-base-tf_model.h5',
"config_path": base_path + 'roberta-base-config.json'
}
with open('config.json', 'w') as json_file:
json.dump(json.loads(json.dumps(config)), json_file)
```
# Model
```
module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TFRobertaModel.from_pretrained(config['base_model_path'], config=module_config, name="base_model")
last_hidden_state, _ = base_model({'input_ids': input_ids, 'attention_mask': attention_mask})
x_start = layers.Dropout(.1)(last_hidden_state)
x_start = layers.Conv1D(1, 1)(x_start)
x_start = layers.Flatten()(x_start)
x_end = layers.Dropout(.1)(last_hidden_state)
x_end = layers.Conv1D(1, 1)(x_end)
x_end = layers.Flatten()(x_end)
y_start = layers.Subtract()([x_start, x_end])
y_start = layers.Activation('softmax', name='y_start')(x_start)
y_end = layers.Subtract()([x_end, x_start])
y_end = layers.Activation('softmax', name='y_end')(x_end)
x_jaccard = layers.GlobalAveragePooling1D()(last_hidden_state)
x_jaccard = layers.Dropout(.1)(x_jaccard)
y_jaccard = layers.Dense(1, activation='linear', name='y_jaccard')(x_jaccard)
model = Model(inputs=[input_ids, attention_mask], outputs=[y_start, y_end, y_jaccard])
optimizer = RectifiedAdam(lr=config['LEARNING_RATE'],
total_steps=(len(k_fold[k_fold['fold_1'] == 'train']) // config['BATCH_SIZE']) * config['EPOCHS'],
warmup_proportion=0.1,
min_lr=1e-7)
model.compile(optimizer, loss={'y_start': losses.CategoricalCrossentropy(),
'y_end': losses.CategoricalCrossentropy(),
'y_jaccard': losses.MeanSquaredError()},
metrics={'y_start': metrics.CategoricalAccuracy(),
'y_end': metrics.CategoricalAccuracy(),
'y_jaccard': metrics.RootMeanSquaredError()})
return model
```
# Tokenizer
```
tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path,
lowercase=True, add_prefix_space=True)
tokenizer.save('./')
```
# Train
```
history_list = []
for n_fold in range(config['N_FOLDS']):
n_fold +=1
print('\nFOLD: %d' % (n_fold))
# Load data
base_data_path = 'fold_%d/' % (n_fold)
x_train = np.load(base_data_path + 'x_train.npy')
y_train = np.load(base_data_path + 'y_train.npy')
x_valid = np.load(base_data_path + 'x_valid.npy')
y_valid = np.load(base_data_path + 'y_valid.npy')
y_train_aux = np.load(base_data_path + 'y_train_aux.npy')[1]
y_valid_aux = np.load(base_data_path + 'y_valid_aux.npy')[1]
### Delete data dir
shutil.rmtree(base_data_path)
# Train model
model_path = 'model_fold_%d.h5' % (n_fold)
model = model_fn(config['MAX_LEN'])
es = EarlyStopping(monitor='val_loss', mode='min', patience=config['ES_PATIENCE'],
restore_best_weights=True, verbose=1)
checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min',
save_best_only=True, save_weights_only=True)
history = model.fit(list(x_train), list([y_train[0], y_train[1], y_train_aux]),
validation_data=(list(x_valid), list([y_valid[0], y_valid[1], y_valid_aux])),
batch_size=config['BATCH_SIZE'],
callbacks=[checkpoint, es],
epochs=config['EPOCHS'],
verbose=2).history
history_list.append(history)
# Make predictions
train_preds = model.predict(list(x_train))
valid_preds = model.predict(list(x_valid))
k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'train', 'start_fold_%d' % (n_fold)] = train_preds[0].argmax(axis=-1)
k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'train', 'end_fold_%d' % (n_fold)] = train_preds[1].argmax(axis=-1)
k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'validation', 'start_fold_%d' % (n_fold)] = valid_preds[0].argmax(axis=-1)
k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'validation', 'end_fold_%d' % (n_fold)] = valid_preds[1].argmax(axis=-1)
k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'train', 'jaccard_fold_%d' % (n_fold)] = train_preds[2]
k_fold.loc[k_fold['fold_%d' % (n_fold)] == 'validation', 'jaccard_fold_%d' % (n_fold)] = valid_preds[2]
k_fold['end_fold_%d' % (n_fold)] = k_fold['end_fold_%d' % (n_fold)].astype(int)
k_fold['start_fold_%d' % (n_fold)] = k_fold['start_fold_%d' % (n_fold)].astype(int)
k_fold['end_fold_%d' % (n_fold)].clip(0, k_fold['text_len'], inplace=True)
k_fold['start_fold_%d' % (n_fold)].clip(0, k_fold['end_fold_%d' % (n_fold)], inplace=True)
k_fold['prediction_fold_%d' % (n_fold)] = k_fold.apply(lambda x: decode(x['start_fold_%d' % (n_fold)], x['end_fold_%d' % (n_fold)], x['text'], tokenizer), axis=1)
k_fold['prediction_fold_%d' % (n_fold)].fillna(k_fold["text"], inplace=True)
k_fold['jaccard_fold_%d' % (n_fold)] = k_fold.apply(lambda x: jaccard(x['selected_text'], x['prediction_fold_%d' % (n_fold)]), axis=1)
```
# Model loss graph
```
sns.set(style="whitegrid")
for n_fold in range(config['N_FOLDS']):
print('Fold: %d' % (n_fold+1))
plot_metrics(history_list[n_fold])
```
# Model evaluation
```
display(evaluate_model_kfold(k_fold, config['N_FOLDS']).style.applymap(color_map))
```
# Visualize predictions
```
display(k_fold[[c for c in k_fold.columns if not (c.startswith('textID') or
c.startswith('text_len') or
c.startswith('selected_text_len') or
c.startswith('text_wordCnt') or
c.startswith('selected_text_wordCnt') or
c.startswith('fold_') or
c.startswith('start_fold_') or
c.startswith('end_fold_'))]].head(15))
```
| github_jupyter |
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
**Note:** This notebook can run using TensorFlow 2.5.0
```
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import numpy as np
tokenizer = Tokenizer()
data="In the town of Athy one Jeremy Lanigan \n Battered away til he hadnt a pound. \nHis father died and made him a man again \n Left him a farm and ten acres of ground. \nHe gave a grand party for friends and relations \nWho didnt forget him when come to the wall, \nAnd if youll but listen Ill make your eyes glisten \nOf the rows and the ructions of Lanigans Ball. \nMyself to be sure got free invitation, \nFor all the nice girls and boys I might ask, \nAnd just in a minute both friends and relations \nWere dancing round merry as bees round a cask. \nJudy ODaly, that nice little milliner, \nShe tipped me a wink for to give her a call, \nAnd I soon arrived with Peggy McGilligan \nJust in time for Lanigans Ball. \nThere were lashings of punch and wine for the ladies, \nPotatoes and cakes; there was bacon and tea, \nThere were the Nolans, Dolans, OGradys \nCourting the girls and dancing away. \nSongs they went round as plenty as water, \nThe harp that once sounded in Taras old hall,\nSweet Nelly Gray and The Rat Catchers Daughter,\nAll singing together at Lanigans Ball. \nThey were doing all kinds of nonsensical polkas \nAll round the room in a whirligig. \nJulia and I, we banished their nonsense \nAnd tipped them the twist of a reel and a jig. \nAch mavrone, how the girls got all mad at me \nDanced til youd think the ceiling would fall. \nFor I spent three weeks at Brooks Academy \nLearning new steps for Lanigans Ball. \nThree long weeks I spent up in Dublin, \nThree long weeks to learn nothing at all,\n Three long weeks I spent up in Dublin, \nLearning new steps for Lanigans Ball. \nShe stepped out and I stepped in again, \nI stepped out and she stepped in again, \nShe stepped out and I stepped in again, \nLearning new steps for Lanigans Ball. \nBoys were all merry and the girls they were hearty \nAnd danced all around in couples and groups, \nTil an accident happened, young Terrance McCarthy \nPut his right leg through miss Finnertys hoops. \nPoor creature fainted and cried Meelia murther, \nCalled for her brothers and gathered them all. \nCarmody swore that hed go no further \nTil he had satisfaction at Lanigans Ball. \nIn the midst of the row miss Kerrigan fainted, \nHer cheeks at the same time as red as a rose. \nSome of the lads declared she was painted, \nShe took a small drop too much, I suppose. \nHer sweetheart, Ned Morgan, so powerful and able, \nWhen he saw his fair colleen stretched out by the wall, \nTore the left leg from under the table \nAnd smashed all the Chaneys at Lanigans Ball. \nBoys, oh boys, twas then there were runctions. \nMyself got a lick from big Phelim McHugh. \nI soon replied to his introduction \nAnd kicked up a terrible hullabaloo. \nOld Casey, the piper, was near being strangled. \nThey squeezed up his pipes, bellows, chanters and all. \nThe girls, in their ribbons, they got all entangled \nAnd that put an end to Lanigans Ball."
corpus = data.lower().split("\n")
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index) + 1
print(tokenizer.word_index)
print(total_words)
input_sequences = []
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
# pad sequences
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
# create predictors and label
xs, labels = input_sequences[:,:-1],input_sequences[:,-1]
ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)
print(tokenizer.word_index['in'])
print(tokenizer.word_index['the'])
print(tokenizer.word_index['town'])
print(tokenizer.word_index['of'])
print(tokenizer.word_index['athy'])
print(tokenizer.word_index['one'])
print(tokenizer.word_index['jeremy'])
print(tokenizer.word_index['lanigan'])
print(xs[6])
print(ys[6])
print(xs[5])
print(ys[5])
print(tokenizer.word_index)
# model.add() method is used here for building the neural network
model = Sequential()
model.add(Embedding(total_words, 64, input_length=max_sequence_len-1))
model.add(Bidirectional(LSTM(20)))
model.add(Dense(total_words, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(xs, ys, epochs=500, verbose=1)
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.show()
plot_graphs(history, 'accuracy')
seed_text = "Laurence went to dublin"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
```
| github_jupyter |
```
%matplotlib inline
```
Between-subject SVM classification based on network weight features, for CIMAQ memory encoding task (fMRI data).
Network weights reflect the engagement of a particular network for each trial.
Parcellations include:
- 7 networks
- 20 networks
- 64 networks
Trials (conditions) are classifierd according to:
- task condition (encoding or control task)
- memory performance (hit vs miss, correct vs incorrect source)
- stimulus category (?)
```
import os
import sys
import glob
import numpy as np
import pandas as pd
import nilearn
import scipy
import nibabel as nb
import sklearn
import seaborn as sns
import itertools
from numpy import nan as NaN
from matplotlib import pyplot as plt
from nilearn import image, plotting
from nilearn import masking
from nilearn import plotting
from nilearn import datasets
from nilearn.plotting import plot_stat_map, plot_roi, plot_anat, plot_img, show
from nilearn.input_data import NiftiMasker
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, precision_score, f1_score
from sklearn.model_selection import cross_val_predict, cross_val_score
from sklearn.preprocessing import MinMaxScaler
```
Step 1: import list of participants, and generate sublists of participants who have enough trials per category for each classification
1. Encoding vs Control task conditions (all 94)
2. Stimulus category (all 94)
3. Hit versus Miss (42 participants; at least 15 trials per condition)
4. Correct Source versus Wrong Source (49 participants; at least 15 trials per condition)
5. Correct Source versus Miss (38 participants; at least 15 trials per condition)
**NOTE: ADD filter to exclude participants with too many scrubbed frames?? **
```
# Path to directory with participant lists
data_file = '/Users/mombot/Documents/Simexp/CIMAQ/Data/Participants/Splitting/Sub_list.tsv'
sub_data = pd.read_csv(data_file, sep = '\t')
# Exclude participants who failed QC
sub_data = sub_data[sub_data['QC_status']!= 'F']
# Exclude participants with bad X matrices
sub_data = sub_data[sub_data['net_NaN']!= 'N']
## ADD filter to exclude participants with too many scrubbed frames?? ##
# Set minimal number of trials needed per subject to include them in analysis
num = 14
# Encoding vs Control, and Stimulus Category classifications
all_subs = sub_data['participant_id']
all_diagnosis = sub_data['cognitive_status']
print(all_subs)
print(len(all_subs))
# Hit versus Miss
hm_data = sub_data[sub_data['hits'] > num]
hm_data = hm_data[hm_data['miss'] > num]
hm_subs = hm_data['participant_id']
hm_diagnosis = hm_data['cognitive_status']
print(hm_subs)
print(len(hm_subs))
# Correct Source versus Wrong Source
cw_data = sub_data[sub_data['correct_source'] > num]
cw_data = cw_data[cw_data['wrong_source'] > num]
cw_subs = cw_data['participant_id']
cw_diagnosis = cw_data['cognitive_status']
print(cw_subs)
print(len(cw_subs))
# Correct Source versus Miss
cmiss_data = sub_data[sub_data['correct_source'] > num]
cmiss_data = cmiss_data[cmiss_data['miss'] > num]
cmiss_subs = cmiss_data['participant_id']
cmiss_diagnosis = cmiss_data['cognitive_status']
print(cmiss_subs)
print(len(cmiss_subs))
```
Step 2: For each categorization, randomly assign and split participants into a training set and a test set
Note: stratify to maintain comparable proportions of Cognitively Normal (Controls), Subjective Cognitive Disorder (SCD) and Mild Cognitive Impairment (MCI) participants between the testing and training sets
```
# Encoding vs Control Task Conditions
enc_ctl_train, enc_ctl_test = train_test_split(
all_subs, # list to split
test_size = 0.4, # 60%/40% split between train and test
shuffle= True,
stratify = all_diagnosis, # keep consistent proportions of Controls, SCDs and MCIs between sets
random_state = 123)
print('enc_ctl training:', len(enc_ctl_train),
'enc_ctl testing:', len(enc_ctl_test))
# Hit vs Miss Trials
hit_miss_train, hit_miss_test = train_test_split(
hm_subs, # list to split
test_size = 0.4, # 60%/40% split between train and test
shuffle= True,
stratify = hm_diagnosis, # keep consistent proportions of Controls, SCDs and MCIs between sets
random_state = 52)
print('hit_miss training:', len(hit_miss_train),
'hit_miss testing:', len(hit_miss_test))
# Correct Source vs Wrong Source Trials
cs_ws_train, cs_ws_test = train_test_split(
cw_subs, # list to split
test_size = 0.4, # 60%/40% split between train and test
shuffle= True,
stratify = cw_diagnosis, # keep consistent proportions of Controls, SCDs and MCIs between sets
random_state = 46)
print('cs_ws training:', len(cs_ws_train),
'cs_ws testing:', len(cs_ws_test))
# Correct Source vs Miss Trials
cs_miss_train, cs_miss_test = train_test_split(
cmiss_subs, # list to split
test_size = 0.4, # 60%/40% split between train and test
shuffle= True,
stratify = cmiss_diagnosis, # keep consistent proportions of Controls, SCDs and MCIs between sets
random_state = 103)
print('cs_miss training:', len(cs_miss_train),
'cs_miss testing:', len(cs_miss_test))
```
Step 3: Build training and testing feature matrices
For each participant:
- load matrix of network weigth features (shape = trials per networks)
- load the trial labels
- mask the data (network weights and labels) that correspond to trials of interest
- concatenate the participant's weights and label data into two matrices (weights and labels). There should be two matrices per set (train and test) per analysis.
Note:
Trying three different grains of segmentation: 7, 20 and 64 networks
ALSO:
Import MIST network labels to identify and interpret features
```
# set paths to directories of interest
beta_dir = '/Users/mombot/Documents/Simexp/CIMAQ/Data/Nistats/NetworkWeights'
label_dir = '/Users/mombot/Documents/Simexp/CIMAQ/Data/Nistats/Events'
output_dir = '/Users/mombot/Documents/Simexp/CIMAQ/Data/Nilearn/features'
# ENCODING VERSUS CONTROL TASK CLASSIFICATION
# For each set (training and test), create an empty numpy array to store
# concatenated network weight maps (one row per trial; size = trials * networks).
# 1. set the parcellation level
numnet = 7
# numnet = 20
# numnet = 64
# 2. determine the number of rows needed (sum of trials per participants in set)
numrow_train = 0
numrow_test = 0
for sub in enc_ctl_train:
labels_file = os.path.join(label_dir, 'sub-'+str(sub)+'_enco_ctl.tsv')
y_enco_ctl = pd.read_csv(labels_file, sep='\t')
numrow_train = numrow_train + y_enco_ctl.shape[0]
for sub in enc_ctl_test:
labels_file = os.path.join(label_dir, 'sub-'+str(sub)+'_enco_ctl.tsv')
y_enco_ctl = pd.read_csv(labels_file, sep='\t')
numrow_test = numrow_test + y_enco_ctl.shape[0]
print('number of trials in the training set: ', numrow_train,
'number of trials in the test set: ', numrow_test)
# 3. create an empty numpy array to store the data
X_enc_ctl_train = np.empty(shape=(numrow_train, numnet))
X_enc_ctl_test = np.empty(shape=(numrow_test, numnet))
print(X_enc_ctl_train.shape, X_enc_ctl_test.shape)
# 4. create empty dataframes to store trial labels (one per set)
y_enc_ctl_train = pd.DataFrame()
y_enc_ctl_train.insert(loc = 0, column = 'condition', value = 'TBD', allow_duplicates=True)
y_enc_ctl_train.insert(loc = 1, column = 'dccid', value = 'TBD', allow_duplicates=True)
y_enc_ctl_train.insert(loc = 2, column = 'trialnum', value = 'NaN', allow_duplicates=True)
y_enc_ctl_test = y_enc_ctl_train.copy()
# 5. Fill the X (beta weights per voxel) and y (trial labels) data matrices
# note: nilearn.image.load_img concatenates 3D beta maps in alphabetical order
# trial numbers must be PADDED with zeros to preserve their temporal order when alphabetized
# TRAINING SET
j = 0
for sub in enc_ctl_train:
print(sub)
weights_file = os.path.join(beta_dir, 'MIST_'+str(numnet), 'sub-'+str(sub)+'-MIST_'+str(numnet)+'networks_117Trials.tsv')
X_netWeights = pd.read_csv(weights_file, sep='\t')
#print(X_netWeights)
X_enc_ctl_train[j:(j+X_netWeights.shape[0]), :] = X_netWeights
j = j + X_netWeights.shape[0]
print(np.where(np.isnan(X_netWeights)))
print('number of X filled rows: ', j,
'subject X_shape:', X_netWeights.shape,
'total X_shape:', X_enc_ctl_train.shape)
labels_file = os.path.join(label_dir, 'sub-'+str(sub)+'_enco_ctl.tsv')
y_enco_ctl = pd.read_csv(labels_file, sep='\t')
trialnum = y_enco_ctl.index
y_enco_ctl.insert(loc = y_enco_ctl.shape[1], column = 'dccid',
value = sub, allow_duplicates=True)
y_enco_ctl.insert(loc = y_enco_ctl.shape[1], column = 'trialnum',
value = trialnum+1, allow_duplicates=True)
y_enc_ctl_train = y_enc_ctl_train.append(y_enco_ctl, ignore_index=True)
print('subject y_shape:', y_enco_ctl.shape,
'total y_shape:', y_enc_ctl_train.shape)
print(y_enco_ctl.condition.value_counts())
print('The training data set is built!')
# TESTING SET
j = 0
for sub in enc_ctl_test:
print(sub)
weights_file = os.path.join(beta_dir, 'MIST_'+str(numnet), 'sub-'+str(sub)+'-MIST_'+str(numnet)+'networks_117Trials.tsv')
X_netWeights = pd.read_csv(weights_file, sep='\t')
#print(X_netWeights)
X_enc_ctl_test[j:(j+X_netWeights.shape[0]), :] = X_netWeights
j = j + X_netWeights.shape[0]
print(np.where(np.isnan(X_netWeights)))
print('number of X filled rows: ', j,
'subject X_shape:', X_netWeights.shape,
'total X_shape:', X_enc_ctl_test.shape)
labels_file = os.path.join(label_dir, 'sub-'+str(sub)+'_enco_ctl.tsv')
y_enco_ctl = pd.read_csv(labels_file, sep='\t')
trialnum = y_enco_ctl.index
y_enco_ctl.insert(loc = y_enco_ctl.shape[1], column = 'dccid',
value = sub, allow_duplicates=True)
y_enco_ctl.insert(loc = y_enco_ctl.shape[1], column = 'trialnum',
value = trialnum+1, allow_duplicates=True)
y_enc_ctl_test= y_enc_ctl_test.append(y_enco_ctl, ignore_index=True)
print('subject y_shape:', y_enco_ctl.shape,
'total y_shape:', y_enc_ctl_test.shape)
print(y_enco_ctl.condition.value_counts())
print('The testing data set is built!')
# 6. extract the label columns from the y data dataframes (to input model)
y_enco_ctl_labels_train = y_enc_ctl_train['condition']
y_enco_ctl_labels_test = y_enc_ctl_test['condition']
# Data to input the Support Vector Machine model for different classifications:
# ENCODING vs CONTROL condition:
# Training: X_enc_ctl_train, y_enco_ctl_labels_train
# Testing: X_enc_ctl_test, y_enco_ctl_labels_test
# HIT vs MISS trials:
# Training: X_hit_miss_train, y_hit_miss_labels_train
# Testing: X_hit_miss_test, y_hit_miss_labels_test
# CORRECT SOURCE vs WRONG SOURCE trials:
# Training: X_cs_ws_train, y_cs_ws_labels_train
# Testing: X_cs_ws_test, y_cs_ws_labels_test
# CORRECT SOURCE vs MISS trials:
# Training: X_cs_miss_train, y_cs_miss_labels_train
# Testing: X_cs_miss_test, y_cs_miss_labels_test
X_train = X_enc_ctl_train
y_train = y_enco_ctl_labels_train
X_test = X_enc_ctl_test
y_test = y_enco_ctl_labels_test
# initialise the SVC model
# Note that class_weight gives equivalent influence to different categories
# important if number of trials differs per condition
#trial_svc = SVC(kernel='linear', class_weight='balanced') #define the model
trial_svc = LinearSVC(class_weight='balanced') #define the model
print(trial_svc)
trial_svc.fit(X_train, y_train) #train the model
# MAKE SURE: mettre poids egal par categorie.
# class-weight: balanced!!!
# predict the training data based on the model
y_pred = trial_svc.predict(X_train)
# calculate the model accuracy
acc = trial_svc.score(X_train, y_train)
# calculate the model precision, recall and f1 in one report
cr = classification_report(y_true=y_train,
y_pred = y_pred)
# get a table to help us break down these scores
cm = confusion_matrix(y_true=y_train, y_pred = y_pred)
# print results
print('accuracy:', acc)
print(cr)
print(cm)
# plot confusion matrix (training data)
cmdf = pd.DataFrame(cm, index = ['Control','Encoding'], columns = ['Control','Encoding'])
sns.heatmap(cmdf, cmap = 'RdBu_r')
plt.xlabel('Predicted')
plt.ylabel('Observed')
# label cells in matrix
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j+0.5, i+0.5, format(cm[i, j], 'd'),
horizontalalignment="center",
color="white")
# Set up 10-fold cross-validation to evaluate the model's performance over the training set
# predict
y_pred = cross_val_predict(trial_svc, X_train, y_train,
groups=y_train, cv=10)
# scores
acc = cross_val_score(trial_svc, X_train, y_train,
groups=y_train, cv=10)
#Look at accuracy of prediction for each fold of the cross-validation
for i in range(10):
print('Fold %s -- Acc = %s'%(i, acc[i]))
#look at the overall accuracy of the model
overall_acc = accuracy_score(y_pred = y_pred, y_true = y_train)
overall_cr = classification_report(y_pred = y_pred, y_true = y_train)
overall_cm = confusion_matrix(y_pred = y_pred, y_true = y_train)
print('Accuracy:',overall_acc)
print(overall_cr)
thresh = overall_cm.max() / 2
cmdf = pd.DataFrame(overall_cm, index = ['CTL','Enc'], columns = ['CTL','Enc'])
sns.heatmap(cmdf, cmap='copper')
plt.xlabel('Predicted')
plt.ylabel('Observed')
for i, j in itertools.product(range(overall_cm.shape[0]), range(overall_cm.shape[1])):
plt.text(j+0.5, i+0.5, format(overall_cm[i, j], 'd'),
horizontalalignment="center",
color="white")
# Test model on unseen data from the test set
# Unscaled
trial_svc.fit(X_train, y_train)
y_pred = trial_svc.predict(X_test) # classify age class using testing data
acc = trial_svc.score(X_test, y_test) # get accuracy
cr = classification_report(y_pred=y_pred, y_true=y_test) # get prec., recall & f1
cm = confusion_matrix(y_pred=y_pred, y_true=y_test) # get confusion matrix
# print results
print('accuracy =', acc)
print(cr)
# plot results
thresh = cm.max() / 2
cmdf = pd.DataFrame(cm, index = ['Control','Encoding'], columns = ['Control','Encoding'])
sns.heatmap(cmdf, cmap='RdBu_r')
plt.xlabel('Predicted')
plt.ylabel('Observed')
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j+0.5, i+0.5, format(cm[i, j], 'd'),
horizontalalignment="center",
color="white")
#Display feature weights
coef_ = trial_svc.coef_[0]
print(coef_.shape)
# To interpret MIST parcellation labels:
# https://simexp.github.io/multiscale_dashboard/index.html
basc_dir = '/Users/mombot/Documents/Simexp/CIMAQ/Data/MIST/Release/Parcellations'
basc = image.load_img(os.path.join(basc_dir, 'MIST_'+str(numnet)+'.nii'))
print(basc.header.get_data_shape())
#print(basc.header)
b_labels = os.path.join('/Users/mombot/Documents/Simexp/CIMAQ/Data/MIST/Release/Parcel_Information/MIST_'+str(numnet)+'.csv')
basc_labels = pd.read_csv(b_labels, sep=';')
basc_labels.insert(loc=3, column='coef', value=coef_, allow_duplicates=True)
print(basc_labels.iloc[:, 2:4])
```
| github_jupyter |
### Data processing
- Data Processing is used for improve the quality of data
- Problems in data:
- insufficient of data
- too much data
- Missing data
- Duplicate data
- outliers
- Standardization(standard scaler)
- Roboust Scaling
- DataRange(MinMax Scalar)
- Normalization
### Standardization:
```
import pandas as pd
df = pd.read_csv("Advertisement.csv")
df.head()
import numpy as np
data = pd.DataFrame({"names":["a","b",np.nan],"rollnumber":[123,156,np.nan]})
data
data.isnull()
data.isnull().sum()
data.isnull().sum().sum()
df.isnull()
df.isnull().sum()
df.isnull().sum().sum()
df.columns
df["TV"].min()
df["TV"].max()
df.std()
import matplotlib.pyplot as plt
import seaborn as sns
plt.title("before scaling dataset")
sns.kdeplot(df["TV"])
sns.kdeplot(df["radio"])
sns.kdeplot(df["newspaper"])
sns.kdeplot(df["sales"])
df[["newspaper","sales","TV"]].head()
from sklearn.preprocessing import StandardScaler
std = StandardScaler()
std_data = std.fit_transform(df)
std_data
std_data = pd.DataFrame(std_data,columns=df.columns)#["tv","radio"]
std_data.head()
plt.title("after scaling dataset")
sns.kdeplot(std_data["TV"])
sns.kdeplot(std_data["radio"])
sns.kdeplot(std_data["newspaper"])
sns.kdeplot(std_data["sales"])
std_data["TV"].mean()
std_data["TV"].std()
df["TV"].mean()
df["TV"].std()
```
#### Roboust Scaling
- Roboust scaling also used for scale the outliers,it scales using median and IQR
```
from sklearn.preprocessing import RobustScaler
rb = RobustScaler()
rb_data = rb.fit_transform(df)
rb_data
rb_data_df = pd.DataFrame(rb_data,columns=df.columns)
rb_data_df.head()
plt.title("after scaling dataset")
sns.kdeplot(rb_data_df["TV"])
sns.kdeplot(rb_data_df["radio"])
sns.kdeplot(rb_data_df["newspaper"])
sns.kdeplot(rb_data_df["sales"])
```
#### DataRange(MinMax Scaler)
```
from sklearn.preprocessing import MinMaxScaler
mi = MinMaxScaler(feature_range=(-1,1))
mi_data = mi.fit_transform(df)
mi_data
mi_data_df = pd.DataFrame(mi_data,columns=df.columns)
mi_data_df.head()
plt.title("after scaling dataset")
sns.kdeplot(mi_data_df["TV"])
sns.kdeplot(mi_data_df["radio"])
sns.kdeplot(mi_data_df["newspaper"])
sns.kdeplot(mi_data_df["sales"])
```
#### Normalization
- upto now we are scaling by using features
- In certain cases we want to scale the individual data observations(rows)
- when clustering data we need to use normalization
```
from sklearn.preprocessing import Normalizer
n = Normalizer()
n_data = n.fit_transform(df)
n_data
n_data_df = pd.DataFrame(n_data,columns=df.columns)
n_data_df.head()
plt.title("after scaling dataset")
sns.kdeplot(n_data_df["TV"])
sns.kdeplot(n_data_df["radio"])
sns.kdeplot(n_data_df["newspaper"])
sns.kdeplot(n_data_df["sales"])
```
### Data cleaning
```
wea = pd.read_csv("weather.csv")
wea
wea.isnull().sum()
wea["day"][0]
df2 = pd.read_csv("weather.csv",parse_dates=["day"])
df2
df2.set_index("day",inplace=True)
df2
df2.isnull().sum()
df2.fillna(0)
df2.fillna({"temparature":0,"winspeed":0,"event":"no data available"})
```
| github_jupyter |
```
import info
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
from datetime import datetime
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, accuracy_score
import lightgbm as lgb
import warnings
import os.path
#import lightgbm as lgb
from utils import *
from backtest_algos import *
warnings.filterwarnings("ignore")
path_pc = 'C:/Users/admin/Desktop/AI Plan/Finance with AI/Notebooks/'
today = datetime.today()
print("Today's date:", today.strftime("%Y-%m-%d"))
def ann_ret(ts):
return np.power((ts[-1]/ts[0]),(252/len(ts)))-1
def ann_ret(ts):
return np.power((ts[-1]/ts[0]),(252/len(ts)))-1
def dd(ts):
return np.min(ts/np.maximum.accumulate(ts))-1
def performance(result, window):
perf = result.copy()
perf['daily_returns'] = perf['porfolio_value'].pct_change()
rolling_window = result.porfolio_value.rolling(window)
perf['annualized_return'] = rolling_window.apply(ann_ret)
perf['annualized_volatility'] = perf.daily_returns.rolling(window).std()*np.sqrt(252)
perf['sharpe_ratio'] = perf['annualized_return']/perf['annualized_volatility']
perf['drawdown'] = rolling_window.apply(dd)
perf['exposure'] = perf['positions_value']/500000
return perf
versions = ['v63','v64','v65','v66','v67','v68']
lookback = 250
results = []
cols = []
for version in versions:
result = pd.read_csv(path_pc+'LGB_v2_result_long_short_'+version+'_250.csv')
result.drop(axis = 1, labels = 'Unnamed: 0', inplace = True)
result = result.rename(columns={'porfolio_value':'porfolio_value_'+version})
result['date'] = result['date'].astype('datetime64[ns]')
result = result.set_index('date')
cols.append('porfolio_value_'+version)
results.append(result)
HSI = pd.read_csv(path_pc+'^HSI.csv')
HSI['Date'] = HSI['Date'].astype('datetime64[ns]')
HSI['date'] = HSI['Date']
HSI=HSI.set_index('date')
HSI=HSI.reindex(results[0].index)
combined = results[0].copy()
for i in range(1,len(results)):
combined = combined.combine_first(results[i])
plot_data=combined.combine_first(HSI)
plot_data=plot_data.rename(columns={"Adj Close": "HSI"})
plot_data = plot_data[['HSI']+cols][-lookback:]
rebased_cols = []
for col in plot_data:
plot_data[col+'_rebased']=(plot_data[col].pct_change()+1).cumprod()
rebased_cols.append(col+'_rebased')
plot_data=plot_data[rebased_cols]
%matplotlib notebook
fig = plt.figure(figsize = (5,4))
ax=fig.add_subplot(111)
for col in rebased_cols:
ax.plot(plot_data[col], label=col[15:18])
ax.legend()
plt.xticks(rotation=45)
rebased_cols
for i in range(len(cols)):
results[i]['porfolio_value'] = results[i][cols[i]]
perfs = []
window = 50
for result in results:
perf = performance(result, window)
perfs.append(perf)
sharpe_ratios = []
for perf in perfs:
sharpe_ratio = (perf['daily_returns'].mean()*252)/(perf['daily_returns'].std()*np.sqrt(252))
sharpe_ratios.append(sharpe_ratio)
print('Sharpe Ratios')
for i in range(len(versions)):
print ('{}: {}'.format(versions[i],round(sharpe_ratios[i],2)))
print('Annual Returns')
for i in range(len(versions)):
print ('{}: {}'.format(versions[i],round(ann_ret(results[i]['porfolio_value']),2)))
print('Annualized Daily Volatility')
for i in range(len(versions)):
print ('{}: {}'.format(versions[i],round(perfs[i]['daily_returns'].std()*16,2)))
print('Mean Windowed Max Drawdown')
for i in range(len(versions)):
print ('{}: {}'.format(versions[i],round(perfs[i]['drawdown'].max(),3)))
```
| github_jupyter |
*Analytical Information Systems*
# Tutorial 6 - Predictive Modeling II
Matthias Griebel<br>
Lehrstuhl für Wirtschaftsinformatik und Informationsmanagement
SS 2019
<h1>Agenda<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Modeling" data-toc-modified-id="Modeling-1"><span class="toc-item-num">1 </span>Modeling</a></span><ul class="toc-item"><li><span><a href="#Models-for-supervised-learning" data-toc-modified-id="Models-for-supervised-learning-1.1"><span class="toc-item-num">1.1 </span>Models for supervised learning</a></span></li><li><span><a href="#Metrics-for-regression" data-toc-modified-id="Metrics-for-regression-1.2"><span class="toc-item-num">1.2 </span>Metrics for regression</a></span></li></ul></li><li><span><a href="#Up-to-you:--Price-forecasting-for-used-cars" data-toc-modified-id="Up-to-you:--Price-forecasting-for-used-cars-2"><span class="toc-item-num">2 </span>Up to you: Price forecasting for used cars</a></span></li><li><span><a href="#Exam-Questions" data-toc-modified-id="Exam-Questions-3"><span class="toc-item-num">3 </span>Exam Questions</a></span><ul class="toc-item"><li><span><a href="#Exam-AIS-SS-2018" data-toc-modified-id="Exam-AIS-SS-2018-3.1"><span class="toc-item-num">3.1 </span>Exam AIS SS 2018</a></span></li></ul></li></ul></div>
## Modeling
__Recap: CRISP-DM__
<img align="right" src="http://statistik-dresden.de/wp-content/uploads/2012/04/CRISP-DM_Process_Diagram1.png" style="width:50%">
Today, we will focus on
- `Data Preparation`
- `Modeling` for regression tasks
### Models for supervised learning
`parsnip` contains wrappers for a number of [models](https://tidymodels.github.io/parsnip/articles/articles/Models.html).
- Classification
- Regression: `logistic_reg()`, `multinom_reg()`
- Tree based:`decision_tree()`, `rand_forest()`, `boost_tree()`
- ANN: `mlp()`
- KNN: `nearest_neighbor()`
- SVM: `svm_poly()`, `svm_rbf()`
- Regression
- Regression: `linear_reg()`
- Tree based: `decision_tree()`, `rand_forest()`, `boost_tree()`
- ANN: `mlp()`
- KNN: `nearest_neighbor()`
- SVM: `svm_poly()`, `svm_rbf()`
__LightGBM__
[LightGBM](https://lightgbm.readthedocs.io/en/latest/) is a gradient boosting framework that uses tree based learning algorithms
- Faster training speed and higher efficiency
- Lower memory usage
- Better accuracy
- Support of parallel and GPU learning
- Capable of handling large-scale data
But: not yet supported by `parsnip`
### Metrics for regression
There are several metrics for evaluating regression models. As with classification metrics, the `yardstick` package contains all common regression metrics.
*Note: We define $x_i$ as the actual value and $y_i$ as the predicted value*
__Mean absolute error (MAE)__
$\frac{1}{n}\sum_{i=1}^{n}|x_i-y_i|$
- absolute difference between $yi$ and $xi$
- good interpretability
__Root-mean-square error (RMSE)__
$\sqrt{\frac{1}{n}\sum_{i=1}^{n}(x_i-y_i)^2}$
- square root of the average of squared errors (MSE)
- proportional to the size of the squared error: larger errors have a disproportionately large effect
__Coefficient of determination ($R^2$)__
<img align="center" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/6b863cb70dd04b45984983cb6ed00801d5eddc94" style="width:15%">
<img align="center" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Coefficient_of_Determination.svg/600px-Coefficient_of_Determination.svg.png" style="width:30%">
where
sum of squares of residuals:
$SS_{tot} = \sum_{i}(x_i - \bar{x})^2$
total sum of squares:
$SS_{res} = \sum_{i}(x_i - y_i)^2$
- proportion of the variance in the dependent variable that is predictable from the independent variable(s)
- usually between 0 and 1
Source: [Wikipedia](https://en.wikipedia.org/wiki/Coefficient_of_determination)
__Mean Absolute Percentage Error (MAPE)__
$\frac{100\%}{n}\sum_{i=1}^{n}\left |\frac{x_i-y_i}{x_i}\right|$
- frequently used for (time series) forecasting
- cannot be used if there are zero values
- puts a heavier penalty on negative errors (biased: systematically select a method whose forecasts are too low)
## Up to you: Price forecasting for used cars
__Kaggle used cars database__
Over 370,000 used cars scraped from Ebay Kleinanzeigen. See description on [Kaggle.com](https://www.kaggle.com/orgesleka/used-cars-database)
Why is that interesting?
<img align="center" src="images/06/wkda.png" style="width:80%">
Load required packages
```
library(tidyverse)
library(tidymodels)
```
Load data
```
autos <- read_csv('data/T06/autos.csv.zip')
autos %>%
glimpse()
```
__Up to you: Price forecasting for used cars__
Build a regression model that predicts the price for used cars
1. Split the data into train and test set
```
autos_split <- initial_split(autos, prop = 3/4)
train_set <- training(autos_split)
test_set <- testing(autos_split)
```
__Up to you: Price forecasting for used cars__
2. Prepare a recipe for data preprocessing, removing outliers or inconsistencies
```
train_set %>%
recipe(price ~ vehicleType + yearOfRegistration + gearbox + powerPS
+ kilometer + fuelType + brand) -> rec
rec
```
*Check Prices*
```
sum(is.na(train_set$price))
options(repr.plot.width=7, repr.plot.height=3)
options(scipen=999)
train_set %>%
ggplot(aes(x=vehicleType, y=price)) + geom_boxplot() + ylim(0,1000000)
```
Some outliers need to be removed
```
quantiles_price <- quantile(train_set$price, probs = c(0.01, 0.05, 0.95, 0.99))
quantiles_price
train_set %>%
filter(price >= quantiles_price[1], price <= quantiles_price[4]) %>%
ggplot(aes(x=vehicleType, y=price)) + geom_boxplot()
```
Add findings to recipe
```
rec %>%
step_filter(price >= quantiles_price[2], price <= quantiles_price[4]) -> rec
rec
```
*Check vehicle type*
```
unique(train_set$vehicleType)
table(train_set$vehicleType)
sum(is.na(train_set$vehicleType))
```
Add findings to recipe
```
rec %>%
step_naomit(vehicleType) %>%
step_dummy(vehicleType) -> rec
rec
```
*Check power*
```
train_set %>%
ggplot(aes(x=vehicleType, y=powerPS)) + geom_boxplot()
quantiles_power <- quantile(train_set$powerPS, probs = c(0.05, 0.1, 0.15, 0.95, 0.99))
quantiles_power
train_set %>%
filter(powerPS > 0, powerPS <= quantiles_power[4]) %>%
ggplot(aes(x=vehicleType, y=powerPS)) + geom_boxplot()
```
Add findings to recipe
```
rec %>%
step_filter(powerPS > 0, powerPS <= quantiles_power[4]) -> rec
rec
```
*Check year of registration*
```
train_set$yearOfRegistration %>% summary()
train_set %>%
filter(yearOfRegistration > 1900, yearOfRegistration <= 2016) %>%
ggplot(aes(x=vehicleType, y=yearOfRegistration)) + geom_boxplot()
```
Add findings to recipe
```
rec %>%
step_filter(yearOfRegistration > 1950, yearOfRegistration <= 2016) -> rec
rec
```
*Check fuel type*
```
unique(train_set$fuelType)
table(train_set$fuelType)
sum(is.na(train_set$fuelType))
```
Add findings to recipe
```
rec %>%
#step_knnimpute(fuelType) %>%
step_naomit(fuelType) %>%
step_other(fuelType, threshold = 0.01) %>%
step_dummy(fuelType) -> rec
rec
```
*Check gearbox*
```
unique(train_set$gearbox)
table(train_set$gearbox)
sum(is.na(train_set$gearbox))
```
Add findings to recipe
```
rec %>%
step_naomit(gearbox) %>%
step_dummy(gearbox) -> rec
rec
```
*Check brand*
```
train_set %>% distinct(brand) %>% pull()
```
Add findings to recipe
```
german_brands = c('volkswagen', 'audi', 'bmw', 'mercedes_benz', 'porsche','opel')
rec %>%
step_mutate(brand=if_else(brand %in% german_brands, 'german', 'foreign')) %>%
step_string2factor(brand) %>%
step_dummy(brand)-> rec
rec
```
*Check Kilometer*
```
train_set %>%
ggplot(aes(x=vehicleType, y=kilometer)) + geom_boxplot()
unique(train_set$kilometer)
```
Prepare recipe
```
rec %>%
check_missing(all_predictors()) %>%
prep() -> prepped_rec
```
Bake train and test set
```
train_set_baked <- prepped_rec %>% juice()
test_set_baked <- prepped_rec %>% bake(new_data=test_set)
train_set_baked %>% head()
```
__Up to you: Price forecasting for used cars__
3. Fit and evaluate two different models on the train set
*Linear Regression*
```
linear_reg(mode = 'regression') %>%
set_engine('lm') %>%
fit(price ~ ., data = train_set_baked) %>%
predict(new_data = test_set_baked) %>%
cbind(truth = test_set_baked$price) %>%
metrics(truth, .pred) -> res_lin
res_lin
```
*XGBoost* (detailed [parameters](https://xgboost.readthedocs.io/en/latest/parameter.html))
```
boost_tree(mode="regression", tree_depth = 6, learn_rate = 0.3) %>%
set_engine('xgboost') %>%
fit(price ~ ., data = train_set_baked) %>%
predict(new_data = test_set_baked) %>%
cbind(truth = test_set_baked$price) %>%
metrics(truth, .pred) -> res_xgb
res_xgb
```
## Exam Questions
### Exam AIS SS 2018
__Question 5: Supervised Learning__
(a) (3 points) Overfitting is a key problem which arises in supervised learning. Explain the central underlying trade-off using a simple plot.
> <img src="http://scott.fortmann-roe.com/docs/docs/BiasVariance/biasvariance.png" style="width:70%">
Source: http://scott.fortmann-roe.com/docs/docs/BiasVariance/biasvariance.png
(b) (2 points) For each of the following machine learning approaches name a measure / algorithm variant which allows controlling over-fitting tendencies. You should only consider measures which are specific to this algorithm (i.e., not cross-validation or other generic approaches).
Decision Tree
> - Pre-Pruning (Early Stopping Rule): Stop the algorithm before it becomes a fully-grown tree
- Post-pruning: Grow decision tree to its entirety, then trim the nodes of the decision tree in a bottom-up fashion
k nearest Neighbors
> - _increase_ k
Boosting Algorithms
> - Learning Rate
- other hyperparameters, i.e., number of boosting rounds
Linear Regression
> - Limit the number of independent variables
- Ridge: Penalize by sum-of-squares of parameters
- Lasso: Penalize by sum-of-absolute values of parameters
(c) __Support Vector Machines__
A certain kind of SVM is characterized by the following optimization problem:
$$\min \underbrace{\frac{1}{2} w^Tw}_{A} + \underbrace{C \sum_k \epsilon_k}_{B}$$
subject to
$$y_i (wx_i+b) \geq 1 - \epsilon_i$$
i. (2 points) What kind of SVM is described here? Provide an intuition of the role of $\epsilon$ in the constraint.
> - Soft Margin SVM
- Slack variables $\epsilon_i$ can be added to allow misclassification of difficult or noisy examples
ii. (2 points) Briefly explain the two parts A and B of the objective function.
$$\min \underbrace{\frac{1}{2} w^Tw}_{A} + \underbrace{C \sum_k \epsilon_k}_{B}$$
> A: Margin between hyperplanes
> B: Penalty term for misclassification, parameter C is a regularization parameter to control overfitting,
(d) (2 points) Briefly explain the concept of bootstrap aggregation (bagging) and how it benefits supervised learning.
> Create ensembles of weak learners by repeatedly randomly resampling the training data
- Given a training set of size n, create m samples of size n by drawing n examples from the original data, with replacement
- Create m models from m samples
- Combine the m resulting models using simple majority vote (classification) or averaging (regression)
> Decreases error by decreasing the variance in the results due to unstable learners, bias remains unchanged.
(e) (2 points) How would you assess the relative importance of variables in a random forest. Explain your answer. (You may consider the next question for an illustration.)
From (f) - See Tutorial 5
<img align="center" src="images/05/rf.png" style="width:60%">
Solution (e)
> Number of splits (across all tress) that include the feature renders the feature more important (*Sex*: 3, *Age/Pclass*: 2); Position of split matters as well (first split always *Sex* - high information gain)
>Not in lecture:
- Gini Importance / Mean Decrease in Impurity (MDI)
- Calculate the sum over the number of splits (across all tress) that include the feature, proportionally to the number of samples it splits.
- Permutation Importance or Mean Decrease in Accuracy (MDA)
>see (https://medium.com/the-artificial-impostor/feature-importance-measures-for-tree-models-part-i-47f187c1a2c3)
| github_jupyter |
# Formal Language Definition
```
import pandas as pd
import lux
from lux.vis.VisList import VisList
from lux.vis.Vis import Vis
# Collecting basic usage statistics for Lux (For more information, see: https://tinyurl.com/logging-consent)
lux.logger = True # Remove this line if you do not want your interactions recorded
```
The Lux intent specification can be defined as a context-free grammar (CFG). Here, we introduce a formal definition of the intent language in Lux for interested readers.
```
df = pd.read_csv('https://github.com/lux-org/lux-datasets/blob/master/data/cars.csv?raw=true')
df["Year"] = pd.to_datetime(df["Year"], format='%Y')
```
## Composing a Lux *Intent* with `Clause` objects
An *intent* in Lux corresponds to the Kleene star of `Clause` objects, i.e., it can have either zero, one, or multiple `Clause`s.
\begin{equation}
\langle Intent\rangle \rightarrow \langle Clause\rangle^* \\
\end{equation}
```
spec1 = lux.Clause("MilesPerGal")
spec2 = lux.Clause("Horsepower")
spec3 = lux.Clause("Origin=USA")
intent = [spec1, spec2, spec3]
```
Here is an example of how we can formulate an intent as a list of `Clause` and generate a visualization. In this tutorial, we will discuss how the `Clause` breaks down to different production rules.
```
Vis(intent,df)
```
A `Clause` can either be an `Axis` specification or a `Filter` specification.
Note that it is not possible for a `Clause` to be both an `Axis` and a `Filter`, but they can be specified as separate `Clause`s in the intent.
\begin{equation}
\begin{split}
\langle Clause\rangle &\rightarrow \langle Axis \rangle \\
&\rightarrow \langle Filter \rangle
\end{split}
\end{equation}
```
axisSpec = lux.Clause(attribute="MilesPerGal")
# Equivalent, easier-to-specify Clause syntax : lux.Clause("MilesPerGal")
axisSpec
filterSpec = lux.Clause(attribute="Origin",filter_op="=",value="USA")
# Equivalent, easier-to-specify Clause syntax : lux.Clause("Origin=USA")
filterSpec
```
## `Axis` specification
An `Axis` requires an `attribute` specification, and an optional `channel`, `aggregation`, or `bin_size` specification.
\begin{equation}
\langle Axis \rangle \rightarrow \langle attribute \rangle \langle channel \rangle \langle aggregation \rangle \langle bin\_size \rangle
\end{equation}
An `attribute` can either be a single column in the dataset, a list of columns, or a `wildcard`.
\begin{equation}
\begin{split}
\langle attribute \rangle &\rightarrow \textrm{attribute} \\
&\rightarrow \textrm{attribute} \cup \langle attribute \rangle\\
&\rightarrow \langle wildcard \rangle
\end{split}
\end{equation}
```
# user is interested in "MilesPerGal"
attribute = lux.Clause("Origin")
# user is interested in "MilesPerGal","Horsepower", or "Weight"
attribute = lux.Clause(["MilesPerGal","Horsepower","Weight"])
# user is interested in any attribute
attribute = lux.Clause("?")
```
Optional specification of the `Axis` include :
\begin{equation}
\begin{aligned}
&\langle channel\rangle \rightarrow (\textrm{x } |\textrm{ y }|\textrm{ color }|\textrm{ auto})\\
&\langle aggregation\rangle \rightarrow (\textrm{mean }| \textrm{ sum } | \textrm{ count } | \textrm{ min } | \textrm{ max } | \textrm{ any numpy aggregation function }| \textrm{ auto})\\
&\langle bin\_size \rangle \rightarrow ( \textrm{any integer } | \textrm{ auto})\\
\end{aligned}
\end{equation}
```
# Ensure that "MilesPerGal" is placed on the x axis
axisSpec = lux.Clause("MilesPerGal",channel="x")
# Apply sum on "MilesPerGal"
axisSpec = lux.Clause("MilesPerGal",aggregation="sum")
# Divide "MilesPerGal" into 50 bins
axisSpec = lux.Clause("MilesPerGal",bin_size=50)
```
#### Example: Effects of optional attribute specification parameters
By default, if we specify only an attribute, the system automatically infers the appropriate `channel`, `aggregation`, or `bin_size`.
```
axisSpec = "MilesPerGal"
Vis([axisSpec],df)
```
We can increase the `bin_size` as an optional parameter:
```
bin50MPG = lux.Clause("MilesPerGal",bin_size=50)
Vis([bin50MPG],df)
```
For bar charts, Lux uses a default aggregation of `mean` and displays a horizontal bar chart with `Origin` on the y axis.
```
axisSpec1 = "MilesPerGal"
axisSpec2 = "Origin"
Vis([axisSpec1,axisSpec2],df)
```
We can change the `mean` to a `sum` aggregation:
```
axisSpec1 = lux.Clause("MilesPerGal",aggregation="sum")
axisSpec2 = "Origin"
Vis([axisSpec1,axisSpec2],df)
```
Or we can set the `Origin` on the x-axis to get a vertical bar chart instead:
```
axisSpec1 = "MilesPerGal"
axisSpec2 = lux.Clause("Origin",channel="x")
Vis([axisSpec1,axisSpec2],df)
```
### `Wildcard` attribute specifier
The `wildcard` consists of an "any" specifier (?) with an optional `constraint` clause, that constrains the set of attributes that Lux enumerates over.
\begin{equation}
\langle wildcard \rangle \rightarrow \textrm{( ? )} \langle constraint\rangle\\
\end{equation}
\begin{equation}
\langle constraint \rangle \rightarrow \langle data\_model\rangle \langle data\_type\rangle\\
\end{equation}
\begin{equation}
\begin{aligned}
&\langle data\_type\rangle \rightarrow (\textrm{quantitative }| \textrm{ nominal } | \textrm{ ordinal } | \textrm{ temporal } | \textrm{ auto})\\
&\langle data\_model\rangle \rightarrow (\textrm{dimension }|\textrm{ measure }|\textrm{ auto})\\
\end{aligned}
\end{equation}
```
# user is interested in any ordinal attribute
wildcard = lux.Clause("?",data_type="temporal")
# user is interested in any measure attribute
wildcard = lux.Clause("?",data_model="measure")
```
#### Example: `Origin` with respect to other measure variables
```
origin = lux.Clause("Origin")
anyMeasure = lux.Clause("?",data_model="measure")
VisList([origin, anyMeasure],df)
```
## `Filter` specification
\begin{equation}
\langle Filter \rangle \rightarrow \langle attribute\rangle (=|>|<|\leq|\geq|\neq) \langle value\rangle\\
\end{equation}
\begin{equation}
\begin{split}
\langle value \rangle &\rightarrow \textrm{value} \\
&\rightarrow \textrm{value} \cup \langle value \rangle\\
&\rightarrow (\textrm{?})
\end{split}
\end{equation}
```
# user is interested in only Ford cars
value = "ford"
filterSpec = lux.Clause(attribute="Brand", filter_op="=",value=value)
# user is interested in cars that are either Ford, Chevrolet, or Toyota
value = ["ford","chevrolet","toyota"]
filterSpec = lux.Clause(attribute="Brand", filter_op="=",value=value)
# user is interested in cars that are of any Brand
value = "?"
filterSpec = lux.Clause(attribute="Brand", filter_op="=",value=value)
```
#### Example: Distribution of `Horsepower` for different Brands
```
horsepower = lux.Clause("Horsepower")
anyBrand = lux.Clause(attribute="Brand", filter_op="=",value="?")
VisList([horsepower, anyBrand],df)
```
| github_jupyter |
# Representing Qubit States
You now know something about bits, and about how our familiar digital computers work. All the complex variables, objects and data structures used in modern software are basically all just big piles of bits. Those of us who work on quantum computing call these *classical variables.* The computers that use them, like the one you are using to read this article, we call *classical computers*.
In quantum computers, our basic variable is the _qubit:_ a quantum variant of the bit. These have exactly the same restrictions as normal bits do: they can store only a single binary piece of information, and can only ever give us an output of `0` or `1`. However, they can also be manipulated in ways that can only be described by quantum mechanics. This gives us new gates to play with, allowing us to find new ways to design algorithms.
To fully understand these new gates, we first need understand how to write down qubit states. For this we will use the mathematics of vectors, matrices and complex numbers. Though we will introduce these concepts as we go, it would be best if you are comfortable with them already. If you need a more in-depth explanation or refresher, you can find a guide [here](../ch-prerequisites/linear_algebra.html).
## Contents
1. [Classical vs Quantum Bits](#cvsq)
1.1 [Statevectors](#statevectors)
1.2 [Qubit Notation](#notation)
1.3 [Exploring Qubits with Qiskit](#exploring-qubits)
2. [The Rules of Measurement](#rules-measurement)
2.1 [A Very Important Rule](#important-rule)
2.2 [The Implications of this Rule](#implications)
3. [The Bloch Sphere](#bloch-sphere)
3.1 [Describing the Restricted Qubit State](#bloch-sphere-1)
3.2 [Visually Representing a Qubit State](#bloch-sphere-2)
## 1. Classical vs Quantum Bits <a id="cvsq"></a>
### 1.1 Statevectors<a id="statevectors"></a>
In quantum physics we use _statevectors_ to describe the state of our system. Say we wanted to describe the position of a car along a track, this is a classical system so we could use a number $x$:

$$ x=4 $$
Alternatively, we could instead use a collection of numbers in a vector called a _statevector._ Each element in the statevector contains the probability of finding the car in a certain place:

$$
|x\rangle = \begin{bmatrix} 0\\ \vdots \\ 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}
\begin{matrix} \\ \\ \\ \leftarrow \\ \\ \\ \\ \end{matrix}
\begin{matrix} \\ \\ \text{Probability of} \\ \text{car being at} \\ \text{position 4} \\ \\ \\ \end{matrix}
$$
This isn’t limited to position, we could also keep a statevector of all the possible speeds the car could have, and all the possible colours the car could be. With classical systems (like the car example above), this is a silly thing to do as it requires keeping huge vectors when we only really need one number. But as we will see in this chapter, statevectors happen to be a very good way of keeping track of quantum systems, including quantum computers.
### 1.2 Qubit Notation <a id="notation"></a>
Classical bits always have a completely well-defined state: they are either `0` or `1` at every point during a computation. There is no more detail we can add to the state of a bit than this. So to write down the state of a of classical bit (`c`), we can just use these two binary values. For example:
c = 0
This restriction is lifted for quantum bits. Whether we get a `0` or a `1` from a qubit only needs to be well-defined when a measurement is made to extract an output. At that point, it must commit to one of these two options. At all other times, its state will be something more complex than can be captured by a simple binary value.
To see how to describe these, we can first focus on the two simplest cases. As we saw in the last section, it is possible to prepare a qubit in a state for which it definitely gives the outcome `0` when measured.
We need a name for this state. Let's be unimaginative and call it $0$ . Similarly, there exists a qubit state that is certain to output a `1`. We'll call this $1$. These two states are completely mutually exclusive. Either the qubit definitely outputs a ```0```, or it definitely outputs a ```1```. There is no overlap. One way to represent this with mathematics is to use two orthogonal vectors.
$$
|0\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix} \, \, \, \, |1\rangle =\begin{bmatrix} 0 \\ 1 \end{bmatrix}.
$$
This is a lot of notation to take in all at once. First, let's unpack the weird $|$ and $\rangle$. Their job is essentially just to remind us that we are talking about the vectors that represent qubit states labelled $0$ and $1$. This helps us distinguish them from things like the bit values ```0``` and ```1``` or the numbers 0 and 1. It is part of the bra-ket notation, introduced by Dirac.
If you are not familiar with vectors, you can essentially just think of them as lists of numbers which we manipulate using certain rules. If you are familiar with vectors from your high school physics classes, you'll know that these rules make vectors well-suited for describing quantities with a magnitude and a direction. For example, the velocity of an object is described perfectly with a vector. However, the way we use vectors for quantum states is slightly different to this, so don't hold on too hard to your previous intuition. It's time to do something new!
With vectors we can describe more complex states than just $|0\rangle$ and $|1\rangle$. For example, consider the vector
$$
|q_0\rangle = \begin{bmatrix} \tfrac{1}{\sqrt{2}} \\ \tfrac{i}{\sqrt{2}} \end{bmatrix} .
$$
To understand what this state means, we'll need to use the mathematical rules for manipulating vectors. Specifically, we'll need to understand how to add vectors together and how to multiply them by scalars.
<p>
<details>
<summary>Reminder: Matrix Addition and Multiplication by Scalars (Click here to expand)</summary>
<p>To add two vectors, we add their elements together:
$$|a\rangle = \begin{bmatrix}a_0 \\ a_1 \\ \vdots \\ a_n \end{bmatrix}, \quad
|b\rangle = \begin{bmatrix}b_0 \\ b_1 \\ \vdots \\ b_n \end{bmatrix}$$
$$|a\rangle + |b\rangle = \begin{bmatrix}a_0 + b_0 \\ a_1 + b_1 \\ \vdots \\ a_n + b_n \end{bmatrix} $$
</p>
<p>And to multiply a vector by a scalar, we multiply each element by the scalar:
$$x|a\rangle = \begin{bmatrix}x \times a_0 \\ x \times a_1 \\ \vdots \\ x \times a_n \end{bmatrix}$$
</p>
<p>These two rules are used to rewrite the vector $|q_0\rangle$ (as shown above):
$$
\begin{aligned}
|q_0\rangle & = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle \\
& = \tfrac{1}{\sqrt{2}}\begin{bmatrix}1\\0\end{bmatrix} + \tfrac{i}{\sqrt{2}}\begin{bmatrix}0\\1\end{bmatrix}\\
& = \begin{bmatrix}\tfrac{1}{\sqrt{2}}\\0\end{bmatrix} + \begin{bmatrix}0\\\tfrac{i}{\sqrt{2}}\end{bmatrix}\\
& = \begin{bmatrix}\tfrac{1}{\sqrt{2}} \\ \tfrac{i}{\sqrt{2}} \end{bmatrix}\\
\end{aligned}
$$
</details>
</p>
<p>
<details>
<summary>Reminder: Orthonormal Bases (Click here to expand)</summary>
<p>
It was stated before that the two vectors $|0\rangle$ and $|1\rangle$ are orthonormal, this means they are both <i>orthogonal</i> and <i>normalised</i>. Orthogonal means the vectors are at right angles:
</p><p><img src="images/basis.svg"></p>
<p>And normalised means their magnitudes (length of the arrow) is equal to 1. The two vectors $|0\rangle$ and $|1\rangle$ are <i>linearly independent</i>, which means we cannot describe $|0\rangle$ in terms of $|1\rangle$, and vice versa. However, using both the vectors $|0\rangle$ and $|1\rangle$, and our rules of addition and multiplication by scalars, we can describe all possible vectors in 2D space:
</p><p><img src="images/basis2.svg"></p>
<p>Because the vectors $|0\rangle$ and $|1\rangle$ are linearly independent, and can be used to describe any vector in 2D space using vector addition and scalar multiplication, we say the vectors $|0\rangle$ and $|1\rangle$ form a <i>basis</i>. In this case, since they are both orthogonal and normalised, we call it an <i>orthonormal basis</i>.
</details>
</p>
Since the states $|0\rangle$ and $|1\rangle$ form an orthonormal basis, we can represent any 2D vector with a combination of these two states. This allows us to write the state of our qubit in the alternative form:
$$ |q_0\rangle = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle $$
This vector, $|q_0\rangle$ is called the qubit's _statevector,_ it tells us everything we could possibly know about this qubit. For now, we are only able to draw a few simple conclusions about this particular example of a statevector: it is not entirely $|0\rangle$ and not entirely $|1\rangle$. Instead, it is described by a linear combination of the two. In quantum mechanics, we typically describe linear combinations such as this using the word 'superposition'.
Though our example state $|q_0\rangle$ can be expressed as a superposition of $|0\rangle$ and $|1\rangle$, it is no less a definite and well-defined qubit state than they are. To see this, we can begin to explore how a qubit can be manipulated.
### 1.3 Exploring Qubits with Qiskit <a id="exploring-qubits"></a>
First, we need to import all the tools we will need:
```
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
```
In Qiskit, we use the `QuantumCircuit` object to store our circuits, this is essentially a list of the quantum gates in our circuit and the qubits they are applied to.
```
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
```
In our quantum circuits, our qubits always start out in the state $|0\rangle$. We can use the `initialize()` method to transform this into any state. We give `initialize()` the vector we want in the form of a list, and tell it which qubit(s) we want to initialise in this state:
```
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
qc.draw() # Let's view our circuit
```
We can then use one of Qiskit’s simulators to view the resulting state of our qubit. To begin with we will use the statevector simulator, but we will explain the different simulators and their uses later.
```
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
```
To get the results from our circuit, we use `execute` to run our circuit, giving the circuit and the backend as arguments. We then use `.result()` to get the result of this:
```
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
result = execute(qc,backend).result() # Do the simulation, returning the result
```
from `result`, we can then get the final statevector using `.get_statevector()`:
```
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
result = execute(qc,backend).result() # Do the simulation, returning the result
out_state = result.get_statevector()
print(out_state) # Display the output state vector
```
**Note:** Python uses `j` to represent $i$ in complex numbers. We see a vector with two complex elements: `0.+0.j` = 0, and `1.+0.j` = 1.
Let’s now measure our qubit as we would in a real quantum computer and see the result:
```
qc.measure_all()
qc.draw()
```
This time, instead of the statevector we will get the counts for the `0` and `1` results using `.get_counts()`:
```
result = execute(qc,backend).result()
counts = result.get_counts()
plot_histogram(counts)
```
We can see that we (unsurprisingly) have a 100% chance of measuring $|1\rangle$. This time, let’s instead put our qubit into a superposition and see what happens. We will use the state $|q_0\rangle$ from earlier in this section:
$$ |q_0\rangle = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle $$
We need to add these amplitudes to a python list. To add a complex amplitude we use `complex`, giving the real and imaginary parts as arguments:
```
initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q>
```
And we then repeat the steps for initialising the qubit as before:
```
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0) # Initialise the 0th qubit in the state `initial_state`
state = execute(qc,backend).result().get_statevector() # Execute the circuit
print(state) # Print the result
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
```
We can see we have equal probability of measuring either $|0\rangle$ or $|1\rangle$. To explain this, we need to talk about measurement.
## 2. The Rules of Measurement <a id="rules-measurement"></a>
### 2.1 A Very Important Rule <a id="important-rule"></a>
There is a simple rule for measurement. To find the probability of measuring a state $|\psi \rangle$ in the state $|x\rangle$ we do:
$$p(|x\rangle) = | \langle \psi| x \rangle|^2$$
The symbols $\langle$ and $|$ tell us $\langle \psi |$ is a row vector. In quantum mechanics we call the column vectors _kets_ and the row vectors _bras._ Together they make up _bra-ket_ notation. Any ket $|a\rangle$ has a corresponding bra $\langle a|$, and we convert between them using the conjugate transpose.
<details>
<summary>Reminder: The Inner Product (Click here to expand)</summary>
<p>There are different ways to multiply vectors, here we use the <i>inner product</i>. The inner product is a generalisation of the <i>dot product</i> which you may already be familiar with. In this guide, we use the inner product between a bra (row vector) and a ket (column vector), and it follows this rule:
$$\langle a| = \begin{bmatrix}a_0^*, & a_1^*, & \dots & a_n^* \end{bmatrix}, \quad
|b\rangle = \begin{bmatrix}b_0 \\ b_1 \\ \vdots \\ b_n \end{bmatrix}$$
$$\langle a|b\rangle = a_0^* b_0 + a_1^* b_1 \dots a_n^* b_n$$
</p>
<p>We can see that the inner product of two vectors always gives us a scalar. A useful thing to remember is that the inner product of two orthogonal vectors is 0, for example if we have the orthogonal vectors $|0\rangle$ and $|1\rangle$:
$$\langle1|0\rangle = \begin{bmatrix} 0 , & 1\end{bmatrix}\begin{bmatrix}1 \\ 0\end{bmatrix} = 0$$
</p>
<p>Additionally, remember that the vectors $|0\rangle$ and $|1\rangle$ are also normalised (magnitudes are equal to 1):
$$
\begin{aligned}
\langle0|0\rangle & = \begin{bmatrix} 1 , & 0\end{bmatrix}\begin{bmatrix}1 \\ 0\end{bmatrix} = 1 \\
\langle1|1\rangle & = \begin{bmatrix} 0 , & 1\end{bmatrix}\begin{bmatrix}0 \\ 1\end{bmatrix} = 1
\end{aligned}
$$
</p>
</details>
In the equation above, $|x\rangle$ can be any qubit state. To find the probability of measuring $|x\rangle$, we take the inner product of $|x\rangle$ and the state we are measuring (in this case $|\psi\rangle$), then square the magnitude. This may seem a little convoluted, but it will soon become second nature.
If we look at the state $|q_0\rangle$ from before, we can see the probability of measuring $|0\rangle$ is indeed $0.5$:
$$
\begin{aligned}
|q_0\rangle & = \tfrac{1}{\sqrt{2}}|0\rangle + \tfrac{i}{\sqrt{2}}|1\rangle \\
\langle q_0| & = \tfrac{1}{\sqrt{2}}\langle0| - \tfrac{i}{\sqrt{2}}\langle 1| \\
\langle q_0| 0 \rangle & = \tfrac{1}{\sqrt{2}}\langle 0|0\rangle - \tfrac{i}{\sqrt{2}}\langle 1|0\rangle \\
\langle q_0| 0 \rangle & = \tfrac{1}{\sqrt{2}}\cdot 1 - \tfrac{i}{\sqrt{2}} \cdot 0\\
\langle q_0| 0 \rangle & = \tfrac{1}{\sqrt{2}}\\
|\langle q_0| 0 \rangle|^2 & = \tfrac{1}{2}
\end{aligned}
$$
You should verify the probability of measuring $|1\rangle$ as an exercise.
This rule governs how we get information out of quantum states. It is therefore very important for everything we do in quantum computation. It also immediately implies several important facts.
### 2.2 The Implications of this Rule <a id="implications"></a>
### #1 Normalisation
The rule shows us that amplitudes are related to probabilities. If we want the probabilities to add up to 1 (which they should!), we need to ensure that the statevector is properly normalized. Specifically, we need the magnitude of the state vector to be 1.
$$ \langle\psi|\psi\rangle = 1 \\ $$
Thus if:
$$ |\psi\rangle = \alpha|0\rangle + \beta|1\rangle $$
Then:
$$ \sqrt{|\alpha|^2 + |\beta|^2} = 1 $$
This explains the factors of $\sqrt{2}$ you have seen throughout this chapter. In fact, if we try to give `initialize()` a vector that isn’t normalised, it will give us an error:
```
vector = [1,1]
qc.initialize(vector, 0)
```
#### Quick Exercise
1. Create a state vector that will give a $1/3$ probability of measuring $|0\rangle$.
2. Create a different state vector that will give the same measurement probabilities.
3. Verify that the probability of measuring $|1\rangle$ for these two states is $2/3$.
You can check your answer in the widget below (you can use 'pi' and 'sqrt' in the vector):
```
# Run the code in this cell to interact with the widget
from qiskit_textbook.widgets import state_vector_exercise
state_vector_exercise(target=1/3)
```
### #2 Alternative measurement
The measurement rule gives us the probability $p(|x\rangle)$ that a state $|\psi\rangle$ is measured as $|x\rangle$. Nowhere does it tell us that $|x\rangle$ can only be either $|0\rangle$ or $|1\rangle$.
The measurements we have considered so far are in fact only one of an infinite number of possible ways to measure a qubit. For any orthogonal pair of states, we can define a measurement that would cause a qubit to choose between the two.
This possibility will be explored more in the next section. For now, just bear in mind that $|x\rangle$ is not limited to being simply $|0\rangle$ or $|1\rangle$.
### #3 Global Phase
We know that measuring the state $|1\rangle$ will give us the output `1` with certainty. But we are also able to write down states such as
$$\begin{bmatrix}0 \\ i\end{bmatrix} = i|1\rangle.$$
To see how this behaves, we apply the measurement rule.
$$ |\langle x| (i|1\rangle) |^2 = | i \langle x|1\rangle|^2 = |\langle x|1\rangle|^2 $$
Here we find that the factor of $i$ disappears once we take the magnitude of the complex number. This effect is completely independent of the measured state $|x\rangle$. It does not matter what measurement we are considering, the probabilities for the state $i|1\rangle$ are identical to those for $|1\rangle$. Since measurements are the only way we can extract any information from a qubit, this implies that these two states are equivalent in all ways that are physically relevant.
More generally, we refer to any overall factor $\gamma$ on a state for which $|\gamma|=1$ as a 'global phase'. States that differ only by a global phase are physically indistinguishable.
$$ |\langle x| ( \gamma |a\rangle) |^2 = | \gamma \langle x|a\rangle|^2 = |\langle x|a\rangle|^2 $$
Note that this is distinct from the phase difference _between_ terms in a superposition, which is known as the 'relative phase'. This becomes relevant once we consider different types of measurement and multiple qubits.
### #4 The Observer Effect
We know that the amplitudes contain information about the probability of us finding the qubit in a specific state, but once we have measured the qubit, we know with certainty what the state of the qubit is. For example, if we measure a qubit in the state:
$$ |q\rangle = \alpha|0\rangle + \beta|1\rangle$$
And find it in the state $|0\rangle$, if we measure again, there is a 100% chance of finding the qubit in the state $|0\rangle$. This means the act of measuring _changes_ the state of our qubits.
$$ |q\rangle = \begin{bmatrix} \alpha \\ \beta \end{bmatrix} \xrightarrow{\text{Measure }|0\rangle} |q\rangle = |0\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$$
We sometimes refer to this as _collapsing_ the state of the qubit. It is a potent effect, and so one that must be used wisely. For example, were we to constantly measure each of our qubits to keep track of their value at each point in a computation, they would always simply be in a well-defined state of either $|0\rangle$ or $|1\rangle$. As such, they would be no different from classical bits and our computation could be easily replaced by a classical computation. To acheive truly quantum computation we must allow the qubits to explore more complex states. Measurements are therefore only used when we need to extract an output. This means that we often place the all measurements at the end of our quantum circuit.
We can demonstrate this using Qiskit’s statevector simulator. Let's initialise a qubit in superposition:
```
qc = QuantumCircuit(1) # Redefine qc
initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j]
qc.initialize(initial_state, 0)
qc.draw()
```
This should initialise our qubit in the state:
$$ |q\rangle = \tfrac{i}{\sqrt{2}}|0\rangle + \tfrac{1}{\sqrt{2}}|1\rangle $$
We can verify this using the simulator:
```
state = execute(qc, backend).result().get_statevector()
print("Qubit State = " + str(state))
```
We can see here the qubit is initialised in the state `[0.+0.70710678j 0.70710678+0.j]`, which is the state we expected.
Let’s now measure this qubit:
```
qc.measure_all()
qc.draw()
```
When we simulate this entire circuit, we can see that one of the amplitudes is _always_ 0:
```
state = execute(qc, backend).result().get_statevector()
print("State of Measured Qubit = " + str(state))
```
You can re-run this cell a few times to reinitialise the qubit and measure it again. You will notice that either outcome is equally probable, but that the state of the qubit is never a superposition of $|0\rangle$ and $|1\rangle$. Somewhat interestingly, the global phase on the state $|0\rangle$ survives, but since this is global phase, we can never measure it on a real quantum computer.
### A Note about Quantum Simulators
We can see that writing down a qubit’s state requires keeping track of two complex numbers, but when using a real quantum computer we will only ever receive a yes-or-no (`0` or `1`) answer for each qubit. The output of a 10-qubit quantum computer will look like this:
`0110111110`
Just 10 bits, no superposition or complex amplitudes. When using a real quantum computer, we cannot see the states of our qubits mid-computation, as this would destroy them! This behaviour is not ideal for learning, so Qiskit provides different quantum simulators: The `qasm_simulator` behaves as if you are interacting with a real quantum computer, and will not allow you to use `.get_statevector()`. Alternatively, `statevector_simulator`, (which we have been using in this chapter) does allow peeking at the quantum states before measurement, as we have seen.
## 3. The Bloch Sphere <a id="bloch-sphere"></a>
### 3.1 Describing the Restricted Qubit State <a id="bloch-sphere-1"></a>
We saw earlier in this chapter that the general state of a qubit ($|q\rangle$) is:
$$
|q\rangle = \alpha|0\rangle + \beta|1\rangle
$$
$$
\alpha, \beta \in \mathbb{C}
$$
(The second line tells us $\alpha$ and $\beta$ are complex numbers). The first two implications in section 2 tell us that we cannot differentiate between some of these states. This means we can be more specific in our description of the qubit.
Firstly, since we cannot measure global phase, we can only measure the difference in phase between the states $|0\rangle$ and $|1\rangle$. Instead of having $\alpha$ and $\beta$ be complex, we can confine them to the real numbers and add a term to tell us the relative phase between them:
$$
|q\rangle = \alpha|0\rangle + e^{i\phi}\beta|1\rangle
$$
$$
\alpha, \beta, \phi \in \mathbb{R}
$$
Finally, since the qubit state must be normalised, i.e.
$$
\sqrt{\alpha^2 + \beta^2} = 1
$$
we can use the trigonometric identity:
$$
\sqrt{\sin^2{x} + \cos^2{x}} = 1
$$
to describe the real $\alpha$ and $\beta$ in terms of one variable, $\theta$:
$$
\alpha = \cos{\tfrac{\theta}{2}}, \quad \beta=\sin{\tfrac{\theta}{2}}
$$
From this we can describe the state of any qubit using the two variables $\phi$ and $\theta$:
$$
|q\rangle = \cos{\tfrac{\theta}{2}}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle
$$
$$
\theta, \phi \in \mathbb{R}
$$
### 3.2 Visually Representing a Qubit State <a id="bloch-sphere-2"></a>
We want to plot our general qubit state:
$$
|q\rangle = \cos{\tfrac{\theta}{2}}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle
$$
If we interpret $\theta$ and $\phi$ as spherical co-ordinates ($r = 1$, since the magnitude of the qubit state is $1$), we can plot any qubit state on the surface of a sphere, known as the _Bloch sphere._
Below we have plotted a qubit in the state $|{+}\rangle$. In this case, $\theta = \pi/2$ and $\phi = 0$.
(Qiskit has a function to plot a bloch sphere, `plot_bloch_vector()`, but at the time of writing it only takes cartesian coordinates. We have included a function that does the conversion automatically).
```
from qiskit_textbook.widgets import plot_bloch_vector_spherical
coords = [pi/2,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
```
#### Warning!
When first learning about qubit states, it's easy to confuse the qubits _statevector_ with its _Bloch vector_. Remember the statevector is the vector disucssed in [1.1](#notation), that holds the amplitudes for the two states our qubit can be in. The Bloch vector is a visualisation tool that maps the 2D, complex statevector onto real, 3D space.
#### Quick Exercise
Use `plot_bloch_vector()` or `plot_bloch_sphere_spherical()` to plot a qubit in the states:
1. $|0\rangle$
2. $|1\rangle$
3. $\tfrac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$
4. $\tfrac{1}{\sqrt{2}}(|0\rangle - i|1\rangle)$
5. $\tfrac{1}{\sqrt{2}}\begin{bmatrix}i\\1\end{bmatrix}$
We have also included below a widget that converts from spherical co-ordinates to cartesian, for use with `plot_bloch_vector()`:
```
from qiskit_textbook.widgets import bloch_calc
bloch_calc()
import qiskit
qiskit.__qiskit_version__
```
| github_jupyter |
> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.
# 5.4. Accelerating Python code with Cython
We use Cython to accelerate the generation of the Mandelbrot fractal.
```
import numpy as np
```
We initialize the simulation and generate the grid
in the complex plane.
```
size = 200
iterations = 100
```
## Pure Python
```
def mandelbrot_python(m, size, iterations):
for i in range(size):
for j in range(size):
c = -2 + 3./size*j + 1j*(1.5-3./size*i)
z = 0
for n in range(iterations):
if np.abs(z) <= 10:
z = z*z + c
m[i, j] = n
else:
break
%%timeit -n1 -r1 m = np.zeros((size, size))
mandelbrot_python(m, size, iterations)
```
## Cython versions
We first import Cython.
```
%load_ext cythonmagic
```
### Take 1
First, we just add the %%cython magic.
```
%%cython -a
import numpy as np
def mandelbrot_cython(m, size, iterations):
for i in range(size):
for j in range(size):
c = -2 + 3./size*j + 1j*(1.5-3./size*i)
z = 0
for n in range(iterations):
if np.abs(z) <= 10:
z = z*z + c
m[i, j] = n
else:
break
%%timeit -n1 -r1 m = np.zeros((size, size), dtype=np.int32)
mandelbrot_cython(m, size, iterations)
```
Virtually no speedup.
### Take 2
Now, we add type information, using memory views for NumPy arrays.
```
%%cython -a
import numpy as np
def mandelbrot_cython(int[:,::1] m,
int size,
int iterations):
cdef int i, j, n
cdef complex z, c
for i in range(size):
for j in range(size):
c = -2 + 3./size*j + 1j*(1.5-3./size*i)
z = 0
for n in range(iterations):
if z.real**2 + z.imag**2 <= 100:
z = z*z + c
m[i, j] = n
else:
break
%%timeit -n1 -r1 m = np.zeros((size, size), dtype=np.int32)
mandelbrot_cython(m, size, iterations)
```
Interesting speedup!
> You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
> [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).
| github_jupyter |
# <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 8</font>
## Download: http://github.com/dsacademybr
### Exercícios Sobre Módulos Python Para Análise de Dados
### ****** ATENÇÃO ******
### Alguns dos exercícios podem requerer pesquisa adicional na documentação dos pacotes. Pesquise!
### Exercício 1
```
# Crie um array NumPy com 1000000 e uma lista com 1000000.
# Multiplique cada elemento do array e da lista por 2 e calcule o tempo de execução com cada um dos objetos (use %time).
# Qual objeto oferece melhor performance, array NumPy ou lista?
import numpy as np
my_arr = np.arange(1000000)
my_list = list(range(1000000))
%time for _ in range(10): my_arr2 = my_arr * 2
%time for _ in range(10): my_list2 = [x * 2 for x in my_list]
```
### Exercício 2
```
# Exercício 2
# Crie um array de 10 elementos
# Altere o valores de todos os elementos dos índices 5 a 8 para 0
import numpy as np
arr = np.arange(10)
arr
arr[5:8] = 0
arr
```
### Exercício 3
```
# Crie um array de 3 dimensões e imprima a dimensão 1
import numpy as np
arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
arr3d
arr3d[0]
```
### Exercício 4
```
# Crie um array de duas dimensões (matriz).
# Imprima os elementos da terceira linha da matriz
# Imprima todos os elementos da primeira e segunda linhas e segunda e terceira colunas
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr2d
# Imprima os elementos da terceira linha da matriz
arr2d[2]
# Imprima todos os elementos da primeira e segunda linhas e segunda e terceira colunas
arr2d[:2, 1:]
```
### Exercício 5
```
# Calcule a transposta da matriz abaixo
arr = np.arange(15).reshape((3, 5))
arr
arr.T
```
### Exercício 6
```
# Considere os 3 arrays abaixo
# Retorne o valor do array xarr se o valor for True no array cond. Caso contrário, retorne o valor do array yarr.
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])
for x, y, c in zip(xarr, yarr, cond):
print(x, y, c)
resultado = [(x if c else y) for x, y, c in zip(xarr, yarr, cond)]
resultado
```
### Exercício 7
```
# Crie um array A com 10 elementos e salve o array em disco com a extensão npy
# Depois carregue o array do disco no array B
A = np.arange(10)
print(A)
np.save('array_a', A)
B = np.load('array_a.npy')
print(B)
```
### Exercício 8
```
# Considerando a série abaixo, imprima os valores únicos na série
import pandas as pd
obj = pd.Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c', 'a', 'b'])
uniques = obj.unique()
uniques
```
### Exercício 9
```
# Considerando o trecho de código que conecta em uma url na internet, imprima o dataframe conforme abaixo.
import requests
url = 'https://api.github.com/repos/pandas-dev/pandas/issues'
resp = requests.get(url)
resp
data = resp.json()
data[0]['title']
issues = pd.DataFrame(data, columns=['number', 'title', 'labels', 'state'])
issues
```
### Exercício 10
```
# Crie um banco de dados no SQLite, crie uma tabela, insira registros,
# consulte a tabela e retorne os dados em dataframe do Pandas
import sqlite3
import pandas as pd
query = """
CREATE TABLE TESTE
(Cidade VARCHAR(20),
Estado VARCHAR(20),
taxa REAL,
Impostos INTEGER
);"""
con = sqlite3.connect('dsa.db')
con.execute(query)
con.commit()
data = [('Natal', 'Rio Grande do Norte', 1.25, 6),
('Recife', 'Pernambuco', 2.6, 3),
('Londrina', 'Paraná', 1.7, 5)]
stmt = "INSERT INTO TESTE VALUES(?, ?, ?, ?)"
con.executemany(stmt, data)
con.commit()
cursor = con.execute('select * from teste')
rows = cursor.fetchall()
rows
cursor.description
pd.DataFrame(rows, columns=[x[0] for x in cursor.description])
```
# Fim
### Obrigado - Data Science Academy - <a href="http://facebook.com/dsacademybr">facebook.com/dsacademybr</a>
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
```
# Text classification of movie reviews with Keras and TensorFlow Hub
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/beta/tutorials/keras/basic_text_classification_with_tfhub"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/keras/basic_text_classification_with_tfhub.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/keras/basic_text_classification_with_tfhub.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/r2/tutorials/keras/basic_text_classification_with_tfhub.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
This notebook classifies movie reviews as *positive* or *negative* using the text of the review. This is an example of *binary*—or two-class—classification, an important and widely applicable kind of machine learning problem.
The tutorial demonstrates the basic application of transfer learning with TensorFlow Hub and Keras.
We'll use the [IMDB dataset](https://www.tensorflow.org/api_docs/python/tf/keras/datasets/imdb) that contains the text of 50,000 movie reviews from the [Internet Movie Database](https://www.imdb.com/). These are split into 25,000 reviews for training and 25,000 reviews for testing. The training and testing sets are *balanced*, meaning they contain an equal number of positive and negative reviews.
This notebook uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow, and [TensorFlow Hub](https://www.tensorflow.org/hub), a library and platform for transfer learning. For a more advanced text classification tutorial using `tf.keras`, see the [MLCC Text Classification Guide](https://developers.google.com/machine-learning/guides/text-classification/).
```
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
!pip install tensorflow==2.0.0-beta1
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.test.is_gpu_available() else "NOT AVAILABLE")
```
## Download the IMDB dataset
The IMDB dataset is available on [imdb reviews](https://github.com/tensorflow/datasets/blob/master/docs/datasets.md#imdb_reviews) or on [TensorFlow datasets](https://github.com/tensorflow/datasets). The following code downloads the IMDB dataset to your machine (or the colab runtime):
```
# Split the training set into 60% and 40%, so we'll end up with 15,000 examples
# for training, 10,000 examples for validation and 25,000 examples for testing.
train_validation_split = tfds.Split.TRAIN.subsplit([6, 4])
(train_data, validation_data), test_data = tfds.load(
name="imdb_reviews",
split=(train_validation_split, tfds.Split.TEST),
as_supervised=True)
```
## Explore the data
Let's take a moment to understand the format of the data. Each example is a sentence representing the movie review and a corresponding label. The sentence is not preprocessed in any way. The label is an integer value of either 0 or 1, where 0 is a negative review, and 1 is a positive review.
Let's print first 10 examples.
```
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
train_examples_batch
```
Let's also print the first 10 labels.
```
train_labels_batch
```
## Build the model
The neural network is created by stacking layers—this requires three main architectural decisions:
* How to represent the text?
* How many layers to use in the model?
* How many *hidden units* to use for each layer?
In this example, the input data consists of sentences. The labels to predict are either 0 or 1.
One way to represent the text is to convert sentences into embeddings vectors. We can use a pre-trained text embedding as the first layer, which will have three advantages:
* we don't have to worry about text preprocessing,
* we can benefit from transfer learning,
* the embedding has a fixed size, so it's simpler to process.
For this example we will use a **pre-trained text embedding model** from [TensorFlow Hub](https://www.tensorflow.org/hub) called [google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1).
There are three other pre-trained models to test for the sake of this tutorial:
* [google/tf2-preview/gnews-swivel-20dim-with-oov/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim-with-oov/1) - same as [google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1), but with 2.5% vocabulary converted to OOV buckets. This can help if vocabulary of the task and vocabulary of the model don't fully overlap.
* [google/tf2-preview/nnlm-en-dim50/1](https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1) - A much larger model with ~1M vocabulary size and 50 dimensions.
* [google/tf2-preview/nnlm-en-dim128/1](https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1) - Even larger model with ~1M vocabulary size and 128 dimensions.
Let's first create a Keras layer that uses a TensorFlow Hub model to embed the sentences, and try it out on a couple of input examples. Note that no matter the length of the input text, the output shape of the embeddings is: `(num_examples, embedding_dimension)`.
```
embedding = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])
```
Let's now build the full model:
```
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()
```
The layers are stacked sequentially to build the classifier:
1. The first layer is a TensorFlow Hub layer. This layer uses a pre-trained Saved Model to map a sentence into its embedding vector. The pre-trained text embedding model that we are using ([google/tf2-preview/gnews-swivel-20dim/1](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1)) splits the sentence into tokens, embeds each token and then combines the embedding. The resulting dimensions are: `(num_examples, embedding_dimension)`.
2. This fixed-length output vector is piped through a fully-connected (`Dense`) layer with 16 hidden units.
3. The last layer is densely connected with a single output node. Using the `sigmoid` activation function, this value is a float between 0 and 1, representing a probability, or confidence level.
Let's compile the model.
### Loss function and optimizer
A model needs a loss function and an optimizer for training. Since this is a binary classification problem and the model outputs a probability (a single-unit layer with a sigmoid activation), we'll use the `binary_crossentropy` loss function.
This isn't the only choice for a loss function, you could, for instance, choose `mean_squared_error`. But, generally, `binary_crossentropy` is better for dealing with probabilities—it measures the "distance" between probability distributions, or in our case, between the ground-truth distribution and the predictions.
Later, when we are exploring regression problems (say, to predict the price of a house), we will see how to use another loss function called mean squared error.
Now, configure the model to use an optimizer and a loss function:
```
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
```
## Train the model
Train the model for 20 epochs in mini-batches of 512 samples. This is 20 iterations over all samples in the `x_train` and `y_train` tensors. While training, monitor the model's loss and accuracy on the 10,000 samples from the validation set:
```
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=20,
validation_data=validation_data.batch(512),
verbose=1)
```
## Evaluate the model
And let's see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy.
```
results = model.evaluate(test_data.batch(512), verbose=0)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
```
This fairly naive approach achieves an accuracy of about 87%. With more advanced approaches, the model should get closer to 95%.
## Further reading
For a more general way to work with string inputs and for a more detailed analysis of the progress of accuracy and loss during training, take a look [here](https://www.tensorflow.org/tutorials/keras/basic_text_classification).
| github_jupyter |
# Introduction
With all that you've learned, your SQL queries are getting pretty long, which can make them hard understand (and debug).
You are about to learn how to use **AS** and **WITH** to tidy up your queries and make them easier to read.
Along the way, we'll use the familiar `pets` table, but now it includes the ages of the animals.

# AS
You learned in an earlier tutorial how to use **AS** to rename the columns generated by your queries, which is also known as **aliasing**. This is similar to how Python uses `as` for aliasing when doing imports like `import pandas as pd` or `import seaborn as sns`.
To use **AS** in SQL, insert it right after the column you select. Here's an example of a query _without_ an **AS** clause:

And here's an example of the same query, but _with_ **AS**.

These queries return the same information, but in the second query the column returned by the **COUNT()** function will be called `Number`, rather than the default name of `f0__`.
# WITH ... AS
On its own, **AS** is a convenient way to clean up the data returned by your query. It's even more powerful when combined with **WITH** in what's called a "common table expression".
A **common table expression** (or **CTE**) is a temporary table that you return within your query. CTEs are helpful for splitting your queries into readable chunks, and you can write queries against them.
For instance, you might want to use the `pets` table to ask questions about older animals in particular. So you can start by creating a CTE which only contains information about animals more than five years old like this:

While this incomplete query above won't return anything, it creates a CTE that we can then refer to (as `Seniors`) while writing the rest of the query.
We can finish the query by pulling the information that we want from the CTE. The complete query below first creates the CTE, and then returns all of the IDs from it.

You could do this without a CTE, but if this were the first part of a very long query, removing the CTE would make it much harder to follow.
Also, it's important to note that CTEs only exist inside the query where you create them, and you can't reference them in later queries. So, any query that uses a CTE is always broken into two parts: (1) first, we create the CTE, and then (2) we write a query that uses the CTE.
# Example: How many Bitcoin transactions are made per month?
We're going to use a CTE to find out how many Bitcoin transactions were made each day for the entire timespan of a bitcoin transaction dataset.
We'll investigate the `transactions` table. Here is a view of the first few rows. (_The corresponding code is hidden, but you can un-hide it by clicking on the "Code" button below._)
```
#$HIDE_INPUT$
from google.cloud import bigquery
# Create a "Client" object
client = bigquery.Client()
# Construct a reference to the "crypto_bitcoin" dataset
dataset_ref = client.dataset("crypto_bitcoin", project="bigquery-public-data")
# API request - fetch the dataset
dataset = client.get_dataset(dataset_ref)
# Construct a reference to the "transactions" table
table_ref = dataset_ref.table("transactions")
# API request - fetch the table
table = client.get_table(table_ref)
# Preview the first five lines of the "transactions" table
client.list_rows(table, max_results=5).to_dataframe()
```
Since the `block_timestamp` column contains the date of each transaction in DATETIME format, we'll convert these into DATE format using the **DATE()** command.
We do that using a CTE, and then the next part of the query counts the number of transactions for each date and sorts the table so that earlier dates appear first.
```
# Query to select the number of transactions per date, sorted by date
query_with_CTE = """
WITH time AS
(
SELECT DATE(block_timestamp) AS trans_date
FROM `bigquery-public-data.crypto_bitcoin.transactions`
)
SELECT COUNT(1) AS transactions,
trans_date
FROM time
GROUP BY trans_date
ORDER BY trans_date
"""
# Set up the query (cancel the query if it would use too much of
# your quota, with the limit set to 1 GB)
safe_config = bigquery.QueryJobConfig(maximum_bytes_billed=1e9)
query_job = client.query(query_with_CTE, job_config=safe_config)
# API request - run the query, and convert the results to a pandas DataFrame
transactions_by_date = query_job.to_dataframe()
# Print the first five rows
transactions_by_date.head()
```
Since they're returned sorted, we can easily plot the raw results to show us the number of Bitcoin transactions per day over the whole timespan of this dataset.
```
transactions_by_date.set_index('trans_date').plot()
```
As you can see, common table expressions (CTEs) let you shift a lot of your data cleaning into SQL. That's an especially good thing in the case of BigQuery, because it is vastly faster than doing the work in Pandas.
# Your turn
You now have the tools to stay organized even when writing more complex queries. Now **[use them here](#$NEXT_NOTEBOOK_URL$)**.
| github_jupyter |
# <font color="#0000cd">SSDの中身が意味プなのでがんばって解剖してみたい件</font>
***
## <font color="#4169e1">non maximum suppressionの実装</font>
1. Conjugate Contours : coords
座標をもとにバウンディングボックスを結合する
2. Conjugate Contours : areas
面積の重複が閾値を超えたら削除する
3. non maximum suppression : Python
Pythonでのnon maximum suppressionの実装
4. non maximum suppression : tensorflow
tensorflowで実装されているnon maximum suppression
## 1. Conjugate Contours : coords
```
import datetime
import cv2
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
contours = [
[782, 363, 53, 31], [752, 360, 58, 18], [800, 600, 100, 125], [779, 349, 20, 10],
[816, 294, 77, 52], [1042, 247, 139, 91], [1079, 171, 84, 132], [1141, 161, 67, 62],
[488, 126, 44, 43], [702, 121, 50, 48], [721, 108, 59, 64], [606, 90, 21, 31],
[896, 75, 1, 1], [897, 70, 1, 1], [590, 30, 24, 27], [616, 17, 94, 94], [349, 0, 666, 652]]
fig = plt.figure(figsize=(8,6))
plt.xlim(200, 1400)
plt.ylim(-100, 800)
ax = fig.add_subplot(111)
for i in contours:
rect = plt.Rectangle((i[0],i[1]),i[2],i[3], fill=False)
ax.add_patch(rect)
plt.show()
def draw_image(contours):
old=datetime.datetime.now()
fig = plt.figure(figsize=(8,6))
plt.xlim(200, 1400)
plt.ylim(-100, 800)
ax = fig.add_subplot(111)
for i in contours:
rect = plt.Rectangle((i[0],i[1]),i[2],i[3], fill=False)
ax.add_patch(rect)
for i in conjugate_contours(contours):
rect = plt.Rectangle((i[0],i[1]),i[2],i[3], fill=False, edgecolor='#ff0000')
#rect = plt.Rectangle((i[0],i[1]),i[2]-i[0],i[3]-i[1], fill=False, edgecolor='#ff0000')
ax.add_patch(rect)
print('-------------------------------------------------------')
print('・cost time : ',(datetime.datetime.now()-old))
print('-------------------------------------------------------')
return plt.show()
def conjugate_contours(contours):
# 固定座標のインデックス, 無限ループを終えるための変数を設定
index = 0
stop = 0
while (index < len(contours) and stop < 5):
# 比較座標は固定座標の右隣からスタート
step = 1
# 一周したらリセット(最後がFalseで終了)
if index + 1 == len(contours):
index = 0
stop += 1
while (index + step < len(contours)):
# 固定座標
xmin = contours[index][0]
ymin = contours[index][1]
xmax = contours[index][2] + xmin
ymax = contours[index][3] + ymin
# 比較座標
cxmin = contours[index + step][0]
cymin = contours[index + step][1]
cxmax = contours[index + step][2] + cxmin
cymax = contours[index + step][3] + cymin
# AがBを含む、もしくはAがBに含まれる場合
if (xmin <= cxmin <= xmax or xmin <= cxmax <= xmax or cxmin <= xmin <= cxmax or cxmin <= xmax <= cxmax)\
and (ymin <= cymin <= ymax or ymin <= cymax <= ymax or cymin <= ymin <= cymax or cymin <= ymax <= cymax):
# 統合された座標
nxmin = min(xmin, cxmin)
nymin = min(ymin, cymin)
nxmax = max(xmax, cxmax)
nymax = max(ymax, cymax)
# 固定座標を統合座標で更新
contours[index] = [nxmin, nymin, nxmax-nxmin, nymax-nymin]
# 比較座標を削除
contours.pop(index + step)
# 一周したらリセット(最後がTrueで終了)
if step == 1 and index + step == len(contours):
index = 0
step = 1
# どちらにも含まれない場合、比較座標を1つずらす
else:
step += 1
# 重なるboxがなくなったら固定座標を1つずらす
else:
index += 1
return contours
draw_image(contours)
```
## 2. Conjugate Contours : areas
```
def non_max_suppression_slow(boxes, overlapThresh):
# if there are no boxes, return an empty list
if len(boxes) == 0:
return []
# initialize the list of picked indexes
pick = []
# grab the coordinates of the bounding boxes
x1 = boxes[:,0] # xmin
y1 = boxes[:,1] # ymin
x2 = boxes[:,2] # xmax
y2 = boxes[:,3] # ymax
# compute the area of the bounding boxes and sort the bounding
# boxes by the bottom-right y-coordinate of the bounding box
area = (x2 - x1 + 1) * (y2 - y1 + 1)
idxs = np.argsort(y2) # ymaxの値を昇順, [0, 2, 1]
print('idxs', idxs)
# keep looping while some indexes still remain in the indexes
# list
while len(idxs) > 0:
# grab the last index in the indexes list, add the index
# value to the list of picked indexes, then initialize
# the suppression list (i.e. indexes that will be deleted)
# using the last index
last = len(idxs) - 1 # index of biggest ymax in sort boxes
i = idxs[last] # index of biggest ymax in boxes
pick.append(i) # pick = [1]
suppress = [last] # suppress = [2]
# loop over all indexes in the indexes list
for pos in range(0, last): # last = 2
# grab the current index
j = idxs[pos]
# find the largest (x, y) coordinates for the start of
# the bounding box and the smallest (x, y) coordinates
# for the end of the bounding box
xx1 = max(x1[i], x1[j])
yy1 = max(y1[i], y1[j])
xx2 = min(x2[i], x2[j])
yy2 = min(y2[i], y2[j])
# compute the width and height of the bounding box
w = max(0, xx2 - xx1 + 1) # 接触していなければ0
h = max(0, yy2 - yy1 + 1)
# compute the ratio of overlap between the computed
# bounding box and the bounding box in the area list
overlap = float(w * h) / area[j]
# if there is sufficient overlap, suppress the
# current bounding box
if overlap > overlapThresh:
suppress.append(pos)
# delete all indexes from the index list that are in the
# suppression list
idxs = np.delete(idxs, suppress)
# return only the bounding boxes that were picked
return boxes[pick]
images = [
("audrey.jpg", np.array([
(120, 10, 1120, 810),
(240, 100, 1390, 1100),
(300, 250, 1100, 1000)]))]
for (imagePath, boundingBoxes) in images:
# originalのbounding boxを描画(左図)
image = cv2.imread("audrey.jpg")
plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1)
plt.imshow(image)
#plt.axis('off')
currentAxis = plt.gca()
for xmin, ymin, xmax, ymax in boundingBoxes:
coords = (xmin, ymin), xmax - xmin +1, ymax - ymin +1
currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor='#ff0000', linewidth=2))
print('original : ', coords)
# after non maximum suppressionのbounding boxを描画(右図)
plt.subplot(1, 2, 2)
plt.imshow(image)
#plt.axis('off')
currentAxis = plt.gca()
old=datetime.datetime.now()
pick = non_max_suppression_slow(boundingBoxes, 0.3)
print('-------------------------------------------------------')
print('・cost time : ',(datetime.datetime.now()-old))
print('-------------------------------------------------------')
for xmin, ymin, xmax, ymax in pick:
coords = (xmin, ymin), xmax - xmin +1, ymax - ymin +1
currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor='#00ff00', linewidth=2))
print('after nms : ', coords)
```
## 3. non maximum suppression : Python
```
coords = [[187, 82, 337, 317],[150, 67, 305, 282],[246, 121, 368, 304]]
bounding_boxes = [[187, 82, 337-187, 317-82],[150, 67, 305-150, 282-67],[246, 121, 368-246, 304-121]]
confidence_score = [0.9, 0.75, 0.8]
fig = plt.figure(figsize=(8,6))
plt.xlim(0, 400)
plt.ylim(0, 400)
ax = fig.add_subplot(111)
for label, i in enumerate(bounding_boxes):
# rect = plt.Rectangle((i[0],i[1]),i[2],i[3], fill=False)
coords = (i[0], i[1]), i[2], i[3]
plt.gca().add_patch(plt.Rectangle(*coords, fill=False, edgecolor='#FF0000', linewidth=2))
plt.gca().text(i[0], i[1]+i[3], str(confidence_score[label]), bbox={'facecolor':'#FF0000', 'alpha':0.5})
#ax.add_patch(rect)
plt.show()
def nms(bounding_boxes, score, threshold):
# If no bounding boxes, return empty list
if len(bounding_boxes) == 0:
return [], [] # picked boxes, picked scores
# coordinates of bounding boxes
start_x = bounding_boxes[:, 0]
start_y = bounding_boxes[:, 1]
end_x = bounding_boxes[:, 2]
end_y = bounding_boxes[:, 3]
# Picked bounding boxes
picked_boxes = []
picked_score = []
intersection_areas = []
# Compute areas of bounding boxes
areas = (end_x - start_x + 1) * (end_y - start_y + 1)
# Sort by confidence score of bounding boxes
order = np.argsort(score)
# Iterate bounding boxes
while order.size > 0:
# The index of largest confidence score
index = order[-1]
# Pick the bounding box with largest confidence score
picked_boxes.append(bounding_boxes[index])
picked_score.append(confidence_score[index])
# Compute ordinates of intersection-over-union(IOU)
x1 = np.maximum(start_x[index], start_x[order[:-1]])
x2 = np.minimum(end_x[index], end_x[order[:-1]])
y1 = np.maximum(start_y[index], start_y[order[:-1]])
y2 = np.minimum(end_y[index], end_y[order[:-1]])
intersection_areas.append([x1, y1, x2, y2])
# Compute areas of intersection-over-union
w = np.maximum(0.0, x2 - x1 + 1)
h = np.maximum(0.0, y2 - y1 + 1)
intersection = w * h
# Compute the ratio between intersection and union
ratio = intersection / (areas[index] + areas[order[:-1]] - intersection)
left = np.where(ratio < threshold)
order = order[left]
return picked_boxes, picked_score, intersection_areas
bounding_boxes =np.asarray([[187, 82, 337, 317],[150, 67, 305, 282],[246, 121, 368, 304]],dtype=np.float32)
confidence_score = np.asarray([0.9, 0.75, 0.8],dtype=np.float32)
# IoU threshold
threshold = 0.5
old=datetime.datetime.now()
picked_boxes, picked_score, intersection_areas = nms(bounding_boxes, confidence_score, threshold)
print('-------------------------------------------------------')
print('・cost time : ',(datetime.datetime.now()-old))
print('-------------------------------------------------------')
#print('nms : ', picked_boxes,picked_score)
fig = plt.figure(figsize=(8,6))
plt.xlim(0, 400)
plt.ylim(0, 400)
#ax1 = fig.add_subplot(121)
#ax2 = fig.add_subplot(122)
for label, i in enumerate(bounding_boxes):
# rect = plt.Rectangle((i[0],i[1]),i[2],i[3], fill=False)
coords = (i[0], i[1]), i[2]-i[0]+1, i[3]-i[1]+1
inter_xmin = intersection_areas[0][0][0]
inter_ymin = intersection_areas[0][1][0]
inter_xmax = intersection_areas[0][2][0]
inter_ymax = intersection_areas[0][3][0]
inter_coords = (inter_xmin, inter_ymin), inter_xmax-inter_xmin+1, inter_ymax-inter_ymin+1
plt.gca().add_patch(plt.Rectangle(*coords, fill=False, edgecolor='#FF0000', linewidth=2))
#plt.gca().add_patch(plt.Rectangle(*inter_coords, fill=True, facecolor={'facecolor':'#FF0000','alpha':0.5}, edgecolor='#FF0000', linewidth=0))
plt.gca().text(i[0], i[3], str(confidence_score[label]), bbox={'facecolor':'#FF0000', 'alpha':0.5})
#ax.add_patch(rect)
#plt.show()
fig = plt.figure(figsize=(8,6))
plt.xlim(0, 400)
plt.ylim(0, 400)
#plt.subplot(1,2,2)
for label, i in enumerate(picked_boxes):
rect = plt.Rectangle((i[0],i[1]),i[2],i[3], fill=False)
coords = (i[0], i[1]), i[2]-i[0]+1, i[3]-i[1]+1
plt.gca().add_patch(plt.Rectangle(*coords, fill=False, edgecolor='#FF0000', linewidth=2))
plt.gca().text(i[0], i[3], str(picked_score[label]), bbox={'facecolor':'#FF0000', 'alpha':0.5})
#ax.add_patch(rect)
#plt.subplot(1,2,2)
#plt.show()
#print(intersection_areas)
#print(intersection_areas[0][0])
```
## 4. non maximum suppression : tensorflow
Predictionsとして数千のバウンディングボックスの座標が出力される
→max_output_sizeとして定めた値まで減らす
```
# non maximum suppression : Python
print(picked_boxes, picked_score)
import tensorflow as tf
threshold = 0.5
with tf.Session() as sess:
for i in range(3): # forなしだと、nms.eval()がエラー、expected an indented block
old=datetime.datetime.now()
nms = tf.image.non_max_suppression(bounding_boxes,confidence_score, max_output_size=5, iou_threshold=threshold)
print('-------------------------------------------------------')
print('・cost time : ',(datetime.datetime.now()-old)) # .microseconds
print('・face detected : ', len(nms.eval()))
for index, value in enumerate(nms.eval()): # nms.eval() → インデックスを返す
rect = bounding_boxes[value]
print('・value : ', value)
print('・rect : ', rect)
```
# <font color="#4169e1">感想</font>
***
・tensorflow作ったひとすごい
・SSD作ったひともすごい
・車輪の再発明も勉強になるから悪くない
・1つ1つ処理せずに行列でまとめて処理したほうが確かにスーパー早い
・nmsしてもmax_output_sizeを200とかにしてるから画面がバウンディングボックスで埋まる
・テスト画像にオードリーヘップバーンを使うとテンション上がる
・引き続きSSDを解明していきたい
| github_jupyter |
<img src='https://www.anadronestarting.com/wp-content/uploads/intel-main_opt.png' width=50%>
# 모바일넷을 이용한 이미지분류
<font size=5><b>(Image Classification using Mobilenet)<b></font>
<div align='right'>성 민 석<br>(Minsuk Sung)</div>
<img src='https://miro.medium.com/max/356/1*fTQtXyApxWPoW2vzSEk_Pw.png' width=60%>
---
<h1>강의목차<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#필요한-라이브러리-및-옵션" data-toc-modified-id="필요한-라이브러리-및-옵션-1"><span class="toc-item-num">1 </span>필요한 라이브러리 및 옵션</a></span><ul class="toc-item"><li><span><a href="#기본-라이브러리(Library)" data-toc-modified-id="기본-라이브러리(Library)-1.1"><span class="toc-item-num">1.1 </span>기본 라이브러리(Library)</a></span></li><li><span><a href="#옵션(Option)" data-toc-modified-id="옵션(Option)-1.2"><span class="toc-item-num">1.2 </span>옵션(Option)</a></span></li></ul></li><li><span><a href="#예제---CIFAR100" data-toc-modified-id="예제---CIFAR100-2"><span class="toc-item-num">2 </span>예제 - CIFAR100</a></span><ul class="toc-item"><li><span><a href="#CIFAR-100-데이터-불러오기" data-toc-modified-id="CIFAR-100-데이터-불러오기-2.1"><span class="toc-item-num">2.1 </span>CIFAR-100 데이터 불러오기</a></span></li><li><span><a href="#CIFAR10-데이터-형태-확인하기" data-toc-modified-id="CIFAR10-데이터-형태-확인하기-2.2"><span class="toc-item-num">2.2 </span>CIFAR10 데이터 형태 확인하기</a></span><ul class="toc-item"><li><span><a href="#Train-데이터셋" data-toc-modified-id="Train-데이터셋-2.2.1"><span class="toc-item-num">2.2.1 </span>Train 데이터셋</a></span></li><li><span><a href="#Validation-데이터셋" data-toc-modified-id="Validation-데이터셋-2.2.2"><span class="toc-item-num">2.2.2 </span>Validation 데이터셋</a></span></li><li><span><a href="#Test-데이터셋" data-toc-modified-id="Test-데이터셋-2.2.3"><span class="toc-item-num">2.2.3 </span>Test 데이터셋</a></span></li></ul></li><li><span><a href="#데이터-시각화하기" data-toc-modified-id="데이터-시각화하기-2.3"><span class="toc-item-num">2.3 </span>데이터 시각화하기</a></span></li><li><span><a href="#모델링" data-toc-modified-id="모델링-2.4"><span class="toc-item-num">2.4 </span>모델링</a></span><ul class="toc-item"><li><span><a href="#ResNet50모델-생성" data-toc-modified-id="ResNet50모델-생성-2.4.1"><span class="toc-item-num">2.4.1 </span>ResNet50모델 생성</a></span></li><li><span><a href="#ResNet50-미세-조정" data-toc-modified-id="ResNet50-미세-조정-2.4.2"><span class="toc-item-num">2.4.2 </span>ResNet50 미세 조정</a></span></li><li><span><a href="#전체적인-모델-구성" data-toc-modified-id="전체적인-모델-구성-2.4.3"><span class="toc-item-num">2.4.3 </span>전체적인 모델 구성</a></span></li></ul></li><li><span><a href="#모델-컴파일" data-toc-modified-id="모델-컴파일-2.5"><span class="toc-item-num">2.5 </span>모델 컴파일</a></span></li><li><span><a href="#모델-확인하기" data-toc-modified-id="모델-확인하기-2.6"><span class="toc-item-num">2.6 </span>모델 확인하기</a></span></li><li><span><a href="#모델-학습하기" data-toc-modified-id="모델-학습하기-2.7"><span class="toc-item-num">2.7 </span>모델 학습하기</a></span></li><li><span><a href="#모델-평가하기" data-toc-modified-id="모델-평가하기-2.8"><span class="toc-item-num">2.8 </span>모델 평가하기</a></span><ul class="toc-item"><li><span><a href="#Train-/-Validation-Loss" data-toc-modified-id="Train-/-Validation-Loss-2.8.1"><span class="toc-item-num">2.8.1 </span>Train / Validation Loss</a></span></li><li><span><a href="#Train-/-Validation-Accuaracy" data-toc-modified-id="Train-/-Validation-Accuaracy-2.8.2"><span class="toc-item-num">2.8.2 </span>Train / Validation Accuaracy</a></span></li><li><span><a href="#Train-/-Validation-Top5-Accuracy" data-toc-modified-id="Train-/-Validation-Top5-Accuracy-2.8.3"><span class="toc-item-num">2.8.3 </span>Train / Validation Top5 Accuracy</a></span></li></ul></li><li><span><a href="#신경망-모델-검증하기" data-toc-modified-id="신경망-모델-검증하기-2.9"><span class="toc-item-num">2.9 </span>신경망 모델 검증하기</a></span></li><li><span><a href="#다음-예제에서는" data-toc-modified-id="다음-예제에서는-2.10"><span class="toc-item-num">2.10 </span>다음 예제에서는</a></span></li></ul></li><li><span><a href="#참고" data-toc-modified-id="참고-3"><span class="toc-item-num">3 </span>참고</a></span></li></ul></div>
## 필요한 라이브러리 및 옵션
### 기본 라이브러리(Library)
```
import os
import sys
import glob
import random
import warnings
import itertools
from tqdm import tqdm
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
import cv2
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from IPython.display import SVG
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, ElementTree
import keras
import tensorflow as tf
from tensorflow.keras.datasets import mnist,cifar10,cifar100
from tensorflow.keras.preprocessing.image import load_img,img_to_array,ImageDataGenerator
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.models import Model,Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, Conv2D,GlobalAveragePooling2D
from tensorflow.keras.optimizers import RMSprop, Adam
from tensorflow.keras.utils import to_categorical,plot_model
from tensorflow.keras.losses import categorical_crossentropy,binary_crossentropy
from tensorflow.keras.callbacks import Callback
from tensorflow.keras.metrics import top_k_categorical_accuracy
from tensorflow.python.client import device_lib
```
### 옵션(Option)
```
os.environ["CUDA_VISIBLE_DEVICES"]="0"
warnings.filterwarnings(action='ignore')
warnings.filterwarnings(action='default')
%matplotlib inline
print(device_lib.list_local_devices())
keras.backend.tensorflow_backend._get_available_gpus()
```
---
## 예제 - CIFAR100

이 데이터 세트는 CIFAR-10과 똑같다. 단, 각각 600개의 이미지가 포함된 100개의 클래스가 있다. 학습용 영상은 500개, 시험용 영상은 클래스당 100개씩이다. CIFAR-100의 100개 클래스는 20개의 슈퍼 클래스로 분류된다. 각 이미지에는 "fine"클래스과 "coarse" 라벨이 함께 나온다.
CIFAR-100의 클래스 목록은 다음과 같다.
출처 : [The CIFAR-100 dataset document](https://www.cs.toronto.edu/~kriz/cifar.html)
```
# CIFAR-100 클래스
CIFAR100_CLASSES = sorted(['beaver', 'dolphin', 'otter', 'seal', 'whale', # aquatic mammals
'aquarium' 'fish', 'flatfish', 'ray', 'shark', 'trout', # fish
'orchids', 'poppies', 'roses', 'sunflowers', 'tulips', # flowers
'bottles', 'bowls', 'cans', 'cups', 'plates', # food containers
'apples', 'mushrooms', 'oranges', 'pears', 'sweet peppers', # fruit and vegetables
'clock', 'computer' 'keyboard', 'lamp', 'telephone', 'television', # household electrical devices
'bed', 'chair', 'couch', 'table', 'wardrobe', # household furniture
'bee', 'beetle', 'butterfly', 'caterpillar', 'cockroach', # insects
'bear', 'leopard', 'lion', 'tiger', 'wolf', # large carnivores
'bridge', 'castle', 'house', 'road', 'skyscraper', # large man-made outdoor things
'cloud', 'forest', 'mountain', 'plain', 'sea', # large natural outdoor scenes
'camel', 'cattle', 'chimpanzee', 'elephant', 'kangaroo', # large omnivores and herbivores
'fox', 'porcupine', 'possum', 'raccoon', 'skunk', # medium-sized mammals
'crab', 'lobster', 'snail', 'spider', 'worm', # non-insect invertebrates
'baby', 'boy', 'girl', 'man', 'woman', # people
'crocodile', 'dinosaur', 'lizard', 'snake', 'turtle', # reptiles
'hamster', 'mouse', 'rabbit', 'shrew', 'squirrel', # small mammals
'maple', 'oak', 'palm', 'pine', 'willow', # trees
'bicycle', 'bus', 'motorcycle', 'pickup truck', 'train', # vehicles 1
'lawn-mower', 'rocket', 'streetcar', 'tank', 'tractor' # vehicles 2
])
```
### CIFAR-100 데이터 불러오기
```
# Keras에서 제공하는 CIFAR-100 데이터를 불러오는 함수 : cifar100.load_data()
(X_train, y_train), (X_test,y_test) = cifar100.load_data()
# Train / Validation 데이터 분리하기
# Train 데이터를 Train / Validation 으로 나누어줌으로써 Overfitting 여부를 파악
# X_train, X_valid = X_train[:40000], X_train[40000:]
# y_train, y_valid = y_train[:40000], y_train[40000:]
X_train,X_valid,y_train,y_valid = train_test_split(X_train,y_train,test_size=0.2,shuffle=True,random_state=0)
# Train / Test 데이터의 크기 확인
print('CIFAR-100 Train 데이터의 크기 : {}'.format(len(X_train)))
print('CIFAR-100 Validation 데이터의 크기 : {}'.format(len(X_valid)))
print('CIFAR-100 Test 데이터의 크기 : {}'.format(len(X_test)))
```
### CIFAR10 데이터 형태 확인하기
#### Train 데이터셋
```
print("X_train Shape : ",X_train.shape) # 32*32짜리 크기의 RGB 이미지 40000개
print("y_train Shape : ",y_train.shape) # 각 이미지별 레이블 40000개
```
#### Validation 데이터셋
```
print("X_val Shape : ",X_valid.shape) # 32*32짜리 크기의 RGB 이미지 10000개
print("y_val Shape : ",y_valid.shape) # 각 이미지별 레이블 10000개
```
#### Test 데이터셋
```
print("X_train Shape : ",X_test.shape) # 32*32짜리 크기의 RGB 이미지 10000개
print("y_train Shape : ",y_test.shape) # 각 이미지별 레이블 10000개
```
### 데이터 시각화하기
CIFAR100의 Train 데이터셋의 첫번재 데이터를 확인해보자
```
idx = 0
X_train[idx] # 3채널 RGB 이미지
plt.imshow(X_train[idx], interpolation='nearest')
plt.title('Label : {}'.format(CIFAR100_CLASSES[y_train[idx][0]]))
plt.show()
```
조금 더 많은 CIFAR 데이터셋을 확인해보자
```
# 재연성을 위하여 랜덤시드 고정
np.random.seed(1234)
# random 함수를 통해서 임의의 16개 데이터 가져오기
samples = np.random.randint(0,len(X_train)+1,size=16)
# MNIST를 그릴 Figure 준비
plt.figure(figsize=(12,8))
# 16개의 이미지 시각화
for count, n in enumerate(samples,start=1):
plt.subplot(4, 4, count)
plt.imshow(X_train[n], interpolation='nearest')
label_name = "Label:" + str(CIFAR100_CLASSES[y_train[n][0]])
plt.title(label_name)
plt.tight_layout()
plt.show()
# 데이터 크기 조정(Data Reshape)
X_train = X_train.reshape(X_train.shape[0],32,32,3)
X_valid = X_valid.reshape(X_valid.shape[0],32,32,3)
X_test = X_test.reshape(X_test.shape[0],32,32,3)
# 데이터 포맷 바꾸기
# 정수(int)인 데이터에서 실수(float)으로 변환
X_train = X_train.astype('float32')
X_valid = X_valid.astype('float32')
X_test = X_test.astype('float32')
# 데이터 정규화(Data Regularization)
# 이 과정을 통해서 추후 학습할 신경망이 조금 더 학습이 원할히 될 수 있게함
X_train = X_train / 255
X_valid = X_valid / 255
X_test = X_test / 255
# 원-핫 인코딩(One Hot Encoding)
# Keras의 to_categorical함수를 통해서 모든 Train 데이터의 레이블을 벡터화(Vectorize)
# ex) [3] -> [0 0 0 1 0 0 0 0 0 0]
y_train = to_categorical(y_train, 100)
y_valid = to_categorical(y_valid,100)
y_test = to_categorical(y_test, 100)
```
### 모델링
앞선 예제에서는 직접 CNN 모델을 구성하여 학습을 진행하였지만, 이번 예제에서는 VGGNet, ResNet, MobileNet과 같이 보편적으로 성능이 좋다고 알려져있는 CNN 모델을 사용해보자. Keras에서는 application 모듈에서 Pretrained된 모델을 사용할 수 있다. 이미지 분류에 사용할 수 있는 모델의 목록은 아래와 같다.
- Xception
- VGG16
- VGG19
- ResNet, ResNetV2
- InceptionV3
- InceptionResNetV2
- MobileNet
- MobileNetV2
- DenseNet
- NASNet
출처 : [Keras Documentation](https://keras.io/applications/)
이번 예제에서는 **`ResNet50`을 사용**해보도록 하자.
<img src='https://i.stack.imgur.com/XTo6Q.png' width=50%>
#### ResNet50모델 생성
```
# CIFAR-10의 이미지 형태
INPUT_SHAPE = (32, 32, 3)
# VGG16 객체 생성
base_model = ResNet50(input_shape=INPUT_SHAPE, # CIFAR-10의 이미지 형태
include_top=False, # FC Layer를 제거
weights='imagenet')
# ResNet50의 모든 Layer를 Freezing
base_model.trainable = True
```
#### ResNet50 미세 조정
```
# ResNet의 상단 Layer를 학습가능여부
set_trainable = False
# res5c_branch2a, res5c_branch2b, res5c_branch2c 라는 이름의 Layer를 만나면 학습가능하게끔
for layer in tqdm(base_model.layers):
if layer.name in ['res5a_branch2a','res5a_branch2b','res5a_branch2c',
'res5b_branch2a','res5b_branch2b','res5b_branch2c',
'res5c_branch2a','res5c_branch2b','res5c_branch2c']:
set_trainable = True
if set_trainable:
layer.trainable = True
else:
layer.trainable = False
layers = [(layer, layer.name, layer.trainable) for layer in base_model.layers]
pd.DataFrame(layers, columns=['Layer Type', 'Layer Name', 'Layer Trainable'])
```
#### 전체적인 모델 구성
```
model = Sequential()
model.add(base_model) # ResNet50 추가
model.add(GlobalAveragePooling2D()) # Transfer Learning을 진행할때 항상 GAP Layer 추가
model.add(Dense(len(CIFAR100_CLASSES), activation='softmax')) # 분류할 FC Layer 추가
```
### 모델 컴파일
```
model.compile(loss=categorical_crossentropy,
optimizer=Adam(learning_rate=0.0001),
metrics=['acc','top_k_categorical_accuracy'])
```
### 모델 확인하기
```
model.summary()
plot_model(model, to_file='./img/model/cifar100_resnet_model.png', show_shapes=True)
```
### 모델 학습하기
Keras의 `fit`의 메소드를 통해서 간단하게 학습가능하다. 이번 예제에서는 여기서는 10번의 epoch만으로 학습을 진행하도록 한다. 그리고 앞서 준비한 검증 데이터(Validation Set)을 통해서 신경망의 오버피팅 여부를 판단하도록 하자.
```
EPOCHS = 10
BATCH_SIZE = 64
history = model.fit(X_train, # 학습할 데이터
y_train, # 학습할 레이블
epochs=EPOCHS, # 전체 학습할 횟수
batch_size=BATCH_SIZE, # 배치 사이즈
use_multiprocessing=True,
validation_data=(X_valid, y_valid) # 검증 데이터로 확인
)
model.save('./bin/cifar100_resnet50.h5')
```
### 모델 평가하기
```
# Train 데이터로 평가하기
train_loss, train_acc, train_top5_acc= model.evaluate(X_train,y_train,verbose=0)
print('Train Loss : {}'.format(train_loss))
print('Train Accuracy : {}'.format(train_acc))
print('Train Top5 Accuracy : {}'.format(train_top5_acc))
# Validation 데이터로 평가하기
valid_loss, valid_acc , valid_top5_acc= model.evaluate(X_valid,y_valid,verbose=0)
print('Validation Loss : {}'.format(valid_loss))
print('Validation Accuracy : {}'.format(valid_acc))
print('Validation Top5 Accuracy : {}'.format(valid_top5_acc))
```
#### Train / Validation Loss
```
# Train / Validation 데이터에 대해서 Loss 시각화
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1,len(loss)+1)
plt.plot(epochs,loss,label='Training Loss')
plt.plot(epochs,val_loss,label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.show()
```
#### Train / Validation Accuaracy
```
# Train / Validation 데이터에 대해서 Accuracy 시각화
acc = history.history['acc']
val_acc = history.history['val_acc']
epochs = range(1,len(acc)+1)
plt.plot(epochs,acc,label='Training Accuarcy')
plt.plot(epochs,val_acc,label='Validation Accuarcy')
plt.title('Training and Validation Accuarcy')
plt.xlabel('Epochs')
plt.ylabel('Accuarcy')
plt.legend()
plt.grid(True)
plt.show()
```
#### Train / Validation Top5 Accuracy
```
# Train / Validation 데이터에 대해서 Accuracy 시각화
acc = history.history['top_k_categorical_accuracy']
val_acc = history.history['val_top_k_categorical_accuracy']
epochs = range(1,len(loss)+1)
plt.plot(epochs,acc,label='Training Top5 Accuarcy')
plt.plot(epochs,val_acc,label='Validation Top5 Accuarcy')
plt.title('Training and Validation Top5 Accuarcy')
plt.xlabel('Epochs')
plt.ylabel('Accuarcy')
plt.legend()
plt.grid(True)
plt.show()
```
### 신경망 모델 검증하기
```
test_loss, test_acc, test_top5_acc = model.evaluate(X_test,y_test,verbose=0)
print('Test Loss : {}'.format(test_loss))
print('Test Accuracy : {}'.format(test_acc))
print('Test Accuracy : {}'.format(test_top5_acc))
```
RenNet으로 학습한 신경망이 과연 어떠한 이미지를 잘 못 예측했는지 확인해보자
```
# 재연성을 위하여 랜덤시드 고정
random.seed('intel')
# TEST 데이터 예측하기
predicted_result = model.predict(X_train)
predicted_labels = np.argmax(predicted_result, axis=1)
# TEST 데이터의 정답 가져오기
test_labels = np.argmax(y_test, axis=1)
# random 함수를 통해서 임의의 16개 데이터 가져오기
samples = random.choices(population=test_labels, k=16)
# CIFAR100를 그릴 Figure 준비
plt.figure(figsize=(12, 8))
# 16개의 이미지 시각화
for count, n in enumerate(samples, start=1):
plt.subplot(4, 4, count)
plt.imshow(X_test[n], interpolation='nearest')
label = "Label:" + CIFAR100_CLASSES[test_labels[n]]
pred = "Prediction:" + CIFAR100_CLASSES[predicted_labels[n]]
plt.title(label+', '+pred)
plt.tight_layout()
plt.savefig('./img/result/cifar100_wrong_result.png')
plt.show()
```
### 다음 예제에서는

ResNet50모델을 통해서 이제 VGG-16모델에서 가장 큰 이슈였던 많은 양의 파라미터는 해결됐다. ResNet50은 VGG-16모델보다 적은 파라미터로 더 좋은 성능을 낼 수 있다. 하지만 여전히 이정도의 파라미터는 작은 디바이스에서 학습하기엔 문제가 된다. 그렇기 때문에 이러한 이슈를 해결하고자 다음 예제에서는 `MobileNet`을 이용하는 예제를 해보자.
---
## 참고
- Intel
- https://www.intel.co.kr/
- Intel OpenVINO
- https://software.intel.com/en-us/openvino-toolkit
- MNIST
- http://yann.lecun.com/exdb/mnist/
- CIFAR10
- https://www.cs.toronto.edu/~kriz/cifar.html
- ImageNet
- http://www.image-net.org
- Tensorflow
- https://www.tensorflow.org/?hl=ko
- Keras
- https://keras.io/
- https://tensorflow.blog/2019/03/06/tensorflow-2-0-keras-api-overview/
- https://tykimos.github.io/2017/02/22/Integrating_Keras_and_TensorFlow/
- https://tykimos.github.io/2017/03/08/CNN_Getting_Started/
- https://raw.githubusercontent.com/keras-team/keras-docs-ko/master/sources/why-use-keras.md
- Keras to Caffe
- https://github.com/uhfband/keras2caffe
- http://www.deepvisionconsulting.com/from-keras-to-caffe/
- Fully Connected Layer
- https://sonofgodcom.wordpress.com/2018/12/31/cnn%EC%9D%84-%EC%9D%B4%ED%95%B4%ED%95%B4%EB%B3%B4%EC%9E%90-fully-connected-layer%EB%8A%94-%EB%AD%94%EA%B0%80/
- Convultional Nueral Network
- http://aikorea.org/cs231n/convolutional-networks/
- http://cs231n.stanford.edu/
- CNN Models
- https://ratsgo.github.io/deep%20learning/2017/10/09/CNNs/
- VOC2012
- https://blog.godatadriven.com/rod-keras-multi-label
- https://gist.github.com/rragundez/ae3a17428bfec631d1b35dcdc6296a85#file-multi-label_classification_with_keras_imagedatagenerator-ipynbhttps://fairyonice.github.io/Part_5_Object_Detection_with_Yolo_using_VOC_2012_data_training.html
- http://research.sualab.com/introduction/2017/11/29/image-recognition-overview-1.html
| github_jupyter |
```
from __future__ import absolute_import, division, print_function, unicode_literals
%load_ext autoreload
%autoreload 2
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
%matplotlib inline
%config InlineBackend.figure_format = 'retina' # adapt plots for retina displays
from IPython.core.debugger import set_trace
import os
import utils
from tqdm import tqdm_notebook
from sklearn.model_selection import train_test_split
import multiprocessing
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import datasets, models
```
# Load data
```
# TODO: Describe here where the dataset needs to be stored, i.e. which table, which images and directory structure of the images.
# TODO: Maybe write filepaths here.
# Load the data table with all 1.5 Tesla MRI scans from ADNI.
df = datasets.load_data_table_15T()
```
Let's look at the table. Each row is a single MRI image. Some important columns in the table:
- PTID: Patient ID
- VISCODE: Visit code (bl=baseline, mx=after x months) (see also Visit)
- DX: Diagnosis (CN=control, MCI=mild cognitive impairment, Dementia=Alzheimer's disease)
- Image.ID: Image ID
- filepath: The path to the MRI image (not contained in the original ADNI table but added by `datasets.load_data_table()`
```
df.head()
# Patient-wise train-test-split.
# Select a number of patients for each class, put all their images in the test set
# and all other images in the train set. This is the split that is used in the paper to produce the heatmaps.
test_patients_per_class = 30
patients_AD = df[df['DX'] == 'Dementia']['PTID'].unique()
patients_CN = df[df['DX'] == 'CN']['PTID'].unique()
patients_CN = filter(lambda p: p not in patients_AD, patients_CN) # patients that have both a CN and an AD scan should belong to the AD group
patients_AD_train, patients_AD_test = train_test_split(patients_AD, test_size=test_patients_per_class, random_state=0)
patients_CN_train, patients_CN_test = train_test_split(patients_CN, test_size=test_patients_per_class, random_state=0)
patients_train = np.concatenate([patients_AD_train, patients_CN_train])
patients_test = np.concatenate([patients_AD_test, patients_CN_test])
train_dataset, test_dataset = datasets.build_datasets(df, patients_train, patients_test)
# Plot one MRI scan from the dataset, first without normalization...
i = 0
utils.plot_slices(train_dataset.get_raw_image(i))
# ... and then with normalization, i.e. the way the network sees it.
utils.plot_slices(train_dataset[i][0][0])
train_loader, test_loader = datasets.build_loaders(train_dataset, test_dataset)
```
# Create model and train
```
# This creates the model from the paper in pytorch, and wraps it in a `trainer` via torchsample.
net, trainer, cuda_device = models.build_model()
models.train_model(trainer, train_loader, test_loader, cuda_device, num_epoch=10)
# TODO: Train network to end and check that this works.
utils.plot_learning_curve(trainer.history)
models.calculate_roc_auc(trainer, val_loader, cuda_device)
```
# Save/load model
```
#torch.save(net, 'output/models/softmax-output.pt')
#torch.save(net.state_dict(), 'output/models/softmax-output_state-dict.pt')
net = models.ClassificationModel3D()
net.load_state_dict(torch.load('output/models/softmax-output_state-dict.pt'))
if torch.cuda.is_available():
net.cuda()
cuda_device = torch.cuda.current_device()
print('Moved network to GPU')
else:
cuda_device = -1
print('GPU not available')
```
# K-Fold Cross Validation
```
# This is used to report the accuracy and ROC in the paper.
# We take the metrics on the test fold after 20 epochs, regardless of how good they are or if they've been better during an earlier epoch.
from sklearn.model_selection import KFold
kfold = KFold(n_splits=5, shuffle=True)
patients_all = df['PTID'].unique()
normalize = True
num_epoch = 20
# Split patients into k folds.
for i, (indices_train, indices_test) in enumerate(kfold.split(patients_all)):
print('{}-fold CV - Split {}:'.format(kfold.n_splits, i+1))
print()
print('Preparing datasets...')
patients_train, patients_test = patients_all[indices_train], patients_all[indices_test]
train_dataset, test_dataset = datasets.build_datasets(df, patients_train, patients_test, normalize=normalize)
train_loader, test_loader = datasets.build_loaders(train_dataset, test_dataset)
print('Building model and trainer...')
net, trainer, cuda_device = models.build_model()
print('Starting training...')
models.train_model(trainer, train_loader, test_loader, cuda_device, num_epoch=num_epoch)
utils.plot_learning_curve(trainer.history)
print('Evaluating ROC...')
roc_auc = models.calculate_roc_auc(trainer, test_loader, cuda_device)
print('ROC AUC:', roc_auc)
print()
print('-'*80)
print()
```
| github_jupyter |
# Thermodynamics correlations for pure components
En esta sección se muestra la class *Thermodynamic_correlations()* la cual permite realizar el cálculo de propiedades termodinámicas de sustancias puras como una función de la temperatura. En este caso se pueden tener 6 situaciones para cada una de las 13 propiedades termofísicas soportadas:
1. Especificar una sustancia pura sin especificar una temperatura. En este caso por defecto la propiedad termodinámica se calcula entre el intervalo mínimo y máximo de validez experimental para cada correlación.
2. Especificar una sustancia pura y especificar una temperatura.
3. Especificar una sustancia pura y especificar varias temperaturas.
4. Especificar varias sustancias puras sin especificar una temperatura.
5. Especificar varias sustancias puras y especificar una temperatura.
6. Especificar varias sustancias puras y especificar varias temperaturas
la clase *Thermodynamics_correlations* es usada para calcular 13 propiedades termodinámicas de sustancias puras en función de la temperatura y se sigue la siguente convención para presentar identificar las propiedades termodinámicas
property thermodynamics = name property, units, correlation, equation
The thermodynamic correlations are:
-**Solid_Density** = "Solid Density", "[kmol/m^3]", "A+B*T+C*T^2+D*T^3+E*T^4", 0
-**Liquid_Density** = "Liquid Density", "[kmol/m^3]", "A/B^(1+(1-T/C)^D)", 1
-**Vapour_Pressure** = "Vapour Pressure", "[Bar]", "exp(A+B/T+C*ln(T)+D*T^E) * 1e-5", 2
-**Heat_of_Vaporization** = "Heat of Vaporization", "[J/kmol]", "A*(1-Tr)^(B+C*Tr+D*Tr^2)", 3
-**Solid_Heat_Capacity** = "Solid Heat Capacity", "[J/(kmol*K)]", "A+B*T+C*T^2+D*T^3+E*T^4", 4
-**Liquid_Heat_Capacity** = "Liquid Heat Capacity", "[J/(kmol*K)]", "A^2/(1-Tr)+B-2*A*C*(1-Tr)-A*D*(1-Tr)^2-C^2*(1-Tr)^3/3-C*D*(1-Tr)^4/2-D^2*(1-Tr)^5/5", 5
-**Ideal_Gas_Heat_Capacity** = "Ideal Gas Heat Capacity" "[J/(kmol*K)]", "A+B*(C/T/sinh(C/T))^2+D*(E/T/cosh(E/T))^2", 6
-**Second_Virial_Coefficient** = "Second Virial Coefficient", "[m^3/kmol]", "A+B/T+C/T^3+D/T^8+E/T^9", 7
-**Liquid_Viscosity** = "Liquid Viscosity", "[kg/(m*s)]", "exp(A+B/T+C*ln(T)+D*T^E)", 8
-**Vapour_Viscosity** = "Vapour Viscosity", "[kg/(m*s)]", "A*T^B/(1+C/T+D/T^2)", 9
-**Liquid_Thermal_Conductivity** = "Liquid Thermal Conductivity", "[J/(m*s*K)]", "A+B*T+C*T^2+D*T^3+E*T^4", 10
-**Vapour_Thermal_Conductivity** = "Vapour Thermal Conductivity", "[J/(m*s*K)]", "A*T^B/(1+C/T+D/T^2)", 11
-**Surface_Tension** = "Surface Tension", "[kg/s^2]", "A*(1-Tr)^(B+C*Tr+D*Tr^2)", 12
Para empezar se importan las librerías que se van a utilizar, que en este caso son numpy, pandas, pyther y especificar que las figuras generadas se muesten dentro del jupyter notebook
```
import numpy as np
import pandas as pd
import pyther as pt
import matplotlib.pyplot as plt
#%matplotlib inline
```
# 1. Especificar una sustancia pura sin especificar una temperatura.
Luego se carga el archivo que contine las constantes de las correlaciones de las propiedades termodinamicas, que se llama en este caso *"PureFull_mod_properties.xls"* y se asigna a la variable *dppr_file*.
Creamos un objeto llamado **thermodynamic_correlations** y se pasan como parametros las variables **component** y **property_thermodynamics** que en el ejemplo se especifica para el componente METHANE la Vapour_Pressure
```
dppr_file = "PureFull_mod_properties.xls"
thermodynamic_correlations = pt.Thermodynamic_correlations(dppr_file)
component = ['METHANE']
property_thermodynamics = "Vapour_Pressure"
Vapour_Pressure = thermodynamic_correlations.property_cal(component, property_thermodynamics)
print("Vapour Pressure = {0}". format(Vapour_Pressure))
```
para realizar un gráfico simple de la propiedad termodinámica se utiliza el método **graphical(temperature, property_thermodynamics, label_property_thermodynamics, units)**.
En donde se pasan como argumentos la temperatura a la cual se claculó la propiedad termodinamica, los valores calculados de la propiedad termodinamica, el label de la propiedad termodinámica y las unidades correspondientes de temperatura y la propiedad termodinámica en cada caso.
```
temperature_vapour = thermodynamic_correlations.temperature
units = thermodynamic_correlations.units
print(units)
thermodynamic_correlations.graphical(temperature_vapour, Vapour_Pressure, property_thermodynamics, units)
```
# 2. Especificar una sustancia pura y una temperatura.
Siguiendo con la sustacia pura *METHANE* se tiene el segundo caso en el cual ademas de especificiar el componente se especifica también solo un valor de temperatura, tal como se muestra en la variable *temperature*.
Dado que cada correlación de propiedad termodinámica tiene un rango mínimo y máximo de temperatura en la cual es valida, al especificar un valor de temperatura se hace una verificación para determinar si la temperatura ingresada se encuentra entre el intervalo aceptado para cada componente y cada propiedad termodinámica. En caso contrario la temperatura se clasifica como invalida y no se obtiene valor para la propiedad termodinámica seleccionada.
```
component = ['METHANE']
property_thermodynamics = "Vapour_Pressure"
temperature = [180.4]
Vapour_Pressure = thermodynamic_correlations.property_cal(component, property_thermodynamics, temperature)
print("Vapour Pressure = {0} {1}". format(Vapour_Pressure, units[1]))
```
# 3. Especificar una sustancia pura y especificar varias temperaturas.
Ahora se tiene la situación de contar con un solo componente "METHANE" sin embargo, esta vez se especifica varios valores para la temperatura en las cuales se quiere determinar el correspondiente valor de una proiedad termodinámica, que como en los casos anteriores es la *Vapour_Pressure*.
```
component = ['METHANE']
property_thermodynamics = "Vapour_Pressure"
temperature = [180.4, 181.4, 185.3, 210, 85]
Vapour_Pressure = thermodynamic_correlations.property_cal(component, "Vapour_Pressure", temperature)
print("Vapour Pressure = {0} {1}". format(Vapour_Pressure, units[1]))
```
Se debe notar que al ingresar una serie de valores de temperatura, en este caso 5 valores, se obtienen solo 3 valores de la propiedad termodinámica. Esto se debe a que para este caso 2 valores de temperatura no se encuentran en el valor mínimo y máximo en donde es valida la correlación termodinámica. Por tanto, esto se avisa por medio del mensaje: *Temperature_invalid = ['210 K is a temperature not valid', '85 K is a temperature not valid']*
# 4. Especificar varias sustancias puras sin especificar una temperatura.
Otra de las posibilidades que se puede tener es la opción de especificar varios componentes para una misma propiedad termodinámica sin que se especifique una o más valores de temperatura. En esta opción se pueden ingresar multiples componentes sin un limite, siempre y cuando estén en la base de datos con la que se trabaja o en dado caso sean agregados a la base de datos nuevas correlaciones para sustancias puras *Ver sección base de datos*. Para este ejemplo se utiliza una *list components* con 3 sustancias puras por cuestiones de visibilidad de las gráficas de *Vapour_Pressure*.
```
components = ["METHANE", "n-TETRACOSANE", "ISOBUTANE"]
property_thermodynamics = "Vapour_Pressure"
Vapour_Pressure = thermodynamic_correlations.property_cal(components, property_thermodynamics)
temperature_vapour = thermodynamic_correlations.temperature
```
por medio del método *multi_graphical(components, temperature, property_thermodynamics)* al cual se pasan los parámetros correspondiente a las sustancias puras, la temperatura a la cual se realiza el calculo de la propiedad termodinámica y los valores de la propiedad termodinámica de cada sustancia pura, para obtener la siguiente figura.
```
thermodynamic_correlations.multi_graphical(components, temperature_vapour, Vapour_Pressure)
```
sin embargo como se menciono anteriormente, es posible calcular una propiedad termodinámica para un gran número de sustancias puras y luego realizar las gráficas correspondientes dependiendo de las necesidades de visualización entre otros criterios. Para ejemplificar esto, ahora se tienen 7 sustancias puras y se quiere gŕaficar la propiedad termodinámica de solo: *n-PENTACOSANE, ETHANE y el ISOBUTANE*.
```
components = ["METHANE", "n-TETRACOSANE", "n-PENTACOSANE", "ETHANE", "ISOBUTANE", "PROPANE", "3-METHYLHEPTANE"]
property_thermodynamics = "Vapour_Pressure"
Vapour_Pressure = thermodynamic_correlations.property_cal(components, property_thermodynamics)
temperature_vapour = thermodynamic_correlations.temperature
thermodynamic_correlations.multi_graphical(components[2:5], temperature_vapour[2:5], Vapour_Pressure[2:5])
```
# 5. Especificar varias sustancias puras y una temperatura.
Como en el caso anterios, en este ejemplo se espcifican 3 sustancias puras pero con la especificación de un solo valor de temperatura. Esta temperatura será común para las sustancias puras con las que se trabaje por tanto puede darse el caso de que sea una temperatura valida para algunas sustancias puras mientras que para otras no dependiendo del intervalo de valides de cada correlación termodinámica.
```
dppr_file = "PureFull_mod_properties.xls"
thermodynamic_correlations = pt.Thermodynamic_correlations(dppr_file)
components = ["METHANE", "n-TETRACOSANE", "ISOBUTANE"]
property_thermodynamics = "Vapour_Pressure"
temperature = [180.4]
Vapour_Pressure = thermodynamic_correlations.property_cal(components, property_thermodynamics, temperature)
print("Vapour Pressure = {0} {1}". format(Vapour_Pressure, units[1]))
```
en este caso se tiene como resultado un con 2 valores de presión de vapor, uno para METHANE y otro para ISOBUTANE, mientras que se obtiene un array vacio en el caso "de n-TETRACOSANE, puesto que la temperatura de 180 K especificada no se encuentra como valida.
para verificar tanto los valores de las constantes como los valores mínimos y máximos de cada correlación termodinámica para cada una de las sustancias puras que se especifique se utiliza el atributo *component_constans* tal como se muestra a continuación
```
thermodynamic_correlations.component_constans
```
# 6. Especificar varias sustancias puras y especificar varias temperaturas
En esta opción se puede manipular varias sustancias puras de forma simultanea con la especificación de varios valores de temperaturas, en donde cada valor de temperatura especificado será común para cada sustancia pura, de tal forma que se obtendra valores adecuados para aquellos valores de temperatura que sean validos para cada caso considerado.
```
import numpy as np
import pandas as pd
import pyther as pt
import matplotlib.pyplot as plt
%matplotlib inline
dppr_file = "PureFull_mod_properties.xls"
thermodynamic_correlations = pt.Thermodynamic_correlations(dppr_file)
#components = ["METHANE", "n-TETRACOSANE", "ISOBUTANE"]
components = ["METHANE", "n-TETRACOSANE", "n-PENTACOSANE", "ETHANE", "ISOBUTANE", "PROPANE", "3-METHYLHEPTANE"]
property_thermodynamics = "Vapour_Pressure"
temperature = [180.4, 181.4, 185.3, 210, 800]
Vapour_Pressure = thermodynamic_correlations.property_cal(components, property_thermodynamics, temperature)
print("Vapour Pressure = {0}". format(Vapour_Pressure))
```
como se muestra en los resultados anteriores, se comienza a complicar la manipulación de los datos conforme incrementa el número de sustancias puras y temperaturas involucradas en el analisis, por tal motivo conviene utilizar las bondades de librerías especializadas para el procesamiento de datos como *Pandas* para obtener resultados más eficientes.
El método *data_temperature(components, temperature, Vapour_Pressure, temp_enter)* presenta un DataFrame con los resultados obtenidos luego de calcular la propiedad termodinámica indicada, señalan que para las temperaturas invalidas en el intervalo de aplicación de la correlación termodinámica, el resultado será *NaN*, tal como se muestra con el ejemplo a continuación.
```
temp_enter = thermodynamic_correlations.temperature_enter
thermodynamic_correlations.data_temperature(components, temperature, Vapour_Pressure, temp_enter)
```
# 7. Future work
- Actualmente PyTher se encuentra implementando la opción de multiples propiedades termodinámicas de forma simultanea para el caso de multiples sustancias puras con multiples opciones de temepratura.
- Dar soporte a la manipulación de bases de datos por parte de usuarios para agregar, modificar, eliminar, renombrar sustancias puras y/o correlaciones termodinámicas.
# 8. References
Numpy
| github_jupyter |
<a href="https://colab.research.google.com/github/stephenbeckr/numerical-analysis-class/blob/master/Demos/Ch1_SymbolicTaylorSeries.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Manipulate Taylor series using the **SymPy** package in Python, following the tutorial at [scipy-lectures.org/packages/sympy.html](https://scipy-lectures.org/packages/sympy.html). SymPy is used in [SageMath](https://www.sagemath.org/).
You can do this in Maple, which is a bit old-school, or Mathematica (which we have a license for at CU). Wolfram Alpha is another choice (by the company that makes Mathematica) though the free version does have some limitations.
The nice thing about Python is that it is free and community supported, so if you take the time to use it, it won't go away. If you learn Mathematica now, you may not be able to use it in your job, since it's an expensive license.
```
# Load the package
import sympy as sym
from sympy import init_printing
init_printing() # This will make output look very nice!
import math # has things like math.pi (which is the numerical value of pi)
# First, all symbolic variables must be declared. This is in contrast to Mathematica
x = sym.Symbol('x')
# Now, let's ask for a Taylor series expansion
sym.series( sym.cos(x), x )
# We can see the Docstring for the function to see all the options
?sym.series
```
Before going further, let's play with cos(pi/4)
```
print( math.cos( math.pi/4 ) )
# or, ask to print out 20 decimal places
print( '%.20f' % math.cos( math.pi/4 ) ) # this is old-school: see https://docs.python.org/3/tutorial/inputoutput.html#old-string-formatting
print( math.cos( sym.pi/4) )
print( sym.cos( math.pi/4) )
print( sym.cos( sym.pi/4) )
sym.cos( sym.pi/4) # same as above, but use fancy formatting
```
Now let's explore the series. In particular, let's try to evaluate cos( .75 ), using only addition and multiplication, and a few "memorized" values of sine/cosine (let's assume that we memorize the fact that $\cos( \pi/4 ) = \sqrt{2}/2$ and that $\sin( \pi/4 ) = \sqrt{2}/2$.
Since .75 is not that far from $\pi/4 \approx 0.785$, let's do a Taylor expansion of $\cos$ around $\pi/4$.
```
Taylor = sym.series( sym.cos(x), x, x0=sym.pi/4, n=5)
Taylor
Taylor.subs(x,.75) # Not what we want
Taylor.evalf( subs={x: .75})
# Numerically evaluating this was a problem, because of the O( x^5 ) term. Let's remove it.
# See https://docs.sympy.org/latest/tutorial/calculus.html
Taylor.removeO()
guess = Taylor.removeO().subs(x,.75).evalf()
print("Our guess is: \t%.15f" % guess)
print("True value is: \t%.15f" % math.cos( .75) )
print("Discrepency is: \t%.3e" % abs( guess - math.cos(.75) ))
```
Our *absolute* error is about $3\times 10^{-10}$. Is this what we'd expect? Let's use math to be able to **guarantee** a small error (without having known the true answer first)
Let's look at the remainder term in the Taylor series
```
x0=sym.Symbol('x0')
sym.series( sym.cos(x), x, x0=x0, n=5)
xi = sym.Symbol('xi')
Remainder = -(x-x0)**5*sym.sin(xi)/120
Remainder
```
By Taylor's remainder theorem, we know $\xi \in [x,x_0]$ (or $\xi \in [x_0,x]$ if $x_0 < x$) such that the above remainder is the error in the Taylor series. We don't know exactly what $\xi$ is, but that's OK, because for any $\xi$, we can just bound $|\sin(\xi)| \le 1$. So using this,...
```
RemainderBound = -(x-x0)**5/120
RemainderBound
# See https://docs.sympy.org/latest/tutorial/basic_operations.html
RemainderBound.subs( [ (x,.75), (x0,math.pi/4) ])
```
To summarize, our Taylor series approximation had error $3.25 \times 10^{-10}$. We were able to use math to give an *a priori* bound that the error was no more than $4.63 \times 10^{-10}$ (though in that bound, we disregarded potentially cancellation errors when summing the series)
| github_jupyter |
# Healthcare Stocks Growth
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import math
import warnings
warnings.filterwarnings("ignore")
# yahoo finance data
import yfinance as yf
yf.pdr_override()
# input
# Growth Stock
title = "Healthcare Stocks Growth"
symbols = ['UTHR', 'AXSM', 'CCXI']
start = '2020-04-01'
end = '2020-07-09'
df = pd.DataFrame()
for s in symbols:
df[s] = yf.download(s,start,end)['Adj Close']
from datetime import datetime
from dateutil import relativedelta
d1 = datetime.strptime(start, "%Y-%m-%d")
d2 = datetime.strptime(end, "%Y-%m-%d")
delta = relativedelta.relativedelta(d2,d1)
print('How many years of investing?')
print('%s years' % delta.years)
number_of_years = delta.years
days = (df.index[-1] - df.index[0]).days
days
df.head()
df.tail()
plt.figure(figsize=(12,8))
plt.plot(df)
plt.title(title + ' Closing Price')
plt.legend(labels=df.columns)
# Normalize the data
normalize = (df - df.min())/ (df.max() - df.min())
plt.figure(figsize=(18,12))
plt.plot(normalize)
plt.title(title + ' Stocks Normalize')
plt.legend(labels=normalize.columns)
stock_rets = df.pct_change().dropna()
plt.figure(figsize=(12,8))
plt.plot(stock_rets)
plt.title(title + ' Stocks Returns')
plt.legend(labels=stock_rets.columns)
plt.figure(figsize=(12,8))
plt.plot(stock_rets.cumsum())
plt.title(title + ' Stocks Returns Cumulative Sum')
plt.legend(labels=stock_rets.columns)
sns.set(style='ticks')
ax = sns.pairplot(stock_rets, diag_kind='hist')
nplot = len(stock_rets.columns)
for i in range(nplot) :
for j in range(nplot) :
ax.axes[i, j].locator_params(axis='x', nbins=6, tight=True)
ax = sns.PairGrid(stock_rets)
ax.map_upper(plt.scatter, color='purple')
ax.map_lower(sns.kdeplot, color='blue')
ax.map_diag(plt.hist, bins=30)
for i in range(nplot) :
for j in range(nplot) :
ax.axes[i, j].locator_params(axis='x', nbins=6, tight=True)
plt.figure(figsize=(10,10))
corr = stock_rets.corr()
# plot the heatmap
sns.heatmap(corr,
xticklabels=corr.columns,
yticklabels=corr.columns,
cmap="Reds")
# Box plot
stock_rets.plot(kind='box',figsize=(24,8))
rets = stock_rets.dropna()
plt.figure(figsize=(16,8))
plt.scatter(rets.std(), rets.mean(),alpha = 0.5)
plt.title('Stocks Risk & Returns')
plt.xlabel('Risk')
plt.ylabel('Expected Returns')
plt.grid(which='major')
for label, x, y in zip(rets.columns, rets.std(), rets.mean()):
plt.annotate(
label,
xy = (x, y), xytext = (50, 50),
textcoords = 'offset points', ha = 'right', va = 'bottom',
arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3'))
rets = stock_rets.dropna()
area = np.pi*20.0
sns.set(style='darkgrid')
plt.figure(figsize=(16,8))
plt.scatter(rets.std(), rets.mean(), s=area)
plt.xlabel("Risk", fontsize=15)
plt.ylabel("Expected Return", fontsize=15)
plt.title("Return vs. Risk for Stocks", fontsize=20)
for label, x, y in zip(rets.columns, rets.std(), rets.mean()) :
plt.annotate(label, xy=(x,y), xytext=(50, 0), textcoords='offset points',
arrowprops=dict(arrowstyle='-', connectionstyle='bar,angle=180,fraction=-0.2'),
bbox=dict(boxstyle="round", fc="w"))
def annual_risk_return(stock_rets):
tradeoff = stock_rets.agg(["mean", "std"]).T
tradeoff.columns = ["Return", "Risk"]
tradeoff.Return = tradeoff.Return*252
tradeoff.Risk = tradeoff.Risk * np.sqrt(252)
return tradeoff
tradeoff = annual_risk_return(stock_rets)
tradeoff
import itertools
colors = itertools.cycle(["r", "b", "g"])
tradeoff.plot(x = "Risk", y = "Return", kind = "scatter", figsize = (13,9), s = 20, fontsize = 15, c='g')
for i in tradeoff.index:
plt.annotate(i, xy=(tradeoff.loc[i, "Risk"]+0.002, tradeoff.loc[i, "Return"]+0.002), size = 15)
plt.xlabel("Annual Risk", fontsize = 15)
plt.ylabel("Annual Return", fontsize = 15)
plt.title("Return vs. Risk for " + title + " Stocks", fontsize = 20)
plt.show()
rest_rets = rets.corr()
pair_value = rest_rets.abs().unstack()
pair_value.sort_values(ascending = False)
# Normalized Returns Data
Normalized_Value = ((rets[:] - rets[:].min()) /(rets[:].max() - rets[:].min()))
Normalized_Value.head()
Normalized_Value.corr()
normalized_rets = Normalized_Value.corr()
normalized_pair_value = normalized_rets.abs().unstack()
normalized_pair_value.sort_values(ascending = False)
print("Stock returns: ")
print(rets.mean())
print('-' * 50)
print("Stock risks:")
print(rets.std())
table = pd.DataFrame()
table['Returns'] = rets.mean()
table['Risk'] = rets.std()
table.sort_values(by='Returns')
table.sort_values(by='Risk')
rf = 0.01
table['Sharpe Ratio'] = (table['Returns'] - rf) / table['Risk']
table
table['Max Returns'] = rets.max()
table['Min Returns'] = rets.min()
table['Median Returns'] = rets.median()
total_return = stock_rets[-1:].transpose()
table['Total Return'] = 100 * total_return
table
table['Average Return Days'] = (1 + total_return)**(1 / days) - 1
table
initial_value = df.iloc[0]
ending_value = df.iloc[-1]
table['CAGR'] = ((ending_value / initial_value) ** (252.0 / days)) -1
table
table.sort_values(by='Average Return Days')
```
| github_jupyter |
# Direct Search Optimiser Example
The Direct Search Optimiser module is used to optimise the thresholds of an existing set of rules, given a labelled dataset, using Direct Search-type Optimisation algorithms.
## Requirements
To run, you'll need the following:
* A rule set stored in the standard Iguanas lambda expression format, along with the keyword arguments for each lambda expression (more information on how to do this later)
* A labelled dataset containing the features present in the rule set.
----
### Import packages
```
from iguanas.rule_optimisation import DirectSearchOptimiser
from iguanas.rules import Rules
from iguanas.rule_application import RuleApplier
from iguanas.metrics.classification import FScore
import pandas as pd
from sklearn.model_selection import train_test_split
```
### Read in data
Firstly, we need to read in the raw data containing the features and the fraud label:
```
data = pd.read_csv(
'dummy_data/dummy_pipeline_output_data.csv',
index_col='eid'
)
```
Then we need to split out the dataset into the features (`X`) and the target column (`y`):
```
fraud_column = 'sim_is_fraud'
X = data.drop(fraud_column, axis=1)
y = data[fraud_column]
```
Finally, we can split the features and target column into training and test sets:
```
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.33,
random_state=0
)
```
## Read in the rules
In this example, we'll read in the rule conditions from a pickle file, where they are stored in the standard Iguanas string format. However, you can use any Iguanas-ready rule format - see the example notebook in the `rules` module.
```
import pickle
with open('dummy_data/rule_strings.pkl', 'rb') as f:
rule_strings = pickle.load(f)
```
Now we can instantiate the `Rules` class with these rules:
```
rules = Rules(rule_strings=rule_strings)
```
We now need to convert the rules into the standard Iguanas lambda expression format. This format allows new threshold values to be injected into the rule condition before being evaluated - this is how the Bayesian Optimiser finds the optimal threshold values:
```
rule_lambdas = rules.as_rule_lambdas(
as_numpy=False,
with_kwargs=True
)
```
By converting the rule conditions to the standard Iguanas lambda expression format, we also generate a dictionary which gives the keyword arguments to each lambda expression (this dictionary is saved as the class attribute `lambda_kwargs`). Using these keyword arguments as inputs to the lambda expressions will convert them into the standard Iguanas string format.
----
## Optimise rules
### Set up class parameters
Now we can set our class parameters for the Direct Search Optimiser.
Here we're using the F1 score as the optimisation function (you can choose a different function from the `metrics` module or create your own - see the `classification.ipynb` example notebook in the `metrics` module).
**Note that if you're using the FScore, Precision or Recall score as the optimisation function, use the *FScore*, *Precision* or *Recall* classes in the *metrics.classification* module rather than the same functions from Sklearn's *metrics* module, as the former are ~100 times faster on larger datasets.**
We're also using the `Nelder-Mead` algorithm, which often benefits from setting the optional `initial_simplex` parameter. This is set through the `options` keyword argument. Here, we'll generate the initial simplex of each rule using the `create_initial_simplexes` method (but you can create your own if required).
**Please see the class docstring for more information on each parameter.**
```
f1 = FScore(beta=1)
initial_simplexes = DirectSearchOptimiser.create_initial_simplexes(
X=X_train,
lambda_kwargs=rules.lambda_kwargs,
shape='Minimum-based'
)
params = {
'rule_lambdas': rule_lambdas,
'lambda_kwargs': rules.lambda_kwargs,
'metric': f1.fit,
'method': 'Nelder-Mead',
'options': initial_simplexes,
'verbose': 1,
}
```
### Instantiate class and run fit method
Once the parameters have been set, we can run the `fit` method to optimise the rules.
```
ro = DirectSearchOptimiser(**params)
X_rules = ro.fit(
X=X_train,
y=y_train,
sample_weight=None
)
```
### Outputs
The `fit` method returns a dataframe giving the binary columns of the optimised + unoptimisable (but applicable) rules as applied to the training dataset. See the `Attributes` section in the class docstring for a description of each attribute generated:
```
X_rules.head()
ro.opt_rule_performances
```
----
## Apply rules to a separate dataset
Use the `transform` method to apply the optimised rules to a separate dataset:
```
X_rules_test = ro.transform(X=X_test)
```
### Outputs
The `transform` method returns a dataframe giving the binary columns of the rules as applied to the given dataset:
```
X_rules_test.head()
```
---
## Plotting the performance uplift
We can visualise the performance uplift of the optimised rules using the `plot_performance_uplift` and `plot_performance_uplift_distribution` methods:
* `plot_performance_uplift`: Generates a scatterplot showing the performance of each rule before and after optimisation.
* `plot_performance_uplift_distribution`: Generates a boxplot showing the distribution of performance uplifts (original rules vs optimised rules).
### On the training set
To visualise the uplift on the training set, we can use the class attributes `orig_rule_performances` and `opt_rule_performances` in the plotting methods, as these were generated as part of the optimisation process:
```
ro.plot_performance_uplift(
orig_rule_performances=ro.orig_rule_performances,
opt_rule_performances=ro.opt_rule_performances,
figsize=(10, 5)
)
ro.plot_performance_uplift_distribution(
orig_rule_performances=ro.orig_rule_performances,
opt_rule_performances=ro.opt_rule_performances,
figsize=(3, 7)
)
```
### On the test set
To visualise the uplift on the test set, we first need to generate the `orig_rule_performances` and `opt_rule_performances` parameters used in the plotting methods as these aren't created as part of the optimisation process. To do this, we need to apply both the original rules and the optimised rules to the test set.
**Note:** before we apply the original rules, we need to remove those that either have no optimisable conditions, have zero variance features or have features that are missing in `X_train`:
```
# Original rules
rules_to_exclude = ro.rule_names_missing_features + ro.rule_names_no_opt_conditions + ro.rule_names_zero_var_features
rules.filter_rules(exclude=rules_to_exclude)
orig_X_rules = rules.transform(X_test)
orig_f1s = f1.fit(orig_X_rules, y_test)
orig_rule_performances_test = dict(zip(orig_X_rules.columns.tolist(), orig_f1s))
# Optimised rules
opt_X_rules = ro.transform(X_test)
opt_f1s = f1.fit(opt_X_rules, y_test)
opt_rule_performances_test = dict(zip(opt_X_rules.columns.tolist(), opt_f1s))
ro.plot_performance_uplift(
orig_rule_performances=orig_rule_performances_test,
opt_rule_performances=opt_rule_performances_test,
figsize=(10, 5)
)
ro.plot_performance_uplift_distribution(
orig_rule_performances=orig_rule_performances_test,
opt_rule_performances=opt_rule_performances_test,
figsize=(3, 7)
)
```
----
| github_jupyter |
# Tools - NumPy
NumPy is a library for scientific computing with Python. NumPy is centered around a powerful N-dimensional array object, and it also contains useful linear algebra, Fourier transform, and random number functions.
```
import numpy as np
```
## Creating Arrays
```
#np.zeros
arr = np.zeros([5,3])
arr
#np.ones
arr = np.ones([5,3])
arr
#np.full - tuple + value
arr = np.full([2,2],5)
arr
#np.empty
arr = np.empty((2,4))
arr
# Creating an identity matrix
np.eye(3,3)
#np.array
np.array([2,3,4])
#np.arange - two args and three args
np.arange(100,1,-5)
#np.linspace
np.linspace(0,10,6)
#np.random.rand and np.random.randn
uniform = np.random.rand(1000) #random number between 0 and 1 - probability of getting same probability
normal = np.random.randn(100) #
print(uniform.mean())
print(normal.mean())
```
Some vocabulary
In NumPy, each dimension is called an axis.
The number of axes is called the rank.
For example, the above 3x4 matrix is an array of rank 2 (it is 2-dimensional).
The first axis has length 3, the second has length 4.
An array's list of axis lengths is called the shape of the array.
For example, the above matrix's shape is (3, 4).
The rank is equal to the shape's length.
The size of an array is the total number of elements, which is the product of all axis lengths (eg. 3*4=12)
## Examining Properties
```
#arr.shape
np.shape(arr)
#arr.ndim - equal to len(a.shape)
arr1 = np.full(5,5)
arr2 = np.full(5,9)
np.stack([arr1,arr2])
#arr.size
np.size(arr)
##arr.dtype
arr.dtype
```
## Reshaping an Array
```
#arr.shape
arr = np.arange(1,13)
#print(arr, np.size(arr))
#2X6, 3X4, 4X3
arr.shape = (3,2,2)
print(arr,np.size(arr))
arr2 = arr.reshape(3,4)
# arr1 = np.linspace(1,10,9)
# print(arr)
# np.size(arr)
#arr.reshape
np.size(arr.reshape([3,4]))
arr1.reshape(3,3)
```
## Arithmatic Operations
```
a = np.array([14, 23, 32, 41])
b = np.array([5, 4, 3, 2])
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a // b =", a // b)
print("a % b =", a % b)
print("a ** b =", a ** b)
```
## Broadcasting - broad + casting

```
arr1 = np.full(3,5)
print('arr1', arr1,np.shape(arr1))
arr2 = np.full((2,3),1)
print('arr2',arr2,np.shape(arr2))
print(arr1+arr2)
print(arr2+2)
```
## Logical Operators
```
arr = np.array([3,25,27,89])
arr > 25
# arr > [1,2,45,3]
arr[arr>25]
```
## Mathematical and Statistical Functions
```
arr.mean()
arr = np.random.rand(999)
arr.shape = (3,3,111)
arr.mean()
arr.add()
# arr.square()
# np.square(arr)
```
## Indexing
```
lst = [1,2,3,4,5,6]
print(lst[3:5])
arr = np.random.rand(9)
arr.shape = (3,3)
print(arr)
arr[1:,:2]
```
## difference between regular python arrays and numpy arrays
```
lst = [1,2,3,4,5,6]
new_lst = lst[3:5]
print(new_lst)
new_lst[0] = 22
print(new_lst)
print(lst)
arr = np.array([1,2,3,4,5,6])
new_arr = arr[3:5]
print(new_arr)
new_arr[0] = 22
print(new_arr)
print(arr)
```
## Linear Algebra
```
#Dot product
import numpy.linalg as linalg
#Calculating inv
linalg.inv(arr)
#Finding the identity matrix - dot product of inv of the matrix with itself. How would you do it?
```
## Why numpy?
```
def multiply_loops(A, B):
c = np.zeros((A.shape[0], B.shape[1]))
for i in range(A.shape[1]):
for j in range(B.shape[0]):
c[i,j] = A[i,j] * B[j,i]
return c
def multiply_vector(A, B):
return A @ B
X = np.random.random((100, 100))
Y = np.random.random((100, 100))
%timeit multiply_loops(X, Y)
%timeit multiply_vector(X, Y)
def func1(num1,num2):
return num1+num2
def func2(num1,num2):
print (num1+num2)
%timeit func1(2,3)
%timeit func2(2,3)
```
## Reading from files
```
import numpy as np
import os
import pandas as pd
# defining housing.csv file path
HOUSING_PATH = './'
# reading the large housing.csv file using pandas
housing_raw = pd.read_csv(os.path.join(HOUSING_PATH, "housing.csv"))
# extracting only a few rows (5 rows) of data from the pandas dataframe 'my_df'
my_df = housing_raw.iloc[ : 5]
# creating a new small csv file - 'housing_short.csv' - containing the above extracted 5 rows of data
my_df.to_csv('housing_short.csv', index=False)
import numpy as np
import os
FILE = 'housing_short.csv'
def load_housing_data(file = FILE ):
return np.loadtxt(file, dtype={'names': ('longitude','latitude','housing_median_age','total_rooms','total_bedrooms','population','households','median_income','median_house_value','ocean_proximity'),'formats': ('f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', '|S15')}, delimiter=',', skiprows=1, unpack=True)
longitude_arr,latitude_arr,housing_median_age_arr,total_rooms_arr,total_bedrooms_arr,population_arr,households_arr,median_income_arr,median_house_value_arr,ocean_proximity_arr = load_housing_data()
print(median_house_value_arr, type(median_house_value_arr))
```
| github_jupyter |
# Name
Batch prediction using Cloud Machine Learning Engine
# Label
Cloud Storage, Cloud ML Engine, Kubeflow, Pipeline, Component
# Summary
A Kubeflow Pipeline component to submit a batch prediction job against a deployed model on Cloud ML Engine.
# Details
## Intended use
Use the component to run a batch prediction job against a deployed model on Cloud ML Engine. The prediction output is stored in a Cloud Storage bucket.
## Runtime arguments
| Argument | Description | Optional | Data type | Accepted values | Default |
|--------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|--------------|-----------------|---------|
| project_id | The ID of the Google Cloud Platform (GCP) project of the job. | No | GCPProjectID | | |
| model_path | The path to the model. It can be one of the following:<br/> <ul> <li>projects/[PROJECT_ID]/models/[MODEL_ID]</li> <li>projects/[PROJECT_ID]/models/[MODEL_ID]/versions/[VERSION_ID]</li> <li>The path to a Cloud Storage location containing a model file.</li> </ul> | No | GCSPath | | |
| input_paths | The path to the Cloud Storage location containing the input data files. It can contain wildcards, for example, `gs://foo/*.csv` | No | List | GCSPath | |
| input_data_format | The format of the input data files. See [REST Resource: projects.jobs](https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#DataFormat) for more details. | No | String | DataFormat | |
| output_path | The path to the Cloud Storage location for the output data. | No | GCSPath | | |
| region | The Compute Engine region where the prediction job is run. | No | GCPRegion | | |
| output_data_format | The format of the output data files. See [REST Resource: projects.jobs](https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#DataFormat) for more details. | Yes | String | DataFormat | JSON |
| prediction_input | The JSON input parameters to create a prediction job. See [PredictionInput](https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#PredictionInput) for more information. | Yes | Dict | | None |
| job_id_prefix | The prefix of the generated job id. | Yes | String | | None |
| wait_interval | The number of seconds to wait in case the operation has a long run time. | Yes | | | 30 |
## Input data schema
The component accepts the following as input:
* A trained model: It can be a model file in Cloud Storage, a deployed model, or a version in Cloud ML Engine. Specify the path to the model in the `model_path `runtime argument.
* Input data: The data used to make predictions against the trained model. The data can be in [multiple formats](https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#DataFormat). The data path is specified by `input_paths` and the format is specified by `input_data_format`.
## Output
Name | Description | Type
:--- | :---------- | :---
job_id | The ID of the created batch job. | String
output_path | The output path of the batch prediction job | GCSPath
## Cautions & requirements
To use the component, you must:
* Set up a cloud environment by following this [guide](https://cloud.google.com/ml-engine/docs/tensorflow/getting-started-training-prediction#setup).
* Run the component under a secret [Kubeflow user service account](https://www.kubeflow.org/docs/started/getting-started-gke/#gcp-service-accounts) in a Kubeflow cluster. For example:
```python
mlengine_predict_op(...).apply(gcp.use_gcp_secret('user-gcp-sa'))
```
* Grant the following types of access to the Kubeflow user service account:
* Read access to the Cloud Storage buckets which contains the input data.
* Write access to the Cloud Storage bucket of the output directory.
## Detailed description
Follow these steps to use the component in a pipeline:
1. Install the Kubeflow Pipeline SDK:
```
%%capture --no-stderr
KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.14/kfp.tar.gz'
!pip3 install $KFP_PACKAGE --upgrade
```
2. Load the component using KFP SDK
```
import kfp.components as comp
mlengine_batch_predict_op = comp.load_component_from_url(
'https://raw.githubusercontent.com/kubeflow/pipelines/e7a021ed1da6b0ff21f7ba30422decbdcdda0c20/components/gcp/ml_engine/batch_predict/component.yaml')
help(mlengine_batch_predict_op)
```
### Sample Code
Note: The following sample code works in an IPython notebook or directly in Python code.
In this sample, you batch predict against a pre-built trained model from `gs://ml-pipeline-playground/samples/ml_engine/census/trained_model/` and use the test data from `gs://ml-pipeline-playground/samples/ml_engine/census/test.json`.
#### Inspect the test data
```
!gsutil cat gs://ml-pipeline-playground/samples/ml_engine/census/test.json
```
#### Set sample parameters
```
# Required Parameters
PROJECT_ID = '<Please put your project ID here>'
GCS_WORKING_DIR = 'gs://<Please put your GCS path here>' # No ending slash
# Optional Parameters
EXPERIMENT_NAME = 'CLOUDML - Batch Predict'
OUTPUT_GCS_PATH = GCS_WORKING_DIR + '/batch_predict/output/'
```
#### Example pipeline that uses the component
```
import kfp.dsl as dsl
import kfp.gcp as gcp
import json
@dsl.pipeline(
name='CloudML batch predict pipeline',
description='CloudML batch predict pipeline'
)
def pipeline(
project_id = PROJECT_ID,
model_path = 'gs://ml-pipeline-playground/samples/ml_engine/census/trained_model/',
input_paths = '["gs://ml-pipeline-playground/samples/ml_engine/census/test.json"]',
input_data_format = 'JSON',
output_path = OUTPUT_GCS_PATH,
region = 'us-central1',
output_data_format='',
prediction_input = json.dumps({
'runtimeVersion': '1.10'
}),
job_id_prefix='',
wait_interval='30'):
mlengine_batch_predict_op(
project_id=project_id,
model_path=model_path,
input_paths=input_paths,
input_data_format=input_data_format,
output_path=output_path,
region=region,
output_data_format=output_data_format,
prediction_input=prediction_input,
job_id_prefix=job_id_prefix,
wait_interval=wait_interval).apply(gcp.use_gcp_secret('user-gcp-sa'))
```
#### Compile the pipeline
```
pipeline_func = pipeline
pipeline_filename = pipeline_func.__name__ + '.zip'
import kfp.compiler as compiler
compiler.Compiler().compile(pipeline_func, pipeline_filename)
```
#### Submit the pipeline for execution
```
#Specify pipeline argument values
arguments = {}
#Get or create an experiment and submit a pipeline run
import kfp
client = kfp.Client()
experiment = client.create_experiment(EXPERIMENT_NAME)
#Submit a pipeline run
run_name = pipeline_func.__name__ + ' run'
run_result = client.run_pipeline(experiment.id, run_name, pipeline_filename, arguments)
```
#### Inspect prediction results
```
OUTPUT_FILES_PATTERN = OUTPUT_GCS_PATH + '*'
!gsutil cat OUTPUT_FILES_PATTERN
```
## References
* [Component python code](https://github.com/kubeflow/pipelines/blob/master/components/gcp/container/component_sdk/python/kfp_component/google/ml_engine/_batch_predict.py)
* [Component docker file](https://github.com/kubeflow/pipelines/blob/master/components/gcp/container/Dockerfile)
* [Sample notebook](https://github.com/kubeflow/pipelines/blob/master/components/gcp/ml_engine/batch_predict/sample.ipynb)
* [Cloud Machine Learning Engine job REST API](https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs)
## License
By deploying or using this software you agree to comply with the [AI Hub Terms of Service](https://aihub.cloud.google.com/u/0/aihub-tos) and the [Google APIs Terms of Service](https://developers.google.com/terms/). To the extent of a direct conflict of terms, the AI Hub Terms of Service will control.
| github_jupyter |
# Deep Neural Network for Image Classification: Application
When you finish this, you will have finished the last programming assignment of Week 4, and also the last programming assignment of this course!
You will use the functions you'd implemented in the previous assignment to build a deep network, and apply it to cat vs non-cat classification. Hopefully, you will see an improvement in accuracy relative to your previous logistic regression implementation.
**After this assignment you will be able to:**
- Build and apply a deep neural network to supervised learning.
Let's get started!
## 1 - Packages
Let's first import all the packages that you will need during this assignment.
- [numpy](https://www.numpy.org/) is the fundamental package for scientific computing with Python.
- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.
- [h5py](http://www.h5py.org) is a common package to interact with a dataset that is stored on an H5 file.
- [PIL](http://www.pythonware.com/products/pil/) and [scipy](https://www.scipy.org/) are used here to test your model with your own picture at the end.
- dnn_app_utils provides the functions implemented in the "Building your Deep Neural Network: Step by Step" assignment to this notebook.
- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work.
```
import time
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from dnn_app_utils_v3 import *
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
np.random.seed(1)
```
## 2 - Dataset
You will use the same "Cat vs non-Cat" dataset as in "Logistic Regression as a Neural Network" (Assignment 2). The model you had built had 70% test accuracy on classifying cats vs non-cats images. Hopefully, your new model will perform a better!
**Problem Statement**: You are given a dataset ("data.h5") containing:
- a training set of m_train images labelled as cat (1) or non-cat (0)
- a test set of m_test images labelled as cat and non-cat
- each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB).
Let's get more familiar with the dataset. Load the data by running the cell below.
```
train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
```
The following code will show you an image in the dataset. Feel free to change the index and re-run the cell multiple times to see other images.
```
# Example of a picture
index = 10
plt.imshow(train_x_orig[index])
print ("y = " + str(train_y[0,index]) + ". It's a " + classes[train_y[0,index]].decode("utf-8") + " picture.")
# Explore your dataset
m_train = train_x_orig.shape[0]
num_px = train_x_orig.shape[1]
m_test = test_x_orig.shape[0]
print ("Number of training examples: " + str(m_train))
print ("Number of testing examples: " + str(m_test))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_x_orig shape: " + str(train_x_orig.shape))
print ("train_y shape: " + str(train_y.shape))
print ("test_x_orig shape: " + str(test_x_orig.shape))
print ("test_y shape: " + str(test_y.shape))
```
As usual, you reshape and standardize the images before feeding them to the network. The code is given in the cell below.
<img src="images/imvectorkiank.png" style="width:450px;height:300px;">
<caption><center> <u>Figure 1</u>: Image to vector conversion. <br> </center></caption>
```
# Reshape the training and test examples
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The "-1" makes reshape flatten the remaining dimensions
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
# Standardize data to have feature values between 0 and 1.
train_x = train_x_flatten/255.
test_x = test_x_flatten/255.
print ("train_x's shape: " + str(train_x.shape))
print ("test_x's shape: " + str(test_x.shape))
```
$12,288$ equals $64 \times 64 \times 3$ which is the size of one reshaped image vector.
## 3 - Architecture of your model
Now that you are familiar with the dataset, it is time to build a deep neural network to distinguish cat images from non-cat images.
You will build two different models:
- A 2-layer neural network
- An L-layer deep neural network
You will then compare the performance of these models, and also try out different values for $L$.
Let's look at the two architectures.
### 3.1 - 2-layer neural network
<img src="images/2layerNN_kiank.png" style="width:650px;height:400px;">
<caption><center> <u>Figure 2</u>: 2-layer neural network. <br> The model can be summarized as: ***INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT***. </center></caption>
<u>Detailed Architecture of figure 2</u>:
- The input is a (64,64,3) image which is flattened to a vector of size $(12288,1)$.
- The corresponding vector: $[x_0,x_1,...,x_{12287}]^T$ is then multiplied by the weight matrix $W^{[1]}$ of size $(n^{[1]}, 12288)$.
- You then add a bias term and take its relu to get the following vector: $[a_0^{[1]}, a_1^{[1]},..., a_{n^{[1]}-1}^{[1]}]^T$.
- You then repeat the same process.
- You multiply the resulting vector by $W^{[2]}$ and add your intercept (bias).
- Finally, you take the sigmoid of the result. If it is greater than 0.5, you classify it to be a cat.
### 3.2 - L-layer deep neural network
It is hard to represent an L-layer deep neural network with the above representation. However, here is a simplified network representation:
<img src="images/LlayerNN_kiank.png" style="width:650px;height:400px;">
<caption><center> <u>Figure 3</u>: L-layer neural network. <br> The model can be summarized as: ***[LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID***</center></caption>
<u>Detailed Architecture of figure 3</u>:
- The input is a (64,64,3) image which is flattened to a vector of size (12288,1).
- The corresponding vector: $[x_0,x_1,...,x_{12287}]^T$ is then multiplied by the weight matrix $W^{[1]}$ and then you add the intercept $b^{[1]}$. The result is called the linear unit.
- Next, you take the relu of the linear unit. This process could be repeated several times for each $(W^{[l]}, b^{[l]})$ depending on the model architecture.
- Finally, you take the sigmoid of the final linear unit. If it is greater than 0.5, you classify it to be a cat.
### 3.3 - General methodology
As usual you will follow the Deep Learning methodology to build the model:
1. Initialize parameters / Define hyperparameters
2. Loop for num_iterations:
a. Forward propagation
b. Compute cost function
c. Backward propagation
d. Update parameters (using parameters, and grads from backprop)
4. Use trained parameters to predict labels
Let's now implement those two models!
## 4 - Two-layer neural network
**Question**: Use the helper functions you have implemented in the previous assignment to build a 2-layer neural network with the following structure: *LINEAR -> RELU -> LINEAR -> SIGMOID*. The functions you may need and their inputs are:
```python
def initialize_parameters(n_x, n_h, n_y):
...
return parameters
def linear_activation_forward(A_prev, W, b, activation):
...
return A, cache
def compute_cost(AL, Y):
...
return cost
def linear_activation_backward(dA, cache, activation):
...
return dA_prev, dW, db
def update_parameters(parameters, grads, learning_rate):
...
return parameters
```
```
### CONSTANTS DEFINING THE MODEL ####
n_x = 12288 # num_px * num_px * 3
n_h = 7
n_y = 1
layers_dims = (n_x, n_h, n_y)
# GRADED FUNCTION: two_layer_model
def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
"""
Implements a two-layer neural network: LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (n_x, number of examples)
Y -- true "label" vector (containing 1 if cat, 0 if non-cat), of shape (1, number of examples)
layers_dims -- dimensions of the layers (n_x, n_h, n_y)
num_iterations -- number of iterations of the optimization loop
learning_rate -- learning rate of the gradient descent update rule
print_cost -- If set to True, this will print the cost every 100 iterations
Returns:
parameters -- a dictionary containing W1, W2, b1, and b2
"""
np.random.seed(1)
grads = {}
costs = [] # to keep track of the cost
m = X.shape[1] # number of examples
(n_x, n_h, n_y) = layers_dims
# Initialize parameters dictionary, by calling one of the functions you'd previously implemented
### START CODE HERE ### (≈ 1 line of code)
parameters = None
### END CODE HERE ###
# Get W1, b1, W2 and b2 from the dictionary parameters.
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: LINEAR -> RELU -> LINEAR -> SIGMOID. Inputs: "X, W1, b1, W2, b2". Output: "A1, cache1, A2, cache2".
### START CODE HERE ### (≈ 2 lines of code)
A1, cache1 = None
A2, cache2 = None
### END CODE HERE ###
# Compute cost
### START CODE HERE ### (≈ 1 line of code)
cost = None
### END CODE HERE ###
# Initializing backward propagation
dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
# Backward propagation. Inputs: "dA2, cache2, cache1". Outputs: "dA1, dW2, db2; also dA0 (not used), dW1, db1".
### START CODE HERE ### (≈ 2 lines of code)
dA1, dW2, db2 = None
dA0, dW1, db1 = None
### END CODE HERE ###
# Set grads['dWl'] to dW1, grads['db1'] to db1, grads['dW2'] to dW2, grads['db2'] to db2
grads['dW1'] = dW1
grads['db1'] = db1
grads['dW2'] = dW2
grads['db2'] = db2
# Update parameters.
### START CODE HERE ### (approx. 1 line of code)
parameters = None
### END CODE HERE ###
# Retrieve W1, b1, W2, b2 from parameters
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Print the cost every 100 training example
if print_cost and i % 100 == 0:
print("Cost after iteration {}: {}".format(i, np.squeeze(cost)))
if print_cost and i % 100 == 0:
costs.append(cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
```
Run the cell below to train your parameters. See if your model runs. The cost should be decreasing. It may take up to 5 minutes to run 2500 iterations. Check if the "Cost after iteration 0" matches the expected output below, if not click on the square (⬛) on the upper bar of the notebook to stop the cell and try to find your error.
```
parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True)
```
**Expected Output**:
<table>
<tr>
<td> **Cost after iteration 0**</td>
<td> 0.6930497356599888 </td>
</tr>
<tr>
<td> **Cost after iteration 100**</td>
<td> 0.6464320953428849 </td>
</tr>
<tr>
<td> **...**</td>
<td> ... </td>
</tr>
<tr>
<td> **Cost after iteration 2400**</td>
<td> 0.048554785628770226 </td>
</tr>
</table>
Good thing you built a vectorized implementation! Otherwise it might have taken 10 times longer to train this.
Now, you can use the trained parameters to classify images from the dataset. To see your predictions on the training and test sets, run the cell below.
```
predictions_train = predict(train_x, train_y, parameters)
```
**Expected Output**:
<table>
<tr>
<td> **Accuracy**</td>
<td> 1.0 </td>
</tr>
</table>
```
predictions_test = predict(test_x, test_y, parameters)
```
**Expected Output**:
<table>
<tr>
<td> **Accuracy**</td>
<td> 0.72 </td>
</tr>
</table>
**Note**: You may notice that running the model on fewer iterations (say 1500) gives better accuracy on the test set. This is called "early stopping" and we will talk about it in the next course. Early stopping is a way to prevent overfitting.
Congratulations! It seems that your 2-layer neural network has better performance (72%) than the logistic regression implementation (70%, assignment week 2). Let's see if you can do even better with an $L$-layer model.
## 5 - L-layer Neural Network
**Question**: Use the helper functions you have implemented previously to build an $L$-layer neural network with the following structure: *[LINEAR -> RELU]$\times$(L-1) -> LINEAR -> SIGMOID*. The functions you may need and their inputs are:
```python
def initialize_parameters_deep(layers_dims):
...
return parameters
def L_model_forward(X, parameters):
...
return AL, caches
def compute_cost(AL, Y):
...
return cost
def L_model_backward(AL, Y, caches):
...
return grads
def update_parameters(parameters, grads, learning_rate):
...
return parameters
```
```
### CONSTANTS ###
layers_dims = [12288, 20, 7, 5, 1] # 4-layer model
# GRADED FUNCTION: L_layer_model
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
"""
Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
Arguments:
X -- data, numpy array of shape (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).
learning_rate -- learning rate of the gradient descent update rule
num_iterations -- number of iterations of the optimization loop
print_cost -- if True, it prints the cost every 100 steps
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
np.random.seed(1)
costs = [] # keep track of cost
# Parameters initialization. (≈ 1 line of code)
### START CODE HERE ###
parameters = None
### END CODE HERE ###
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
### START CODE HERE ### (≈ 1 line of code)
AL, caches = None
### END CODE HERE ###
# Compute cost.
### START CODE HERE ### (≈ 1 line of code)
cost = None
### END CODE HERE ###
# Backward propagation.
### START CODE HERE ### (≈ 1 line of code)
grads = None
### END CODE HERE ###
# Update parameters.
### START CODE HERE ### (≈ 1 line of code)
parameters = None
### END CODE HERE ###
# Print the cost every 100 training example
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
if print_cost and i % 100 == 0:
costs.append(cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
```
You will now train the model as a 4-layer neural network.
Run the cell below to train your model. The cost should decrease on every iteration. It may take up to 5 minutes to run 2500 iterations. Check if the "Cost after iteration 0" matches the expected output below, if not click on the square (⬛) on the upper bar of the notebook to stop the cell and try to find your error.
```
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)
```
**Expected Output**:
<table>
<tr>
<td> **Cost after iteration 0**</td>
<td> 0.771749 </td>
</tr>
<tr>
<td> **Cost after iteration 100**</td>
<td> 0.672053 </td>
</tr>
<tr>
<td> **...**</td>
<td> ... </td>
</tr>
<tr>
<td> **Cost after iteration 2400**</td>
<td> 0.092878 </td>
</tr>
</table>
```
pred_train = predict(train_x, train_y, parameters)
```
<table>
<tr>
<td>
**Train Accuracy**
</td>
<td>
0.985645933014
</td>
</tr>
</table>
```
pred_test = predict(test_x, test_y, parameters)
```
**Expected Output**:
<table>
<tr>
<td> **Test Accuracy**</td>
<td> 0.8 </td>
</tr>
</table>
Congrats! It seems that your 4-layer neural network has better performance (80%) than your 2-layer neural network (72%) on the same test set.
This is good performance for this task. Nice job!
Though in the next course on "Improving deep neural networks" you will learn how to obtain even higher accuracy by systematically searching for better hyperparameters (learning_rate, layers_dims, num_iterations, and others you'll also learn in the next course).
## 6) Results Analysis
First, let's take a look at some images the L-layer model labeled incorrectly. This will show a few mislabeled images.
```
print_mislabeled_images(classes, test_x, test_y, pred_test)
```
**A few types of images the model tends to do poorly on include:**
- Cat body in an unusual position
- Cat appears against a background of a similar color
- Unusual cat color and species
- Camera Angle
- Brightness of the picture
- Scale variation (cat is very large or small in image)
## 7) Test with your own image (optional/ungraded exercise) ##
Congratulations on finishing this assignment. You can use your own image and see the output of your model. To do that:
1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub.
2. Add your image to this Jupyter Notebook's directory, in the "images" folder
3. Change your image's name in the following code
4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)!
```
## START CODE HERE ##
my_image = "my_image.jpg" # change this to the name of your image file
my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
## END CODE HERE ##
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))
my_image = my_image/255.
my_predicted_image = predict(my_image, my_label_y, parameters)
plt.imshow(image)
print ("y = " + str(np.squeeze(my_predicted_image)) + ", your L-layer model predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
```
**References**:
- for auto-reloading external module: http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
| github_jupyter |
<a href="https://colab.research.google.com/github/yohanesnuwara/mem/blob/master/altmann2010_poroelasticity.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import numpy as np
import matplotlib.pyplot as plt
import scipy
```
Radius to reservoir from wellbore ranging from 0 to 500 m, in a sandstone reservoir
```
r = np.arange(0, 5010, 10) # radius, m
year = 1
t = year * (3.154E+7) # time, seconds in year
# knowns from Altmann paper
Kd = 12 # drained bulk modulus, GPa
Kg = 40 # grain bulk modulus, GPa
G = 5.5 # shear modulus, GPa
Kf = 2 # fluid bulk modulus, GPa
rhof = 1000 # fluid density, kg/m3
poro = 0.167 # porosity of sandstone
g = 9.8 # gravitational acceleration, m/s2
kf = 0.1E-6 # hydraulic conductivity, m/s
# Gassmann fluid substitution, according to Altmann
Ku = (Kg + (Kd * (poro * (Kg / Kf) - poro - 1))) / (1 - poro - (Kd / Kg) + (poro * (Kg / Kf)))
print('The undrained (saturated) bulk modulus:', Ku, 'GPa')
# Biot-Willis coeff
alpha = 1 - (Kd / Kg)
print('The Biot-Willis coefficient:', alpha)
# Lame parameter lambda
lame_lambda = Kd - (2 * G / 3)
# undrained Lame parameter lambda
lame_lambda_u = Ku - (2 * G / 3)
# stress path defined by Engelder & Fischer (1994), assume infinite reservoir
v = lame_lambda / (3 * Kd - lame_lambda)
sp = alpha * ((1 - 2 * v) / (1 - v))
print('Stress path at infinite time and infinite reservoir:', sp, '\n')
# diffusivity
k = kf / (g * rhof)
numerator = (lame_lambda_u - lame_lambda) * (lame_lambda + 2 * G)
denominator = (alpha**2) * (lame_lambda_u + 2 * G)
c = k * ((numerator / denominator) * 1E+9) # GPa to Pa, multiply by 1E+9
print('Diffusivity:', c, 'm2/s')
# boltzmann variable (dimensionless)
boltz = r / np.sqrt(c * t)
# error function
errf = scipy.special.erf(0.5 * boltz)
errfc = 1 - errf
g_func = errf - ((1 / np.sqrt(np.pi)) * boltz * np.exp(-0.25 * (boltz**2)))
# spatio-temporal radial stress path
A = (2 * alpha * G) / (lame_lambda + 2 * G)
B = 1 + ( ((2 / boltz**2) * g_func) / (errfc) )
stress_path_radial = A * B
# plot stress path
plt.figure(figsize=(10,7))
p1 = plt.plot(r, stress_path_radial, color='blue')
p2 = plt.plot([0, max(r)], [sp, sp], '--', color='red')
plt.legend((p1[0], p2[0]), (['Spatio-temporal stress path (Altmann et al, 2010)', 'Stress path at infinite (Engelder and Fischer, 1994)']))
plt.title('Reservoir Stress Path', size=20, pad=10)
plt.xlabel('Radius from wellbore (m)', size=15)
plt.ylabel('$\Delta \sigma_r / \Delta P$', size=15)
plt.xlim(0, max(r))
plt.ylim(0, 1.5)
```
| github_jupyter |
<a href="https://colab.research.google.com/github/predicthq/phq-data-science-docs/blob/master/features-api/features-api.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Features API
The Features API provides features for ML Models across all types of demand causal factors, including attended events and non-attended events.
It allows you to go straight to feature-importance testing and improving your models rather than having to worry about first building a data lake and then aggregating the data.
Features API is new and features will be expanded and added to over time. The endpoint currently supports:
* PHQ Attendance features (for attendance based events)
* PHQ Rank features (for scheduled, non-attendance based events)
* PHQ Viewership features (for viewership based events)
This notebook will guide you through how to use the Features API.
- [Setup](#setup)
- [Getting Started](#getting-started)
- [PHQ Attendance](#phq-attendance)
- [PHQ Rank](#phq-rank)
- [Academic Events](#academic-events)
- [Wide Data ranges](#wide-data-ranges)
- [Exploring the data](#exploring-the-data)
- [Concert trends for San Francisco vs Oakland](#concert)
- [Exploring TV Viewership with the Feature API](#tv-viewership)
- [Retrieving Multiple Locations](#multiple-locations)
- [List of lat/lon](#lat-lon)
- [Multiple Categories](#multiple-categories)
<a id='setup'></a>
# Setup
If using Google Colab uncomment the following code block.
```
# %%capture
# !git clone https://github.com/predicthq/phq-data-science-docs.git
# %cd phq-data-science-docs/features-api
# !pip install aiohttp==3.7.4.post0 asyncio==3.4.3 backoff==1.10.0 bleach==3.3.0 calmap==0.0.9 iso8601==0.1.14 matplotlib==3.4.2 numpy==1.20.3 pandas==1.2.4 seaborn==0.11.1 uvloop==0.15.2
```
### Requirements
If running locally, configure the required dependencies in your Python environment by using the [requirements.txt](https://github.com/predicthq/phq-data-science-docs/blob/master/features-api/requirements.txt) file which is shared alongside the notebook.
These requirements can be installed by running the command `pip install -r requirements.txt`
```
import requests
import json
```
<a id='getting-started'></a>
## Getting Started
### Access Token
You will need an access token that has the `events` scope. The following link will guide you through setting up an access token: [https://docs.predicthq.com/guides/quickstart/](https://docs.predicthq.com/guides/quickstart/)
### Basic Concepts
Every request to the API must specify which features are needed. Throughout the notebook you will become familiar with the naming convention for features, and we will talk about features by name.
Each request must specify a date range and location (that applies to all features in that request).
Certain groups of features support additional filtering/parameters.
Results are at the daily level.
Each request can currently fetch up to 90 days worth - for longer date ranges, multiple requests must be made and we have some examples of how to do that in this notebook. There is no pagination in this API.
```
# Paste your access token here
ACCESS_TOKEN = '<TOKEN>'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'Bearer {ACCESS_TOKEN}'
}
url = 'https://api.predicthq.com/v1/features'
```
<a id='phq-attendance'></a>
## PHQ Attendance
This group of features is based on PHQ Attendance. The following features are supported:
- `phq_attendance_sports`
- `phq_attendance_conferences`
- `phq_attendance_expos`
- `phq_attendance_concerts`
- `phq_attendance_festivals`
- `phq_attendance_performing_arts`
- `phq_attendance_community`
- `phq_attendance_academic_graduation`
- `phq_attendance_academic_social`
Each of these features includes stats. You define which stats you need (or don't define any and receive the default set of stats). Supported stats are:
- `sum` (included in default set of stats)
- `count` (included in default set of stats)
- `min`
- `max`
- `avg`
- `median`
- `std_dev`
These features also support filtering by PHQ Rank as you'll see in the example below.
```
payload = {
'active': {
'gte': '2019-11-28',
'lte': '2019-11-30'
},
'location': {
'place_id': [5224323, 5811704, 4887398]
},
'phq_attendance_concerts': True,
'phq_attendance_sports': {
'stats': ['count', 'std_dev', 'median'],
'phq_rank': {
'gt': 50
}
}
}
response = requests.request('POST', url, headers=headers, json=payload)
print(json.dumps(response.json(), indent=4))
```
### Example with a lat/lon
The location filter supports Place IDs and lat/lon with a radius.
```
payload = {
'active': {
'gte': '2019-11-28',
'lte': '2019-11-30'
},
'location': {
'geo': {
'lat': 47.62064,
'lon': -117.40401,
'radius': '50km'
}
},
'phq_attendance_concerts': True,
'phq_attendance_sports': {
'stats': ['count', 'std_dev', 'median'],
'phq_rank': {
'gt': 50
}
}
}
response = requests.request('POST', url, headers=headers, json=payload)
print(json.dumps(response.json(), indent=4))
```
<a id='phq-rank'></a>
## PHQ Rank
This group of features is based on PHQ Rank for non-attendance based events (mostly scheduled non-attendance based). The following features are supported:
- `phq_rank_public_holidays`
- `phq_rank_school_holidays`
- `phq_rank_observances`
- `phq_rank_politics`
- `phq_rank_daylight_savings`
- `phq_rank_health_warnings`
- `phq_rank_academic_session`
- `phq_rank_academic_exam`
- `phq_rank_academic_holiday`
Results are broken down by PHQ Rank Level (1 to 5). Rank Levels are groupings of Rank and are grouped as follows:
- 1 = between 0 and 20
- 2 = between 21 and 40
- 3 = between 41 and 60
- 4 = between 61 and 80
- 5 = between 81 and 100
Additional filtering for PHQ Rank features is not currently supported.
```
payload = {
'active': {
'gte': '2019-11-28',
'lte': '2019-11-30'
},
'location': {
'place_id': [5224323, 5811704, 4887398]
},
'phq_rank_school_holidays': True,
'phq_rank_public_holidays': True,
'phq_rank_health_warnings': True
}
response = requests.request('POST', url, headers=headers, json=payload)
print(json.dumps(response.json(), indent=4))
```
## Academic Events
Academic events are slightly different in that they contain both attended and non-attended events. You may have noted above that there are features in PHQ Attendance and PHQ Rank for academic events.
There are 5 different academic types - namely:
- `graduation`
- `social`
- `academic-session`
- `exam`
- `holiday`
The types `graduation` and `social` are attendance based events which (as noted earlier) means we have the following PHQ Attendance features:
- `phq_attendance_academic_graduation`
- `phq_attendance_academic_social`
The types `academic-session`, `exam` and `holiday` are non-attendace based events which means we have the following PHQ Rank features:
- `phq_rank_academic_session`
- `phq_rank_academic_exam`
- `phq_rank_academic_holiday`
<a id='wide-data-ranges'></a>
# Wide Date Ranges
As mentioned earlier, the API currently supports a date range of up to 90 days. In order to fetch data across a wider range, multiple requests must be made. Here is an example using asyncio that fetches a few years worth of data in parallel.
There are a few functions we'll define first.
```
import asyncio
import aiohttp
import uvloop
import iso8601
import backoff
from datetime import timedelta
asyncio.set_event_loop(uvloop.new_event_loop())
query = {
'location': {
'place_id': [5391959] # 5391959 = San Francisco
},
'phq_attendance_concerts': {
'stats': ['count', 'std_dev', 'median', 'avg'],
'phq_rank': {
'gt': 60
}
},
'phq_attendance_sports': {
'stats': ['count', 'std_dev', 'median'],
'phq_rank': {
'gt': 50
}
},
'phq_attendance_community': {
'stats': ['count', 'std_dev', 'median'],
'phq_rank': {
'gt': 50
}
},
'phq_attendance_conferences': {
'stats': ['count', 'std_dev', 'median'],
'phq_rank': {
'gt': 50
}
},
'phq_rank_public_holidays': True,
'phq_attendance_academic_graduation': True
}
format_date = lambda x: x.strftime('%Y-%m-%d')
parse_date = lambda x: iso8601.parse_date(x)
# The API has rate limits so failed requests should be retried automatically
@backoff.on_exception(backoff.expo, (aiohttp.ClientError), max_time=60)
async def get(
session: aiohttp.ClientSession,
query: dict,
start: str,
end: str,
**kwargs ) -> dict:
payload = {
'active': {
'gte': start,
'lte': end
},
**query
}
resp = await session.request('POST', url=url, headers=headers, raise_for_status=True, json=payload, **kwargs)
data = await resp.json()
return data
async def gather_with_concurrency(n, *tasks):
semaphore = asyncio.Semaphore(n)
async def sem_task(task):
async with semaphore:
return await task
return await asyncio.gather(*(sem_task(task) for task in tasks))
async def gather_stats(query: dict, start_date: str, end_date: str, **kwargs):
date_ranges = []
start_date = parse_date(start_date)
end_date = parse_date(end_date)
start_ref = start_date
while start_ref + timedelta(days=90) < end_date:
date_ranges.append({'start': format_date(start_ref),
'end': format_date(start_ref + timedelta(days=90))})
start_ref = start_ref + timedelta(days=91)
date_ranges.append({'start': format_date(start_ref),
'end': format_date(end_date)})
async with aiohttp.ClientSession() as session:
tasks = []
for date_range in date_ranges:
tasks.append(
get(
session=session,
query=query,
start=date_range['start'],
end=date_range['end'], **kwargs))
responses = await gather_with_concurrency(5, *tasks)
results = []
for response in responses:
results.extend(response['results'])
return results
```
If using Google Colab uncomment the following code block to fix broken async functionality.
This is as a result of how Google implemented notebooks and are running their async event loop.
Google Colab's Tornado 5.0 (Currently running 5.1.x) update bricked asyncio functionalities after the addition of its own asyncio event loop.
Thus, for any asyncio functionality to run on Google Colab Notebook you cannot invoke a `run_until_complete()` or `await`, since the loop you will receive from `asyncio.get_event_loop()` will be active and throw the exception seen.
JupterHub/JupyterLab had the same issue but have since fixed this, which is why you can easily just `await` the resolution, processing and response of an async call with the await keyword.
So we need to `"monkey patch"` the running event loop on Google Colab to hijack the event loop to allow us to issue tasks to be scheduled!
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# responses = awaitx(gather_stats(
# query=query,
# start_date='2016-01-01',
# end_date='2021-12-31'))
# len(responses)
```
## Use the following code block only if running locally in JupyterHub or JupyterLab
```
responses = await gather_stats(
query=query,
start_date='2016-01-01',
end_date='2021-12-31')
len(responses)
print(json.dumps(responses[0], indent=4))
```
<a id='exploring-the-data'></a>
# Exploring the Data
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import os
import calmap
import warnings
# To display more columns and with a larger width in the DataFrame
pd.set_option('display.max_columns', None)
pd.options.display.max_colwidth = 100
```
<a id='concert'></a>
## Concert Trends for San Francisco vs Oakland
```
# IDs are from https://www.geonames.org/
sf_id = 5391959
oak_id = 5378538
# San Francisco
query = {
'location': {
'place_id': [sf_id]
},
'phq_attendance_concerts': {
'stats': ['count', 'sum', 'median']
},
'phq_attendance_festivals': {
'stats': ['count', 'sum', 'median']
}
}
```
If running on Google Colab uncomment following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# sf_responses = awaitx(gather_stats(
# query=query,
# start_date='2016-01-01',
# end_date='2021-04-01'))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
sf_responses = await gather_stats(
query=query,
start_date='2016-01-01',
end_date='2021-04-01')
# Oakland
query = {
'location': {
'place_id': [oak_id]
},
'phq_attendance_concerts': {'stats': ['count', 'sum', 'median'], },
'phq_attendance_festivals': {'stats': ['count', 'sum', 'median'], },
}
```
If running on Google Colab uncomment following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# oak_responses = awaitx(gather_stats(
# query=query,
# start_date='2016-01-01',
# end_date='2021-04-01'))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
oak_responses = await gather_stats(
query=query,
start_date='2016-01-01',
end_date='2021-04-01')
sf_df = pd.DataFrame.from_dict(sf_responses)
oak_df = pd.DataFrame.from_dict(oak_responses)
sf_df.head()
```
Reshaping the responses into tabular form
```
FIELDS = ['sum', 'count', 'median']
def parse_element(response: dict, fields: list) -> np.array:
"""
Extracts the feature fields from a dictionary into an array
"""
blank_response = np.zeros(shape=(len(fields)))
if isinstance(response, dict):
if not 'stats' in response: return blank_response
stats = response['stats']
if stats['count'] == 0: return blank_response
return np.array([stats[field] for field in fields])
def add_flat_features(df: pd.DataFrame, column: str,
feature_name: str, fields: list) -> pd.DataFrame:
"""
Adds features into dataframe
"""
list_feature = df[column].apply(parse_element, fields=fields)
fts = pd.DataFrame(list_feature.to_list(), columns=fields)
fts.columns = [f'{feature_name}_{col}' for col in fts.columns]
return df.join(fts)
sf_flat = add_flat_features(sf_df, 'phq_attendance_concerts', 'concerts', fields=FIELDS)
sf_flat = add_flat_features(sf_flat, 'phq_attendance_festivals', 'festivals', fields=FIELDS)
oak_flat = add_flat_features(oak_df, 'phq_attendance_concerts', 'concerts', fields=FIELDS)
oak_flat = add_flat_features(oak_flat, 'phq_attendance_festivals', 'festivals', fields=FIELDS)
sf_flat['date'] = pd.to_datetime(sf_flat['date'])
oak_flat['date'] = pd.to_datetime(oak_flat['date'])
sf_flat.head(2)
oak_flat.head(2)
def truncate_to_month(date_col):
return date_col - pd.Timedelta('1 day') * (date_col.dt.day - 1)
sf_flat['month'] = truncate_to_month(sf_flat['date'])
oak_flat['month'] = truncate_to_month(oak_flat['date'])
agg_dict = {'concerts_sum': 'sum',
'concerts_count': 'sum',
'concerts_median': 'median',
'festivals_sum': 'sum',
'festivals_count': 'sum',
'festivals_median': 'median',}
sf_monthly = (sf_flat
.groupby('month')
.agg(agg_dict)
)
oak_monthly = (oak_flat
.groupby('month')
.agg(agg_dict)
)
sf_monthly.columns = [f'{col}_sf' for col in sf_monthly.columns]
oak_monthly.columns = [f'{col}_oak' for col in oak_monthly.columns]
both_monthly = sf_monthly.join(oak_monthly).reset_index()
both_monthly.head()
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'concerts_count_sf',
'concerts_count_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
sns.lineplot(data=both_monthly[['month', 'concerts_sum_sf',
'concerts_sum_oak']], ax=ax)
# plt.xticks(both_monthly['month'])
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
sns.lineplot(data=both_monthly[['month', 'concerts_median_sf',
'concerts_median_oak']], ax=ax)
# plt.xticks(both_monthly['month'])
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
sns.lineplot(data=both_monthly[['month', 'festivals_count_sf',
'festivals_count_oak']], ax=ax)
# plt.xticks(both_monthly['month'])
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
plt.xticks(rotation=90);
```
<a id='tv-viewership'></a>
## Exploring TV Viewership with the Features API
This group of features is based on PHQ Viewership. The following features are some examples that are supported:
- `phq_viewership_sports_american_football` (viewership across all supported American Football leagues)
- `phq_viewership_sports_american_football_nfl` (viewership for NFL)
- `phq_viewership_sports_baseball` (viewership across all supported Baseball leagues)
- `phq_viewership_sports_soccer_mls` (viewership for MLS)
- `phq_viewership_sports_basketball` (viewership across all supported Basketball leagues)
- `phq_viewership_sports_basketball_nba` (viewership for NBA)
- `phq_viewership_sports_ice_hockey_nhl` (viewership for NHL)
The full list of available viewership feature fields are in our documentation [here](https://docs.predicthq.com/resources/features/#viewership-based-feature-fields).
For this section we will demonstrate how to apply the Features API to explore the viewership for two different sports. For one example we will be comparing viewership for all supported American Football leagues in San Francisco against viewership for all supported American Football leagues in Oakland. The second example we will be comparing viewership for all supported Basketball leagues in San Francisco against viewership for all supported Basketball leagues in Oakland.
```
# San Francisco
query = {
'location': {
'place_id': [sf_id]
},
'phq_viewership_sports_american_football': {
'stats': ['count', 'sum', 'median'],
},
'phq_viewership_sports_basketball': {
'stats': ['count', 'sum', 'median'],
},
}
```
If running on Google Colab uncomment the following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# sf_responses = awaitx(gather_stats(
# query=query,
# start_date='2020-01-01',
# end_date='2020-12-31'))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
sf_responses = await gather_stats(
query=query,
start_date='2020-01-01',
end_date='2020-12-31')
sf_df = pd.DataFrame.from_dict(sf_responses)
sf_df.head()
# Oakland
query = {
'location': {
'place_id': [oak_id]
},
'phq_viewership_sports_american_football': {
'stats': ['count', 'sum', 'median'],
},
'phq_viewership_sports_basketball': {
'stats': ['count', 'sum', 'median'],
},
}
```
If running on Google Colab uncomment the following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# oak_responses = awaitx(gather_stats(
# query=query,
# start_date='2020-01-01',
# end_date='2020-12-31'))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
oak_responses = await gather_stats(
query=query,
start_date='2020-01-01',
end_date='2020-12-31')
oak_df = pd.DataFrame.from_dict(oak_responses)
oak_df.head()
sf_view_flat = add_flat_features(sf_df, 'phq_viewership_sports_american_football', 'american_football', fields=FIELDS)
sf_view_flat = add_flat_features(sf_view_flat, 'phq_viewership_sports_basketball', 'basketball', fields=FIELDS)
oak_view_flat = add_flat_features(oak_df, 'phq_viewership_sports_american_football', 'american_football', fields=FIELDS)
oak_view_flat = add_flat_features(oak_view_flat, 'phq_viewership_sports_basketball', 'basketball', fields=FIELDS)
sf_view_flat['date'] = pd.to_datetime(sf_view_flat['date'])
oak_view_flat['date'] = pd.to_datetime(oak_view_flat['date'])
sf_view_flat['month'] = truncate_to_month(sf_view_flat['date'])
oak_view_flat['month'] = truncate_to_month(oak_view_flat['date'])
sf_view_flat.head()
oak_view_flat.head()
```
Reshaping the responses into tabular form
```
agg_dict = {'american_football_sum': 'sum',
'american_football_count': 'sum',
'american_football_median': 'median',
'basketball_sum': 'sum',
'basketball_count': 'sum',
'basketball_median': 'median',}
sf_monthly = (sf_view_flat
.groupby('month')
.agg(agg_dict)
)
oak_monthly = (oak_view_flat
.groupby('month')
.agg(agg_dict)
)
sf_monthly.columns = [f'{col}_sf' for col in sf_monthly.columns]
oak_monthly.columns = [f'{col}_oak' for col in oak_monthly.columns]
both_monthly = sf_monthly.join(oak_monthly).reset_index()
both_monthly.head()
```
The results of viewership between San Francisco and Oakland for All American Football are graphed below.
```
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'american_football_count_sf',
'american_football_count_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'american_football_sum_sf',
'american_football_sum_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'american_football_median_sf',
'american_football_median_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
```
The results for viewership between San Francisco and Oakland for All Basketball are graphed below.
```
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'basketball_count_sf',
'basketball_count_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'basketball_sum_sf',
'basketball_sum_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fig, ax = plt.subplots()
both_monthly['month'] = pd.to_datetime(both_monthly['month'])
sns.lineplot(data=both_monthly[['month', 'basketball_median_sf',
'basketball_median_oak']], ax=ax)
ax.set_xticklabels(both_monthly['month'].dt.strftime('%Y-%m'))
ticks = [item.get_text() for item in ax.get_xticklabels()]
plt.xticks(rotation=90);
```
<a id='multiple-locations'></a>
### Retrieving Multiple Locations
You can specify multiple locations in a single request and the results for all specified locations will be aggregated together as in the example below.
```
query = {
'location': {
'place_id': [sf_id, oak_id]
},
'phq_attendance_concerts': {
'stats': ['count', 'sum', 'median']
},
'phq_attendance_festivals': {
'stats': ['count', 'sum', 'median']
}
}
```
If running on Google Colab uncomment following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# both_responses = awaitx(gather_stats(
# query=query,
# start_date='2016-01-01',
# end_date='2021-04-01'))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
both_responses = await gather_stats(
query=query,
start_date='2016-01-01',
end_date='2021-04-01')
pd.DataFrame.from_dict(both_responses).head(5)
```
<a id='lat-lon'></a>
## List of lat/lon
You might need to fetch data for a wide date range as well as a large number of different locations. This example loads a list of lat/lon from a CSV file and fetches data for each of them.
```
examples = pd.read_csv('./data/lat_lon_examples.csv').sample(50)
examples.head(5)
# Check number of locations
len(examples)
query_f = lambda lat, long: {
'location': {
'geo': {
'lat': float(lat),
'lon': float(long),
'radius': '10km'
}
},
'phq_attendance_sports': {
'stats': ['count', 'avg'],
'phq_rank': {
'gt': 50
}
},
"phq_attendance_concerts": {
'stats': ['count', 'avg'],
'phq_rank': {
'gt': 50
}
},
}
async def pull_one_lat_long(city, lat, long):
response = await gather_stats(
query=query_f(lat, long),
start_date='2016-01-01',
end_date='2021-04-01')
return {city: response}
import time
start_time = time.time()
all_locations = []
for ix , row in examples.iterrows():
all_locations += [pull_one_lat_long(row['City'],
row['Latitude'],
row['Longitude'])]
```
If running on Google Colab uncomment following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# # This might take a few seconds
# all_results = awaitx(gather_with_concurrency(5, *all_locations))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
# This might take a few seconds
all_results = await gather_with_concurrency(5, *all_locations)
end_time = time.time()
taken = (time.time() - start_time)
print(f"{taken}s processing time")
features_list = [
"phq_attendance_sports",
"phq_attendance_concerts"
]
all_counts = [val[key]['stats']['count'] for place_data in all_results
for place_name, data in place_data.items() for val in data for key in features_list]
print(
f"Features analysed for {sum(all_counts)} events across 21 quarters or ~1920 days for 2 different categories ")
FIELDS = ['count', 'avg']
all_locs = []
for city in all_results:
one_loc = pd.DataFrame(list(city.values())[0])
one_loc = add_flat_features(one_loc, 'phq_attendance_sports',
'sports', FIELDS)
one_loc.drop(['phq_attendance_sports'],
axis=1, inplace=True)
one_loc['City'] = list(city.keys())[0]
all_locs.append(one_loc)
cities = pd.concat(all_locs)
cities.pivot_table(index='date', columns='City', values='sports_avg')
```
<a id='multiple-categories'></a>
## Multiple Categories
For San Francisco
```
FIELDS = ['sum', 'count']
query = {
'location': {
'place_id': [sf_id]
},
'phq_attendance_concerts': {
'stats': FIELDS
},
'phq_attendance_community': {
'stats': FIELDS
},
'phq_attendance_conferences': {
'stats': FIELDS
},
'phq_attendance_expos': {
'stats': FIELDS
},
'phq_attendance_performing_arts': {
'stats': FIELDS
},
'phq_attendance_sports': {
'stats': FIELDS
},
'phq_attendance_festivals': {
'stats': FIELDS
},
'phq_rank_public_holidays': True,
'phq_rank_school_holidays': True,
'phq_rank_observances': True
}
```
If running on Google Colab uncomment following block to obtain results.
```
# import asyncio
# import nest_asyncio
# nest_asyncio.apply()
# def awaitx(x): return asyncio.get_event_loop().run_until_complete(x)
# sf_mlt_responses = awaitx(gather_stats(
# query=query,
# start_date='2016-01-01',
# end_date='2021-04-01'))
```
If running locally or within JupyterHub/JupyterLab use this block instead to obtain results.
```
sf_mlt_responses = await gather_stats(
query=query,
start_date='2016-01-01',
end_date='2021-04-01')
```
Parse Rank Columns
```
def parse_rank_column(col):
rank_levels = col.apply(lambda x: x['rank_levels'])
max_values = []
for row in rank_levels:
not_null = {k: v for k, v in row.items() if v>0}
if not_null:
max_values.append(int(max(not_null)))
else:
# all values were zero
max_values.append(0)
return max_values
holidays_att = pd.DataFrame.from_dict(sf_mlt_responses)
holidays_att['public-holiday'] = \
parse_rank_column(holidays_att['phq_rank_public_holidays'])
holidays_att['public-holiday'] = \
parse_rank_column(holidays_att['phq_rank_public_holidays'])
holidats_pa = add_flat_features(holidays_att, 'phq_attendance_performing_arts',
'performing_arts', FIELDS)
holidats_pa = add_flat_features(holidats_pa, 'phq_attendance_concerts',
'concerts', FIELDS)
holidats_pa = add_flat_features(holidats_pa, 'phq_attendance_community',
'community', FIELDS)
holidats_pa = add_flat_features(holidats_pa, 'phq_attendance_conferences',
'conferences', FIELDS)
holidats_pa = add_flat_features(holidats_pa, 'phq_attendance_expos',
'expos', FIELDS)
holidats_pa = add_flat_features(holidats_pa, 'phq_attendance_festivals',
'festivals', FIELDS)
holidats_pa = add_flat_features(holidats_pa, 'phq_attendance_sports',
'sports', FIELDS)
holidats_pa.set_index('date', inplace=True)
holidats_pa.index = pd.to_datetime(holidats_pa.index)
(holidats_pa
.groupby('public-holiday')
.agg({'conferences_sum': 'median',
'community_sum': 'median',
'conferences_count': 'median',
'community_count': 'median',
}
)
)
```
Visualize in a Calendar
```
for category in ['performing-arts', 'conferences']:
feature = category.replace('-','_')+'_count'
fig, ax = calmap.calendarplot(holidats_pa[feature], cmap="YlGn")
fig.set_size_inches(18, 15)
fig.colorbar(ax[0].get_children()[1], ax=ax.ravel().tolist())
_ = fig.suptitle(f"Number of {category} per day in calmap")
```
| github_jupyter |
# 1. Import
```
# System
import os
# Time
import time
import datetime
# Numerical
import numpy as np
import pandas as pd
# Tools
import itertools
from collections import Counter
# NLP
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import SnowballStemmer
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
# from pywsd.utils import lemmatize_sentence
# Preprocessing
from sklearn import preprocessing
from sklearn.utils import class_weight as cw
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
# Model Selection
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
# Machine Learning Models
from sklearn.linear_model import LogisticRegression
from sklearn import svm
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, BaggingClassifier, ExtraTreesClassifier
from sklearn.tree import DecisionTreeClassifier
# Evaluation Metrics
from sklearn import metrics
from sklearn.metrics import f1_score, accuracy_score,confusion_matrix,classification_report
# Deep Learing Preprocessing - Keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing import sequence
from keras.utils import to_categorical
# Deep Learning Model - Keras
from keras.models import Model
from keras.models import Sequential
# Deep Learning Model - Keras - CNN
from keras.layers import Conv1D, Conv2D, Convolution1D, MaxPooling1D, SeparableConv1D, SpatialDropout1D, \
GlobalAvgPool1D, GlobalMaxPool1D, GlobalMaxPooling1D
from keras.layers.pooling import _GlobalPooling1D
from keras.layers import MaxPooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D
# Deep Learning Model - Keras - RNN
from keras.layers import Embedding, LSTM, Bidirectional
# Deep Learning Model - Keras - General
from keras.layers import Input, Add, concatenate, Dense, Activation, BatchNormalization, Dropout, Flatten
from keras.layers import LeakyReLU, PReLU, Lambda, Multiply
# Deep Learning Parameters - Keras
from keras.optimizers import RMSprop, Adam
# Deep Learning Callbacs - Keras
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, ReduceLROnPlateau
# Visualization
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
print(os.listdir("../input"))
```
# 2. Functions
```
# print date and time for given type of representation
def date_time(x):
if x==1:
return 'Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
if x==2:
return 'Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now())
if x==3:
return 'Date now: %s' % datetime.datetime.now()
if x==4:
return 'Date today: %s' % datetime.date.today()
```
# 3. Read Data
```
input_directory = r"../input/"
output_directory = r"../output/"
if not os.path.exists(output_directory):
os.mkdir(output_directory)
figure_directory = "../output/figures"
if not os.path.exists(figure_directory):
os.mkdir(figure_directory)
file_name_pred_batch = figure_directory+r"/result"
file_name_pred_sample = figure_directory+r"/sample"
df = pd.read_csv(input_directory + "spam.csv", encoding='latin-1')
df.head()
df.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1, inplace=True)
df = df.rename(columns={"v1":"label", "v2":"text"})
df.head()
df_new = df.copy()
df_stat = df.copy()
lmm = WordNetLemmatizer()
porter_stemmer = PorterStemmer()
snowball_stemmer = SnowballStemmer('english')
stop_words = set(stopwords.words('english'))
# df_new['parsed'] = df_new['text'].apply(lambda x: x.lower())
# df_new['parsed'] = df_new['parsed'].apply(lambda x: word_tokenize(x))
# df_new['no_stop'] = df_new['parsed'].apply(lambda x: [word for word in str(x).split() if word not in stop_words])
# df_new['stem'] = df_new['no_stop'].apply(lambda x: [snowball_stemmer.stem(word) for word in x])
# df_new['stem'] = df_new['stem'].apply(lambda x: " ".join(x))
# df_new['lemi'] = df_new['no_stop'].apply(lambda x: " ".join(x))
# df_new['lemi'] = df_new['lemi'].apply(lambda x: lmm.lemmatize(x))
# df_new['parsed'] = df_new['parsed'].apply(lambda x: ' '.join(x))
# df_new['no_stop'] = df_new['no_stop'].apply(lambda x: ' '.join(x))
# df_new['stem'] = df_new['stem'].apply(lambda x: ' '.join(x))
# df_new['lemi'] = df_new['lemi'].apply(lambda x: ' '.join(x))
# df_new.head()
df_stat["text_clean"] = df_stat["text"].apply(lambda x: re.sub("[^a-zA-Z]", " ", x.lower()))
df_stat["length"] = df_stat["text"].apply(lambda x: len(x))
df_stat["token_count"] = df_stat["text"].apply(lambda x: len(x.split(" ")))
df_stat["unique_token_count"] = df_stat["text"].apply(lambda x: len(set(x.lower().split(" "))))
df_stat["unique_token_count_percent"] = df_stat["unique_token_count"]/df_stat["token_count"]
df_stat["length_clean"] = df_stat["text_clean"].apply(lambda x: len(x))
df_stat["token_count_clean"] = df_stat["text_clean"].apply(lambda x: len(x.split(" ")))
df_stat.head()
```
# 4 . Visualization
```
sns.set_style("ticks")
figsize=(20, 5)
ticksize = 18
titlesize = ticksize + 8
labelsize = ticksize + 5
xlabel = "Label"
ylabel = "Count"
title = "Number of ham and spam messages"
params = {'figure.figsize' : figsize,
'axes.labelsize' : labelsize,
'axes.titlesize' : titlesize,
'xtick.labelsize': ticksize,
'ytick.labelsize': ticksize}
plt.rcParams.update(params)
col1 = "label"
col2 = "label"
sns.countplot(x=df[col1])
plt.title(title.title())
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.xticks(rotation=90)
plt.plot()
df.label.value_counts()
s1 = df_stat[df_stat['label'] == 'ham']['text'].str.len()
s2 = df_stat[df_stat['label'] == 'spam']['text'].str.len()
s3 = df_stat[df_stat['label'] == 'ham']['text_clean'].str.len()
s4 = df_stat[df_stat['label'] == 'spam']['text_clean'].str.len()
s5 = df_stat[df_stat['label'] == 'ham']['text'].str.split().str.len()
s6 = df_stat[df_stat['label'] == 'spam']['text'].str.split().str.len()
s7 = df_stat[df_stat['label'] == 'ham']['text_clean'].str.split().str.len()
s8 = df_stat[df_stat['label'] == 'spam']['text_clean'].str.split().str.len()
sns.set()
sns.set_style("ticks")
figsize=(20, 15)
ticksize = 14
titlesize = ticksize + 8
labelsize = ticksize + 5
xlabel = "Length"
ylabel = "Count"
title1 = "Length Distribution"
title2 = "Length Distribution (Clean)"
title3 = "Word Count Distribution"
title4 = "Word Count Distribution (Clean)"
params = {'figure.figsize' : figsize,
'axes.labelsize' : labelsize,
'axes.titlesize' : titlesize,
'xtick.labelsize': ticksize,
'ytick.labelsize': ticksize}
plt.rcParams.update(params)
# fig.subplots_adjust(hspace=0.5, wspace=0.5)
col1 = "len"
col2 = "label"
plt.subplot(221)
sns.distplot(s1, label='Ham')
sns.distplot(s2, label='Spam')
plt.title(title1.title())
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
plt.subplot(222)
sns.distplot(s3, label='Ham (Clean)')
sns.distplot(s4, label='Spam (Clean)')
plt.title(title2.title())
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
plt.subplot(223)
sns.distplot(s5, label='Ham Word')
sns.distplot(s6, label='Spam Word')
plt.title(title3.title())
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
plt.subplot(224)
sns.distplot(s7, label='Ham Word')
sns.distplot(s8, label='Spam Word')
plt.title(title4.title())
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
plt.show()
```
# 5. Preprocessing
```
X_train,X_test,y_train,y_test = train_test_split(df["text"],df["label"], test_size = 0.2, random_state = 10)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
```
# 6. Feature Extraction
```
vect = CountVectorizer()
X_train_df = vect.fit_transform(X_train)
X_test_df = vect.transform(X_test)
print(vect.get_feature_names()[0:20])
print(vect.get_feature_names()[-20:])
```
# 7. Model Trainning
```
models = {
"SVC": svm.SVC(kernel="linear"),
"MultinomialNB": MultinomialNB(),
"LogisticRegression": LogisticRegression(),
"KNeighborsClassifier": KNeighborsClassifier(),
"DecisionTreeClassifier": DecisionTreeClassifier(),
"RandomForestClassifier": RandomForestClassifier(),
"AdaBoostClassifier": AdaBoostClassifier(),
"BaggingClassifier": BaggingClassifier(),
"ExtraTreesClassifier": ExtraTreesClassifier()
}
prediction = dict()
score_map = {}
for model_name in models:
model = models[model_name]
model.fit(X_train_df,y_train)
prediction[model_name] = model.predict(X_test_df)
score = accuracy_score(y_test, prediction[model_name])
score_map[model_name] = score
# print("{}{}{}".format(model_name, ": ", score))
result = pd.DataFrame()
result["model"] = score_map.keys()
result["score"] = score_map.values()
result["score"] = result["score"].apply(lambda x: x*100)
def plot_model_performace(result):
sns.set_style("ticks")
figsize=(22, 6)
ticksize = 12
titlesize = ticksize + 8
labelsize = ticksize + 5
xlabel = "Model"
ylabel = "Score"
title = "Model Performance"
params = {'figure.figsize' : figsize,
'axes.labelsize' : labelsize,
'axes.titlesize' : titlesize,
'xtick.labelsize': ticksize,
'ytick.labelsize': ticksize}
plt.rcParams.update(params)
col1 = "model"
col2 = "score"
sns.barplot(x=col1, y=col2, data=result)
plt.title(title.title())
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.xticks(rotation=90)
plt.grid()
plt.plot()
plt.show()
print(result)
plot_model_performace(result)
```
# 8. Hyper Parameter Search
```
param_grid = {
"C": np.concatenate(
[
np.arange(0.0001, 0.001, 0.0001),
np.arange(0.001, 0.01, 0.001),
np.arange(0.01, 0.1, 0.01),
np.arange(0.1, 1, 0.1),
np.arange(1, 10, 1),
np.arange(10, 100, 5)
],
axis=None),
"kernel": ("linear", "rbf", "poly", "sigmoid"),
# "kernel": ("linear", "poly"),
# "degree": list(np.arange(1,25, 1)),
# "gamma": np.concatenate(
# [
# np.arange(0.0001, 0.001, 0.0001),
# np.arange(0.001, 0.01, 0.001),
# np.arange(0.01, 0.1, 0.01),
# np.arange(0.1, 1, 0.1),
# np.arange(1, 10, 1),
# np.arange(10, 100, 5)
# ],
# axis=None)
}
# print(param_grid)
# model = svm.SVC(class_weight="balanced")
# grid = GridSearchCV(model, param_grid, n_jobs=-1, verbose=1, cv=3)
# grid.fit(X_train_df,y_train)
# print("{}{}".format("Best Estimator: ", grid.best_estimator_))
# print("{}{}".format("Best Params: ", grid.best_params_))
# print("{}{}".format("Best Scores: ", grid.best_score_))
param_grid = {
"alpha": np.concatenate(
[
np.arange(0.0001, 0.001, 0.0001),
np.arange(0.001, 0.01, 0.001),
np.arange(0.01, 0.1, 0.01),
np.arange(0.1, 1, 0.1),
np.arange(1, 10, 1),
np.arange(10, 100, 5)
])
}
model = MultinomialNB()
grid_cv_model = GridSearchCV(model, param_grid, n_jobs=-1, verbose=3, cv=3)
grid_cv_model.fit(X_train_df, y_train)
```
# 9. Evaluation Metrics
```
print("{}{}".format("Best Estimator: ", grid_cv_model.best_estimator_))
print("{}{}".format("Best Params: ", grid_cv_model.best_params_))
print("{}{}".format("Best Scores: ", grid_cv_model.best_score_))
print(classification_report(y_test, prediction['MultinomialNB'], target_names = ["Ham", "Spam"]))
def plot_confusion_matrix(y_test, y_pred, title=""):
conf_mat = confusion_matrix(y_test, y_pred)
conf_mat_normalized = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis]
# sns.set_style("ticks")
figsize=(22, 5)
ticksize = 18
titlesize = ticksize + 8
labelsize = ticksize + 5
xlabel = "Predicted label"
ylabel = "True label"
params = {'figure.figsize' : figsize,
'axes.labelsize' : labelsize,
'axes.titlesize' : titlesize,
'xtick.labelsize': ticksize,
'ytick.labelsize': ticksize}
plt.rcParams.update(params)
plt.subplot(121)
sns.heatmap(conf_mat, annot=True)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.subplot(122)
sns.heatmap(conf_mat_normalized, annot=True)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
print("Confusion Matrix:\n")
print(conf_mat)
print("\n\nConfusion Matrix Normalized:\n")
print(conf_mat_normalized)
plot_confusion_matrix(y_test, prediction['MultinomialNB'], title="MultinomialNB")
X_test[y_test < prediction["MultinomialNB"] ]
X_test[y_test > prediction["MultinomialNB"] ]
```
# 10. Deep Learning
## Output Configuration
```
main_model_dir = output_directory + r"models/"
main_log_dir = output_directory + r"logs/"
try:
os.mkdir(main_model_dir)
except:
print("Could not create main model directory")
try:
os.mkdir(main_log_dir)
except:
print("Could not create main log directory")
model_dir = main_model_dir + time.strftime('%Y-%m-%d %H-%M-%S') + "/"
log_dir = main_log_dir + time.strftime('%Y-%m-%d %H-%M-%S')
try:
os.mkdir(model_dir)
except:
print("Could not create model directory")
try:
os.mkdir(log_dir)
except:
print("Could not create log directory")
model_file = model_dir + "{epoch:02d}-val_acc-{val_acc:.2f}-val_loss-{val_loss:.2f}.hdf5"
print("Settting Callbacks")
checkpoint = ModelCheckpoint(
model_file,
monitor='val_acc',
save_best_only=True)
early_stopping = EarlyStopping(
monitor='val_loss',
patience=2,
verbose=1,
restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(
monitor='val_loss',
factor=0.6,
patience=1,
verbose=1)
callbacks = [checkpoint, reduce_lr, early_stopping]
# callbacks = [early_stopping]
print("Set Callbacks at ", date_time(1))
```
## 10.1. Preprocessing
```
X = df.text
Y = df.label
label_encoder = LabelEncoder()
Y = label_encoder.fit_transform(Y)
Y = Y.reshape(-1, 1)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15)
max_words = len(set(" ".join(X_train).split()))
max_len = X_train.apply(lambda x: len(x)).max()
# max_words = 1000
# max_len = 150
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(X_train)
X_train_seq = tokenizer.texts_to_sequences(X_train)
X_train_seq = sequence.pad_sequences(X_train_seq, maxlen=max_len)
# Calculate Class Weights
def get_weight(y):
class_weight_current = cw.compute_class_weight('balanced', np.unique(y), y)
return class_weight_current
class_weight = get_weight(Y_train.flatten())
```
## 10.2 Model
```
def get_rnn_model():
model = Sequential()
model.add(Embedding(max_words, 50, input_length=max_len))
model.add(LSTM(64))
model.add(Dropout(0.5))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()
return model
def get_cnn_model():
model = Sequential()
model.add(Embedding(max_words, 50, input_length=max_len))
model.add(Conv1D(64, 3, padding='valid', activation='relu', strides=1))
model.add(GlobalMaxPooling1D())
model.add(Dropout(0.5))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()
return model
def plot_performance(history=None, figure_directory=None, ylim_pad=[0, 0]):
xlabel = 'Epoch'
legends = ['Training', 'Validation']
plt.figure(figsize=(20, 5))
y1 = history.history['acc']
y2 = history.history['val_acc']
min_y = min(min(y1), min(y2))-ylim_pad[0]
max_y = max(max(y1), max(y2))+ylim_pad[0]
plt.subplot(121)
plt.plot(y1)
plt.plot(y2)
plt.title('Model Accuracy\n'+date_time(1), fontsize=17)
plt.xlabel(xlabel, fontsize=15)
plt.ylabel('Accuracy', fontsize=15)
plt.ylim(min_y, max_y)
plt.legend(legends, loc='upper left')
plt.grid()
y1 = history.history['loss']
y2 = history.history['val_loss']
min_y = min(min(y1), min(y2))-ylim_pad[1]
max_y = max(max(y1), max(y2))+ylim_pad[1]
plt.subplot(122)
plt.plot(y1)
plt.plot(y2)
plt.title('Model Loss\n'+date_time(1), fontsize=17)
plt.xlabel(xlabel, fontsize=15)
plt.ylabel('Loss', fontsize=15)
plt.ylim(min_y, max_y)
plt.legend(legends, loc='upper left')
plt.grid()
if figure_directory:
plt.savefig(figure_directory+"/history")
plt.show()
model1 = get_rnn_model()
# loss = 'categorical_crossentropy'
loss = 'binary_crossentropy'
metrics = ['accuracy']
```
## 10.3. Model Trainning
### 10.3.1. RNN
```
print("Starting...\n")
start_time = time.time()
print(date_time(1))
print("\n\nCompliling Model ...\n")
learning_rate = 0.001
optimizer = Adam(learning_rate)
# optimizer = Adam()
model1.compile(optimizer=optimizer, loss=loss, metrics=metrics)
verbose = 1
epochs = 100
batch_size = 128
validation_split = 0.2
print("Trainning Model ...\n")
history1 = model1.fit(
X_train_seq,
Y_train,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_split=validation_split,
class_weight =class_weight
)
elapsed_time = time.time() - start_time
elapsed_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
print("\nElapsed Time: " + elapsed_time)
print("Completed Model Trainning", date_time(1))
```
#### 10.3.1.2 Visualization
```
plot_performance(history=history1)
```
### 10.3.1. RNN
```
model2 = get_cnn_model()
print("Starting...\n")
start_time = time.time()
print(date_time(1))
print("\n\nCompliling Model ...\n")
learning_rate = 0.001
optimizer = Adam(learning_rate)
# optimizer = Adam()
model2.compile(optimizer=optimizer, loss=loss, metrics=metrics)
verbose = 1
epochs = 100
batch_size = 128
validation_split = 0.2
print("Trainning Model ...\n")
history2 = model2.fit(
X_train_seq,
Y_train,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_split=validation_split,
class_weight =class_weight
)
elapsed_time = time.time() - start_time
elapsed_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
print("\nElapsed Time: " + elapsed_time)
print("Completed Model Trainning", date_time(1))
```
#### 10.3.1.2 Visualization
```
plot_performance(history=history2)
```
## 10.5 Inference/ Prediction
```
test_X_seq = tokenizer.texts_to_sequences(X_test)
test_X_seq = sequence.pad_sequences(test_X_seq, maxlen=max_len)
accuracy1 = model1.evaluate(test_X_seq, Y_test)
accuracy2 = model2.evaluate(test_X_seq, Y_test)
```
### 10.5.1 Evaluation
```
print("Model Performance of RNN (Test Accuracy):")
print('Accuracy: {:0.2f}%\nLoss: {:0.3f}\n'.format(accuracy1[1]*100, accuracy1[0]))
print("\nModel Performance of RNN (Test Accuracy):")
print('v: {:0.2f}%\nLoss: {:0.3f}\n'.format(accuracy2[1]*100, accuracy2[0]))
ypreds1 = model1.predict_classes(test_X_seq, verbose=1)
ypreds2 = model2.predict_classes(test_X_seq, verbose=1)
print(classification_report(Y_test, ypreds1, target_names = ["Ham", "Spam"]))
plot_confusion_matrix(Y_test, ypreds1, title="RNN")
print(classification_report(Y_test, ypreds2, target_names = ["Ham", "Spam"]))
```
#### 10.5.1.2 Visualization
```
plot_confusion_matrix(Y_test, ypreds2, title="CNN")
row1 = pd.DataFrame({'model': 'RNN', 'score': accuracy1[1]*100}, index=[-1])
result = pd.concat([row1, result.ix[:]]).reset_index(drop=True)
row2 = pd.DataFrame({'model': 'CNN', 'score': accuracy2[1]*100}, index=[-1])
result = pd.concat([row2, result.ix[:]]).reset_index(drop=True)
plot_model_performace(result)
```
# Reference:
1. [Text Preprocessing and Machine Learning Modeling](https://www.kaggle.com/futurist/text-preprocessing-and-machine-learning-modeling)
2. [keras mlp cnn test for text classification](https://www.kaggle.com/jacklinggu/keras-mlp-cnn-test-for-text-classification)
| github_jupyter |
# Using the PyTorch JIT Compiler with Pyro
This tutorial shows how to use the PyTorch [jit compiler](https://pytorch.org/docs/master/jit.html) in Pyro models.
#### Summary:
- You can use compiled functions in Pyro models.
- You cannot use pyro primitives inside compiled functions.
- If your model has static structure, you can use a `Jit*` version of an `ELBO` algorithm, e.g.
```diff
- Trace_ELBO()
+ JitTrace_ELBO()
```
- The [HMC](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.HMC) and [NUTS](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.NUTS) classes accept `jit_compile=True` kwarg.
- Models should input all tensors as `*args` and all non-tensors as `**kwargs`.
- Each different value of `**kwargs` triggers a separate compilation.
- Use `**kwargs` to specify all variation in structure (e.g. time series length).
- To ignore jit warnings in safe code blocks, use `with pyro.util.ignore_jit_warnings():`.
- To ignore all jit warnings in `HMC` or `NUTS`, pass `ignore_jit_warnings=True`.
#### Table of contents
- [Introduction](#Introduction)
- [A simple model](#A-simple-model)
- [Varying structure](#Varying-structure)
```
import os
import torch
import pyro
import pyro.distributions as dist
from torch.distributions import constraints
from pyro import poutine
from pyro.distributions.util import broadcast_shape
from pyro.infer import Trace_ELBO, JitTrace_ELBO, TraceEnum_ELBO, JitTraceEnum_ELBO, SVI
from pyro.infer.mcmc import MCMC, NUTS
from pyro.infer.autoguide import AutoDiagonalNormal
from pyro.optim import Adam
smoke_test = ('CI' in os.environ)
assert pyro.__version__.startswith('1.7.0')
```
## Introduction
PyTorch 1.0 includes a [jit compiler](https://pytorch.org/docs/master/jit.html) to speed up models. You can think of compilation as a "static mode", whereas PyTorch usually operates in "eager mode".
Pyro supports the jit compiler in two ways. First you can use compiled functions inside Pyro models (but those functions cannot contain Pyro primitives). Second, you can use Pyro's jit inference algorithms to compile entire inference steps; in static models this can reduce the Python overhead of Pyro models and speed up inference.
The rest of this tutorial focuses on Pyro's jitted inference algorithms: [JitTrace_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.trace_elbo.JitTrace_ELBO), [JitTraceGraph_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.tracegraph_elbo.JitTraceGraph_ELBO), [JitTraceEnum_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.traceenum_elbo.JitTraceEnum_ELBO), [JitMeanField_ELBO](http://docs.pyro.ai/en/dev/inference_algos.html#pyro.infer.trace_mean_field_elbo.JitTraceMeanField_ELBO), [HMC(jit_compile=True)](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.HMC), and [NUTS(jit_compile=True)](http://docs.pyro.ai/en/dev/mcmc.html#pyro.infer.mcmc.NUTS). For further reading, see the [examples/](https://github.com/pyro-ppl/pyro/tree/dev/examples) directory, where most examples include a `--jit` option to run in compiled mode.
## A simple model
Let's start with a simple Gaussian model and an [autoguide](http://docs.pyro.ai/en/dev/infer.autoguide.html).
```
def model(data):
loc = pyro.sample("loc", dist.Normal(0., 10.))
scale = pyro.sample("scale", dist.LogNormal(0., 3.))
with pyro.plate("data", data.size(0)):
pyro.sample("obs", dist.Normal(loc, scale), obs=data)
guide = AutoDiagonalNormal(model)
data = dist.Normal(0.5, 2.).sample((100,))
```
First let's run as usual with an SVI object and `Trace_ELBO`.
```
%%time
pyro.clear_param_store()
elbo = Trace_ELBO()
svi = SVI(model, guide, Adam({'lr': 0.01}), elbo)
for i in range(2 if smoke_test else 1000):
svi.step(data)
```
Next to run with a jit compiled inference, we simply replace
```diff
- elbo = Trace_ELBO()
+ elbo = JitTrace_ELBO()
```
Also note that the `AutoDiagonalNormal` guide behaves a little differently on its first invocation (it runs the model to produce a prototype trace), and we don't want to record this warmup behavior when compiling. Thus we call the `guide(data)` once to initialize, then run the compiled SVI,
```
%%time
pyro.clear_param_store()
guide(data) # Do any lazy initialization before compiling.
elbo = JitTrace_ELBO()
svi = SVI(model, guide, Adam({'lr': 0.01}), elbo)
for i in range(2 if smoke_test else 1000):
svi.step(data)
```
Notice that we have a more than 2x speedup for this small model.
Let us now use the same model, but we will instead use MCMC to generate samples from the model's posterior. We will use the No-U-Turn(NUTS) sampler.
```
%%time
nuts_kernel = NUTS(model)
pyro.set_rng_seed(1)
mcmc_run = MCMC(nuts_kernel, num_samples=100).run(data)
```
We can compile the potential energy computation in NUTS using the `jit_compile=True` argument to the NUTS kernel. We also silence JIT warnings due to the presence of tensor constants in the model by using `ignore_jit_warnings=True`.
```
%%time
nuts_kernel = NUTS(model, jit_compile=True, ignore_jit_warnings=True)
pyro.set_rng_seed(1)
mcmc_run = MCMC(nuts_kernel, num_samples=100).run(data)
```
We notice a significant increase in sampling throughput when JIT compilation is enabled.
## Varying structure
Time series models often run on datasets of multiple time series with different lengths. To accomodate varying structure like this, Pyro requires models to separate all model inputs into tensors and non-tensors.$^\dagger$
- Non-tensor inputs should be passed as `**kwargs` to the model and guide. These can determine model structure, so that a model is compiled for each value of the passed `**kwargs`.
- Tensor inputs should be passed as `*args`. These must not determine model structure. However `len(args)` may determine model structure (as is used e.g. in semisupervised models).
To illustrate this with a time series model, we will pass in a sequence of observations as a tensor `arg` and the sequence length as a non-tensor `kwarg`:
```
def model(sequence, num_sequences, length, state_dim=16):
# This is a Gaussian HMM model.
with pyro.plate("states", state_dim):
trans = pyro.sample("trans", dist.Dirichlet(0.5 * torch.ones(state_dim)))
emit_loc = pyro.sample("emit_loc", dist.Normal(0., 10.))
emit_scale = pyro.sample("emit_scale", dist.LogNormal(0., 3.))
# We're doing manual data subsampling, so we need to scale to actual data size.
with poutine.scale(scale=num_sequences):
# We'll use enumeration inference over the hidden x.
x = 0
for t in pyro.markov(range(length)):
x = pyro.sample("x_{}".format(t), dist.Categorical(trans[x]),
infer={"enumerate": "parallel"})
pyro.sample("y_{}".format(t), dist.Normal(emit_loc[x], emit_scale),
obs=sequence[t])
guide = AutoDiagonalNormal(poutine.block(model, expose=["trans", "emit_scale", "emit_loc"]))
# This is fake data of different lengths.
lengths = [24] * 50 + [48] * 20 + [72] * 5
sequences = [torch.randn(length) for length in lengths]
```
Now lets' run SVI as usual.
```
%%time
pyro.clear_param_store()
elbo = TraceEnum_ELBO(max_plate_nesting=1)
svi = SVI(model, guide, Adam({'lr': 0.01}), elbo)
for i in range(1 if smoke_test else 10):
for sequence in sequences:
svi.step(sequence, # tensor args
num_sequences=len(sequences), length=len(sequence)) # non-tensor args
```
Again we'll simply swap in a `Jit*` implementation
```diff
- elbo = TraceEnum_ELBO(max_plate_nesting=1)
+ elbo = JitTraceEnum_ELBO(max_plate_nesting=1)
```
Note that we are manually specifying the `max_plate_nesting` arg. Usually Pyro can figure this out automatically by running the model once on the first invocation; however to avoid this extra work when we run the compiler on the first step, we pass this in manually.
```
%%time
pyro.clear_param_store()
# Do any lazy initialization before compiling.
guide(sequences[0], num_sequences=len(sequences), length=len(sequences[0]))
elbo = JitTraceEnum_ELBO(max_plate_nesting=1)
svi = SVI(model, guide, Adam({'lr': 0.01}), elbo)
for i in range(1 if smoke_test else 10):
for sequence in sequences:
svi.step(sequence, # tensor args
num_sequences=len(sequences), length=len(sequence)) # non-tensor args
```
Again we see more than 2x speedup. Note that since there were three different sequence lengths, compilation was triggered three times.
$^\dagger$ Note this section is only valid for SVI, and HMC/NUTS assume fixed model arguments.
| github_jupyter |
# Game-playing Agent
Notebook version of the project [Build a Game-playing Agent](https://github.com/udacity/AIND-Isolation) from [Udacity's Artificial Intelligence Nanodegree](https://www.udacity.com/course/artificial-intelligence-nanodegree--nd889) <br>
**Goal**: Implement an effective adversarial search agent to play the game **Isolation**
Isolation is a deterministic, two-player game of perfect information in which the players alternate turns moving a single piece from one cell to another on a board. Whenever either player occupies a cell, that cell becomes blocked for the remainder of the game. The first player with no remaining legal moves loses, and the opponent is declared the winner.
This project uses a version of Isolation where each agent is restricted to L-shaped movements (like a knight in chess) on a rectangular grid (like a chess or checkerboard). The agents can move to any open cell on the board that is 2-rows and 1-column or 2-columns and 1-row away from their current position on the board. Movements are blocked at the edges of the board (the board does not wrap around), however, the player can "jump" blocked or occupied spaces (just like a knight in chess).
Additionally, agents will have a fixed time limit each turn to search for the best move and respond. If the time limit expires during a player's turn, that player forfeits the match, and the opponent wins.
These rules are implemented in the `isolation.Board` class provided in the repository.
The final evaluation will estimate the strength rating of student-agent with iterative deepening and
a custom heuristic evaluation function against fixed-depth minimax and
alpha-beta search agents by running a round-robin tournament for the student
agent. The student agent plays a fixed number of "fair" matches against each test
agent. The matches are fair because the board is initialized randomly for both
players, and the players play each match twice -- switching the player order
between games. This helps to correct for imbalances in the game due to both
starting position and initiative.
For example, if the random moves chosen for initialization are (5, 2) and
(1, 3), then the first match will place agent A at (5, 2) as player 1 and
agent B at (1, 3) as player 2 then play to conclusion; the agents swap
initiative in the second match with agent B at (5, 2) as player 1 and agent A at
(1, 3) as player 2.
## Sample players
Collection of player classes for comparison with the custom agent and example heuristic functions
```
from random import randint
def null_score(game, player):
"""This heuristic presumes no knowledge for non-terminal states, and returns the same
uninformative value for all other states. """
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
return 0.
def open_move_score(game, player):
"""The basic evaluation function dthat outputs a score equal to the number of moves open
for your computer player on the board. """
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
return float(len(game.get_legal_moves(player)))
def improved_score(game, player):
"""The "Improved" evaluation function that outputs a score equal to the difference in the
number of moves available to the two players. """
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = len(game.get_legal_moves(player))
opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
return float(own_moves - opp_moves)
class RandomPlayer():
"""Player that chooses a move randomly."""
def get_move(self, game, legal_moves, time_left):
"""Randomly select a move from the available legal moves."""
if not legal_moves:
return (-1, -1)
return legal_moves[randint(0, len(legal_moves) - 1)]
class GreedyPlayer():
"""Player that chooses next move to maximize heuristic score. This is equivalent to a
minimax search agent with a search depth of one. """
def __init__(self, score_fn=open_move_score):
self.score = score_fn
def get_move(self, game, legal_moves, time_left):
if not legal_moves:
return (-1, -1)
_, move = max([(self.score(game.forecast_move(m), self), m) for m in legal_moves])
return move
class HumanPlayer():
"""Player that chooses a move according to user's input."""
def get_move(self, game, legal_moves, time_left):
"""
Select a move from the available legal moves based on user input at the
terminal. If testing with this player, remember to disable move timeout in
the call to `Board.play()`. """
if not legal_moves:
return (-1, -1)
print(('\t'.join(['[%d] %s' % (i, str(move)) for i, move in enumerate(legal_moves)])))
valid_choice = False
while not valid_choice:
try:
index = int(input('Select move index:'))
valid_choice = 0 <= index < len(legal_moves)
if not valid_choice:
print('Illegal move! Try again.')
except ValueError:
print('Invalid index! Try again.')
return legal_moves[index]
```
## Custom heuristic score: Lock, mobility, and moves with a tuned linear function
Zero-sum function based on player’s mobility (moves / blank_spaces ), also predicting if one player can lock the other in its next ply:
- Predict if the player is about to win or lose when the adversary has no move available for its next play: +inf, -inf <br> This case is not detected by game.is_winner() or game.is_loser() due their inactive/active player condition.
- Predict if a player can reach the unique move available to the adversary, thus winning the game: +inf, inf
- The usual scenario is valued as: `score = A * own_mobility + B * opp_mobility + C * own_moves + D * opp_moves`. Mobility is defined as the ratio between the available move of the player and the total available cells of the board. Thus the value of looking for more legal moves will be increased when the game is about to end due to lack of empty cells. After a few tournaments, the selected parameters were tuned to: `A = 10, B = -10, C = 1, D = 0`
```
def custom_score(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves_list = game.get_legal_moves(player)
own_moves = len(own_moves_list)
opp_moves_list = (game.get_legal_moves(game.get_opponent(player)))
opp_moves = len(opp_moves_list)
# game.is_loser() game.is_winner depends on the active player.
# These cases can occur. e.g.: Opponent has no moves while Own is active
if opp_moves == 0:
return float("inf")
if own_moves == 0:
return float("-inf")
# Thus we can predict 1 ply more
# This easy killing move can also be predicted:
# Lock the opponent if, in your turn, you can get to its unique move
if (player == game.active_player and opp_moves == 1
and opp_moves_list[0] in own_moves_list):
return float("inf")
# opposite case
if (player != game.active_player and own_moves == 1
and own_moves_list[0] in opp_moves_list):
return float("-inf")
# heuristic values for the rest of the cases
blank_spaces = game.width * game.height - game.move_count
own_mobility = own_moves / blank_spaces
opp_mobility = opp_moves / blank_spaces
score = 10 * (own_mobility - opp_mobility) + own_moves
return float(score)
```
## Custom Player
Game-playing agent that chooses a move using your evaluation function and a depth-limited minimax algorithm with alpha-beta pruning; also making sure it properly uses minimax and alpha-beta to return a good move before the search time limit expires.
- `CustomPlayer.minimax()`: implement minimax search
- `CustomPlayer.alphabeta()`: implement minimax search with alpha-beta pruning
- `CustomPlayer.get_move()`: implement fixed-depth and iterative deepening search
```
class CustomPlayer:
"""
Parameters
----------
search_depth : int (optional)
A strictly positive integer (i.e., 1, 2, 3,...) for the number of
layers in the game tree to explore for fixed-depth search. (i.e., a
depth of one (1) would only explore the immediate sucessors of the
current state.)
score_fn : callable (optional)
A function to use for heuristic evaluation of game states.
iterative : boolean (optional)
Flag indicating whether to perform fixed-depth search (False) or
iterative deepening search (True).
method : {'minimax', 'alphabeta'} (optional)
The name of the search method to use in get_move().
timeout : float (optional)
Time remaining (in milliseconds) when search is aborted. Should be a
positive value large enough to allow the function to return before the
timer expires.
"""
def __init__(self,
search_depth=3,
score_fn=custom_score,
iterative=True,
method='minimax',
timeout=10.):
self.search_depth = search_depth
self.iterative = iterative
self.score = score_fn
self.method = method
self.time_left = None
self.TIMER_THRESHOLD = timeout
def get_move(self, game, legal_moves, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
legal_moves : list<(int, int)>
A list containing legal moves. Moves are encoded as tuples of pairs
of ints defining the next (row, col) for the agent to occupy.
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
move = None
if not legal_moves:
return -1, -1
try:
if self.iterative: # Iterative search
depth = 1
# Get the best move found (higher value) evaluating each level
# (from top to bottom) before searching in the next level.
# Timeout or an optimal state found (e.g. win) returns
while True:
if self.method == 'minimax':
score, move = self.minimax(game, depth)
elif self.method == 'alphabeta':
score, move = self.alphabeta(game, depth)
depth += 1
# No need to wait for Timeout if an optimal move is reached
if score == float('inf'):
return move
else: # Depth-first search
if self.method == 'minimax':
_, move = self.minimax(game, self.search_depth)
elif self.method == 'alphabeta':
_, move = self.alphabeta(game, self.search_depth)
except Timeout:
pass
# Return the best move from the last completed search iteration
return move
def minimax(self, game, depth, maximizing_player=True):
"""Implement the minimax search algorithm as described in the lectures.
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
maximizing_player : bool
Flag indicating whether the current search depth corresponds to a
maximizing layer (True) or a minimizing layer (False)
Returns
-------
float
The score for the current search branch
tuple(int, int)
The best move for the current branch; (-1, -1) for no legal moves
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
legal_moves = game.get_legal_moves()
move = (-1, -1)
# If no more moves -> Terminal state: return its score with move (-1,-1)
if not legal_moves:
return self.score(game, self), move
# depth 0 evaluates and returns directly the value for the current state
# The current location here is the move to return
# (it won't be evaualted again since depth = 0)
if depth == 0:
score = self.score(game, self)
move = game.get_player_location(self)
return score, move
depth -= 1 # Each recursive call to minimax will have one less depth
if maximizing_player:
# MAX-VALUE node: Get the maximum value from the MIN-VALUE nodes of
# its next level
score, move = max([(self.minimax(game.forecast_move(m), depth, False)[0], m)
for m in legal_moves])
else:
# MIN-VALUE node: Get the minimum value from the MAX-VALUE nodes of
# its next level
score, move = min([(self.minimax(game.forecast_move(m), depth, True)[0], m)
for m in legal_moves])
return score, move
def alphabeta(self,
game,
depth,
alpha=float("-inf"),
beta=float("inf"),
maximizing_player=True):
"""Implement minimax search with alpha-beta pruning as described in the
lectures.
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
maximizing_player : bool
Flag indicating whether the current search depth corresponds to a
maximizing layer (True) or a minimizing layer (False)
Returns
-------
float
The score for the current search branch
tuple(int, int)
The best move for the current branch; (-1, -1) for no legal moves
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
legal_moves = game.get_legal_moves()
move = (-1, -1)
score = None
# If no more moves -> Terminal state: return its score with move (-1,-1)
if not legal_moves:
return self.score(game, self), move
# depth 0 evaluates and returns directly the value for the current state
# The current location here is the move to return
# (it won't be evaluated again since depth = 0)
if depth == 0:
score = self.score(game, self)
move = game.get_player_location(self) # Todo
return score, move
depth -= 1 # Each recursive call to alphabeta will have one less depth
# A dict with key=move and value=score is used for pruning the branches
scores = {}
if maximizing_player: # MAX-VALUE node
for m in legal_moves:
# evaluate the next level of m (minimizing player)
# and return its scores dictionary
scores[m], _ = self.alphabeta(game.forecast_move(m), depth, alpha, beta, False)
# get the max value of the resulted scores dictionary for the
# current level(maximizing player)
move = max(scores, key=scores.get)
score = scores[move]
# Prune the next branches (for the next m's) if the value
# obtained so far is larger than beta
# (best choice for MIN in the higher level).
if score >= beta:
return score, move
# Update alpha (best choice for MAX) for the next evaluation
# (minimizing player)
alpha = max(alpha, score)
else:
for m in legal_moves: # MIN-VALUE node
# evaluate the next level of m (maximizing player) and return
# its scores dictionary
scores[m], _ = self.alphabeta(game.forecast_move(m), depth, alpha, beta, True)
# get the min value of the resulted scores dictionary for the
# current level(minimizing player)
move = min(scores, key=scores.get)
score = scores[move]
# Prune the next branches (for the next m's) if the value
# obtained so far is smaller than alpha
# (best choice for MAX in the higher level).
if score <= alpha:
return score, move
# Update beta (best choice for MIN) for the next evaluation
# (maximazing player)
beta = min(beta, score)
return score, move
```
## Game setup
```
import itertools
import random
import warnings
from collections import namedtuple
from isolation import Board
NUM_MATCHES = 5 # number of matches against each opponent
TIME_LIMIT = 30 # number of milliseconds before timeout
TIMEOUT_WARNING = "One or more agents lost a match this round due to " + \
"timeout. The get_move() function must return before " + \
"time_left() reaches 0 ms. You will need to leave some " + \
"time for the function to return, and may need to " + \
"increase this margin to avoid timeouts during " + \
"tournament play."
Agent = namedtuple("Agent", ["player", "name"])
class Timeout(Exception):
"""Subclass base exception for code clarity."""
pass
```
Play a "fair" set of matches between two agents by playing two games between the players, forcing each agent to play from randomly selected positions. This should control for differences in outcome resulting from advantage due to starting position on the board.
```
def play_match(player1, player2):
num_wins = {player1: 0, player2: 0}
num_timeouts = {player1: 0, player2: 0}
num_invalid_moves = {player1: 0, player2: 0}
games = [Board(player1, player2), Board(player2, player1)]
# initialize both games with a random move and response
for _ in range(2):
move = random.choice(games[0].get_legal_moves())
games[0].apply_move(move)
games[1].apply_move(move)
# play both games and tally the results
for game in games:
winner, _, termination = game.play(time_limit=TIME_LIMIT)
if player1 == winner:
num_wins[player1] += 1
if termination == "timeout":
num_timeouts[player2] += 1
else:
num_invalid_moves[player2] += 1
elif player2 == winner:
num_wins[player2] += 1
if termination == "timeout":
num_timeouts[player1] += 1
else:
num_invalid_moves[player1] += 1
if sum(num_timeouts.values()) != 0:
warnings.warn(TIMEOUT_WARNING)
return num_wins[player1], num_wins[player2]
```
Play one round (i.e., a single match between each pair of opponents)
```
def play_round(agents, num_matches):
agent_1 = agents[-1]
wins = 0.
total = 0.
print("\nPlaying Matches:")
print("----------")
for idx, agent_2 in enumerate(agents[:-1]):
counts = {agent_1.player: 0., agent_2.player: 0.}
names = [agent_1.name, agent_2.name]
print(" Match {}: {!s:^11} vs {!s:^11}".format(idx + 1, *names), end=' ')
# Each player takes a turn going first
for p1, p2 in itertools.permutations((agent_1.player, agent_2.player)):
for _ in range(num_matches):
score_1, score_2 = play_match(p1, p2)
counts[p1] += score_1
counts[p2] += score_2
total += score_1 + score_2
wins += counts[agent_1.player]
print("\tResult: {} to {}".format(
int(counts[agent_1.player]), int(counts[agent_2.player])))
return 100. * wins / total
```
## Evaluation
This section evaluates the performance of the custom heuristic function by
comparing the strength of an agent using iterative deepening (ID) search with
alpha-beta pruning against the strength rating of agents using other heuristic
functions. The `ID_Improved` agent provides a baseline by measuring the
performance of a basic agent using Iterative Deepening and the "improved"
heuristic (from lecture) on your hardware. The `Student` agent then measures
the performance of Iterative Deepening and the custom heuristic against the
same opponents.
The performance of time-limited iterative deepening search is hardware dependent (faster hardware is expected to search deeper than slower hardware in the same amount of time). The script controls for these effects by also measuring the baseline performance of an agent called "ID_Improved" that uess Iterative Deepening and the improved_score heuristic from the above sample players.
The tournament opponents are listed below:
- Random: An agent that randomly chooses a move each turn.
- MM_Null: CustomPlayer agent using fixed-depth minimax search and the null_score heuristic
- MM_Open: CustomPlayer agent using fixed-depth minimax search and the open_move_score heuristic
- MM_Improved: CustomPlayer agent using fixed-depth minimax search and the improved_score heuristic
- AB_Null: CustomPlayer agent using fixed-depth alpha-beta search and the null_score heuristic
- AB_Open: CustomPlayer agent using fixed-depth alpha-beta search and the open_move_score heuristic
- AB_Improved: CustomPlayer agent using fixed-depth alpha-beta search and the improved_score heuristic
```
HEURISTICS = [("Null", null_score), ("Open", open_move_score), ("Improved", improved_score)]
AB_ARGS = {"search_depth": 5, "method": 'alphabeta', "iterative": False}
MM_ARGS = {"search_depth": 3, "method": 'minimax', "iterative": False}
CUSTOM_ARGS = {"method": 'alphabeta', 'iterative': True}
# Create a collection of CPU agents
mm_agents = [
Agent(CustomPlayer(score_fn=h, **MM_ARGS), "MM_" + name) for name, h in HEURISTICS
]
ab_agents = [
Agent(CustomPlayer(score_fn=h, **AB_ARGS), "AB_" + name) for name, h in HEURISTICS
]
random_agents = [Agent(RandomPlayer(), "Random")]
# ID_Improved agent is used for comparison to the performance of the
# submitted agent for calibration on the performance across different
# systems; i.e., the performance of the student agent is considered
# relative to the performance of the ID_Improved agent to account for
# faster or slower computers.
test_agents = [
Agent(CustomPlayer(score_fn=improved_score, **CUSTOM_ARGS), "ID_Improved"),
Agent(CustomPlayer(score_fn=custom_score, **CUSTOM_ARGS), "Student")
]
for agentUT in test_agents:
print("")
print("*************************")
print("{:^25}".format("Evaluating: " + agentUT.name))
print("*************************")
agents = random_agents + mm_agents + ab_agents + [agentUT]
win_ratio = play_round(agents, NUM_MATCHES)
print("\n\nResults:")
print("----------")
print("{!s:<15}{:>10.2f}%".format(agentUT.name, win_ratio))
```
| github_jupyter |
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import sys
from collections import OrderedDict
import warnings
warnings.filterwarnings("ignore")
def applypca(dataset):
X = dataset
#In general a good idea is to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)
pca = PCA()
x_new = pca.fit_transform(X)
score = x_new[:,0:2]
coeff = np.transpose(pca.components_[0:2, :])
return pca, x_new, score, coeff
```
# M31
```
# M31
m31_oid = np.memmap('../data/oid_m31.dat', mode='r', dtype=np.uint64)
m31_names = open('../data/feature_m31.name').read().split()
m31_x = np.memmap('../data/feature_m31.dat', mode='r', dtype=np.float32, shape=(m31_oid.size, len(m31_names)))
m31 = pd.DataFrame(m31_x, index=m31_oid, columns=m31_names)
m31
#RUN PCA
pca_m31, x_new_m31, score_m31, coeff_m31 = applypca(m31)
pca_num = []
for i in range(1, 43):
pca_num.append('PCA{}'.format(i))
pca_drop = []
for i in range(16, 43): #drop PCA features you don't want
pca_drop.append('PCA{}'.format(i))
pca42_m31 = pd.DataFrame(x_new_m31, index=m31_oid, columns=pca_num) #original result
pca15_m31 = pca42_m31.drop(pca_drop, axis=1) #choose subset only 15 most important features!
pca15_m31
# create .dat file
m_m31 = np.memmap('../data/feature_m31_pca15.dat', mode='w+', dtype=np.float32, shape=pca15_m31.shape)
m_m31[:] = pca15_m31
del(m_m31)
# create .name file
with open('../data/feature_m31_pca15.name', 'w') as f:
for pcaname in pca15_m31.columns:
f.write("{}\n".format(pcaname))
```
# DISK
```
# DISK
disk_oid = np.memmap('../data/oid_disk.dat', mode='r', dtype=np.uint64)
disk_names = open('../data/feature_disk.name').read().split()
disk_x = np.memmap('../data/feature_disk.dat', mode='r', dtype=np.float32, shape=(disk_oid.size, len(disk_names)))
disk = pd.DataFrame(disk_x, index=disk_oid, columns=disk_names)
disk
#RUN PCA
pca_disk, x_new_disk, score_disk, coeff_disk = applypca(disk)
pca_num = []
for i in range(1, 43):
pca_num.append('PCA{}'.format(i))
pca_drop = []
for i in range(16, 43): #drop PCA features you don't want
pca_drop.append('PCA{}'.format(i))
pca42_disk = pd.DataFrame(x_new_disk, index=disk_oid, columns=pca_num) #original result
pca15_disk = pca42_disk.drop(pca_drop, axis=1) #choose subset only 15 most important features!
pca15_disk
# create .dat file
m_disk = np.memmap('../data/feature_disk_pca15.dat', mode='w+', dtype=np.float32, shape=pca15_disk.shape)
m_disk[:] = pca15_disk
del(m_disk)
# create .name file
with open('../data/feature_disk_pca15.name', 'w') as f:
for pcaname in pca15_disk.columns:
f.write("{}\n".format(pcaname))
```
# DEEP
```
# DEEP
deep_oid = np.memmap('../data/oid_deep.dat', mode='r', dtype=np.uint64)
deep_names = open('../data/feature_deep.name').read().split()
deep_x = np.memmap('../data/feature_deep.dat', mode='r', dtype=np.float32, shape=(deep_oid.size, len(deep_names)))
deep = pd.DataFrame(deep_x, index=deep_oid, columns=deep_names)
deep
#RUN PCA
pca_deep, x_new_deep, score_deep, coeff_deep = applypca(deep)
pca_num = []
for i in range(1, 43):
pca_num.append('PCA{}'.format(i))
pca_drop = []
for i in range(16, 43): #drop PCA features you don't want
pca_drop.append('PCA{}'.format(i))
pca42_deep = pd.DataFrame(x_new_deep, index=deep_oid, columns=pca_num) #original result
pca15_deep = pca42_deep.drop(pca_drop, axis=1) #choose subset only 15 most important features!
pca15_deep
# create .dat file
m_deep = np.memmap('../data/feature_deep_pca15.dat', mode='w+', dtype=np.float32, shape=pca15_deep.shape)
m_deep[:] = pca15_deep
del(m_deep)
# create .name file
with open('../data/feature_deep_pca15.name', 'w') as f:
for pcaname in pca15_deep.columns:
f.write("{}\n".format(pcaname))
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import surprise
from surprise import SVD
from surprise import accuracy
from surprise import KNNBasic, KNNWithMeans, KNNBaseline
from surprise import Reader
from surprise.model_selection import train_test_split
from surprise import Dataset
!pip install surprise
movie_df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/movie.csv')
rating_df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/rating.csv')
link_df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/link.csv')
tag_df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/tag.csv')
genome_tags_df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/genome_tags.csv')
genome_scores_df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/genome_scores.csv')
```
### Cleaning Data
```
#function returns a small sample of rating and movie data combined (5 million data)
def movie_rating_sample_data(movie_df,rating_df):
movie_rating_combined = pd.merge(movie_df,rating_df,on='movieId')
combined_small = movie_rating_combined.iloc[:5000000]
return combined_small
#function to remove rating counts less than 1000
def filter_less_thrsh(combined_small,thresh = 1000):
combined_small = combined_small[combined_small.groupby('title').rating.transform('count')>thresh]
return combined_small
#function to remove and rename columns
def remove_rename(combined_small):
combined_small = combined_small[['userId','movieId','rating']]
combined_small = combined_small.rename(columns={'userId':'user','movieId':'item',})
return combined_small
combined_small = movie_rating_sample_data(movie_df,rating_df)
combined_small = filter_less_thrsh(combined_small)
#lets check our data
combined_small.head(5)
```
### EDA
```
#function returns number of ratings per movie
def movie_info_count(combined_small):
#movie rating count
movie_rating_count = combined_small.groupby('title')['rating'].count().sort_values(ascending=False)
#unique movie length
movie_length = len(combined_small['title'].unique())
print("movi rating count:\n")
print(movie_rating_count)
print('-----'*20)
print('length of unique movies: ',movie_length)
#function to plot important information
def plot_info(combined_small):
#plot number of users per rating
combined_small.groupby('rating').count()['userId'].plot.bar(figsize=(12,8))
plt.show()
#plot average rating for a title
combined_small.groupby('title').mean()['rating'].plot.bar(figsize=(12,8))
plt.show()
#plot
movie_info_count(combined_small)
plot_info(combined_small)
```
## Building Basic Collaborative filtering
```
print(len(combined_small['title'].unique()))
#remove columns and rename them
combined_small = remove_rename(combined_small)
#combined_small.drop(['genres','title'],inplace=True,axis=1)
combined_small.head(5)
#combined_small.to_csv('/content/drive/MyDrive/Colab Notebooks/movie_lens/combined_small.csv')
reader = Reader(rating_scale=(1, 5))
data = Dataset.load_from_df(combined_small, reader)
trainset, testset = train_test_split(data, test_size=.25)
algorithm = SVD()
algorithm.fit(trainset)
predictions = algorithm.test(testset)
surprise.dump.dump('/content/drive/MyDrive/Colab Notebooks/movie_lens/my_model',predictions=predictions)
predictions[1]
```
### Checking accuracy and predicting
```
# check the accuracy using Root Mean Square Error
accuracy.rmse(predictions)
#movie_rating cropped
movie_rating_combined = pd.merge(movie_df,rating_df,on='movieId')
movie_info_small = movie_rating_combined.iloc[:5000000]
movie_info_small.head(3)
#create index item name and value item id series
movies_list_id = pd.Series(movie_info_small['movieId'].unique(),index=movie_info_small['title'].unique())
movies_list_id
def get_movies_recommendation(movie_name):
item_id = []
movie_id = movies_list_id.loc[movies_list_id.index == movie_name][0]
user_id = combined_small.loc[combined_small.item == movie_id]['user'].tolist()[:5]
for id in user_id:
for i in range(len(predictions)):
if predictions[i].uid == id:
item_id.append(predictions[i].iid)
movies_names = movies_list_id.loc[movies_list_id.isin(item_id)].index.tolist()[:5]
return movies_names
get_movies_recommendation('Funny Face (1957)')
```
| github_jupyter |
```
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
import pandas as pd
import plotly.graph_objects as go
import numpy as np
from typing import List
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from tqdm import tqdm
from collections import namedtuple
df = pd.read_hdf('../datasets/XBTUSD_1min.h5', key='XBT')
df['Open'] = pd.to_numeric(df['Open'])
df['High'] = pd.to_numeric(df['High'])
df['Low'] = pd.to_numeric(df['Low'])
df['Close'] = pd.to_numeric(df['Close'])
df['Volume'] = pd.to_numeric(df['Volume'])
df_month = df['2019-08-1':'2019-08-2']
low_indx = df_month['Low'].argsort().values
class LongTrade():
def __init__(self, entry_price : float, take_profit_pct : float, entry_date : datetime, leverage : int = 10):
self.entry_price = entry_price
self.take_profit_pct = take_profit_pct
self.entry_date = entry_date
self.leverage = leverage
self.close_price : float = None
self.close_date : datetime = None
self.profit = None
def calc_exit(self, df_prices):
tp_price = self.entry_price * (1 + self.take_profit_pct / 100)
res = df_prices[df_prices['High'] >= tp_price]
if len(res) == 0:
return
self.close_price : float = tp_price
self.close_date : datetime = res.index[0]
self.profit : float = self.take_profit_pct * self.leverage
def isTradeOverlapping(trades: List[LongTrade], trade: LongTrade):
if len(trades) == 0:
return False
for t in trades:
if trade.entry_date <= t.close_date and trade.entry_date >= t.entry_date:
return True
if trade.close_date <= t.close_date and trade.close_date >= t.entry_date:
return True
if trade.close_date >= t.close_date and trade.entry_date <= t.entry_date:
return True
return False
trades : List[LongTrade] = []
PROFIT_PCTG = 2
for low_i in tqdm(low_indx):
trade = LongTrade(df_month['Low'].iloc[low_i], PROFIT_PCTG, df_month.index[low_i])
trade.calc_exit(df_month.iloc[low_i+1:])
if trade.profit is not None and not isTradeOverlapping(trades, trade):
trades.append(trade)
print(len(trades), sum([t.profit for t in trades]))
fig = go.Figure(data=[go.Candlestick(x=df_month.index,
open=df_month['Open'], high=df_month['High'],
low=df_month['Low'], close=df_month['Close'])
])
for t in trades:
fig.add_shape(type="rect",
x0=t.entry_date, y0=t.entry_price, x1=t.close_date, y1=t.close_price,
line=dict(
color="RoyalBlue",
width=2,
)
)
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/josephineHonore/AIF360/blob/master/colab_examples/colab_workshop_adversarial_debiasing.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Colab Setup
This section configures your environment to be able to run this notebook on Google Colab. Before you run this notebook, make sure you are running in a python 3 environment. You can change your runtime environment by choosing
> Runtime > Change runtime type
in the menu.
```
!python --version
# This notebook runs in Tensorflow 1.x. Soon will default be 2.x in Colab.
%tensorflow_version 1.x
!pip install -q -U \
aif360==0.2.2 \
tqdm==4.38.0 \
tensorflow==1.15 \
numpy==1.17.4 \
matplotlib==3.1.1 \
pandas==0.25.3 \
scipy==1.3.2 \
scikit-learn==0.21.3 \
cvxpy==1.0.25 \
scs==2.1.0 \
numba==0.42.0 \
networkx==2.4 \
imgaug==0.2.6 \
BlackBoxAuditing==0.1.54 \
lime==0.1.1.36 \
adversarial-robustness-toolbox==1.0.1
```
## Notes
- The above pip command is created using AIF360's [requirements.txt](https://github.com/josephineHonore/AIF360/blob/master/requirements.txt). At the moment, the job to update these libraries is manual.
- The original notebook uses Markdown to display formated text. Currently this is [unsupported](https://github.com/googlecolab/colabtools/issues/322) in Colab.
- The tensorflow dependency is not needed for all other notebooks.
- We have changed TensorFlow's logging level to `ERROR`, just after the import of the library, to limit the amount of logging shown to the user.
- We have added code to fix the random seeds for reproducibility
```
def printb(text):
"""Auxiliar function to print in bold.
Compensates for bug in Colab that doesn't show Markdown(diplay('text'))
"""
print('\x1b[1;30m'+text+'\x1b[0m')
```
# Start of Original Notebook
#### This notebook demonstrates the use of adversarial debiasing algorithm to learn a fair classifier.
Adversarial debiasing [1] is an in-processing technique that learns a classifier to maximize prediction accuracy and simultaneously reduce an adversary's ability to determine the protected attribute from the predictions. This approach leads to a fair classifier as the predictions cannot carry any group discrimination information that the adversary can exploit. We will see how to use this algorithm for learning models with and without fairness constraints and apply them on the Adult dataset.
```
%matplotlib inline
# Load all necessary packages
import sys
sys.path.append("../")
from aif360.datasets import BinaryLabelDataset
from aif360.datasets import AdultDataset, GermanDataset, CompasDataset
from aif360.metrics import BinaryLabelDatasetMetric
from aif360.metrics import ClassificationMetric
from aif360.metrics.utils import compute_boolean_conditioning_vector
from aif360.algorithms.preprocessing.optim_preproc_helpers.data_preproc_functions import load_preproc_data_adult, load_preproc_data_compas, load_preproc_data_german
from aif360.algorithms.inprocessing.adversarial_debiasing import AdversarialDebiasing
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler, MaxAbsScaler
from sklearn.metrics import accuracy_score
from IPython.display import Markdown, display
import matplotlib.pyplot as plt
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.logging.ERROR)
SEED = 42
```
#### Load dataset and set options
```
# Get the dataset and split into train and test
dataset_orig = load_preproc_data_adult()
privileged_groups = [{'sex': 1}]
unprivileged_groups = [{'sex': 0}]
dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=True, seed=SEED)
# print out some labels, names, etc.
#display(Markdown("#### Training Dataset shape"))
printb('#### Training Dataset shape')
print(dataset_orig_train.features.shape)
#display(Markdown("#### Favorable and unfavorable labels"))
printb("#### Favorable and unfavorable labels")
print(dataset_orig_train.favorable_label, dataset_orig_train.unfavorable_label)
#display(Markdown("#### Protected attribute names"))
printb("#### Protected attribute names")
print(dataset_orig_train.protected_attribute_names)
#display(Markdown("#### Privileged and unprivileged protected attribute values"))
printb("#### Privileged and unprivileged protected attribute values")
print(dataset_orig_train.privileged_protected_attributes,
dataset_orig_train.unprivileged_protected_attributes)
#display(Markdown("#### Dataset feature names"))
printb("#### Dataset feature names")
print(dataset_orig_train.feature_names)
```
#### Metric for original training data
```
# Metric for the original dataset
metric_orig_train = BinaryLabelDatasetMetric(dataset_orig_train,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
#display(Markdown("#### Original training dataset"))
printb("#### Original training dataset")
print("Train set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.mean_difference())
metric_orig_test = BinaryLabelDatasetMetric(dataset_orig_test,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Test set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_test.mean_difference())
min_max_scaler = MaxAbsScaler()
dataset_orig_train.features = min_max_scaler.fit_transform(dataset_orig_train.features)
dataset_orig_test.features = min_max_scaler.transform(dataset_orig_test.features)
metric_scaled_train = BinaryLabelDatasetMetric(dataset_orig_train,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
#display(Markdown("#### Scaled dataset - Verify that the scaling does not affect the group label statistics"))
printb("#### Scaled dataset - Verify that the scaling does not affect the group label statistics")
print("Train set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_scaled_train.mean_difference())
metric_scaled_test = BinaryLabelDatasetMetric(dataset_orig_test,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Test set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_scaled_test.mean_difference())
```
### Learn plan classifier without debiasing
```
# Load post-processing algorithm that equalizes the odds
# Learn parameters with debias set to False
sess = tf.Session()
tf.set_random_seed(SEED)
plain_model = AdversarialDebiasing(privileged_groups = privileged_groups,
unprivileged_groups = unprivileged_groups,
scope_name='plain_classifier',
debias=False,
sess=sess,
seed=SEED)
plain_model.fit(dataset_orig_train)
# Apply the plain model to test data
dataset_nodebiasing_train = plain_model.predict(dataset_orig_train)
dataset_nodebiasing_test = plain_model.predict(dataset_orig_test)
# Metrics for the dataset from plain model (without debiasing)
#display(Markdown("#### Plain model - without debiasing - dataset metrics"))
printb("#### Plain model - without debiasing - dataset metrics")
metric_dataset_nodebiasing_train = BinaryLabelDatasetMetric(dataset_nodebiasing_train,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Train set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_dataset_nodebiasing_train.mean_difference())
metric_dataset_nodebiasing_test = BinaryLabelDatasetMetric(dataset_nodebiasing_test,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Test set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_dataset_nodebiasing_test.mean_difference())
#display(Markdown("#### Plain model - without debiasing - classification metrics"))
printb("#### Plain model - without debiasing - classification metrics")
classified_metric_nodebiasing_test = ClassificationMetric(dataset_orig_test,
dataset_nodebiasing_test,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Test set: Classification accuracy = %f" % classified_metric_nodebiasing_test.accuracy())
TPR = classified_metric_nodebiasing_test.true_positive_rate()
TNR = classified_metric_nodebiasing_test.true_negative_rate()
bal_acc_nodebiasing_test = 0.5*(TPR+TNR)
print("Test set: Balanced classification accuracy = %f" % bal_acc_nodebiasing_test)
print("Test set: Disparate impact = %f" % classified_metric_nodebiasing_test.disparate_impact())
print("Test set: Equal opportunity difference = %f" % classified_metric_nodebiasing_test.equal_opportunity_difference())
print("Test set: Average odds difference = %f" % classified_metric_nodebiasing_test.average_odds_difference())
print("Test set: Theil_index = %f" % classified_metric_nodebiasing_test.theil_index())
```
### Apply in-processing algorithm based on adversarial learning
```
sess.close()
tf.reset_default_graph()
sess = tf.Session()
tf.set_random_seed(SEED)
# Learn parameters with debias set to True
debiased_model = AdversarialDebiasing(privileged_groups = privileged_groups,
unprivileged_groups = unprivileged_groups,
scope_name='debiased_classifier',
debias=True,
sess=sess,
seed=SEED)
debiased_model.fit(dataset_orig_train)
# Apply the plain model to test data
dataset_debiasing_train = debiased_model.predict(dataset_orig_train)
dataset_debiasing_test = debiased_model.predict(dataset_orig_test)
# Metrics for the dataset from plain model (without debiasing)
#display(Markdown("#### Plain model - without debiasing - dataset metrics"))
printb("#### Plain model - without debiasing - dataset metrics")
print("Train set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_dataset_nodebiasing_train.mean_difference())
print("Test set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_dataset_nodebiasing_test.mean_difference())
# Metrics for the dataset from model with debiasing
#display(Markdown("#### Model - with debiasing - dataset metrics"))
printb("#### Model - with debiasing - dataset metrics")
metric_dataset_debiasing_train = BinaryLabelDatasetMetric(dataset_debiasing_train,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Train set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_dataset_debiasing_train.mean_difference())
metric_dataset_debiasing_test = BinaryLabelDatasetMetric(dataset_debiasing_test,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Test set: Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_dataset_debiasing_test.mean_difference())
#display(Markdown("#### Plain model - without debiasing - classification metrics"))
printb("#### Plain model - without debiasing - classification metrics")
print("Test set: Classification accuracy = %f" % classified_metric_nodebiasing_test.accuracy())
TPR = classified_metric_nodebiasing_test.true_positive_rate()
TNR = classified_metric_nodebiasing_test.true_negative_rate()
bal_acc_nodebiasing_test = 0.5*(TPR+TNR)
print("Test set: Balanced classification accuracy = %f" % bal_acc_nodebiasing_test)
print("Test set: Disparate impact = %f" % classified_metric_nodebiasing_test.disparate_impact())
print("Test set: Equal opportunity difference = %f" % classified_metric_nodebiasing_test.equal_opportunity_difference())
print("Test set: Average odds difference = %f" % classified_metric_nodebiasing_test.average_odds_difference())
print("Test set: Theil_index = %f" % classified_metric_nodebiasing_test.theil_index())
#display(Markdown("#### Model - with debiasing - classification metrics"))
printb("#### Model - with debiasing - classification metrics")
classified_metric_debiasing_test = ClassificationMetric(dataset_orig_test,
dataset_debiasing_test,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
print("Test set: Classification accuracy = %f" % classified_metric_debiasing_test.accuracy())
TPR = classified_metric_debiasing_test.true_positive_rate()
TNR = classified_metric_debiasing_test.true_negative_rate()
bal_acc_debiasing_test = 0.5*(TPR+TNR)
print("Test set: Balanced classification accuracy = %f" % bal_acc_debiasing_test)
print("Test set: Disparate impact = %f" % classified_metric_debiasing_test.disparate_impact())
print("Test set: Equal opportunity difference = %f" % classified_metric_debiasing_test.equal_opportunity_difference())
print("Test set: Average odds difference = %f" % classified_metric_debiasing_test.average_odds_difference())
print("Test set: Theil_index = %f" % classified_metric_debiasing_test.theil_index())
```
References:
[1] B. H. Zhang, B. Lemoine, and M. Mitchell, "Mitigating UnwantedBiases with Adversarial Learning,"
AAAI/ACM Conference on Artificial Intelligence, Ethics, and Society, 2018.
# Exploring the results
Let's take a deeper look at the previous results.
```
#@title Code to define `print_table` function to show results in tabular format
from IPython.display import HTML, display
def print_table(headers,data,caption=""):
"""
Prints a table given headers and data
Inputs:
- headers: a list of N headers
- data: a list of N-element lists containing the data to display
- caption: a string describing the data
Outputs:
- A HTML display of the table
Example:
caption = "A caption"
headers = ["row","title 1", "title 2"]
data = [["first row", 1, 2], ["second row", 2, 3]]
print_table(headers,data,caption)
A Caption
-----------------------------------
| row | title 1 | title 2 |
-----------------------------------
| first row | 1 | 2 |
-----------------------------------
| second row | 2 | 3 |
-----------------------------------
"""
display(HTML(
'<table border="1"><caption>{0}</caption><tr>{1}</tr><tr>{2}</tr></table>'.format(
caption,
'<th>{}</th>'.format('</th><th>'.join(line for line in headers)),
'</tr><tr>'.join(
'<td>{}</td>'.format(
'</td><td>'.join(
str(_) for _ in row)) for row in data))
))
table = [["Train set",metric_dataset_nodebiasing_train.mean_difference(),metric_dataset_debiasing_train.mean_difference()],
["Test set",metric_dataset_nodebiasing_test.mean_difference(),metric_dataset_debiasing_test.mean_difference()]]
headers = ['Statistical parity difference','Without debiasing','With debiasing']
caption = "Difference in mean outcomes between unprivileged and privileged groups"
print_table(headers,table,caption)
```
We observe a big reduction in the statistical parity difference by training with Adversarial learning debias mitigation.
Let's look at the result of this technique by evaluating other fairness metrics.
```
metrics_final = [["Accuracy", "%f" % classified_metric_nodebiasing_test.accuracy(), "%f" % classified_metric_debiasing_test.accuracy()],
["Balanced classification accuracy","%f" % bal_acc_nodebiasing_test, "%f" % bal_acc_debiasing_test],
["Disparate impact","%f" % classified_metric_nodebiasing_test.disparate_impact(), "%f" % classified_metric_debiasing_test.disparate_impact()],
["Equal opportunity difference", "%f" % classified_metric_nodebiasing_test.equal_opportunity_difference(), "%f" % classified_metric_debiasing_test.equal_opportunity_difference()],
["Average odds difference", "%f" % classified_metric_nodebiasing_test.average_odds_difference(), "%f" % classified_metric_debiasing_test.average_odds_difference()],
["Theil_index", "%f" % classified_metric_nodebiasing_test.theil_index(), "%f" % classified_metric_debiasing_test.theil_index()]]
headers_final = ["Classification metric", "Without debiasing","With debiasing"]
caption_final = "Difference in model performance by using Adversarial Learning mitigation"
print_table(headers_final, metrics_final, caption_final)
```
It is hard to remember the definition and the ideal expected value for each metric. We can use [explainers](https://aif360.readthedocs.io/en/latest/modules/explainers.html#) to explain each metric. There are two kind of flavours: TEXT and JSON. The JSON explainers provide structured explanations that can be used to present information to the users. Here are some examples.
```
#@title Define `format_json` function for pretty print of JSON explainers
import json
from collections import OrderedDict
def format_json(json_str):
return json.dumps(json.loads(json_str, object_pairs_hook=OrderedDict), indent=2)
from aif360.explainers import MetricJSONExplainer
# Define explainers for the metrics with and without debiasing
ex_nondebias_test = MetricJSONExplainer(classified_metric_nodebiasing_test)
ex_debias_test = MetricJSONExplainer(classified_metric_debiasing_test)
```
Now let's print the explainers for the metrics we used above. Make sure you read the whole text.
```
printb("Nondebiasing")
print(format_json(ex_nondebias_test.accuracy()))
printb("Debiasing")
print(format_json(ex_debias_test.accuracy()))
printb("Nondebiasing")
print(format_json(ex_nondebias_test.disparate_impact()))
printb("Debiasing")
print(format_json(ex_debias_test.disparate_impact()))
printb("Nondebiasing")
print(format_json(ex_nondebias_test.equal_opportunity_difference()))
printb("Debiasing")
print(format_json(ex_debias_test.equal_opportunity_difference()))
printb("Nondebiasing")
print(format_json(ex_nondebias_test.average_odds_difference()))
printb("Debiasing")
print(format_json(ex_debias_test.average_odds_difference()))
printb("Nondebiasing")
print(format_json(ex_nondebias_test.theil_index()))
printb("Debiasing")
print(format_json(ex_debias_test.theil_index()))
```
# Excercises and questions
Let's make sure you understand what you just did while working on this notebook.
1. Rerun this notebook with `race` as the protected attribute. How different are the results on the fairness metrics?
2. What does the `Adversarial Debiasing` technique do?
3. What kind of classifier is this technique using? What hyperparameters could you tune?
4. Can I use the current implementation to optimize for several protected attributes?
| github_jupyter |
We use `notebooks/examples/1 - Make Channel Network` removing extraneous discussion and visualizations wherever possible. We also include a node attribute that uses the distance transform in a node's associated segment. This will be used to very roughly compare [RivGraph](https://github.com/jonschwenk/RivGraph/tree/master/rivgraph) and [ChanGeom](https://www.burchfisher.com/data.html)'s approach to measuring width.
```
import rasterio
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
import networkx as nx
from orinoco import (get_distance_in_channel,
get_distance_segments,
get_undirected_channel_network,
direct_channel_network,
export_edges_to_geodataframe,
export_nodes_to_geodataframe,
get_map_centroid_from_binary_mask,
add_flow_attributes,
split_tuple_pairs,
get_segment_df,
get_geo_width_df,
update_graph_with_widths,
get_width_features_from_segments,
add_width_features_to_graph,
get_array_from_features
)
from skimage.color import label2rgb
import random
import geopandas as gpd
from shapely.geometry import Point
from tqdm import tqdm
```
# Initialize the Tile Directory
```
tile_name = 'NH15'
tile_dir = Path(f'out/{tile_name}')
tile_dir.exists()
```
# Read Data from the Tile Directory
```
with rasterio.open(tile_dir/f'water_mask_{tile_name}.tif') as ds:
water_mask = ds.read(1)
with rasterio.open(tile_dir/f'ocean_mask_{tile_name}.tif') as ds:
ocean_mask = ds.read(1)
profile = ds.profile
plt.imshow(water_mask, interpolation='none')
```
# Generate Orinoco Products
## Obtaining the Distance Function
```
transform = profile['transform']
dx, dy = transform.a, -transform.e
dist = get_distance_in_channel(water_mask,
ocean_mask,
dx=dx,
dy=dy,
# removes areas with less than percentage of total size
min_rel_area=0.0,
# Applys a 1 pixel buffer for distance computation
# for artifical 8-connectivity.
# See: https://github.com/scikit-fmm/scikit-fmm/issues/32
# Removes buffer after computation complete.
# Only recommended for GRWL
apply_mask_buffer=True
)
plt.imshow(dist, interpolation='none')
```
Save the distance product.
```
p = profile.copy()
p['dtype'] = 'float32'
with rasterio.open(tile_dir/f'distance_{tile_name}.tif', 'w', **p) as ds:
ds.write(dist.astype(np.float32), 1)
```
## Segmentation of the Channel
```
pixel_step = 5
segments, interface_adj_segments = get_distance_segments(dist,
pixel_step,
dx=dx,
dy=dy,
connectivity=8,
min_size=4)
segments_rgb = label2rgb(segments, bg_label=0)
plt.imshow(segments_rgb, interpolation='none')
```
We save both the `segments` and the `segments_rgb` to disk.
```
p = profile.copy()
p['dtype'] = 'int32'
with rasterio.open(tile_dir/f'segments_{tile_name}.tif', 'w', **p) as ds:
ds.write(segments.astype(np.int32), 1)
p = profile.copy()
p['dtype'] = 'float32'
p['count'] = 3
with rasterio.open(tile_dir/f'segments_rgb_{tile_name}.tif', 'w', **p) as ds:
ds.write(segments_rgb.transpose([2, 0, 1]).astype(np.float32))
```
## Obtaining the Undirected Network
```
chanG_undirected = get_undirected_channel_network(segments,
dist,
profile,
interface_adj_segments,
connectivity=8)
node_data = chanG_undirected.nodes(data=True)
[(node, data) for (node, data) in node_data if data['label'] == 268]
```
## Obtaining the Directed Network
```
chanG = direct_channel_network(chanG_undirected,
# The keywords below are how the pruning occurs
# Specifies pruning will be done
remove_dangling=True,
# Do not prune nodes within 1 km of interface
interface_buffer_m=1_000,
# Remove edge groups with an degree 1 endpoint and size <=3
group_min_size=3,
# How many times to do this pruning
dangling_iterations=1
)
```
Let's do a quick sanity check.
```
df_edges = export_edges_to_geodataframe(chanG, profile['crs'])
df_edges.plot(column='segment_id', categorical=True)
```
## Obtaining the Widths
### Using the distance transform
We are going to use the distance transform within a segment. We have a function that determines the width according to $2\cdot d - 1$ where d is the distance to the land mask according to the distance transform in a small 1-pixel buffer around the segment (if this is 0, we use the full distance transform on the channel mask).
```
width_features = get_width_features_from_segments(segments, profile)
widths = get_array_from_features(segments, width_features)
plt.imshow(widths, interpolation='none')
plt.colorbar()
```
We now add these attributes to the graph.
```
chanG = add_width_features_to_graph(chanG, width_features.ravel())
node_data =dict(chanG.nodes(data=True))
random.choice(list(node_data.items()))
```
### Using $\nabla \varphi$
We compute width using the gradient of the distance function (and possibly the network structure). First we obtain the orientation of along wich to obtain these measured widths (perpendicular to the artificial flow).
```
chanG = add_flow_attributes(chanG, dist, profile['transform'])
```
To perform intersection, we must extract the polygons of the segments. This takes a bit of time to polygonize the segments, so be patient.
```
%%time
df_segments = get_segment_df(segments, chanG, profile, connectivity=8)
df_segments.head()
```
We will save the geometries to a file for later inspection.
```
df_segments_out = split_tuple_pairs(df_segments)
df_segments_out.to_file(tile_dir/'segments.geojson',
driver='GeoJSON')
```
Now we extract the widths are associated geometry. This is the most expensive computation in the notebook, so be very patient. Could take 5 minutes or so.
```
%%time
df_geo_widths = get_geo_width_df(df_segments, chanG, radius=1)
df_geo_widths.head()
```
Let's save the widths again for later inspection.
```
df_geo_widths_out = split_tuple_pairs(df_geo_widths)
df_geo_widths_out = df_geo_widths_out[~df_geo_widths_out.geometry.is_empty]
df_geo_widths_out.to_file(tile_dir/'width_geometries.geojson',
driver='GeoJSON')
```
We update the node attributes. And we see all of the attributes we have added.
```
len(chanG)
chanG = update_graph_with_widths(chanG, df_geo_widths)
node_data =dict(chanG.nodes(data=True))
random.choice(list(node_data.items()))
```
# Save Network
We now save the nodes and edges to `geojson` files and serialize the NetworkX `DiGraph` with `pickle`.
```
df_nodes = export_nodes_to_geodataframe(chanG, profile['crs'])
df_nodes = split_tuple_pairs(df_nodes)
df_edges = export_edges_to_geodataframe(chanG, profile['crs'])
df_edges.to_file(tile_dir/f'{tile_name}_edges.geojson', driver='GeoJSON')
df_nodes.drop(columns=['interface_adj']).to_file(tile_dir/f'{tile_name}_nodes.geojson', driver='GeoJSON')
nx.write_gpickle(chanG, tile_dir/f'{tile_name}_network.pkl')
```
| github_jupyter |
# General Structured Output Models with Shogun Machine Learning Toolbox
#### Shell Hu (GitHub ID: [hushell](https://github.com/hushell))
#### Thanks Patrick Pletscher and Fernando J. Iglesias García for taking time to help me finish the project! Shoguners = awesome! Me = grateful!
## Introduction
This notebook illustrates the training of a <a href="http://en.wikipedia.org/wiki/Factor_graph">factor graph</a> model using <a href="http://en.wikipedia.org/wiki/Structured_support_vector_machine">structured SVM</a> in Shogun. We begin by giving a brief outline of factor graphs and <a href="http://en.wikipedia.org/wiki/Structured_prediction">structured output learning</a> followed by the corresponding API in Shogun. Finally, we test the scalability by performing an experiment on a real <a href="http://en.wikipedia.org/wiki/Optical_character_recognition">OCR</a> data set for <a href="http://en.wikipedia.org/wiki/Handwriting_recognition">handwritten character recognition</a>.
### Factor Graph
A factor graph explicitly represents the factorization of an undirected graphical model in terms of a set of factors (potentials), each of which is defined on a clique in the original graph [1]. For example, a MRF distribution can be factorized as
$$
P(\mathbf{y}) = \frac{1}{Z} \prod_{F \in \mathcal{F}} \theta_F(\mathbf{y}_F),
$$
where $F$ is the factor index, $\theta_F(\mathbf{y}_F)$ is the energy with respect to assignment $\mathbf{y}_F$. In this demo, we focus only on table representation of factors. Namely, each factor holds an energy table $\theta_F$, which can be viewed as an unnormalized CPD. According to different factorizations, there are different types of factors. Usually we assume the Markovian property is held, that is, factors have the same parameterization if they belong to the same type, no matter how location or time changes. In addition, we have parameter free factor type, but nothing to learn for such kinds of types. More detailed implementation will be explained later.
### Structured Prediction
Structured prediction typically involves an input $\mathbf{x}$ (can be structured) and a structured output $\mathbf{y}$. A joint feature map $\Phi(\mathbf{x},\mathbf{y})$ is defined to incorporate structure information into the labels, such as chains, trees or general graphs. In general, the linear parameterization will be used to give the prediction rule. We leave the kernelized version for future work.
$$
\hat{\mathbf{y}} = \underset{\mathbf{y} \in \mathcal{Y}}{\operatorname{argmax}} \langle \mathbf{w}, \Phi(\mathbf{x},\mathbf{y}) \rangle
$$
where $\Phi(\mathbf{x},\mathbf{y})$ is the feature vector by mapping local factor features to corresponding locations in terms of $\mathbf{y}$, and $\mathbf{w}$ is the global parameter vector. In factor graph model, parameters are associated with a set of factor types. So $\mathbf{w}$ is a collection of local parameters.
The parameters are learned by regularized risk minimization, where the risk defined by user provided loss function $\Delta(\mathbf{y},\mathbf{\hat{y}})$ is usually non-convex and non-differentiable, e.g. the Hamming loss. So the empirical risk is defined in terms of the surrogate hinge loss $H_i(\mathbf{w}) = \max_{\mathbf{y} \in \mathcal{Y}} \Delta(\mathbf{y}_i,\mathbf{y}) - \langle \mathbf{w}, \Psi_i(\mathbf{y}) \rangle $, which is an upper bound of the user defined loss. Here $\Psi_i(\mathbf{y}) = \Phi(\mathbf{x}_i,\mathbf{y}_i) - \Phi(\mathbf{x}_i,\mathbf{y})$. The training objective is given by
$$
\min_{\mathbf{w}} \frac{\lambda}{2} ||\mathbf{w}||^2 + \frac{1}{N} \sum_{i=1}^N H_i(\mathbf{w}).
$$
In Shogun's factor graph model, the corresponding implemented functions are:
- <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CStructuredModel.html#a15bd99e15bbf0daa8a727d03dbbf4bcd">FactorGraphModel::get_joint_feature_vector()</a> $\longleftrightarrow \Phi(\mathbf{x}_i,\mathbf{y})$
- <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CFactorGraphModel.html#a36665cfdd7ea2dfcc9b3c590947fe67f">FactorGraphModel::argmax()</a> $\longleftrightarrow H_i(\mathbf{w})$
- <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CFactorGraphModel.html#a17dac99e933f447db92482a6dce8489b">FactorGraphModel::delta_loss()</a> $\longleftrightarrow \Delta(\mathbf{y}_i,\mathbf{y})$
## Experiment: OCR
### Show Data
First of all, we load the OCR data from a prepared mat file. The raw data can be downloaded from <a href="http://www.seas.upenn.edu/~taskar/ocr/">http://www.seas.upenn.edu/~taskar/ocr/</a>. It has 6876 handwritten words with an average length of 8 letters from 150 different persons. Each letter is rasterized into a binary image of size 16 by 8 pixels. Thus, each $\mathbf{y}$ is a chain, and each node has 26 possible states denoting ${a,\cdots,z}$.
```
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
import numpy as np
import scipy.io
dataset = scipy.io.loadmat(os.path.join(SHOGUN_DATA_DIR, 'ocr/ocr_taskar.mat'))
# patterns for training
p_tr = dataset['patterns_train']
# patterns for testing
p_ts = dataset['patterns_test']
# labels for training
l_tr = dataset['labels_train']
# labels for testing
l_ts = dataset['labels_test']
# feature dimension
n_dims = p_tr[0,0].shape[0]
# number of states
n_stats = 26
# number of training samples
n_tr_samples = p_tr.shape[1]
# number of testing samples
n_ts_samples = p_ts.shape[1]
```
Few examples of the handwritten words are shown below. Note that the first capitalized letter has been removed.
```
import matplotlib.pyplot as plt
def show_word(patterns, index):
"""show a word with padding"""
plt.rc('image', cmap='binary')
letters = patterns[0,index][:128,:]
n_letters = letters.shape[1]
for l in range(n_letters):
lett = np.transpose(np.reshape(letters[:,l], (8,16)))
lett = np.hstack((np.zeros((16,1)), lett, np.zeros((16,1))))
lett = np.vstack((np.zeros((1,10)), lett, np.zeros((1,10))))
subplot(1,n_letters,l+1)
imshow(lett)
plt.xticks(())
plt.yticks(())
plt.tight_layout()
show_word(p_tr, 174)
show_word(p_tr, 471)
show_word(p_tr, 57)
```
### Define Factor Types and Build Factor Graphs
Let's define 4 factor types, such that a word will be able to be modeled as a chain graph.
- The unary factor type will be used to define unary potentials that capture the appearance likelihoods of each letter. In our case, each letter has $16 \times 8$ pixels, thus there are $(16 \times 8 + 1) \times 26$ parameters. Here the additional bits in the parameter vector are bias terms. One for each state.
- The pairwise factor type will be used to define pairwise potentials between each pair of letters. This type in fact gives the Potts potentials. There are $26 \times 26$ parameters.
- The bias factor type for the first letter is a compensation factor type, since the interaction is one-sided. So there are $26$ parameters to be learned.
- The bias factor type for the last letter, which has the same intuition as the last item. There are also $26$ parameters.
Putting all parameters together, the global parameter vector $\mathbf{w}$ has length $4082$.
```
from shogun import TableFactorType
# unary, type_id = 0
cards_u = np.array([n_stats], np.int32)
w_gt_u = np.zeros(n_stats*n_dims)
fac_type_u = TableFactorType(0, cards_u, w_gt_u)
# pairwise, type_id = 1
cards = np.array([n_stats,n_stats], np.int32)
w_gt = np.zeros(n_stats*n_stats)
fac_type = TableFactorType(1, cards, w_gt)
# first bias, type_id = 2
cards_s = np.array([n_stats], np.int32)
w_gt_s = np.zeros(n_stats)
fac_type_s = TableFactorType(2, cards_s, w_gt_s)
# last bias, type_id = 3
cards_t = np.array([n_stats], np.int32)
w_gt_t = np.zeros(n_stats)
fac_type_t = TableFactorType(3, cards_t, w_gt_t)
# all initial parameters
w_all = [w_gt_u,w_gt,w_gt_s,w_gt_t]
# all factor types
ftype_all = [fac_type_u,fac_type,fac_type_s,fac_type_t]
```
Next, we write a function to construct the factor graphs and prepare labels for training. For each factor graph instance, the structure is a chain but the number of nodes and edges depend on the number of letters, where unary factors will be added for each letter, pairwise factors will be added for each pair of neighboring letters. Besides, the first and last letter will get an additional bias factor respectively.
```
def prepare_data(x, y, ftype, num_samples):
"""prepare FactorGraphFeatures and FactorGraphLabels """
from shogun import Factor, TableFactorType, FactorGraph
from shogun import FactorGraphObservation, FactorGraphLabels, FactorGraphFeatures
samples = FactorGraphFeatures(num_samples)
labels = FactorGraphLabels(num_samples)
for i in range(num_samples):
n_vars = x[0,i].shape[1]
data = x[0,i].astype(np.float64)
vc = np.array([n_stats]*n_vars, np.int32)
fg = FactorGraph(vc)
# add unary factors
for v in range(n_vars):
datau = data[:,v]
vindu = np.array([v], np.int32)
facu = Factor(ftype[0], vindu, datau)
fg.add_factor(facu)
# add pairwise factors
for e in range(n_vars-1):
datap = np.array([1.0])
vindp = np.array([e,e+1], np.int32)
facp = Factor(ftype[1], vindp, datap)
fg.add_factor(facp)
# add bias factor to first letter
datas = np.array([1.0])
vinds = np.array([0], np.int32)
facs = Factor(ftype[2], vinds, datas)
fg.add_factor(facs)
# add bias factor to last letter
datat = np.array([1.0])
vindt = np.array([n_vars-1], np.int32)
fact = Factor(ftype[3], vindt, datat)
fg.add_factor(fact)
# add factor graph
samples.add_sample(fg)
# add corresponding label
states_gt = y[0,i].astype(np.int32)
states_gt = states_gt[0,:]; # mat to vector
loss_weights = np.array([1.0/n_vars]*n_vars)
fg_obs = FactorGraphObservation(states_gt, loss_weights)
labels.add_label(fg_obs)
return samples, labels
# prepare training pairs (factor graph, node states)
n_tr_samples = 350 # choose a subset of training data to avoid time out on buildbot
samples, labels = prepare_data(p_tr, l_tr, ftype_all, n_tr_samples)
```
An example of graph structure is visualized as below, from which you may have a better sense how a factor graph being built. Note that different colors are used to represent different factor types.
```
try:
import networkx as nx # pip install networkx
except ImportError:
import pip
pip.main(['install', '--user', 'networkx'])
import networkx as nx
import matplotlib.pyplot as plt
# create a graph
G = nx.Graph()
node_pos = {}
# add variable nodes, assuming there are 3 letters
G.add_nodes_from(['v0','v1','v2'])
for i in range(3):
node_pos['v%d' % i] = (2*i,1)
# add factor nodes
G.add_nodes_from(['F0','F1','F2','F01','F12','Fs','Ft'])
for i in range(3):
node_pos['F%d' % i] = (2*i,1.006)
for i in range(2):
node_pos['F%d%d' % (i,i+1)] = (2*i+1,1)
node_pos['Fs'] = (-1,1)
node_pos['Ft'] = (5,1)
# add edges to connect variable nodes and factor nodes
G.add_edges_from([('v%d' % i,'F%d' % i) for i in range(3)])
G.add_edges_from([('v%d' % i,'F%d%d' % (i,i+1)) for i in range(2)])
G.add_edges_from([('v%d' % (i+1),'F%d%d' % (i,i+1)) for i in range(2)])
G.add_edges_from([('v0','Fs'),('v2','Ft')])
# draw graph
fig, ax = plt.subplots(figsize=(6,2))
nx.draw_networkx_nodes(G,node_pos,nodelist=['v0','v1','v2'],node_color='white',node_size=700,ax=ax)
nx.draw_networkx_nodes(G,node_pos,nodelist=['F0','F1','F2'],node_color='yellow',node_shape='s',node_size=300,ax=ax)
nx.draw_networkx_nodes(G,node_pos,nodelist=['F01','F12'],node_color='blue',node_shape='s',node_size=300,ax=ax)
nx.draw_networkx_nodes(G,node_pos,nodelist=['Fs'],node_color='green',node_shape='s',node_size=300,ax=ax)
nx.draw_networkx_nodes(G,node_pos,nodelist=['Ft'],node_color='purple',node_shape='s',node_size=300,ax=ax)
nx.draw_networkx_edges(G,node_pos,alpha=0.7)
plt.axis('off')
plt.tight_layout()
```
### Training
Now we can create the factor graph model and start training. We will use the tree max-product belief propagation to do MAP inference.
```
from shogun import FactorGraphModel, TREE_MAX_PROD
# create model and register factor types
model = FactorGraphModel(samples, labels, TREE_MAX_PROD)
model.add_factor_type(ftype_all[0])
model.add_factor_type(ftype_all[1])
model.add_factor_type(ftype_all[2])
model.add_factor_type(ftype_all[3])
```
In Shogun, we implemented several batch solvers and online solvers. Let's first try to train the model using a batch solver. We choose the dual bundle method solver (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CDualLibQPBMSOSVM.html">DualLibQPBMSOSVM</a>) [2], since in practice it is slightly faster than the primal n-slack cutting plane solver (<a a href="http://www.shogun-toolbox.org/doc/en/latest/PrimalMosekSOSVM_8h.html">PrimalMosekSOSVM</a>) [3]. However, it still will take a while until convergence. Briefly, in each iteration, a gradually tighter piece-wise linear lower bound of the objective function will be constructed by adding more cutting planes (most violated constraints), then the approximate QP will be solved. Finding a cutting plane involves calling the max oracle $H_i(\mathbf{w})$ and in average $N$ calls are required in an iteration. This is basically why the training is time consuming.
```
from shogun import DualLibQPBMSOSVM
from shogun import BmrmStatistics
import pickle
import time
# create bundle method SOSVM, there are few variants can be chosen
# BMRM, Proximal Point BMRM, Proximal Point P-BMRM, NCBM
# usually the default one i.e. BMRM is good enough
# lambda is set to 1e-2
bmrm = DualLibQPBMSOSVM(model, labels, 0.01)
bmrm.put('m_TolAbs', 20.0)
bmrm.put('verbose', True)
bmrm.set_store_train_info(True)
# train
t0 = time.time()
bmrm.train()
t1 = time.time()
w_bmrm = bmrm.get_real_vector('m_w')
print("BMRM took", t1 - t0, "seconds.")
```
Let's check the duality gap to see if the training has converged. We aim at minimizing the primal problem while maximizing the dual problem. By the weak duality theorem, the optimal value of the primal problem is always greater than or equal to dual problem. Thus, we could expect the duality gap will decrease during the time. A relative small and stable duality gap may indicate the convergence. In fact, the gap doesn't have to become zero, since we know it is not far away from the local minima.
```
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4))
primal_bmrm = bmrm.get_helper().get_real_vector('primal')
dual_bmrm = bmrm.get_result().get_hist_Fd_vector()
len_iter = min(primal_bmrm.size, dual_bmrm.size)
primal_bmrm = primal_bmrm[1:len_iter]
dual_bmrm = dual_bmrm[1:len_iter]
# plot duality gaps
xs = range(dual_bmrm.size)
axes[0].plot(xs, (primal_bmrm-dual_bmrm), label='duality gap')
axes[0].set_xlabel('iteration')
axes[0].set_ylabel('duality gap')
axes[0].legend(loc=1)
axes[0].set_title('duality gaps');
axes[0].grid(True)
# plot primal and dual values
xs = range(dual_bmrm.size-1)
axes[1].plot(xs, primal_bmrm[1:], label='primal')
axes[1].plot(xs, dual_bmrm[1:], label='dual')
axes[1].set_xlabel('iteration')
axes[1].set_ylabel('objective')
axes[1].legend(loc=1)
axes[1].set_title('primal vs dual');
axes[1].grid(True)
```
There are other statitics may also be helpful to check if the solution is good or not, such as the number of cutting planes, from which we may have a sense how tight the piece-wise lower bound is. In general, the number of cutting planes should be much less than the dimension of the parameter vector.
```
# statistics
bmrm_stats = bmrm.get_result()
nCP = bmrm_stats.nCP
nzA = bmrm_stats.nzA
print('number of cutting planes: %d' % nCP)
print('number of active cutting planes: %d' % nzA)
```
In our case, we have 101 active cutting planes, which is much less than 4082, i.e. the number of parameters. We could expect a good model by looking at these statistics. Now come to the online solvers. Unlike the cutting plane algorithms re-optimizes over all the previously added dual variables, an online solver will update the solution based on a single point. This difference results in a faster convergence rate, i.e. less oracle calls, please refer to Table 1 in [4] for more detail. Here, we use the stochastic subgradient descent (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CStochasticSOSVM.html">StochasticSOSVM</a>) to compare with the BMRM algorithm shown before.
```
from shogun import StochasticSOSVM
# the 3rd parameter is do_weighted_averaging, by turning this on,
# a possibly faster convergence rate may be achieved.
# the 4th parameter controls outputs of verbose training information
sgd = StochasticSOSVM(model, labels, True, True)
sgd.put('num_iter', 100)
sgd.put('lambda', 0.01)
# train
t0 = time.time()
sgd.train()
t1 = time.time()
w_sgd = sgd.get_real_vector('m_w')
print("SGD took", t1 - t0, "seconds.")
```
We compare the SGD and BMRM in terms of the primal objectives versus effective passes. We first plot the training progress (until both algorithms converge) and then zoom in to check the first 100 passes. In order to make a fair comparison, we set the regularization constant to 1e-2 for both algorithms.
```
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4))
primal_sgd = sgd.get_helper().get_real_vector('primal')
xs = range(dual_bmrm.size-1)
axes[0].plot(xs, primal_bmrm[1:], label='BMRM')
axes[0].plot(range(99), primal_sgd[1:100], label='SGD')
axes[0].set_xlabel('effecitve passes')
axes[0].set_ylabel('primal objective')
axes[0].set_title('whole training progress')
axes[0].legend(loc=1)
axes[0].grid(True)
axes[1].plot(range(99), primal_bmrm[1:100], label='BMRM')
axes[1].plot(range(99), primal_sgd[1:100], label='SGD')
axes[1].set_xlabel('effecitve passes')
axes[1].set_ylabel('primal objective')
axes[1].set_title('first 100 effective passes')
axes[1].legend(loc=1)
axes[1].grid(True)
```
As is shown above, the SGD solver uses less oracle calls to get to converge. Note that the timing is 2 times slower than they actually need, since there are additional computations of primal objective and training error in each pass. The training errors of both algorithms for each pass are shown in below.
```
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4))
terr_bmrm = bmrm.get_helper().get_real_vector('train_error')
terr_sgd = sgd.get_helper().get_real_vector('train_error')
xs = range(terr_bmrm.size-1)
axes[0].plot(xs, terr_bmrm[1:], label='BMRM')
axes[0].plot(range(99), terr_sgd[1:100], label='SGD')
axes[0].set_xlabel('effecitve passes')
axes[0].set_ylabel('training error')
axes[0].set_title('whole training progress')
axes[0].legend(loc=1)
axes[0].grid(True)
axes[1].plot(range(99), terr_bmrm[1:100], label='BMRM')
axes[1].plot(range(99), terr_sgd[1:100], label='SGD')
axes[1].set_xlabel('effecitve passes')
axes[1].set_ylabel('training error')
axes[1].set_title('first 100 effective passes')
axes[1].legend(loc=1)
axes[1].grid(True)
```
Interestingly, the training errors of SGD solver are lower than BMRM's in first 100 passes, but in the end the BMRM solver obtains a better training performance. A probable explanation is that BMRM uses very limited number of cutting planes at beginning, which form a poor approximation of the objective function. As the number of cutting planes increasing, we got a tighter piecewise lower bound, thus improve the performance. In addition, we would like to show the pairwise weights, which may learn important co-occurrances of letters. The hinton diagram is a wonderful tool for visualizing 2D data, in which positive and negative values are represented by white and black squares, respectively, and the size of each square represents the magnitude of each value. In our case, a smaller number i.e. a large black square indicates the two letters tend to coincide.
```
def hinton(matrix, max_weight=None, ax=None):
"""Draw Hinton diagram for visualizing a weight matrix."""
ax = ax if ax is not None else plt.gca()
if not max_weight:
max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for (x,y),w in np.ndenumerate(matrix):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w))
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
ax.invert_yaxis()
# get pairwise parameters, also accessible from
# w[n_dims*n_stats:n_dims*n_stats+n_stats*n_stats]
model.w_to_fparams(w_sgd) # update factor parameters
w_p = ftype_all[1].get_w()
w_p = np.reshape(w_p,(n_stats,n_stats))
hinton(w_p)
```
### Inference
Next, we show how to do inference with the learned model parameters for a given data point.
```
# get testing data
samples_ts, labels_ts = prepare_data(p_ts, l_ts, ftype_all, n_ts_samples)
from shogun import FactorGraphFeatures, FactorGraphObservation, TREE_MAX_PROD, MAPInference
# get a factor graph instance from test data
fg0 = samples_ts.get_sample(100)
fg0.compute_energies()
fg0.connect_components()
# create a MAP inference using tree max-product
infer_met = MAPInference(fg0, TREE_MAX_PROD)
infer_met.inference()
# get inference results
y_pred = infer_met.get_structured_outputs()
y_truth = FactorGraphObservation.obtain_from_generic(labels_ts.get_label(100))
print(y_pred.get_data())
print(y_truth.get_data())
```
### Evaluation
In the end, we check average training error and average testing error. The evaluation can be done by two methods. We can either use the apply() function in the structured output machine or use the <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CSOSVMHelper.html">SOSVMHelper</a>.
```
from shogun import SOSVMHelper
# training error of BMRM method
bmrm.put('m_w', w_bmrm)
model.w_to_fparams(w_bmrm)
lbs_bmrm = bmrm.apply()
acc_loss = 0.0
ave_loss = 0.0
for i in range(n_tr_samples):
y_pred = lbs_bmrm.get_label(i)
y_truth = labels.get_label(i)
acc_loss = acc_loss + model.delta_loss(y_truth, y_pred)
ave_loss = acc_loss / n_tr_samples
print('BMRM: Average training error is %.4f' % ave_loss)
# training error of stochastic method
print('SGD: Average training error is %.4f' % SOSVMHelper.average_loss(w_sgd, model))
# testing error
bmrm.set_features(samples_ts)
bmrm.set_labels(labels_ts)
lbs_bmrm_ts = bmrm.apply()
acc_loss = 0.0
ave_loss_ts = 0.0
for i in range(n_ts_samples):
y_pred = lbs_bmrm_ts.get_label(i)
y_truth = labels_ts.get_label(i)
acc_loss = acc_loss + model.delta_loss(y_truth, y_pred)
ave_loss_ts = acc_loss / n_ts_samples
print('BMRM: Average testing error is %.4f' % ave_loss_ts)
# testing error of stochastic method
print('SGD: Average testing error is %.4f' % SOSVMHelper.average_loss(sgd.get_real_vector('m_w'), model))
```
## References
[1] Kschischang, F. R., B. J. Frey, and H.-A. Loeliger, Factor graphs and the sum-product algorithm, IEEE Transactions on Information Theory 2001.
[2] Teo, C.H., Vishwanathan, S.V.N, Smola, A. and Quoc, V.Le, Bundle Methods for Regularized Risk Minimization, JMLR 2010.
[3] Tsochantaridis, I., Hofmann, T., Joachims, T., Altun, Y., Support Vector Machine Learning for Interdependent and Structured Ouput Spaces, ICML 2004.
[4] Lacoste-Julien, S., Jaggi, M., Schmidt, M., Pletscher, P., Block-Coordinate Frank-Wolfe Optimization for Structural SVMs, ICML 2013.
| github_jupyter |
# Hierarchical Clustering
> A Summary of lecture "Cluster Analysis in Python", via datacamp
- toc: true
- badges: true
- comments: true
- author: Chanseok Kang
- categories: [Python, Datacamp, Machine_Learning]
- image: images/fifa_cluster.png
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
```
## Basics of hierarchical clustering
- Creating a distance matrix using linkage
- ```method```: how to calculate the proximity of clusters
- ```metric```: distance metric
- ```optimal_ordering```: order data points
- Type of Methods
- single: based on two closest objects
- complete: based on two farthest objects
- average: based on the arithmetic mean of all objects
- centroids: based on the geometric mean of all objects
- median: based on the median of all objects
- ward: based on the sum of squares
### Hierarchical clustering: ward method
It is time for Comic-Con! Comic-Con is an annual comic-based convention held in major cities in the world. You have the data of last year's footfall, the number of people at the convention ground at a given time. You would like to decide the location of your stall to maximize sales. Using the ward method, apply hierarchical clustering to find the two points of attraction in the area.
- Preprocess
```
comic_con = pd.read_csv('./dataset/comic_con.csv', index_col=0)
comic_con.head()
from scipy.cluster.vq import whiten
comic_con['x_scaled'] = whiten(comic_con['x_coordinate'])
comic_con['y_scaled'] = whiten(comic_con['y_coordinate'])
from scipy.cluster.hierarchy import linkage, fcluster
# Use the linkage()
distance_matrix = linkage(comic_con[['x_scaled', 'y_scaled']], method='ward', metric='euclidean')
# Assign cluster labels
comic_con['cluster_labels'] = fcluster(distance_matrix, 2, criterion='maxclust')
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled', hue='cluster_labels', data=comic_con);
```
### Hierarchical clustering: single method
Let us use the same footfall dataset and check if any changes are seen if we use a different method for clustering.
```
# Use the linkage()
distance_matrix = linkage(comic_con[['x_scaled', 'y_scaled']], method='single', metric='euclidean')
# Assign cluster labels
comic_con['cluster_labels'] = fcluster(distance_matrix, 2, criterion='maxclust')
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled', hue='cluster_labels', data=comic_con);
```
### Hierarchical clustering: complete method
For the third and final time, let us use the same footfall dataset and check if any changes are seen if we use a different method for clustering.
```
# Use the linkage()
distance_matrix = linkage(comic_con[['x_scaled', 'y_scaled']], method='complete', metric='euclidean')
# Assign cluster labels
comic_con['cluster_labels'] = fcluster(distance_matrix, 2, criterion='maxclust')
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled', hue='cluster_labels', data=comic_con);
```
## Visualize clusters
- Why visualize clusters?
- Try to make sense of the clusters formed
- An additional step in validation of clusters
- Spot trends in data
### Visualize clusters with matplotlib
We have discussed that visualizations are necessary to assess the clusters that are formed and spot trends in your data. Let us now focus on visualizing the footfall dataset from Comic-Con using the matplotlib module.
```
# Define a colors dictionary for clusters
colors = {1:'red', 2:'blue'}
# Plot the scatter plot
comic_con.plot.scatter(x='x_scaled', y='y_scaled', c=comic_con['cluster_labels'].apply(lambda x: colors[x]));
```
### Visualize clusters with seaborn
Let us now visualize the footfall dataset from Comic Con using the seaborn module. Visualizing clusters using seaborn is easier with the inbuild ```hue``` function for cluster labels.
```
# Plot a scatter plot using seaborn
sns.scatterplot(x='x_scaled', y='y_scaled', hue='cluster_labels', data=comic_con)
```
## How many clusters?
- Introduction to dendrograms
- Strategy till now - decide clusters on visual inspection
- Dendrograms help in showing progressions as clusters are merged
- A dendrogram is a branching diagram that demonstrates how each cluster is composed by branching out into its child nodes
### Create a dendrogram
Dendrograms are branching diagrams that show the merging of clusters as we move through the distance matrix. Let us use the Comic Con footfall data to create a dendrogram.
```
from scipy.cluster.hierarchy import dendrogram
# Create a dendrogram
dn = dendrogram(distance_matrix)
```
### Limitations of hierarchical clustering
- Comparison of runtime of linkage method
- Increasing runtime with data points
- Quadratic increase of runtime
- Not feasible for large datasets
### Timing run of hierarchical clustering
In earlier exercises of this chapter, you have used the data of Comic-Con footfall to create clusters. In this exercise you will time how long it takes to run the algorithm on DataCamp's system.
Remember that you can time the execution of small code snippets with:
```python
%timeit sum([1, 3, 2])
```
```
%timeit linkage(comic_con[['x_scaled', 'y_scaled']], method='ward', metric='euclidean')
```
### FIFA 18: exploring defenders
In the FIFA 18 dataset, various attributes of players are present. Two such attributes are:
- sliding tackle: a number between 0-99 which signifies how accurate a player is able to perform sliding tackles
- aggression: a number between 0-99 which signifies the commitment and will of a player
These are typically high in defense-minded players. In this exercise, you will perform clustering based on these attributes in the data.
This data consists of 5000 rows, and is considerably larger than earlier datasets. Running hierarchical clustering on this data can take up to 10 seconds.
- Preprocess
```
fifa = pd.read_csv('./dataset/fifa_18_dataset.csv')
fifa.head()
fifa['scaled_sliding_tackle'] = whiten(fifa['sliding_tackle'])
fifa['scaled_aggression'] = whiten(fifa['aggression'])
# Fit the data into a hierarchical cluster
distance_matrix = linkage(fifa[['scaled_sliding_tackle', 'scaled_aggression']], method='ward')
# Assign cluster labels to each row of data
fifa['cluster_labels'] = fcluster(distance_matrix, 3, criterion='maxclust')
# Display cluster centers of each cluster
print(fifa[['scaled_sliding_tackle', 'scaled_aggression', 'cluster_labels']].groupby('cluster_labels').mean())
# Create a scatter plot through seaborn
sns.scatterplot(x='scaled_sliding_tackle', y='scaled_aggression', hue='cluster_labels', data=fifa)
plt.savefig('../images/fifa_cluster.png')
```
| github_jupyter |
# CHEM 1000 - Spring 2022
Prof. Geoffrey Hutchison, University of Pittsburgh
Chapter 2 in [*Mathematical Methods for Chemists*](http://sites.bu.edu/straub/mathematical-methods-for-molecular-science/)
## 2. Complex Numbers
By the end of this session, you should be able to:
- Understand complex numbers, including standard arithmetic
- Plot complex numbers on the complex plane in Cartesian and polar coordinates
- Understand converting complex numbers to polar format using Euler's formula
### Why?
A quick diversion into numbers.
We start teaching with 1, 2, 3, 4, 5.. - simple integers. Later we realize that if I have two apples in the kitchen and my kids each eat an apple, then:
```
2 - 2
```
Oops, I better go get more groceries! If I spend too much, my bank account may not look so good:
```
150 - 250
```
Okay, so we realize that zero and negative numbers are "new' kinds of numbers. They're not the only ones. I've skipped over fractions and decimals, which you should understand fairly well already.
```
3.0 / 2.0
```
If we use positive and negative integers, and decimals, we have adding, subtracting, multiplying, and dividing pretty well handled. We run into trouble in other kinds of functions, including trigonometry and square roots:
```
import math
print(math.sqrt(2))
print(math.pi)
```
These are, of course "irrational" numbers that don't have a finite decimal form. But what about:
```
math.sqrt(-1)
```
Uh oh, we broke Python!
So $\sqrt{-1}$ causes problems. You probably know it as an **imaginary number**. We give it a special name $i$. We don't need it in normal day-to-day life, but in science and math, it comes up whenever we take a square root of a negative number. This means, if we try to solve the quadratic equation:
$$x^2 - 2x + 5 = 0$$
The solutions are:
$$x = 1 \pm \sqrt{-4}$$
```
x = 1+2j # Python uses 'j' for the imaginary part, borrowing from electrical engineering
# we can separate out the real part
print(x.real)
# or the imaginary part
print(x.imag, 'i')
```
Python has a special module for complex number math `cmath`
```
import cmath
x = 1 + cmath.sqrt(-4)
print(x)
```
No, I wouldn't have used 'j' to indicate imaginary numbers in Python, but we'll just be careful what symbols we use going forward.
### Arithmetic
Adding and subtracting complex numbers isn't all that different from adding or subtracting real numbers. You just neeed to do it for both real and imaginary parts:
$$ (a + ib) + (c + id) = (a+c) + i(b+d) $$
```
x = 1 + 2j
y = -2 + 4j
print(x+y)
print(x-y)
```
### Multiplying
The usual rules of multiplication apply, just remembering that $i^2 = -1$:
$$ (a + ib)\times(c + id) = (ac + ibc + iad + i^2bd) = (ac - bd) + i(bc + ad)$$
```
print(x*y)
```
So it's possible to multiply two complex numbers and get a real number out... (here -10)
### Plotting on the Complex Plane
Because complex numbers consist of two parts - real and imaginary - we often represent a complex number as a point on a 2D plot, usually with the real component on the x-axis and the imaginary component on the y-axis.
```
# array of three complex numbers
points = [ 1+2j, 3+1j, -1.5-1.5j ]
# paste in our code for plotting with matplotlib
import numpy as np
import matplotlib.pyplot as plt
# insert any graphs into our notebooks directly
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
plt.style.use('./chem1000.mplstyle')
# translate our list into a numpy array for plotting
a = np.array(points)
# scatter plots show multiple independent points
# here with the x from the real component and y from the imaginary component
plt.scatter(a.real, a.imag)
plt.xlabel('real')
plt.ylabel('imaginary')
plt.show()
```
### Magnitude of Complex Numbers
One thing to consider is the magnitude of complex numbers. For real numbers, $|x| = \sqrt{x^2}$ (i.e., you just flip the sign on negative numbers. Can we use that for a complex number $z = x + iy$:
$$\sqrt{z^{2}}=\sqrt{(x+i y)^{2}}=\sqrt{x^{2}-y^{2}+2 i x y}$$
Clearly that's not actually the magnitude:
$$ |z| = \sqrt{x^2 + y^2} $$
So how do we get that?
### Complex Conjugate
If we have a complex number, we can define the 'complex conjugate' which flips the sign of the imaginary part:
$$z = a + ib$$
$$z^* = a - ib$$
Why is that useful?
$$|z| = \sqrt{zz^*} = \sqrt{(a+ib)(a-ib)} = \sqrt{a^2 + iab - iab + b^2} = \sqrt{a^2+b^2}$$
Note that the result of multiplying $z$ by $z^*$ ($zz^*$) is *guaranteed* to be a real number.
### Division
The usual rules of division apply. However, we typically want the result in the form
$z = x + iy$ so we can easily determine the real and imaginary parts. To do that, we need to multiply the fraction with the complex conjugate of the denominator.
$$\frac{a + ib}{c + id} \times \frac{c - id}{c - id} = \frac{(a + ib)(c - id)}{c^2 + d^2}$$
### Polar Coordinates for Complex Numbers
The 2D Cartesian display of complex numbers also lends itself to a polar assignment in terms of $r\theta$:
$$z = x + iy$$
$$z = r\cos\theta + ir\sin\theta$$
This relates to a significant formula, the *Euler relation*:
$$e^{i\theta} = \cos\theta + i\sin\theta$$
$$z= x + iy = r \cos \theta+i r \sin \theta=r(\cos \theta+i \sin \theta)=r e^{i \theta}$$
This means the complex conjugate would be:
$$z^{*} = x - iy = r \cos \theta-i r \sin \theta=r e^{-i \theta}$$
A related finding is:
$$e^{i\pi} = -1$$
$$e^{i\pi} +1 = 0$$
```
x = cmath.pi*cmath.sqrt(-1)
print(x)
print(format(cmath.exp(x) + 1, '.3f'))
```
This is "Euler's relation" or [Euler's formula](https://en.wikipedia.org/wiki/Euler%27s_formula) which connects $e$, $\pi$, $i$, 1, and 0 together.
It's almost unbelievable that these constants should connect - but as we can see, it comes from the connection between polar and Cartesian forms of complex numbers.
-------
This notebook is from Prof. Geoffrey Hutchison, University of Pittsburgh
https://github.com/ghutchis/chem1000
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a>
| github_jupyter |
# Plot the results of a Daedalus simulation
Before running this notebook, you need to run a simulation using `Daedalus` library. Please refer to [README](https://github.com/alan-turing-institute/daedalus/blob/master/README.md), Section: `Run Daedalus via command line`. After running the simulation, an `output` directory is created with the following structure:
```bash
output
└── E08000032
├── config_file_E08000032.yml
├── ssm_E08000032_MSOA11_ppp_2011_processed.csv
└── ssm_E08000032_MSOA11_ppp_2011_simulation.csv
└── year_1
└── ssm_E08000032_MSOA11_ppp_2011_simulation_year_1.csv
└── year_2
└── ssm_E08000032_MSOA11_ppp_2011_simulation_year_2.csv
```
Here, we will plot the results stored in these files.
```
import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pathlib import Path
import time
```
## Run re-assignment and validation
Refer to [the Evaluation section in README](https://github.com/alan-turing-institute/daedalus/blob/master/README.md#evaluation) for more information.
```
!python ../scripts/validation.py --simulation_dir ../output --persistent_data_dir ../persistent_data
```
## Read re-assigned population file
```
pop = pd.read_csv('../output/E08000032/ssm_E08000032_MSOA11_ppp_2011_simulation_reassigned.csv')
print(f"Number of rows: {len(pop)}")
pop.head()
# print some summary stats on the simulation
print('alive..................', len(pop[pop['alive'] == 'alive']))
print('dead...................', len(pop[pop['alive'] == 'dead']))
print('emigrated..............', len(pop[pop['alive'] == 'emigrated']))
print('immigrants.............', len(pop[pop['immigrated'] == 'Yes']))
print('internal migration.....', len(pop[pop['internal_outmigration'] == 'Yes']))
print('new children...........', len(pop[pop['parent_id'] != -1]))
```
## Plots
```
# Min/Max of datetimes in the dataframe
print(f'Min/Max entrance time: {pop["entrance_time"].min()} and {pop["entrance_time"].max()}')
print(f'Max exit time: {pop["exit_time"].dropna().max()}')
# Adjust the min and max dates for plotting (see the previous cell)
min_time = "2011-01-01"
max_time = datetime.datetime.strptime("2013-01-01", "%Y-%m-%d")
print("min_time:", min_time)
print("max_time:", max_time)
# --- input
# intervals for plotting (in days)
interval_in_days = 30.4375
# ---
time_axis = []
curr_pop_axis = []
alive_pop_axis = []
dead_pop_axis = []
emig_pop_axis = []
immg_pop_axis = []
internal_mig_pop_axis = []
new_babies_axis = []
avg_age_axis = []
curr_time = datetime.datetime.strptime(min_time, "%Y-%m-%d")
while curr_time <= max_time:
time_axis.append(curr_time)
# population in the current time step
curr_pop = pop[pop["entrance_time"] <= curr_time.strftime("%Y-%m-%d")]
alive_pop = curr_pop[curr_pop['alive'] == 'alive']
# For dead/emigrant populations, we need to consider both "alive" and "exit_time" columns
dead_pop = curr_pop[(curr_pop["exit_time"] <= curr_time.strftime("%Y-%m-%d")) &
(curr_pop["alive"] == "dead")]
emig_pop = curr_pop[(curr_pop["exit_time"] <= curr_time.strftime("%Y-%m-%d")) &
(curr_pop["alive"] == "emigrated")]
immg_pop = curr_pop[curr_pop["immigrated"] == "Yes"]
internal_mig_pop = curr_pop[(curr_pop["internal_outmigration"] == "Yes") &
(curr_pop["last_outmigration_time"] <= curr_time.strftime("%Y-%m-%d"))]
new_babies = curr_pop[curr_pop["parent_id"] != -1]
curr_pop_axis.append(len(curr_pop))
alive_pop_axis.append(len(alive_pop))
dead_pop_axis.append(len(dead_pop))
emig_pop_axis.append(len(emig_pop))
immg_pop_axis.append(len(immg_pop))
internal_mig_pop_axis.append(len(internal_mig_pop))
new_babies_axis.append(len(new_babies))
avg_age_axis.append(alive_pop["age"].mean())
# go to next time, according to the selected interval_in_days
curr_time = datetime.datetime.strptime(curr_time.strftime("%Y-%m-%d"), "%Y-%m-%d")
curr_time += datetime.timedelta(days=interval_in_days)
# Convert all lists to numpy arrays
curr_pop_axis = np.array(curr_pop_axis)
alive_pop_axis = np.array(alive_pop_axis)
dead_pop_axis = np.array(dead_pop_axis)
emig_pop_axis = np.array(emig_pop_axis)
immg_pop_axis = np.array(immg_pop_axis)
internal_mig_pop_axis = np.array(internal_mig_pop_axis)
new_babies_axis = np.array(new_babies_axis)
avg_age_axis = np.array(avg_age_axis)
# collect different populations (regarless of time)
pop_dead = pop[pop['alive'] == 'dead']
pop_emmig = pop[pop['alive'] == 'emigrated']
pop_immig = pop[pop["immigrated"] == "Yes"]
pop_internal = pop[pop['internal_outmigration'] == "Yes"]
pop_new_babies = pop[pop["parent_id"] != -1]
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
plt.figure(figsize=(30, 40))
# number of rows/columns in the figure
n_rows = 4
n_cols = 2
# ------ subplot 1
plt.subplot(n_rows, n_cols, 1)
plt.plot(time_axis, alive_pop_axis,
c='k', lw=4, label="alive")
plt.plot(time_axis, alive_pop_axis - new_babies_axis,
c='r', lw=4, ls="-", label="alive - newborn")
plt.plot(time_axis, alive_pop_axis - immg_pop_axis,
c='r', lw=4, ls="--", label="alive - immigrants")
plt.xlabel("Time", size=32)
plt.ylabel("Population", size=32)
plt.xticks(size=24, rotation=90)
plt.yticks(size=24)
plt.grid()
plt.legend(fontsize=24)
# ------ subplot 2
plt.subplot(n_rows, n_cols, 2)
plt.plot(time_axis, new_babies_axis,
c='k', lw=4, label="newborns")
plt.plot(time_axis, immg_pop_axis,
c='k', lw=4, ls='--', label="immigrants")
plt.plot(time_axis, dead_pop_axis,
c='r', lw=4, label="dead")
plt.plot(time_axis, emig_pop_axis,
c='r', lw=4, ls='--', label="emigrated")
plt.xlabel("Time", size=32)
plt.ylabel("Population", size=32)
plt.xticks(size=24, rotation=90)
plt.yticks(size=24)
plt.grid()
plt.legend(fontsize=24)
# ------ subplot 3
plt.subplot(n_rows, n_cols, 3)
series2plot = pop_new_babies['ethnicity'].value_counts() / pop["ethnicity"].value_counts() * 100.
indx = range(len(series2plot))
plt.bar(indx, series2plot, color='k')
plt.xticks(indx, series2plot.index, size=24, rotation=90)
plt.yticks(size=24)
plt.xlabel("Ethnicity", size=32)
plt.ylabel("% of newborns (group)", size=32)
plt.grid()
# ------ subplot 4
plt.subplot(n_rows, n_cols, 4)
series2plot = pop_new_babies['ethnicity'].value_counts().sort_index() / len(pop_new_babies["ethnicity"]) * 100.
indx = range(len(series2plot))
plt.bar(indx, series2plot, color='k')
plt.xticks(indx, series2plot.index, size=24, rotation=90)
plt.yticks(size=24)
plt.xlabel("Ethnicity", size=32)
plt.ylabel("% of newborns (total)", size=32)
plt.grid()
# ------ subplot 5
plt.subplot(n_rows, n_cols, 5)
series2plot = pop_immig['ethnicity'].value_counts() / pop["ethnicity"].value_counts() * 100.
indx = range(len(series2plot))
plt.bar(indx, series2plot, color='k')
plt.xticks(indx, series2plot.index, size=24, rotation=90)
plt.yticks(size=24)
plt.xlabel("Ethnicity", size=32)
plt.ylabel("% of immigrants (group)", size=32)
plt.grid()
# ------ subplot 6
plt.subplot(n_rows, n_cols, 6)
series2plot = pop_immig['ethnicity'].value_counts().sort_index() / len(pop_immig["ethnicity"]) * 100.
indx = range(len(series2plot))
plt.bar(indx, series2plot, color='k')
plt.xticks(indx, series2plot.index, size=24, rotation=90)
plt.yticks(size=24)
plt.xlabel("Ethnicity", size=32)
plt.ylabel("% of immigrants (total)", size=32)
plt.grid()
# ------ subplot 7
plt.subplot(n_rows, n_cols, 7)
series2plot = pop_internal['ethnicity'].value_counts() / pop["ethnicity"].value_counts() * 100.
indx = range(len(series2plot))
plt.bar(indx, series2plot, color='k')
plt.xticks(indx, series2plot.index, size=24, rotation=90)
plt.yticks(size=24)
plt.xlabel("Ethnicity", size=32)
plt.ylabel("% of internal migration (group)", size=32)
plt.grid()
# ------ subplot 8
plt.subplot(n_rows, n_cols, 8)
series2plot = pop_internal['ethnicity'].value_counts().sort_index() / len(pop_internal["ethnicity"]) * 100.
indx = range(len(series2plot))
plt.bar(indx, series2plot, color='k')
plt.xticks(indx, series2plot.index, size=24, rotation=90)
plt.yticks(size=24)
plt.xlabel("Ethnicity", size=32)
plt.ylabel("% of internal migration (total)", size=32)
plt.grid()
#plt.legend(fontsize=24)
plt.tight_layout()
plt.show()
plt.figure(figsize=(30, 30))
# ------ subplot 1
plt.subplot(3, 2, 1)
pop.iloc[pop_new_babies["parent_id"]]["age"].hist(bins=range(0, 100, 5),
rwidth=0.9, color='k', align='left')
plt.xlabel("Age", size=32)
plt.ylabel("Newborns", size=32)
plt.xticks(size=24)
plt.yticks(size=24)
# ------ subplot 2
plt.subplot(3, 2, 2)
pop_dead["age"].hist(bins=range(0, 100, 5),
rwidth=0.9, color='k', align='left')
plt.xlabel("Age", size=32)
plt.ylabel("Mortality", size=32)
plt.xticks(size=24)
plt.yticks(size=24)
# ------ subplot 3
plt.subplot(3, 2, 3)
pop_emmig["age"].hist(bins=range(0, 100, 5),
rwidth=0.9, color='k', align='left')
plt.xlabel("Age", size=32)
plt.ylabel("Emmigration", size=32)
plt.xticks(size=24)
plt.yticks(size=24)
# ------ subplot 4
plt.subplot(3, 2, 4)
pop_internal["age"].hist(bins=range(0, 100, 5),
rwidth=0.9, color='k', align='left')
plt.xlabel("Age", size=32)
plt.ylabel("Internal migration", size=32)
plt.xticks(size=24)
plt.yticks(size=24)
plt.tight_layout()
plt.show()
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import armageddon
from scipy.interpolate import interp1d
Cd=1.
H=8000.
rho0=1.2
init_altitude=100e3
n=100
radius = 1.02058734e+02
#def anal(radius, density=1):
init_altitude=100e3
n=100
velocity = 19.2e3
density = 3300
angle = 18.3*np.pi/180
# calcluating
A = np.pi*radius*radius
m = density*A*(4/3)*radius
beta = -H*Cd*A/(2*m*np.sin(angle))
C = beta * np.exp(-init_altitude/H) - np.log(velocity)
z = np.linspace(init_altitude, 0, n) # full range
v = np.exp(beta*np.exp(-z/H) -C)
ke = 0.5*m*v*v
ke_loss = np.diff(ke)/np.diff(z)*4.11e-10
f = interp1d(z[1:]/1e3,ke_loss)
#return f
plt.plot(z[3], f(z[3]))
# chel.. data
chel_df = pd.read_csv("data/ChelyabinskEnergyAltitude.csv")
arr = chel_df.to_numpy()
z_chel = arr[:,0]
dedz = arr[:,1]
z_max = np.amax(z_chel)
z_min = np.amin(z_chel)
# actual arrays
#z = np.linspace(z_max*1e3, z_min*1e3, n)
z = np.linspace(init_altitude, 0, n) # full range
v = np.exp(beta*np.exp(-z/H) -C)
#plt.plot(v,z)
#plt.show
ke = 0.5*m*v*v
ke_loss = np.diff(ke)/np.diff(z)*4.11e-10
#plt.plot(dedz,z_chel)
#plt.plot(ke_loss, z[1:]/1e3)
f = anal(radius)
# PLOT ANALYTICAL SOLUTION
#plt.plot(f(z[1:]/1e3),z[1:]/1e3)
#plt.ylim(22,40)
#plt.xlim(0,80)
dd = np.diff(dedz)
plt.plot(z_chel[1:], dd)
def error_function(radius, density=1):
f = anal(radius, density)
total = 0
for i in range(len(z_chel)):
total += abs(f(z_chel[i])-dedz[i])
return total
rad_vals = np.linspace(1,100,20)
errors = np.zeros(20)
for i in range(len(errors)):
errors[i] = error_function(rad_vals[i])
#plt.plot(errors)
plt.plot(rad_vals, errors)
import armageddon
# We first create a Planet class called "earth",
# which contains all the constants, atmospheric density functions, etc.
earth = armageddon.Planet()
# A user would call the impact function for one scenario like so...
result, outcome = earth.impact(
radius=10, angle=45, strength=1e5, velocity=20e3, density=3000)
# This is equivalent to calling the three individual functions like so...
result = earth.solve_atmospheric_entry(
radius=10, angle=45, strength=1e5, velocity=20e3, density=3000)
result = earth.calculate_energy(result)
outcome = earth.analyse_outcome(result)
from scipy.integrate import solve_ivp
def exponential_decay(t, y): return -0.5 * y
sol = solve_ivp(exponential_decay, [0, 10], [2])
print(sol.t)
def dvdt()
def J(x):
return x**2-2*x
J = error_function
J(156,1.19481459)
iter = 100
u = np.zeros(iter)
u[0] = 1
for j in range(iter-1):
c = 1/np.sqrt(j+10000)
dJ = (J(156.859,u[j] + c) - J(156.859,u[j]-c))/(2*c)
u[j+1] = u[j] - 1/(j+10000)*dJ
vJ = np.vectorize(J)
f(49.17747435)
f(48.17747435)
f(90)
x = np.linspace(1,200,100)
y = np.zeros(100)
for i in range(100):
y[i] = error_function(x[i])
plt.plot(x,y)
from noisyopt import minimizeSPSA
bounds = [[10, 1000], [0.9, 10]]
#x0 = np.array([120, 0.99])
def SPSA(func, x0, bounds, niter=100, a=1.0, alpha=0.602, c=1.0, gamma=0.101):
"""
Minimization of an objective function by a simultaneous perturbation
stochastic approximation.
This algorithm approximates the gradient of the function by finite differences
along stochastic directions Deltak. The elements of Deltak are drawn from
+- 1 with probability one half. The gradient is approximated from the
symmetric difference f(xk + ck*Deltak) - f(xk - ck*Deltak), where the evaluation
step size ck is scaled according ck = c/(k+1)**gamma.
The algorithm takes a step of size ak = a/(0.01*niter+k+1)**alpha along the
negative gradient.
We need to choose the parameters (a, alpha, c, gamma).
Parameters
----------
func: function
function to be minimized:
x0: array-like
initial guess for parameters
bounds: array-like
bounds on the variables
niter: int
number of iterations after which to terminate the algorithm
a: float
scaling parameter for step size
alpha: float
scaling exponent for step size
c: float
scaling parameter for evaluation step size
gamma: float
scaling exponent for evaluation step size
Returns
-------
Optimized parameters to minimize input function over bounds
"""
A = 0.01 * niter
bounds = np.asarray(bounds)
project = lambda x: np.clip(x, bounds[:, 0], bounds[:, 1])
N = len(x0)
x = x0
for k in range(niter):
ak = a/(k+1.0+A)**alpha
ck = c/(k+1.0)**gamma
Deltak = np.random.choice([-1, 1], size=N)
fkwargs = dict()
# check points are in boundaries
xplus = project(x + ck*Deltak)
xminus = project(x - ck*Deltak)
grad = (func(xplus, **fkwargs) - func(xminus, **fkwargs)) / (xplus-xminus)
x = project(x - ak*grad)
return x
res = SPSA(vJ, bounds=bounds, x0=x0, niter=10)
print(res)
fg
import armageddon
# We first create a Planet class called "earth",
# which contains all the constants, atmospheric density functions, etc.
earth = armageddon.Planet()
# A user would call the impact function for one scenario like so...
result, outcome = earth.impact(
radius=10, angle=45, strength=1e5, velocity=20e3, density=3000)
# This is equivalent to calling the three individual functions like so...
result = earth.solve_atmospheric_entry(
radius=10, angle=45, strength=1e5, velocity=20e3, density=3000)
result = earth.calculate_energy(result)
#outcome = earth.analyse_outcome(result)
result
# chel.. data
chel_df = pd.read_csv("data/ChelyabinskEnergyAltitude.csv")
arr = chel_df.to_numpy()
z_chel = arr[:,0]
dedz = arr[:,1]
plt.plot(dedz,z_chel)
#plt.plot(ke_loss, z[1:]/1e3)
solver_dedz = result['dedz'].to_numpy()
solver_z = result['altitude'].to_numpy()
solver_z /= 1e3 # convert to km
plt.plot(solver_dedz, solver_z)
def strength_radius(rad = 150, st=1e6):
#velocity = 19.2e3
#density = 3300
#angle = 18.3
# calcluating
result, outcome = earth.impact(radius=rad, angle=18.3, strength=st, velocity=19.2e3, density=3300)
#print(result.head())
solver_dedz = result['dedz'].to_numpy()
solver_z = result['altitude'].to_numpy()
solver_z /= 1e3 # convert to km
#plt.plot(solver_dedz,solver_z)
#f = interp1d(solver_z,solver_dedz)
return solver_dedz, solver_z
x,y = strength_radius(rad = 8,st = 2e6)
#vf = np.vectorize(func)
#x = np.linspace(0,100,100)
#y = vf(x)
plt.plot(x,y)
plt.plot(dedz,z_chel)
plt.ylim(21,43)
#plt.xlim(0,200)
result_sci = solve_ivp(self.f_com_analytical, (0, t_max), initial_state, t_eval=None, method='RK45', atol=tol, rtol=tol)
a,b,c,d,e = earth.compare_analytical_numerical(self, radius=10, angle=45, strength=1e5, velocity=20e3, density=3000,
init_altitude=100e3, n=100, radians=False)
def error_function(rad=1000, st=1e5):
f = strength_radius(rad, st)
total = 0
for i in range(len(z_chel)):
total += abs(f(z_chel[i])-dedz[i])
return total
rad_vals = np.linspace(10,200,10)
errors = np.zeros(10)
for i in range(len(errors)):
errors[i] = error_function(rad_vals[i], 1e6)
#plt.plot(errors)
plt.plot(rad_vals, errors)
bounds = [[200, 300], [1e5, 1e5]]
vJ = np.vectorize(error_function)
x0 = np.array([100, 1e5])
from noisyopt import minimizeSPSA
res = minimizeSPSA(vJ, bounds=bounds, x0=x0, niter=10, paired=False)
fiducial_impact = {'radius': 10.0,'angle': 10.0,'strength': 0.0,'velocity': 0.0,'density': 0.0}
earth = armageddon.Planet()
ensemble = armageddon.ensemble.solve_ensemble(earth,fiducial_impact,variables=[], radians=False,rmin=8, rmax=12)
ensemble
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Naive forecasting
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l08c02_naive_forecasting.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l08c02_naive_forecasting.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
## Setup
```
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import matplotlib.pyplot as plt
def plot_series(time, series, format="-", start=0, end=None, label=None):
plt.plot(time[start:end], series[start:end], format, label=label)
plt.xlabel("Time")
plt.ylabel("Value")
if label:
plt.legend(fontsize=14)
plt.grid(True)
def trend(time, slope=0):
return slope * time
def seasonal_pattern(season_time):
"""Just an arbitrary pattern, you can change it if you wish"""
return np.where(season_time < 0.4,
np.cos(season_time * 2 * np.pi),
1 / np.exp(3 * season_time))
def seasonality(time, period, amplitude=1, phase=0):
"""Repeats the same pattern at each period"""
season_time = ((time + phase) % period) / period
return amplitude * seasonal_pattern(season_time)
def white_noise(time, noise_level=1, seed=None):
rnd = np.random.RandomState(seed)
return rnd.randn(len(time)) * noise_level
```
## Trend and Seasonality
```
time = np.arange(4 * 365 + 1)
slope = 0.05
baseline = 10
amplitude = 40
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
noise_level = 5
noise = white_noise(time, noise_level, seed=42)
series += noise
plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()
```
All right, this looks realistic enough for now. Let's try to forecast it. We will split it into two periods: the training period and the validation period (in many cases, you would also want to have a test period). The split will be at time step 1000.
```
split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
```
## Naive Forecast
```
naive_forecast = series[split_time - 1:-1]
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid, label="Series")
plot_series(time_valid, naive_forecast, label="Forecast")
```
Let's zoom in on the start of the validation period:
```
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid, start=0, end=150, label="Series")
plot_series(time_valid, naive_forecast, start=1, end=151, label="Forecast")
```
You can see that the naive forecast lags 1 step behind the time series.
Now let's compute the mean absolute error between the forecasts and the predictions in the validation period:
```
errors = naive_forecast - x_valid
abs_errors = np.abs(errors)
mae = abs_errors.mean()
mae
```
That's our baseline, now let's try a moving average.
| github_jupyter |
# Building your Recurrent Neural Network - Step by Step
Welcome to Course 5's first assignment! In this assignment, you will implement your first Recurrent Neural Network in numpy.
Recurrent Neural Networks (RNN) are very effective for Natural Language Processing and other sequence tasks because they have "memory". They can read inputs $x^{\langle t \rangle}$ (such as words) one at a time, and remember some information/context through the hidden layer activations that get passed from one time-step to the next. This allows a uni-directional RNN to take information from the past to process later inputs. A bidirection RNN can take context from both the past and the future.
**Notation**:
- Superscript $[l]$ denotes an object associated with the $l^{th}$ layer.
- Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.
- Superscript $(i)$ denotes an object associated with the $i^{th}$ example.
- Example: $x^{(i)}$ is the $i^{th}$ training example input.
- Superscript $\langle t \rangle$ denotes an object at the $t^{th}$ time-step.
- Example: $x^{\langle t \rangle}$ is the input x at the $t^{th}$ time-step. $x^{(i)\langle t \rangle}$ is the input at the $t^{th}$ timestep of example $i$.
- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.
- Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$.
We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started!
Let's first import all the packages that you will need during this assignment.
```
import numpy as np
from rnn_utils import *
```
## 1 - Forward propagation for the basic Recurrent Neural Network
Later this week, you will generate music using an RNN. The basic RNN that you will implement has the structure below. In this example, $T_x = T_y$.
<img src="images/RNN.png" style="width:500;height:300px;">
<caption><center> **Figure 1**: Basic RNN model </center></caption>
Here's how you can implement an RNN:
**Steps**:
1. Implement the calculations needed for one time-step of the RNN.
2. Implement a loop over $T_x$ time-steps in order to process all the inputs, one at a time.
Let's go!
## 1.1 - RNN cell
A Recurrent neural network can be seen as the repetition of a single cell. You are first going to implement the computations for a single time-step. The following figure describes the operations for a single time-step of an RNN cell.
<img src="images/rnn_step_forward.png" style="width:700px;height:300px;">
<caption><center> **Figure 2**: Basic RNN cell. Takes as input $x^{\langle t \rangle}$ (current input) and $a^{\langle t - 1\rangle}$ (previous hidden state containing information from the past), and outputs $a^{\langle t \rangle}$ which is given to the next RNN cell and also used to predict $y^{\langle t \rangle}$ </center></caption>
**Exercise**: Implement the RNN-cell described in Figure (2).
**Instructions**:
1. Compute the hidden state with tanh activation: $a^{\langle t \rangle} = \tanh(W_{aa} a^{\langle t-1 \rangle} + W_{ax} x^{\langle t \rangle} + b_a)$.
2. Using your new hidden state $a^{\langle t \rangle}$, compute the prediction $\hat{y}^{\langle t \rangle} = softmax(W_{ya} a^{\langle t \rangle} + b_y)$. We provided you a function: `softmax`.
3. Store $(a^{\langle t \rangle}, a^{\langle t-1 \rangle}, x^{\langle t \rangle}, parameters)$ in cache
4. Return $a^{\langle t \rangle}$ , $y^{\langle t \rangle}$ and cache
We will vectorize over $m$ examples. Thus, $x^{\langle t \rangle}$ will have dimension $(n_x,m)$, and $a^{\langle t \rangle}$ will have dimension $(n_a,m)$.
```
# GRADED FUNCTION: rnn_cell_forward
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell as described in Figure (2)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias, numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
"""
# Retrieve parameters from "parameters"
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
### START CODE HERE ### (≈2 lines)
# compute next activation state using the formula given above
a_next = np.tanh(np.dot(Waa, a_prev) + np.dot(Wax, xt) + ba)
# compute output of the current cell using the formula given above
yt_pred = softmax(np.dot(Wya, a_next) + by)
### END CODE HERE ###
# store values you need for backward propagation in cache
cache = (a_next, a_prev, xt, parameters)
return a_next, yt_pred, cache
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
Waa = np.random.randn(5,5)
Wax = np.random.randn(5,3)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
a_next, yt_pred, cache = rnn_cell_forward(xt, a_prev, parameters)
print("a_next[4] = ", a_next[4])
print("a_next.shape = ", a_next.shape)
print("yt_pred[1] =", yt_pred[1])
print("yt_pred.shape = ", yt_pred.shape)
```
**Expected Output**:
<table>
<tr>
<td>
**a_next[4]**:
</td>
<td>
[ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978
-0.18887155 0.99815551 0.6531151 0.82872037]
</td>
</tr>
<tr>
<td>
**a_next.shape**:
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**yt[1]**:
</td>
<td>
[ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212
0.36920224 0.9966312 0.9982559 0.17746526]
</td>
</tr>
<tr>
<td>
**yt.shape**:
</td>
<td>
(2, 10)
</td>
</tr>
</table>
## 1.2 - RNN forward pass
You can see an RNN as the repetition of the cell you've just built. If your input sequence of data is carried over 10 time steps, then you will copy the RNN cell 10 times. Each cell takes as input the hidden state from the previous cell ($a^{\langle t-1 \rangle}$) and the current time-step's input data ($x^{\langle t \rangle}$). It outputs a hidden state ($a^{\langle t \rangle}$) and a prediction ($y^{\langle t \rangle}$) for this time-step.
<img src="images/rnn.png" style="width:800px;height:300px;">
<caption><center> **Figure 3**: Basic RNN. The input sequence $x = (x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, ..., x^{\langle T_x \rangle})$ is carried over $T_x$ time steps. The network outputs $y = (y^{\langle 1 \rangle}, y^{\langle 2 \rangle}, ..., y^{\langle T_x \rangle})$. </center></caption>
**Exercise**: Code the forward propagation of the RNN described in Figure (3).
**Instructions**:
1. Create a vector of zeros ($a$) that will store all the hidden states computed by the RNN.
2. Initialize the "next" hidden state as $a_0$ (initial hidden state).
3. Start looping over each time step, your incremental index is $t$ :
- Update the "next" hidden state and the cache by running `rnn_cell_forward`
- Store the "next" hidden state in $a$ ($t^{th}$ position)
- Store the prediction in y
- Add the cache to the list of caches
4. Return $a$, $y$ and caches
```
# GRADED FUNCTION: rnn_forward
def rnn_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of caches, x)
"""
# Initialize "caches" which will contain the list of all caches
caches = []
# Retrieve dimensions from shapes of x and parameters["Wya"]
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wya"].shape
### START CODE HERE ###
# initialize "a" and "y" with zeros (≈2 lines)
a = np.zeros((n_a, m, T_x))
y_pred = np.zeros((n_y, m, T_x))
# Initialize a_next (≈1 line)
a_next = a0
# loop over all time-steps
for t in range(T_x):
# Update next hidden state, compute the prediction, get the cache (≈1 line)
a_next, yt_pred, cache = rnn_cell_forward(x[:,:,t], a_next, parameters)
# Save the value of the new "next" hidden state in a (≈1 line)
a[:,:,t] = a_next
# Save the value of the prediction in y (≈1 line)
y_pred[:,:,t] = yt_pred
# Append "cache" to "caches" (≈1 line)
caches.append(cache)
### END CODE HERE ###
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y_pred, caches
np.random.seed(1)
x = np.random.randn(3,10,4)
a0 = np.random.randn(5,10)
Waa = np.random.randn(5,5)
Wax = np.random.randn(5,3)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
a, y_pred, caches = rnn_forward(x, a0, parameters)
print("a[4][1] = ", a[4][1])
print("a.shape = ", a.shape)
print("y_pred[1][3] =", y_pred[1][3])
print("y_pred.shape = ", y_pred.shape)
print("caches[1][1][3] =", caches[1][1][3])
print("len(caches) = ", len(caches))
```
**Expected Output**:
<table>
<tr>
<td>
**a[4][1]**:
</td>
<td>
[-0.99999375 0.77911235 -0.99861469 -0.99833267]
</td>
</tr>
<tr>
<td>
**a.shape**:
</td>
<td>
(5, 10, 4)
</td>
</tr>
<tr>
<td>
**y[1][3]**:
</td>
<td>
[ 0.79560373 0.86224861 0.11118257 0.81515947]
</td>
</tr>
<tr>
<td>
**y.shape**:
</td>
<td>
(2, 10, 4)
</td>
</tr>
<tr>
<td>
**cache[1][1][3]**:
</td>
<td>
[-1.1425182 -0.34934272 -0.20889423 0.58662319]
</td>
</tr>
<tr>
<td>
**len(cache)**:
</td>
<td>
2
</td>
</tr>
</table>
Congratulations! You've successfully built the forward propagation of a recurrent neural network from scratch. This will work well enough for some applications, but it suffers from vanishing gradient problems. So it works best when each output $y^{\langle t \rangle}$ can be estimated using mainly "local" context (meaning information from inputs $x^{\langle t' \rangle}$ where $t'$ is not too far from $t$).
In the next part, you will build a more complex LSTM model, which is better at addressing vanishing gradients. The LSTM will be better able to remember a piece of information and keep it saved for many timesteps.
## 2 - Long Short-Term Memory (LSTM) network
This following figure shows the operations of an LSTM-cell.
<img src="images/LSTM.png" style="width:500;height:400px;">
<caption><center> **Figure 4**: LSTM-cell. This tracks and updates a "cell state" or memory variable $c^{\langle t \rangle}$ at every time-step, which can be different from $a^{\langle t \rangle}$. </center></caption>
Similar to the RNN example above, you will start by implementing the LSTM cell for a single time-step. Then you can iteratively call it from inside a for-loop to have it process an input with $T_x$ time-steps.
### About the gates
#### - Forget gate
For the sake of this illustration, lets assume we are reading words in a piece of text, and want use an LSTM to keep track of grammatical structures, such as whether the subject is singular or plural. If the subject changes from a singular word to a plural word, we need to find a way to get rid of our previously stored memory value of the singular/plural state. In an LSTM, the forget gate lets us do this:
$$\Gamma_f^{\langle t \rangle} = \sigma(W_f[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_f)\tag{1} $$
Here, $W_f$ are weights that govern the forget gate's behavior. We concatenate $[a^{\langle t-1 \rangle}, x^{\langle t \rangle}]$ and multiply by $W_f$. The equation above results in a vector $\Gamma_f^{\langle t \rangle}$ with values between 0 and 1. This forget gate vector will be multiplied element-wise by the previous cell state $c^{\langle t-1 \rangle}$. So if one of the values of $\Gamma_f^{\langle t \rangle}$ is 0 (or close to 0) then it means that the LSTM should remove that piece of information (e.g. the singular subject) in the corresponding component of $c^{\langle t-1 \rangle}$. If one of the values is 1, then it will keep the information.
#### - Update gate
Once we forget that the subject being discussed is singular, we need to find a way to update it to reflect that the new subject is now plural. Here is the formulat for the update gate:
$$\Gamma_u^{\langle t \rangle} = \sigma(W_u[a^{\langle t-1 \rangle}, x^{\{t\}}] + b_u)\tag{2} $$
Similar to the forget gate, here $\Gamma_u^{\langle t \rangle}$ is again a vector of values between 0 and 1. This will be multiplied element-wise with $\tilde{c}^{\langle t \rangle}$, in order to compute $c^{\langle t \rangle}$.
#### - Updating the cell
To update the new subject we need to create a new vector of numbers that we can add to our previous cell state. The equation we use is:
$$ \tilde{c}^{\langle t \rangle} = \tanh(W_c[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_c)\tag{3} $$
Finally, the new cell state is:
$$ c^{\langle t \rangle} = \Gamma_f^{\langle t \rangle}* c^{\langle t-1 \rangle} + \Gamma_u^{\langle t \rangle} *\tilde{c}^{\langle t \rangle} \tag{4} $$
#### - Output gate
To decide which outputs we will use, we will use the following two formulas:
$$ \Gamma_o^{\langle t \rangle}= \sigma(W_o[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_o)\tag{5}$$
$$ a^{\langle t \rangle} = \Gamma_o^{\langle t \rangle}* \tanh(c^{\langle t \rangle})\tag{6} $$
Where in equation 5 you decide what to output using a sigmoid function and in equation 6 you multiply that by the $\tanh$ of the previous state.
### 2.1 - LSTM cell
**Exercise**: Implement the LSTM cell described in the Figure (3).
**Instructions**:
1. Concatenate $a^{\langle t-1 \rangle}$ and $x^{\langle t \rangle}$ in a single matrix: $concat = \begin{bmatrix} a^{\langle t-1 \rangle} \\ x^{\langle t \rangle} \end{bmatrix}$
2. Compute all the formulas 1-6. You can use `sigmoid()` (provided) and `np.tanh()`.
3. Compute the prediction $y^{\langle t \rangle}$. You can use `softmax()` (provided).
```
# GRADED FUNCTION: lstm_cell_forward
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev -- Memory state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
bi -- Bias of the update gate, numpy array of shape (n_a, 1)
Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
bo -- Bias of the output gate, numpy array of shape (n_a, 1)
Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
c_next -- next memory state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, c_next, a_prev, c_prev, xt, parameters)
Note: ft/it/ot stand for the forget/update/output gates, cct stands for the candidate value (c tilde),
c stands for the memory value
"""
# Retrieve parameters from "parameters"
Wf = parameters["Wf"]
bf = parameters["bf"]
Wi = parameters["Wi"]
bi = parameters["bi"]
Wc = parameters["Wc"]
bc = parameters["bc"]
Wo = parameters["Wo"]
bo = parameters["bo"]
Wy = parameters["Wy"]
by = parameters["by"]
# Retrieve dimensions from shapes of xt and Wy
n_x, m = xt.shape
n_y, n_a = Wy.shape
### START CODE HERE ###
# Concatenate a_prev and xt (≈3 lines)
concat = np.zeros((n_a+n_x, m))
concat[: n_a, :] = a_prev
concat[n_a :, :] = xt
# Compute values for ft, it, cct, c_next, ot, a_next using the formulas given figure (4) (≈6 lines)
ft = sigmoid(np.dot(Wf, concat) + bf)
it = sigmoid(np.dot(Wi, concat) + bi)
cct = np.tanh(np.dot(Wc, concat) + bc)
c_next = ft * c_prev + it * cct
ot = sigmoid(np.dot(Wo, concat) + bo)
a_next = ot * np.tanh(c_next)
# Compute prediction of the LSTM cell (≈1 line)
yt_pred = softmax(np.dot(Wy, a_next) + by)
### END CODE HERE ###
# store values needed for backward propagation in cache
cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters)
return a_next, c_next, yt_pred, cache
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
c_prev = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
print("a_next[4] = ", a_next[4])
print("a_next.shape = ", c_next.shape)
print("c_next[2] = ", c_next[2])
print("c_next.shape = ", c_next.shape)
print("yt[1] =", yt[1])
print("yt.shape = ", yt.shape)
print("cache[1][3] =", cache[1][3])
print("len(cache) = ", len(cache))
```
**Expected Output**:
<table>
<tr>
<td>
**a_next[4]**:
</td>
<td>
[-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482
0.76566531 0.34631421 -0.00215674 0.43827275]
</td>
</tr>
<tr>
<td>
**a_next.shape**:
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**c_next[2]**:
</td>
<td>
[ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942
0.76449811 -0.0981561 -0.74348425 -0.26810932]
</td>
</tr>
<tr>
<td>
**c_next.shape**:
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**yt[1]**:
</td>
<td>
[ 0.79913913 0.15986619 0.22412122 0.15606108 0.97057211 0.31146381
0.00943007 0.12666353 0.39380172 0.07828381]
</td>
</tr>
<tr>
<td>
**yt.shape**:
</td>
<td>
(2, 10)
</td>
</tr>
<tr>
<td>
**cache[1][3]**:
</td>
<td>
[-0.16263996 1.03729328 0.72938082 -0.54101719 0.02752074 -0.30821874
0.07651101 -1.03752894 1.41219977 -0.37647422]
</td>
</tr>
<tr>
<td>
**len(cache)**:
</td>
<td>
10
</td>
</tr>
</table>
### 2.2 - Forward pass for LSTM
Now that you have implemented one step of an LSTM, you can now iterate this over this using a for-loop to process a sequence of $T_x$ inputs.
<img src="images/LSTM_rnn.png" style="width:500;height:300px;">
<caption><center> **Figure 4**: LSTM over multiple time-steps. </center></caption>
**Exercise:** Implement `lstm_forward()` to run an LSTM over $T_x$ time-steps.
**Note**: $c^{\langle 0 \rangle}$ is initialized with zeros.
```
# GRADED FUNCTION: lstm_forward
def lstm_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network using an LSTM-cell described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
bi -- Bias of the update gate, numpy array of shape (n_a, 1)
Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
bo -- Bias of the output gate, numpy array of shape (n_a, 1)
Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of all the caches, x)
"""
# Initialize "caches", which will track the list of all the caches
caches = []
### START CODE HERE ###
# Retrieve dimensions from shapes of x and parameters['Wy'] (≈2 lines)
n_x, m, T_x = x.shape
n_y, n_a = parameters['Wy'].shape
# initialize "a", "c" and "y" with zeros (≈3 lines)
a = np.zeros((n_a, m, T_x))
c = np.zeros((n_a, m, T_x))
y = np.zeros((n_y, m, T_x))
# Initialize a_next and c_next (≈2 lines)
a_next = a0
c_next = np.zeros((n_a, m))
# loop over all time-steps
for t in range(T_x):
# Update next hidden state, next memory state, compute the prediction, get the cache (≈1 line)
a_next, c_next, yt, cache = lstm_cell_forward(x[:,:,t], a_next, c_next, parameters)
# Save the value of the new "next" hidden state in a (≈1 line)
a[:,:,t] = a_next
# Save the value of the prediction in y (≈1 line)
y[:,:,t] = yt
# Save the value of the next cell state (≈1 line)
c[:,:,t] = c_next
# Append the cache into caches (≈1 line)
caches.append(cache)
### END CODE HERE ###
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y, c, caches
np.random.seed(1)
x = np.random.randn(3,10,7)
a0 = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a, y, c, caches = lstm_forward(x, a0, parameters)
print("a[4][3][6] = ", a[4][3][6])
print("a.shape = ", a.shape)
print("y[1][4][3] =", y[1][4][3])
print("y.shape = ", y.shape)
print("caches[1][1[1]] =", caches[1][1][1])
print("c[1][2][1]", c[1][2][1])
print("len(caches) = ", len(caches))
```
**Expected Output**:
<table>
<tr>
<td>
**a[4][3][6]** =
</td>
<td>
0.172117767533
</td>
</tr>
<tr>
<td>
**a.shape** =
</td>
<td>
(5, 10, 7)
</td>
</tr>
<tr>
<td>
**y[1][4][3]** =
</td>
<td>
0.95087346185
</td>
</tr>
<tr>
<td>
**y.shape** =
</td>
<td>
(2, 10, 7)
</td>
</tr>
<tr>
<td>
**caches[1][1][1]** =
</td>
<td>
[ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139
0.41005165]
</td>
</tr>
<tr>
<td>
**c[1][2][1]** =
</td>
<td>
-0.855544916718
</td>
</tr>
</tr>
<tr>
<td>
**len(caches)** =
</td>
<td>
2
</td>
</tr>
</table>
Congratulations! You have now implemented the forward passes for the basic RNN and the LSTM. When using a deep learning framework, implementing the forward pass is sufficient to build systems that achieve great performance.
The rest of this notebook is optional, and will not be graded.
## 3 - Backpropagation in recurrent neural networks (OPTIONAL / UNGRADED)
In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers do not need to bother with the details of the backward pass. If however you are an expert in calculus and want to see the details of backprop in RNNs, you can work through this optional portion of the notebook.
When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in recurrent neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are quite complicated and we did not derive them in lecture. However, we will briefly present them below.
### 3.1 - Basic RNN backward pass
We will start by computing the backward pass for the basic RNN-cell.
<img src="images/rnn_cell_backprop.png" style="width:500;height:300px;"> <br>
<caption><center> **Figure 5**: RNN-cell's backward pass. Just like in a fully-connected neural network, the derivative of the cost function $J$ backpropagates through the RNN by following the chain-rule from calculas. The chain-rule is also used to calculate $(\frac{\partial J}{\partial W_{ax}},\frac{\partial J}{\partial W_{aa}},\frac{\partial J}{\partial b})$ to update the parameters $(W_{ax}, W_{aa}, b_a)$. </center></caption>
#### Deriving the one step backward functions:
To compute the `rnn_cell_backward` you need to compute the following equations. It is a good exercise to derive them by hand.
The derivative of $\tanh$ is $1-\tanh(x)^2$. You can find the complete proof [here](https://www.wyzant.com/resources/lessons/math/calculus/derivative_proofs/tanx). Note that: $ \text{sech}(x)^2 = 1 - \tanh(x)^2$
Similarly for $\frac{ \partial a^{\langle t \rangle} } {\partial W_{ax}}, \frac{ \partial a^{\langle t \rangle} } {\partial W_{aa}}, \frac{ \partial a^{\langle t \rangle} } {\partial b}$, the derivative of $\tanh(u)$ is $(1-\tanh(u)^2)du$.
The final two equations also follow same rule and are derived using the $\tanh$ derivative. Note that the arrangement is done in a way to get the same dimensions to match.
```
def rnn_cell_backward(da_next, cache):
"""
Implements the backward pass for the RNN-cell (single time-step).
Arguments:
da_next -- Gradient of loss with respect to next hidden state
cache -- python dictionary containing useful values (output of rnn_cell_forward())
Returns:
gradients -- python dictionary containing:
dx -- Gradients of input data, of shape (n_x, m)
da_prev -- Gradients of previous hidden state, of shape (n_a, m)
dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)
dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)
dba -- Gradients of bias vector, of shape (n_a, 1)
"""
# Retrieve values from cache
(a_next, a_prev, xt, parameters) = cache
# Retrieve values from parameters
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
### START CODE HERE ###
# compute the gradient of tanh with respect to a_next (≈1 line)
dtanh = None
# compute the gradient of the loss with respect to Wax (≈2 lines)
dxt = None
dWax = None
# compute the gradient with respect to Waa (≈2 lines)
da_prev = None
dWaa = None
# compute the gradient with respect to b (≈1 line)
dba = None
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dxt": dxt, "da_prev": da_prev, "dWax": dWax, "dWaa": dWaa, "dba": dba}
return gradients
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
Wax = np.random.randn(5,3)
Waa = np.random.randn(5,5)
Wya = np.random.randn(2,5)
b = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
a_next, yt, cache = rnn_cell_forward(xt, a_prev, parameters)
da_next = np.random.randn(5,10)
gradients = rnn_cell_backward(da_next, cache)
print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
print("gradients[\"dba\"][4] =", gradients["dba"][4])
print("gradients[\"dba\"].shape =", gradients["dba"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dxt"][1][2]** =
</td>
<td>
-0.460564103059
</td>
</tr>
<tr>
<td>
**gradients["dxt"].shape** =
</td>
<td>
(3, 10)
</td>
</tr>
<tr>
<td>
**gradients["da_prev"][2][3]** =
</td>
<td>
0.0842968653807
</td>
</tr>
<tr>
<td>
**gradients["da_prev"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWax"][3][1]** =
</td>
<td>
0.393081873922
</td>
</tr>
<tr>
<td>
**gradients["dWax"].shape** =
</td>
<td>
(5, 3)
</td>
</tr>
<tr>
<td>
**gradients["dWaa"][1][2]** =
</td>
<td>
-0.28483955787
</td>
</tr>
<tr>
<td>
**gradients["dWaa"].shape** =
</td>
<td>
(5, 5)
</td>
</tr>
<tr>
<td>
**gradients["dba"][4]** =
</td>
<td>
[ 0.80517166]
</td>
</tr>
<tr>
<td>
**gradients["dba"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
#### Backward pass through the RNN
Computing the gradients of the cost with respect to $a^{\langle t \rangle}$ at every time-step $t$ is useful because it is what helps the gradient backpropagate to the previous RNN-cell. To do so, you need to iterate through all the time steps starting at the end, and at each step, you increment the overall $db_a$, $dW_{aa}$, $dW_{ax}$ and you store $dx$.
**Instructions**:
Implement the `rnn_backward` function. Initialize the return variables with zeros first and then loop through all the time steps while calling the `rnn_cell_backward` at each time timestep, update the other variables accordingly.
```
def rnn_backward(da, caches):
"""
Implement the backward pass for a RNN over an entire sequence of input data.
Arguments:
da -- Upstream gradients of all hidden states, of shape (n_a, m, T_x)
caches -- tuple containing information from the forward pass (rnn_forward)
Returns:
gradients -- python dictionary containing:
dx -- Gradient w.r.t. the input data, numpy-array of shape (n_x, m, T_x)
da0 -- Gradient w.r.t the initial hidden state, numpy-array of shape (n_a, m)
dWax -- Gradient w.r.t the input's weight matrix, numpy-array of shape (n_a, n_x)
dWaa -- Gradient w.r.t the hidden state's weight matrix, numpy-arrayof shape (n_a, n_a)
dba -- Gradient w.r.t the bias, of shape (n_a, 1)
"""
### START CODE HERE ###
# Retrieve values from the first cache (t=1) of caches (≈2 lines)
(caches, x) = None
(a1, a0, x1, parameters) = None
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = None
n_x, m = None
# initialize the gradients with the right sizes (≈6 lines)
dx = None
dWax = None
dWaa = None
dba = None
da0 = None
da_prevt = None
# Loop through all the time steps
for t in reversed(range(None)):
# Compute gradients at time step t. Choose wisely the "da_next" and the "cache" to use in the backward propagation step. (≈1 line)
gradients = None
# Retrieve derivatives from gradients (≈ 1 line)
dxt, da_prevt, dWaxt, dWaat, dbat = gradients["dxt"], gradients["da_prev"], gradients["dWax"], gradients["dWaa"], gradients["dba"]
# Increment global derivatives w.r.t parameters by adding their derivative at time-step t (≈4 lines)
dx[:, :, t] = None
dWax += None
dWaa += None
dba += None
# Set da0 to the gradient of a which has been backpropagated through all time-steps (≈1 line)
da0 = None
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dx": dx, "da0": da0, "dWax": dWax, "dWaa": dWaa,"dba": dba}
return gradients
np.random.seed(1)
x = np.random.randn(3,10,4)
a0 = np.random.randn(5,10)
Wax = np.random.randn(5,3)
Waa = np.random.randn(5,5)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
a, y, caches = rnn_forward(x, a0, parameters)
da = np.random.randn(5, 10, 4)
gradients = rnn_backward(da, caches)
print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
print("gradients[\"dx\"].shape =", gradients["dx"].shape)
print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
print("gradients[\"da0\"].shape =", gradients["da0"].shape)
print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
print("gradients[\"dba\"][4] =", gradients["dba"][4])
print("gradients[\"dba\"].shape =", gradients["dba"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dx"][1][2]** =
</td>
<td>
[-2.07101689 -0.59255627 0.02466855 0.01483317]
</td>
</tr>
<tr>
<td>
**gradients["dx"].shape** =
</td>
<td>
(3, 10, 4)
</td>
</tr>
<tr>
<td>
**gradients["da0"][2][3]** =
</td>
<td>
-0.314942375127
</td>
</tr>
<tr>
<td>
**gradients["da0"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWax"][3][1]** =
</td>
<td>
11.2641044965
</td>
</tr>
<tr>
<td>
**gradients["dWax"].shape** =
</td>
<td>
(5, 3)
</td>
</tr>
<tr>
<td>
**gradients["dWaa"][1][2]** =
</td>
<td>
2.30333312658
</td>
</tr>
<tr>
<td>
**gradients["dWaa"].shape** =
</td>
<td>
(5, 5)
</td>
</tr>
<tr>
<td>
**gradients["dba"][4]** =
</td>
<td>
[-0.74747722]
</td>
</tr>
<tr>
<td>
**gradients["dba"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
## 3.2 - LSTM backward pass
### 3.2.1 One Step backward
The LSTM backward pass is slighltly more complicated than the forward one. We have provided you with all the equations for the LSTM backward pass below. (If you enjoy calculus exercises feel free to try deriving these from scratch yourself.)
### 3.2.2 gate derivatives
$$d \Gamma_o^{\langle t \rangle} = da_{next}*\tanh(c_{next}) * \Gamma_o^{\langle t \rangle}*(1-\Gamma_o^{\langle t \rangle})\tag{7}$$
$$d\tilde c^{\langle t \rangle} = dc_{next}*\Gamma_u^{\langle t \rangle}+ \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * i_t * da_{next} * \tilde c^{\langle t \rangle} * (1-\tanh(\tilde c)^2) \tag{8}$$
$$d\Gamma_u^{\langle t \rangle} = dc_{next}*\tilde c^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * \tilde c^{\langle t \rangle} * da_{next}*\Gamma_u^{\langle t \rangle}*(1-\Gamma_u^{\langle t \rangle})\tag{9}$$
$$d\Gamma_f^{\langle t \rangle} = dc_{next}*\tilde c_{prev} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * c_{prev} * da_{next}*\Gamma_f^{\langle t \rangle}*(1-\Gamma_f^{\langle t \rangle})\tag{10}$$
### 3.2.3 parameter derivatives
$$ dW_f = d\Gamma_f^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{11} $$
$$ dW_u = d\Gamma_u^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{12} $$
$$ dW_c = d\tilde c^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{13} $$
$$ dW_o = d\Gamma_o^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{14}$$
To calculate $db_f, db_u, db_c, db_o$ you just need to sum across the horizontal (axis= 1) axis on $d\Gamma_f^{\langle t \rangle}, d\Gamma_u^{\langle t \rangle}, d\tilde c^{\langle t \rangle}, d\Gamma_o^{\langle t \rangle}$ respectively. Note that you should have the `keep_dims = True` option.
Finally, you will compute the derivative with respect to the previous hidden state, previous memory state, and input.
$$ da_{prev} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c^{\langle t \rangle} + W_o^T * d\Gamma_o^{\langle t \rangle} \tag{15}$$
Here, the weights for equations 13 are the first n_a, (i.e. $W_f = W_f[:n_a,:]$ etc...)
$$ dc_{prev} = dc_{next}\Gamma_f^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} * (1- \tanh(c_{next})^2)*\Gamma_f^{\langle t \rangle}*da_{next} \tag{16}$$
$$ dx^{\langle t \rangle} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c_t + W_o^T * d\Gamma_o^{\langle t \rangle}\tag{17} $$
where the weights for equation 15 are from n_a to the end, (i.e. $W_f = W_f[n_a:,:]$ etc...)
**Exercise:** Implement `lstm_cell_backward` by implementing equations $7-17$ below. Good luck! :)
```
def lstm_cell_backward(da_next, dc_next, cache):
"""
Implement the backward pass for the LSTM-cell (single time-step).
Arguments:
da_next -- Gradients of next hidden state, of shape (n_a, m)
dc_next -- Gradients of next cell state, of shape (n_a, m)
cache -- cache storing information from the forward pass
Returns:
gradients -- python dictionary containing:
dxt -- Gradient of input data at time-step t, of shape (n_x, m)
da_prev -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
dc_prev -- Gradient w.r.t. the previous memory state, of shape (n_a, m, T_x)
dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
dWo -- Gradient w.r.t. the weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
dbo -- Gradient w.r.t. biases of the output gate, of shape (n_a, 1)
"""
# Retrieve information from "cache"
(a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache
### START CODE HERE ###
# Retrieve dimensions from xt's and a_next's shape (≈2 lines)
n_x, m = None
n_a, m = None
# Compute gates related derivatives, you can find their values can be found by looking carefully at equations (7) to (10) (≈4 lines)
dot = None
dcct = None
dit = None
dft = None
# Code equations (7) to (10) (≈4 lines)
dit = None
dft = None
dot = None
dcct = None
# Compute parameters related derivatives. Use equations (11)-(14) (≈8 lines)
dWf = None
dWi = None
dWc = None
dWo = None
dbf = None
dbi = None
dbc = None
dbo = None
# Compute derivatives w.r.t previous hidden state, previous memory state and input. Use equations (15)-(17). (≈3 lines)
da_prev = None
dc_prev = None
dxt = None
### END CODE HERE ###
# Save gradients in dictionary
gradients = {"dxt": dxt, "da_prev": da_prev, "dc_prev": dc_prev, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
"dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
return gradients
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
c_prev = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
da_next = np.random.randn(5,10)
dc_next = np.random.randn(5,10)
gradients = lstm_cell_backward(da_next, dc_next, cache)
print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
print("gradients[\"dc_prev\"][2][3] =", gradients["dc_prev"][2][3])
print("gradients[\"dc_prev\"].shape =", gradients["dc_prev"].shape)
print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
print("gradients[\"dbo\"].shape =", gradients["dbo"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dxt"][1][2]** =
</td>
<td>
3.23055911511
</td>
</tr>
<tr>
<td>
**gradients["dxt"].shape** =
</td>
<td>
(3, 10)
</td>
</tr>
<tr>
<td>
**gradients["da_prev"][2][3]** =
</td>
<td>
-0.0639621419711
</td>
</tr>
<tr>
<td>
**gradients["da_prev"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dc_prev"][2][3]** =
</td>
<td>
0.797522038797
</td>
</tr>
<tr>
<td>
**gradients["dc_prev"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWf"][3][1]** =
</td>
<td>
-0.147954838164
</td>
</tr>
<tr>
<td>
**gradients["dWf"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWi"][1][2]** =
</td>
<td>
1.05749805523
</td>
</tr>
<tr>
<td>
**gradients["dWi"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWc"][3][1]** =
</td>
<td>
2.30456216369
</td>
</tr>
<tr>
<td>
**gradients["dWc"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWo"][1][2]** =
</td>
<td>
0.331311595289
</td>
</tr>
<tr>
<td>
**gradients["dWo"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dbf"][4]** =
</td>
<td>
[ 0.18864637]
</td>
</tr>
<tr>
<td>
**gradients["dbf"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbi"][4]** =
</td>
<td>
[-0.40142491]
</td>
</tr>
<tr>
<td>
**gradients["dbi"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbc"][4]** =
</td>
<td>
[ 0.25587763]
</td>
</tr>
<tr>
<td>
**gradients["dbc"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbo"][4]** =
</td>
<td>
[ 0.13893342]
</td>
</tr>
<tr>
<td>
**gradients["dbo"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
### 3.3 Backward pass through the LSTM RNN
This part is very similar to the `rnn_backward` function you implemented above. You will first create variables of the same dimension as your return variables. You will then iterate over all the time steps starting from the end and call the one step function you implemented for LSTM at each iteration. You will then update the parameters by summing them individually. Finally return a dictionary with the new gradients.
**Instructions**: Implement the `lstm_backward` function. Create a for loop starting from $T_x$ and going backward. For each step call `lstm_cell_backward` and update the your old gradients by adding the new gradients to them. Note that `dxt` is not updated but is stored.
```
def lstm_backward(da, caches):
"""
Implement the backward pass for the RNN with LSTM-cell (over a whole sequence).
Arguments:
da -- Gradients w.r.t the hidden states, numpy-array of shape (n_a, m, T_x)
dc -- Gradients w.r.t the memory states, numpy-array of shape (n_a, m, T_x)
caches -- cache storing information from the forward pass (lstm_forward)
Returns:
gradients -- python dictionary containing:
dx -- Gradient of inputs, of shape (n_x, m, T_x)
da0 -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
dWo -- Gradient w.r.t. the weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
dbo -- Gradient w.r.t. biases of the save gate, of shape (n_a, 1)
"""
# Retrieve values from the first cache (t=1) of caches.
(caches, x) = caches
(a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0]
### START CODE HERE ###
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = None
n_x, m = None
# initialize the gradients with the right sizes (≈12 lines)
dx = None
da0 = None
da_prevt = None
dc_prevt = None
dWf = None
dWi = None
dWc = None
dWo = None
dbf = None
dbi = None
dbc = None
dbo = None
# loop back over the whole sequence
for t in reversed(range(None)):
# Compute all gradients using lstm_cell_backward
gradients = None
# Store or add the gradient to the parameters' previous step's gradient
dx[:,:,t] = None
dWf = None
dWi = None
dWc = None
dWo = None
dbf = None
dbi = None
dbc = None
dbo = None
# Set the first activation's gradient to the backpropagated gradient da_prev.
da0 = None
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dx": dx, "da0": da0, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
"dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
return gradients
np.random.seed(1)
x = np.random.randn(3,10,7)
a0 = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a, y, c, caches = lstm_forward(x, a0, parameters)
da = np.random.randn(5, 10, 4)
gradients = lstm_backward(da, caches)
print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
print("gradients[\"dx\"].shape =", gradients["dx"].shape)
print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
print("gradients[\"da0\"].shape =", gradients["da0"].shape)
print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
print("gradients[\"dbo\"].shape =", gradients["dbo"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dx"][1][2]** =
</td>
<td>
[-0.00173313 0.08287442 -0.30545663 -0.43281115]
</td>
</tr>
<tr>
<td>
**gradients["dx"].shape** =
</td>
<td>
(3, 10, 4)
</td>
</tr>
<tr>
<td>
**gradients["da0"][2][3]** =
</td>
<td>
-0.095911501954
</td>
</tr>
<tr>
<td>
**gradients["da0"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWf"][3][1]** =
</td>
<td>
-0.0698198561274
</td>
</tr>
<tr>
<td>
**gradients["dWf"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWi"][1][2]** =
</td>
<td>
0.102371820249
</td>
</tr>
<tr>
<td>
**gradients["dWi"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWc"][3][1]** =
</td>
<td>
-0.0624983794927
</td>
</tr>
<tr>
<td>
**gradients["dWc"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWo"][1][2]** =
</td>
<td>
0.0484389131444
</td>
</tr>
<tr>
<td>
**gradients["dWo"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dbf"][4]** =
</td>
<td>
[-0.0565788]
</td>
</tr>
<tr>
<td>
**gradients["dbf"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbi"][4]** =
</td>
<td>
[-0.06997391]
</td>
</tr>
<tr>
<td>
**gradients["dbi"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbc"][4]** =
</td>
<td>
[-0.27441821]
</td>
</tr>
<tr>
<td>
**gradients["dbc"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbo"][4]** =
</td>
<td>
[ 0.16532821]
</td>
</tr>
<tr>
<td>
**gradients["dbo"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
### Congratulations !
Congratulations on completing this assignment. You now understand how recurrent neural networks work!
Lets go on to the next exercise, where you'll use an RNN to build a character-level language model.
| github_jupyter |
<img width="10%" alt="Naas" src="https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160"/>
# Remotive - Get jobs from categories
<a href="https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/Remotive/Remotive_Get_jobs_from_categories.ipynb" target="_parent"><img src="https://naasai-public.s3.eu-west-3.amazonaws.com/open_in_naas.svg"/></a>
**Tags:** #remotive #jobs #csv #snippet #opendata #dataframe
**Author:** [Sanjeet Attili](https://www.linkedin.com/in/sanjeet-attili-760bab190/)
With this notebook, you will be able to get jobs offer from Remotive:
- **URL:** Job offer url.
- **TITLE:** Job title.
- **COMPANY:** Company name.
- **PUBLICATION_DATE:** Date of publication.
## Input
### Import libraries
```
import pandas as pd
import requests
import time
from datetime import datetime
```
### Setup Remotive
#### Get categories from Remotive
```
def get_remotejob_categories():
req_url = f"https://remotive.io/api/remote-jobs/categories"
res = requests.get(req_url)
try:
res.raise_for_status()
except requests.HTTPError as e:
return e
res_json = res.json()
# Get categories
jobs = res_json.get('jobs')
return pd.DataFrame(jobs)
df_categories = get_remotejob_categories()
df_categories
```
#### Enter your parameters
```
categories = ['data'] # Pick the list of categories in columns "slug"
date_from = - 10 # Choose date difference in days from now => must be negative
```
### Variables
```
csv_output = "REMOTIVE_JOBS.csv"
```
## Model
### Get all jobs posted after timestamp_date
All jobs posted after the date from will be fetched.<br>
In summary, we can set the value, in seconds, of 'search_data_from' to fetch all jobs posted since this duration
```
REMOTIVE_DATETIME = "%Y-%m-%dT%H:%M:%S"
NAAS_DATETIME = "%Y-%m-%d %H:%M:%S"
def get_remotive_jobs_since(jobs, date):
ret = []
for job in jobs:
publication_date = datetime.strptime(job['publication_date'], REMOTIVE_DATETIME).timestamp()
if publication_date > date:
ret.append({
'URL': job['url'],
'TITLE': job['title'],
'COMPANY': job['company_name'],
'PUBLICATION_DATE': datetime.fromtimestamp(publication_date).strftime(NAAS_DATETIME)
})
return ret
def get_category_jobs_since(category, date, limit):
url = f"https://remotive.io/api/remote-jobs?category={category}&limit={limit}"
res = requests.get(url)
if res.json()['jobs']:
publication_date = datetime.strptime(res.json()['jobs'][-1]['publication_date'], REMOTIVE_DATETIME).timestamp()
if len(res.json()['jobs']) < limit or date > publication_date:
print(f"Jobs from catgory {category} fetched ✅")
return get_remotive_jobs_since(res.json()['jobs'], date)
else:
return get_category_jobs_since(category, date, limit + 5)
return []
def get_jobs_since(categories: list,
date_from: int):
if date_from >= 0:
return("'date_from' must be negative. Please update your parameter.")
# Transform datefrom int to
search_jobs_from = date_from * 24 * 60 * 60 # days in seconds
timestamp_date = time.time() + search_jobs_from
jobs = []
for category in categories:
jobs += get_category_jobs_since(category, timestamp_date, 5)
print(f'- All job since {datetime.fromtimestamp(timestamp_date)} have been fetched:', len(jobs))
return pd.DataFrame(jobs)
df_jobs = get_jobs_since(categories, date_from=date_from)
df_jobs.head(5)
```
## Output
### Save dataframe in csv
```
df_jobs.to_csv(csv_output, index=False)
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import matplotlib.pyplot as pyplot
import matplotlib.gridspec as gridspec
%matplotlib inline
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
tre=np.array([1081.43,
1107.25,
1249.36,
1400.13,
1565.90,
3799.61,
7395.81,
12673.03,
71021.1,
241031.1,
5201111,
20101211
])
de=np.array([111.63,119.39,143.83,235.98,391.18,2831.77,10877.56,
24253.2,266954.006027716,1066321.80982717,26632320.1528028,106517457.862972])
spark = np.array([185.5,
203.62,
215.31,
253,
324.62,
984.06,
2799.78,
5609.28,
53275.78,
206370.8,
5031131,
20062081,
])
gco=np.array([229.85, 231.94, 234.95, 240.35, 248.00, 268.50, 307.96,
347.89, 600.31, 987.55, 3737.52, 7811.83])
## Memory units is MiB
memory_df=pd.DataFrame({'trendsceek':tre,'SpatialDE':de,'scGCO':gco,'spark':spark},
index=[100,250,500,1000,1500,5000,10000,15000,50000,100000,500000,1000000])
memory_df
## MiB -- GB
print('When memory is GB: ','\n',memory_df.iloc[-1,:]/1024,'GB')
## TB
print('When memory is TB: ','\n',memory_df.iloc[-1,:]/1024/1024, 'TB')
memory=memory_df
pyplot.subplots(figsize=(15,8))
pyplot.yscale('log')
pyplot.xscale('log')
colors={'trendsceek':'tab:grey',"scGCO":'tab:red'}
for method in colors:
pyplot.plot(memory.index.values,memory.loc[:,method],lw=6,color="w",label='')
pyplot.plot(memory.index.values,memory.scGCO.values,'r-',marker='.',lw=2,ms=12,label='scGCO')
pyplot.plot(memory.iloc[0:8,3].index, memory.iloc[0:8,3].values, 'b-',marker='.',lw=2,ms=12,label='SPARK')
pyplot.plot(memory.iloc[7:,3].index, memory.iloc[7:,3].values, 'b:',marker='.',lw=2,ms=12)
pyplot.plot(memory.iloc[0:8,1].index.values,memory.iloc[0:8,1].values,'g-',marker='.',lw=2,ms=12,label='spatialDE')
pyplot.plot(memory.iloc[7:,1].index.values,memory.iloc[7:,1].values,'g:',marker='.',lw=2,ms=12)
pyplot.plot(memory.iloc[0:-1,0].index.values,memory.iloc[0:-1,0].values,'c-',marker='.',lw=2,ms=12,
label='trendSceek')
pyplot.plot(memory.iloc[-2:,0].index.values,memory.iloc[-2:,0].values,'c:',marker='.',lw=2,ms=12)
#plt.legend(numpoints=2, frameon=False)
plt.xlabel("Number of cells",size=15)
plt.ylabel("Memory(MiB)",size=15)
#pyplot.title('Running Memory(100 genes)',size=18)
plt.axhline(1024,lw=1,c='k',zorder=0,ls='--')
plt.annotate('1 G',(70,1024*1.05),va='bottom')
plt.axhline(1024*8,lw=1,c='k',zorder=0,ls='--')
plt.annotate('8 G',(70,1024*1.05*8),va='bottom')
plt.axhline(1024*64,lw=1,c='k',zorder=0,ls='--')
plt.annotate('64 G',(70,1024*1.05*64),va='bottom')
plt.axhline(1024*1024*2,lw=1,c='r',zorder=0,ls='--')
plt.annotate('2 T',(70,1024*1.05*1024*2),va='bottom')
plt.axhline(1024*1024*8,lw=1,c='k',zorder=0,ls='--')
plt.annotate('8 T',(70,1024*1.05*1024*8),va='bottom')
plt.axhline(1024*1024*100,lw=1,c='k',zorder=0,ls='--')
plt.annotate('100 T',(70,1024*1.05*1024*100),va='bottom')
xtick=[100,250,500,1000,1500,5000,10000,15000,50000,100000,500000,1000000]
xlabel=['100','250','500','1000','1500','5000','10K','15K','50K','100K','500K','1M']
plt.xticks(xtick,xlabel,rotation=45,fontsize=12)
plt.yticks(fontsize=12)
plt.legend(ncol=4,loc=(0.3,1.05),fontsize=12,frameon=False)
plt.savefig('../../results/Figure/Fig2g.pdf')
pyplot.show()
```
| github_jupyter |
## Model explainability
Explainability is the extent to which a model can be explained in human terms. Interpretability is the extent to which you can explain the outcome of a model after a change in input parameters. Often times we are working with black box models, which only show the prediction and not the steps that led up to that decision. Explainability methods uncover vulnerabilities in models and are able to offer a broader insight as to how differing inputs change the outcome.
We'll start by loading the data and splitting the data into training and test sets.
```
import pandas as pd
import shap
from sklearn import model_selection
import numpy as np
import pickle
from alibi.explainers import CEM, KernelShap
import warnings
warnings.filterwarnings("ignore")
pt_info_clean = pd.read_csv("../data/processed/pt_info_clean.csv")
train, test = model_selection.train_test_split(pt_info_clean, random_state=43)
```
We'll translate the pandas data frame into numpy arrays in order to agree with the necessary inputs for our explainability methods.
```
x_train = np.asarray(train.iloc[:,2:train.shape[1]])
x_test = np.asarray(test.iloc[:,2:train.shape[1]])
y_train = np.asarray(train['mrsa_positive'])
y_test = np.asarray(test['mrsa_positive'])
```
Next, we'll import our logistic regression model from before, fit it to the data, and generate predictions. Note: we could use either model here since the methods are model agnostic.
```
# loading model
filename = '../models/logistic_model.sav'
model = pickle.load(open(filename, 'rb'))
# fit model
model.fit(x_train, y_train)
# generate predictions
y_preds = model.predict(x_test)
```
Our model has now made a classification prediction for each of the test data points. However, we don't have much intuition as to how the model chose to classify these values. Explainability methods exist to offer ways to explore the decision making process of black-box models such as this one. Let's see if we can figure out why this prediction was made.
```
def class_names(idx):
if idx > 0:
print('MRSA+')
else:
print('MRSA-')
```
We'll start by looking at one singular patient and why they were classified the way they were. This is called looking at a _local explanation_.
```
predict_fn = lambda x: model.predict_proba(x) # input needs the prediction
# probabilites for each class
shape_ = (1,) + x_train.shape[1:] # dimension of one row, in this case, one patient
feature_names = list(test.columns[2:])
mode = 'PN'
```
## SHAP
One type of explainability method is [SHAP](https://christophm.github.io/interpretable-ml-book/shap.html), or SHapley Additive exPlanations, where a local prediction is explained by displaying each feature's contribution to the prediction. The output of a SHAP method is a linear model created for a particular instance. We'll use the [Alibi](https://github.com/SeldonIO/alibi) library again to use [KernelSHAP](https://docs.seldon.io/projects/alibi/en/latest/methods/KernelSHAP.html), which is used as a black-box SHAP method for an arbitrary classification model.
```
shap_explainer = KernelShap(predict_fn)
shap_explainer.fit(x_train)
shap_explanation = shap_explainer.explain(x_test, l1_reg=False)
```
## Visualizations
After initializing the explainers, we can look at both global and local explanation methods. We'll use a `force_plot` visualization to better understand the local linear model generated by SHAP. This plot shows which features contributed to making the prediction, and to what extent they moved the prediction from the base value (output of model if no inputs are given) to the output value for that instance.
```
shap.initjs()
idx = 0
instance = test.iloc[idx,2:test.shape[1]] # shape of the instance to be explained
class_idx = y_preds[idx].astype(int) # predicted class
feature_names = list(test.columns[2:])
shap.force_plot(
shap_explainer.expected_value[class_idx],
shap_explanation.shap_values[class_idx][idx, :],
instance,
feature_names = feature_names,
text_rotation=15,
matplotlib=True
)
```
Note that this is a local explanation. Other instances will have different weights for each feature, so we cannot generalize this output to the whole model. We can see from the plot that the ethnicity and location of admission features had the biggest influence on the model's decision to classify this instance. We could look at other explainability methods such as [counterfactuals](https://christophm.github.io/interpretable-ml-book/counterfactual.html) to find out what changes to the input would create the correct classification.
We see what influenced this instance the most, but what about the overall model? SHAP also offers global explanations, which can be viewed best by a `summary_plot`.
```
shap.summary_plot(shap_explanation.shap_values[idx],
test.iloc[:,2:test.shape[1]],
feature_names = feature_names)
```
This plot shows the total sum of each feature's SHAP value for each of the instances in `x_test` with a class `0` (MRSA negative). Features with the highest impact are at the top of the plot. This model has the highest valued features being `ethnicity_HISPANIC/LATINO - PUERTO RICAN`, `gender_F`, and `ethnicity_WHITE`; with the prescence of these values, the model is more likely to predict class `0`. This outcome definitely raises questions in terms of model bias or input bias: what does the underlying population look like that ethnicity and gender are driving features of this function? We would probably expect diagnoses to be more important, but it could be that there are a vast amount of diagnoses for any one to be heavily weighted. If this model was going into production, we would probably want to take a step back and do more research to ensure our model is able to generalize well to all patients.
# Conclusion
In the end, **explainers are not built to fix problems in models, but rather expose them.** Understanding how black-box models make decisions before launching them into production helps ensure transparency and avoid unconscious bias.
## Contrastive Explanation Methods
There's a variety of explainability methods that supply local or global explanations for how a model is making certain classification decisions; we'll use a library called [Alibi](https://github.com/SeldonIO/alibi) in order to create some of these methods. [Contrastive explanation methods](https://arxiv.org/abs/1802.07623), or CEMs, focus on explaining instances in terms of pertinent positives and pertinent negatives. **Pertinent positives** refer to features that should be minimally and sufficiently present to predict the same class as on the original instance. (e.g. if all people who contract MRSA are between the ages 35 and 55). **Pertinent negatives**, on the other hand, identify what features should be minimally and necessarily absent from the instance to be explained in order to maintain the original prediction class (e.g. NO people with respiratory distress contracted MRSA).
Alibi offers black-box explanations for models, which means all that the CEM needs is a predict function for the model. This gives us the flexibility to input nearly any model without having to rewrite any code to initialize the CEM. The only edit we have done is change ```predict``` to ```predict_proba```, which gives the output of the probability of each possible predicted class rather than the prediction itself.
```
cem = CEM(predict_fn,
mode = mode, # either PN or PP
shape = shape_) # instance shape
idx = 0
X = x_test[idx].reshape((1,) + x_test[idx].shape)
cem.fit(x_train, no_info_type='median') # we need to define what feature values contain the least
# info wrt predictions
# here we will naively assume that the feature-wise median
# contains no info
cem_explanation = cem.explain(X, verbose=False)
columns = pd.Series(feature_names)
pn_df = pd.DataFrame(cem_explanation.PN,
columns = columns)
pn_df.loc[:, (pn_df < 0).any(axis=0)]
print('Actual class: ')
class_names(y_test[idx])
print('Model prediction for patient: ')
class_names(model.predict(X))
```
| github_jupyter |

# Experimental Probability
Instead of rolling dice or flipping coins and recording the results, we can write some Python code to do it for us.
We'll use a Python module called `randint` to generate random integers, `matplotlib` to generate graphs, and `Counter` (from `collections`) to count frequencies.
Let's say we wanted to flip a coin 20 times. We could generate a random integer that is **1** or **2** and decide that "heads" is 1 and "tails" is 2. Run the code below by clicking on the cell and clicking the `Run` button above (or pressing Ctrl-Enter).
```
from random import randint
howMany = 20
sides = 2
results = [] # create an empty list that we will store results in
for x in range(0,howMany): # create a loop that will run once for each number of flips
result = randint(1,sides) # generate a random number between 1 and 2
results += [result] # add the result to our list
results # print the list of results
```
Each time you run the above code you should get a different list of numbers.
Now let's do the same thing, but create a bar graph of the frequency of each number.
```
howMany = 20
sides = 2
results = []
for x in range(0,howMany):
result = randint(1,sides)
results += [result]
# count how many times we got each sum
from collections import Counter
counts = Counter(results)
# create a bar graph from that count
import matplotlib.pyplot as plot
%matplotlib inline
plot.bar(counts.keys(),counts.values())
plot.show()
```
The same code would work if we wanted to use dice, we just need to change the number of sides.
```
howMany = 20
sides = 6
results = []
for x in range(0,howMany):
result = randint(1,sides)
results += [result]
counts = Counter(results)
plot.bar(counts.keys(),counts.values())
plot.show()
```
Theoretically we expect each number to be rolled with the same frequency, but `20` is not a large enough sample size.
Change the value of the `howMany` variable in the above code to `5000` and run it again. Does that look more like the theoretical probability?
One more statistics experiment, let's roll two dice and add them together... five thousand times.
```
howMany = 500000
sides = 6
results = []
for x in range(0,howMany):
number1 = randint(1,sides)
number2 = randint(1,sides)
result = number1 + number2
results += [result]
counts = Counter(results)
plot.bar(counts.keys(),counts.values())
plot.show()
```
What is the most common sum? Why?
What are the least common sums? Why?
Would the graph look different with fewer rolls? Why?
Would the graph look different with more rolls? Why?
[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
| github_jupyter |
```
%load_ext load_style
%load_style talk.css
```
# Read SST NetCDF data, Subsample and Save
This notebook carries out some basic operations:
* Open a data file
* Check variables
* Indexing to subsampe a variable
* Save data
## 1. Load basic libraries
```
%matplotlib inline
import numpy as np
from netCDF4 import Dataset # http://unidata.github.io/netcdf4-python/
```
## 2. Set input NetCDF file info
You can download data using wget or aria2c under Linux. In this case, the data is already downloaded and put into the folder of data.
```
#!wget ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.derived/surface_gauss/skt.sfc.mon.mean.nc
ncfile = 'data\skt.mon.mean.nc'
```
## 3. Extract variables
Open a NetCDF file and print the file handler, then you can find the information of its variales from last several lines.
Just like:
* platform: Model
* Conventions: COARDS
* dimensions(sizes): lon(192), lat(94), time(687)
* variables(dimensions): float32 **lat(lat), float32 lon(lon), float64 time(time), float32 skt(time,lat,lon)**
```
fh = Dataset(ncfile, mode='r') # file handle, open in read only mode
print(fh)
fh.close() # close the file
fh = Dataset(ncfile, mode='r') # file handle, open in read only mode
lon = fh.variables['lon'][:]
lat = fh.variables['lat'][:]
nctime = fh.variables['time'][:]
t_unit = fh.variables['time'].units
skt = fh.variables['skt'][:]
try :
t_cal = fh.variables['time'].calendar
except AttributeError : # Attribute doesn't exist
t_cal = u"gregorian" # or standard
fh.close() # close the file
```
## 4. Access the first and the last value of latitude
```
lat[0] # Caution! Python’s indexing starts with zero
lat[-1] # gives the last value of the vector
```
## 5. Select a subregion
* Lat: -50 ~ -90
* Lon: 0 ~ 360
```
lat_so = lat[-21:-1]
lon_so = lon
skt_so = skt[:,-21:-1,:]
```
## 6. Save subregion data
save subregion data (several arrays) into a single file in uncompressed .npz format using np.savez.
```
np.savez('data/skt.so.mon.mean.npz', skt_so=skt_so, lat_so=lat_so, lon_so=lon_so)
```
Surely, you can load these data back.
```
npzfile = np.load('data/skt.so.mon.mean.npz')
npzfile.files
```
## References
http://unidata.github.io/netcdf4-python/
John D. Hunter. Matplotlib: A 2D Graphics Environment, Computing in Science & Engineering, 9, 90-95 (2007), DOI:10.1109/MCSE.2007.55
Stéfan van der Walt, S. Chris Colbert and Gaël Varoquaux. The NumPy Array: A Structure for Efficient Numerical Computation, Computing in Science & Engineering, 13, 22-30 (2011), DOI:10.1109/MCSE.2011.37
Kalnay et al.,The NCEP/NCAR 40-year reanalysis project, Bull. Amer. Meteor. Soc., 77, 437-470, 1996.
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Forecasting with an RNN
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l08c06_forecasting_with_rnn.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l08c06_forecasting_with_rnn.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
## Setup
```
from __future__ import absolute_import, division, print_function, unicode_literals
try:
# Use the %tensorflow_version magic if in colab.
%tensorflow_version 2.x
except Exception:
pass
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
keras = tf.keras
def plot_series(time, series, format="-", start=0, end=None, label=None):
plt.plot(time[start:end], series[start:end], format, label=label)
plt.xlabel("Time")
plt.ylabel("Value")
if label:
plt.legend(fontsize=14)
plt.grid(True)
def trend(time, slope=0):
return slope * time
def seasonal_pattern(season_time):
"""Just an arbitrary pattern, you can change it if you wish"""
return np.where(season_time < 0.4,
np.cos(season_time * 2 * np.pi),
1 / np.exp(3 * season_time))
def seasonality(time, period, amplitude=1, phase=0):
"""Repeats the same pattern at each period"""
season_time = ((time + phase) % period) / period
return amplitude * seasonal_pattern(season_time)
def white_noise(time, noise_level=1, seed=None):
rnd = np.random.RandomState(seed)
return rnd.randn(len(time)) * noise_level
def window_dataset(series, window_size, batch_size=32,
shuffle_buffer=1000):
dataset = tf.data.Dataset.from_tensor_slices(series)
dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
dataset = dataset.shuffle(shuffle_buffer)
dataset = dataset.map(lambda window: (window[:-1], window[-1]))
dataset = dataset.batch(batch_size).prefetch(1)
return dataset
def model_forecast(model, series, window_size):
ds = tf.data.Dataset.from_tensor_slices(series)
ds = ds.window(window_size, shift=1, drop_remainder=True)
ds = ds.flat_map(lambda w: w.batch(window_size))
ds = ds.batch(32).prefetch(1)
forecast = model.predict(ds)
return forecast
time = np.arange(4 * 365 + 1)
slope = 0.05
baseline = 10
amplitude = 40
series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)
noise_level = 5
noise = white_noise(time, noise_level, seed=42)
series += noise
plt.figure(figsize=(10, 6))
plot_series(time, series)
plt.show()
split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
```
## Simple RNN Forecasting
```
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size, batch_size=128)
model = keras.models.Sequential([
keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
input_shape=[None]),
keras.layers.SimpleRNN(100, return_sequences=True),
keras.layers.SimpleRNN(100),
keras.layers.Dense(1),
keras.layers.Lambda(lambda x: x * 200.0)
])
lr_schedule = keras.callbacks.LearningRateScheduler(
lambda epoch: 1e-7 * 10**(epoch / 20))
optimizer = keras.optimizers.SGD(lr=1e-7, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
plt.semilogx(history.history["lr"], history.history["loss"])
plt.axis([1e-7, 1e-4, 0, 30])
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = window_dataset(x_train, window_size, batch_size=128)
valid_set = window_dataset(x_valid, window_size, batch_size=128)
model = keras.models.Sequential([
keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
input_shape=[None]),
keras.layers.SimpleRNN(100, return_sequences=True),
keras.layers.SimpleRNN(100),
keras.layers.Dense(1),
keras.layers.Lambda(lambda x: x * 200.0)
])
optimizer = keras.optimizers.SGD(lr=1.5e-6, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
early_stopping = keras.callbacks.EarlyStopping(patience=50)
model_checkpoint = keras.callbacks.ModelCheckpoint(
"my_checkpoint", save_best_only=True)
model.fit(train_set, epochs=500,
validation_data=valid_set,
callbacks=[early_stopping, model_checkpoint])
model = keras.models.load_model("my_checkpoint")
rnn_forecast = model_forecast(
model,
series[split_time - window_size:-1],
window_size)[:, 0]
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, rnn_forecast)
keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()
```
## Sequence-to-Sequence Forecasting
```
def seq2seq_window_dataset(series, window_size, batch_size=32,
shuffle_buffer=1000):
series = tf.expand_dims(series, axis=-1)
ds = tf.data.Dataset.from_tensor_slices(series)
ds = ds.window(window_size + 1, shift=1, drop_remainder=True)
ds = ds.flat_map(lambda w: w.batch(window_size + 1))
ds = ds.shuffle(shuffle_buffer)
ds = ds.map(lambda w: (w[:-1], w[1:]))
return ds.batch(batch_size).prefetch(1)
for X_batch, Y_batch in seq2seq_window_dataset(tf.range(10), 3,
batch_size=1):
print("X:", X_batch.numpy())
print("Y:", Y_batch.numpy())
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = seq2seq_window_dataset(x_train, window_size,
batch_size=128)
model = keras.models.Sequential([
keras.layers.SimpleRNN(100, return_sequences=True,
input_shape=[None, 1]),
keras.layers.SimpleRNN(100, return_sequences=True),
keras.layers.Dense(1),
keras.layers.Lambda(lambda x: x * 200)
])
lr_schedule = keras.callbacks.LearningRateScheduler(
lambda epoch: 1e-7 * 10**(epoch / 30))
optimizer = keras.optimizers.SGD(lr=1e-7, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])
plt.semilogx(history.history["lr"], history.history["loss"])
plt.axis([1e-7, 1e-4, 0, 30])
keras.backend.clear_session()
tf.random.set_seed(42)
np.random.seed(42)
window_size = 30
train_set = seq2seq_window_dataset(x_train, window_size,
batch_size=128)
valid_set = seq2seq_window_dataset(x_valid, window_size,
batch_size=128)
model = keras.models.Sequential([
keras.layers.SimpleRNN(100, return_sequences=True,
input_shape=[None, 1]),
keras.layers.SimpleRNN(100, return_sequences=True),
keras.layers.Dense(1),
keras.layers.Lambda(lambda x: x * 200.0)
])
optimizer = keras.optimizers.SGD(lr=1e-6, momentum=0.9)
model.compile(loss=keras.losses.Huber(),
optimizer=optimizer,
metrics=["mae"])
early_stopping = keras.callbacks.EarlyStopping(patience=10)
model.fit(train_set, epochs=500,
validation_data=valid_set,
callbacks=[early_stopping])
rnn_forecast = model_forecast(model, series[..., np.newaxis], window_size)
rnn_forecast = rnn_forecast[split_time - window_size:-1, -1, 0]
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, rnn_forecast)
keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()
```
| github_jupyter |
# Peruvian Personal Numbers
## Introduction
The function `clean_pe_cui()` cleans a column containing Peruvian personal number (CUI) strings, and standardizes them in a given format. The function `validate_pe_cui()` validates either a single CUI strings, a column of CUI strings or a DataFrame of CUI strings, returning `True` if the value is valid, and `False` otherwise.
CUI strings can be converted to the following formats via the `output_format` parameter:
* `compact`: only number strings without any seperators or whitespace, like "10117410"
* `standard`: CUI strings with proper whitespace in the proper places. Note that in the case of CUI, the compact format is the same as the standard one.
* `ruc`: convert the number to a valid RUC, like "10101174102".
Invalid parsing is handled with the `errors` parameter:
* `coerce` (default): invalid parsing will be set to NaN
* `ignore`: invalid parsing will return the input
* `raise`: invalid parsing will raise an exception
The following sections demonstrate the functionality of `clean_pe_cui()` and `validate_pe_cui()`.
### An example dataset containing CUI strings
```
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"cui": [
"10117410",
"10117410-3",
'7542011030',
'7552A10004',
'8019010008',
"hello",
np.nan,
"NULL",
],
"address": [
"123 Pine Ave.",
"main st",
"1234 west main heights 57033",
"apt 1 789 s maple rd manhattan",
"robie house, 789 north main street",
"1111 S Figueroa St, Los Angeles, CA 90015",
"(staples center) 1111 S Figueroa St, Los Angeles",
"hello",
]
}
)
df
```
## 1. Default `clean_pe_cui`
By default, `clean_pe_cui` will clean cui strings and output them in the standard format with proper separators.
```
from dataprep.clean import clean_pe_cui
clean_pe_cui(df, column = "cui")
```
## 2. Output formats
This section demonstrates the output parameter.
### `standard` (default)
```
clean_pe_cui(df, column = "cui", output_format="standard")
```
### `compact`
```
clean_pe_cui(df, column = "cui", output_format="compact")
```
### `ruc`
```
clean_pe_cui(df, column = "cui", output_format="ruc")
```
## 3. `inplace` parameter
This deletes the given column from the returned DataFrame.
A new column containing cleaned CUI strings is added with a title in the format `"{original title}_clean"`.
```
clean_pe_cui(df, column="cui", inplace=True)
```
## 4. `errors` parameter
### `coerce` (default)
```
clean_pe_cui(df, "cui", errors="coerce")
```
### `ignore`
```
clean_pe_cui(df, "cui", errors="ignore")
```
## 4. `validate_pe_cui()`
`validate_pe_cui()` returns `True` when the input is a valid CUI. Otherwise it returns `False`.
The input of `validate_pe_cui()` can be a string, a Pandas DataSeries, a Dask DataSeries, a Pandas DataFrame and a dask DataFrame.
When the input is a string, a Pandas DataSeries or a Dask DataSeries, user doesn't need to specify a column name to be validated.
When the input is a Pandas DataFrame or a dask DataFrame, user can both specify or not specify a column name to be validated. If user specify the column name, `validate_pe_cui()` only returns the validation result for the specified column. If user doesn't specify the column name, `validate_pe_cui()` returns the validation result for the whole DataFrame.
```
from dataprep.clean import validate_pe_cui
print(validate_pe_cui('10117410'))
print(validate_pe_cui('10117410-3'))
print(validate_pe_cui('7542011030'))
print(validate_pe_cui('7552A10004'))
print(validate_pe_cui('8019010008'))
print(validate_pe_cui("hello"))
print(validate_pe_cui(np.nan))
print(validate_pe_cui("NULL"))
```
### Series
```
validate_pe_cui(df["cui"])
```
### DataFrame + Specify Column
```
validate_pe_cui(df, column="cui")
```
### Only DataFrame
```
validate_pe_cui(df)
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Image captioning with visual attention
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/text/image_captioning">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png" />
View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/image_captioning.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/image_captioning.ipynb">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />
View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/text/image_captioning.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
Given an image like the example below, your goal is to generate a caption such as "a surfer riding on a wave".

*[Image Source](https://commons.wikimedia.org/wiki/Surfing#/media/File:Surfing_in_Hawaii.jpg); License: Public Domain*
To accomplish this, you'll use an attention-based model, which enables us to see what parts of the image the model focuses on as it generates a caption.

The model architecture is similar to [Show, Attend and Tell: Neural Image Caption Generation with Visual Attention](https://arxiv.org/abs/1502.03044).
This notebook is an end-to-end example. When you run the notebook, it downloads the [MS-COCO](http://cocodataset.org/#home) dataset, preprocesses and caches a subset of images using Inception V3, trains an encoder-decoder model, and generates captions on new images using the trained model.
In this example, you will train a model on a relatively small amount of data—the first 30,000 captions for about 20,000 images (because there are multiple captions per image in the dataset).
```
import tensorflow as tf
# You'll generate plots of attention in order to see which parts of an image
# your model focuses on during captioning
import matplotlib.pyplot as plt
import collections
import random
import numpy as np
import os
import time
import json
from PIL import Image
```
## Download and prepare the MS-COCO dataset
You will use the [MS-COCO dataset](http://cocodataset.org/#home) to train your model. The dataset contains over 82,000 images, each of which has at least 5 different caption annotations. The code below downloads and extracts the dataset automatically.
**Caution: large download ahead**. You'll use the training set, which is a 13GB file.
```
# Download caption annotation files
annotation_folder = '/annotations/'
if not os.path.exists(os.path.abspath('.') + annotation_folder):
annotation_zip = tf.keras.utils.get_file('captions.zip',
cache_subdir=os.path.abspath('.'),
origin='http://images.cocodataset.org/annotations/annotations_trainval2014.zip',
extract=True)
annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'
os.remove(annotation_zip)
# Download image files
image_folder = '/train2014/'
if not os.path.exists(os.path.abspath('.') + image_folder):
image_zip = tf.keras.utils.get_file('train2014.zip',
cache_subdir=os.path.abspath('.'),
origin='http://images.cocodataset.org/zips/train2014.zip',
extract=True)
PATH = os.path.dirname(image_zip) + image_folder
os.remove(image_zip)
else:
PATH = os.path.abspath('.') + image_folder
```
## Optional: limit the size of the training set
To speed up training for this tutorial, you'll use a subset of 30,000 captions and their corresponding images to train your model. Choosing to use more data would result in improved captioning quality.
```
with open(annotation_file, 'r') as f:
annotations = json.load(f)
# Group all captions together having the same image ID.
image_path_to_caption = collections.defaultdict(list)
for val in annotations['annotations']:
caption = f"<start> {val['caption']} <end>"
image_path = PATH + 'COCO_train2014_' + '%012d.jpg' % (val['image_id'])
image_path_to_caption[image_path].append(caption)
image_paths = list(image_path_to_caption.keys())
random.shuffle(image_paths)
# Select the first 6000 image_paths from the shuffled set.
# Approximately each image id has 5 captions associated with it, so that will
# lead to 30,000 examples.
train_image_paths = image_paths[:6000]
print(len(train_image_paths))
train_captions = []
img_name_vector = []
for image_path in train_image_paths:
caption_list = image_path_to_caption[image_path]
train_captions.extend(caption_list)
img_name_vector.extend([image_path] * len(caption_list))
print(train_captions[0])
Image.open(img_name_vector[0])
```
## Preprocess the images using InceptionV3
Next, you will use InceptionV3 (which is pretrained on Imagenet) to classify each image. You will extract features from the last convolutional layer.
First, you will convert the images into InceptionV3's expected format by:
* Resizing the image to 299px by 299px
* [Preprocess the images](https://cloud.google.com/tpu/docs/inception-v3-advanced#preprocessing_stage) using the [preprocess_input](https://www.tensorflow.org/api_docs/python/tf/keras/applications/inception_v3/preprocess_input) method to normalize the image so that it contains pixels in the range of -1 to 1, which matches the format of the images used to train InceptionV3.
```
def load_image(image_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, (299, 299))
img = tf.keras.applications.inception_v3.preprocess_input(img)
return img, image_path
```
## Initialize InceptionV3 and load the pretrained Imagenet weights
Now you'll create a tf.keras model where the output layer is the last convolutional layer in the InceptionV3 architecture. The shape of the output of this layer is ```8x8x2048```. You use the last convolutional layer because you are using attention in this example. You don't perform this initialization during training because it could become a bottleneck.
* You forward each image through the network and store the resulting vector in a dictionary (image_name --> feature_vector).
* After all the images are passed through the network, you save the dictionary to disk.
```
image_model = tf.keras.applications.InceptionV3(include_top=False,
weights='imagenet')
new_input = image_model.input
hidden_layer = image_model.layers[-1].output
image_features_extract_model = tf.keras.Model(new_input, hidden_layer)
```
## Caching the features extracted from InceptionV3
You will pre-process each image with InceptionV3 and cache the output to disk. Caching the output in RAM would be faster but also memory intensive, requiring 8 \* 8 \* 2048 floats per image. At the time of writing, this exceeds the memory limitations of Colab (currently 12GB of memory).
Performance could be improved with a more sophisticated caching strategy (for example, by sharding the images to reduce random access disk I/O), but that would require more code.
The caching will take about 10 minutes to run in Colab with a GPU. If you'd like to see a progress bar, you can:
1. Install [tqdm](https://github.com/tqdm/tqdm):
`!pip install tqdm`
2. Import tqdm:
`from tqdm import tqdm`
3. Change the following line:
`for img, path in image_dataset:`
to:
`for img, path in tqdm(image_dataset):`
```
# Get unique images
encode_train = sorted(set(img_name_vector))
# Feel free to change batch_size according to your system configuration
image_dataset = tf.data.Dataset.from_tensor_slices(encode_train)
image_dataset = image_dataset.map(
load_image, num_parallel_calls=tf.data.AUTOTUNE).batch(16)
for img, path in image_dataset:
batch_features = image_features_extract_model(img)
batch_features = tf.reshape(batch_features,
(batch_features.shape[0], -1, batch_features.shape[3]))
for bf, p in zip(batch_features, path):
path_of_feature = p.numpy().decode("utf-8")
np.save(path_of_feature, bf.numpy())
```
## Preprocess and tokenize the captions
* First, you'll tokenize the captions (for example, by splitting on spaces). This gives us a vocabulary of all of the unique words in the data (for example, "surfing", "football", and so on).
* Next, you'll limit the vocabulary size to the top 5,000 words (to save memory). You'll replace all other words with the token "UNK" (unknown).
* You then create word-to-index and index-to-word mappings.
* Finally, you pad all sequences to be the same length as the longest one.
```
# Find the maximum length of any caption in the dataset
def calc_max_length(tensor):
return max(len(t) for t in tensor)
# Choose the top 5000 words from the vocabulary
top_k = 5000
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,
oov_token="<unk>",
filters='!"#$%&()*+.,-/:;=?@[\]^_`{|}~')
tokenizer.fit_on_texts(train_captions)
tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'
# Create the tokenized vectors
train_seqs = tokenizer.texts_to_sequences(train_captions)
# Pad each vector to the max_length of the captions
# If you do not provide a max_length value, pad_sequences calculates it automatically
cap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post')
# Calculates the max_length, which is used to store the attention weights
max_length = calc_max_length(train_seqs)
```
## Split the data into training and testing
```
img_to_cap_vector = collections.defaultdict(list)
for img, cap in zip(img_name_vector, cap_vector):
img_to_cap_vector[img].append(cap)
# Create training and validation sets using an 80-20 split randomly.
img_keys = list(img_to_cap_vector.keys())
random.shuffle(img_keys)
slice_index = int(len(img_keys)*0.8)
img_name_train_keys, img_name_val_keys = img_keys[:slice_index], img_keys[slice_index:]
img_name_train = []
cap_train = []
for imgt in img_name_train_keys:
capt_len = len(img_to_cap_vector[imgt])
img_name_train.extend([imgt] * capt_len)
cap_train.extend(img_to_cap_vector[imgt])
img_name_val = []
cap_val = []
for imgv in img_name_val_keys:
capv_len = len(img_to_cap_vector[imgv])
img_name_val.extend([imgv] * capv_len)
cap_val.extend(img_to_cap_vector[imgv])
len(img_name_train), len(cap_train), len(img_name_val), len(cap_val)
```
## Create a tf.data dataset for training
Your images and captions are ready! Next, let's create a `tf.data` dataset to use for training your model.
```
# Feel free to change these parameters according to your system's configuration
BATCH_SIZE = 64
BUFFER_SIZE = 1000
embedding_dim = 256
units = 512
vocab_size = top_k + 1
num_steps = len(img_name_train) // BATCH_SIZE
# Shape of the vector extracted from InceptionV3 is (64, 2048)
# These two variables represent that vector shape
features_shape = 2048
attention_features_shape = 64
# Load the numpy files
def map_func(img_name, cap):
img_tensor = np.load(img_name.decode('utf-8')+'.npy')
return img_tensor, cap
dataset = tf.data.Dataset.from_tensor_slices((img_name_train, cap_train))
# Use map to load the numpy files in parallel
dataset = dataset.map(lambda item1, item2: tf.numpy_function(
map_func, [item1, item2], [tf.float32, tf.int32]),
num_parallel_calls=tf.data.AUTOTUNE)
# Shuffle and batch
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
dataset = dataset.prefetch(buffer_size=tf.data.AUTOTUNE)
```
## Model
Fun fact: the decoder below is identical to the one in the example for [Neural Machine Translation with Attention](https://www.tensorflow.org/text/tutorials/nmt_with_attention).
The model architecture is inspired by the [Show, Attend and Tell](https://arxiv.org/pdf/1502.03044.pdf) paper.
* In this example, you extract the features from the lower convolutional layer of InceptionV3 giving us a vector of shape (8, 8, 2048).
* You squash that to a shape of (64, 2048).
* This vector is then passed through the CNN Encoder (which consists of a single Fully connected layer).
* The RNN (here GRU) attends over the image to predict the next word.
```
class BahdanauAttention(tf.keras.Model):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def call(self, features, hidden):
# features(CNN_encoder output) shape == (batch_size, 64, embedding_dim)
# hidden shape == (batch_size, hidden_size)
# hidden_with_time_axis shape == (batch_size, 1, hidden_size)
hidden_with_time_axis = tf.expand_dims(hidden, 1)
# attention_hidden_layer shape == (batch_size, 64, units)
attention_hidden_layer = (tf.nn.tanh(self.W1(features) +
self.W2(hidden_with_time_axis)))
# score shape == (batch_size, 64, 1)
# This gives you an unnormalized score for each image feature.
score = self.V(attention_hidden_layer)
# attention_weights shape == (batch_size, 64, 1)
attention_weights = tf.nn.softmax(score, axis=1)
# context_vector shape after sum == (batch_size, hidden_size)
context_vector = attention_weights * features
context_vector = tf.reduce_sum(context_vector, axis=1)
return context_vector, attention_weights
class CNN_Encoder(tf.keras.Model):
# Since you have already extracted the features and dumped it
# This encoder passes those features through a Fully connected layer
def __init__(self, embedding_dim):
super(CNN_Encoder, self).__init__()
# shape after fc == (batch_size, 64, embedding_dim)
self.fc = tf.keras.layers.Dense(embedding_dim)
def call(self, x):
x = self.fc(x)
x = tf.nn.relu(x)
return x
class RNN_Decoder(tf.keras.Model):
def __init__(self, embedding_dim, units, vocab_size):
super(RNN_Decoder, self).__init__()
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.keras.layers.GRU(self.units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
self.fc1 = tf.keras.layers.Dense(self.units)
self.fc2 = tf.keras.layers.Dense(vocab_size)
self.attention = BahdanauAttention(self.units)
def call(self, x, features, hidden):
# defining attention as a separate model
context_vector, attention_weights = self.attention(features, hidden)
# x shape after passing through embedding == (batch_size, 1, embedding_dim)
x = self.embedding(x)
# x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)
x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)
# passing the concatenated vector to the GRU
output, state = self.gru(x)
# shape == (batch_size, max_length, hidden_size)
x = self.fc1(output)
# x shape == (batch_size * max_length, hidden_size)
x = tf.reshape(x, (-1, x.shape[2]))
# output shape == (batch_size * max_length, vocab)
x = self.fc2(x)
return x, state, attention_weights
def reset_state(self, batch_size):
return tf.zeros((batch_size, self.units))
encoder = CNN_Encoder(embedding_dim)
decoder = RNN_Decoder(embedding_dim, units, vocab_size)
optimizer = tf.keras.optimizers.Adam()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction='none')
def loss_function(real, pred):
mask = tf.math.logical_not(tf.math.equal(real, 0))
loss_ = loss_object(real, pred)
mask = tf.cast(mask, dtype=loss_.dtype)
loss_ *= mask
return tf.reduce_mean(loss_)
```
## Checkpoint
```
checkpoint_path = "./checkpoints/train"
ckpt = tf.train.Checkpoint(encoder=encoder,
decoder=decoder,
optimizer=optimizer)
ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)
start_epoch = 0
if ckpt_manager.latest_checkpoint:
start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1])
# restoring the latest checkpoint in checkpoint_path
ckpt.restore(ckpt_manager.latest_checkpoint)
```
## Training
* You extract the features stored in the respective `.npy` files and then pass those features through the encoder.
* The encoder output, hidden state(initialized to 0) and the decoder input (which is the start token) is passed to the decoder.
* The decoder returns the predictions and the decoder hidden state.
* The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.
* Use teacher forcing to decide the next input to the decoder.
* Teacher forcing is the technique where the target word is passed as the next input to the decoder.
* The final step is to calculate the gradients and apply it to the optimizer and backpropagate.
```
# adding this in a separate cell because if you run the training cell
# many times, the loss_plot array will be reset
loss_plot = []
@tf.function
def train_step(img_tensor, target):
loss = 0
# initializing the hidden state for each batch
# because the captions are not related from image to image
hidden = decoder.reset_state(batch_size=target.shape[0])
dec_input = tf.expand_dims([tokenizer.word_index['<start>']] * target.shape[0], 1)
with tf.GradientTape() as tape:
features = encoder(img_tensor)
for i in range(1, target.shape[1]):
# passing the features through the decoder
predictions, hidden, _ = decoder(dec_input, features, hidden)
loss += loss_function(target[:, i], predictions)
# using teacher forcing
dec_input = tf.expand_dims(target[:, i], 1)
total_loss = (loss / int(target.shape[1]))
trainable_variables = encoder.trainable_variables + decoder.trainable_variables
gradients = tape.gradient(loss, trainable_variables)
optimizer.apply_gradients(zip(gradients, trainable_variables))
return loss, total_loss
EPOCHS = 20
for epoch in range(start_epoch, EPOCHS):
start = time.time()
total_loss = 0
for (batch, (img_tensor, target)) in enumerate(dataset):
batch_loss, t_loss = train_step(img_tensor, target)
total_loss += t_loss
if batch % 100 == 0:
average_batch_loss = batch_loss.numpy()/int(target.shape[1])
print(f'Epoch {epoch+1} Batch {batch} Loss {average_batch_loss:.4f}')
# storing the epoch end loss value to plot later
loss_plot.append(total_loss / num_steps)
if epoch % 5 == 0:
ckpt_manager.save()
print(f'Epoch {epoch+1} Loss {total_loss/num_steps:.6f}')
print(f'Time taken for 1 epoch {time.time()-start:.2f} sec\n')
plt.plot(loss_plot)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Loss Plot')
plt.show()
```
## Caption!
* The evaluate function is similar to the training loop, except you don't use teacher forcing here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.
* Stop predicting when the model predicts the end token.
* And store the attention weights for every time step.
```
def evaluate(image):
attention_plot = np.zeros((max_length, attention_features_shape))
hidden = decoder.reset_state(batch_size=1)
temp_input = tf.expand_dims(load_image(image)[0], 0)
img_tensor_val = image_features_extract_model(temp_input)
img_tensor_val = tf.reshape(img_tensor_val, (img_tensor_val.shape[0],
-1,
img_tensor_val.shape[3]))
features = encoder(img_tensor_val)
dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0)
result = []
for i in range(max_length):
predictions, hidden, attention_weights = decoder(dec_input,
features,
hidden)
attention_plot[i] = tf.reshape(attention_weights, (-1, )).numpy()
predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy()
result.append(tokenizer.index_word[predicted_id])
if tokenizer.index_word[predicted_id] == '<end>':
return result, attention_plot
dec_input = tf.expand_dims([predicted_id], 0)
attention_plot = attention_plot[:len(result), :]
return result, attention_plot
def plot_attention(image, result, attention_plot):
temp_image = np.array(Image.open(image))
fig = plt.figure(figsize=(10, 10))
len_result = len(result)
for i in range(len_result):
temp_att = np.resize(attention_plot[i], (8, 8))
grid_size = max(np.ceil(len_result/2), 2)
ax = fig.add_subplot(grid_size, grid_size, i+1)
ax.set_title(result[i])
img = ax.imshow(temp_image)
ax.imshow(temp_att, cmap='gray', alpha=0.6, extent=img.get_extent())
plt.tight_layout()
plt.show()
# captions on the validation set
rid = np.random.randint(0, len(img_name_val))
image = img_name_val[rid]
real_caption = ' '.join([tokenizer.index_word[i]
for i in cap_val[rid] if i not in [0]])
result, attention_plot = evaluate(image)
print('Real Caption:', real_caption)
print('Prediction Caption:', ' '.join(result))
plot_attention(image, result, attention_plot)
```
## Try it on your own images
For fun, below you're provided a method you can use to caption your own images with the model you've just trained. Keep in mind, it was trained on a relatively small amount of data, and your images may be different from the training data (so be prepared for weird results!)
```
image_url = 'https://tensorflow.org/images/surf.jpg'
image_extension = image_url[-4:]
image_path = tf.keras.utils.get_file('image'+image_extension, origin=image_url)
result, attention_plot = evaluate(image_path)
print('Prediction Caption:', ' '.join(result))
plot_attention(image_path, result, attention_plot)
# opening the image
Image.open(image_path)
```
# Next steps
Congrats! You've just trained an image captioning model with attention. Next, take a look at this example [Neural Machine Translation with Attention](https://www.tensorflow.org/text/tutorials/nmt_with_attention). It uses a similar architecture to translate between Spanish and English sentences. You can also experiment with training the code in this notebook on a different dataset.
| github_jupyter |
# "An overview of basic causal inference algorithms and how to implement them from scratch in Python"
> "In this article we survey a number of basic causal inference algorithms and how to implement them in Python."
- published: false
- toc: true
- branch: master
- badges: true
- comments: true
- categories: [causal inference, python]
```
# hide
import graphviz
def gv(s):
return graphviz.Source('digraph G{ rankdir="LR"' + s + '; }')
```
## Why causal inference and not machine learning?
Businesses, enterprises, and industries often face questions of cause and effect:
- How does offering my customers a discount change their purchase behavior?
- How does tweaking this one variable in my manufacturing process change the quality of my product?
- How does altering this one mechanical piece change the overall behavior of my machinery?
- How does addressing my customers via e-mail or through a planned marketing campaign change their willingness to buy my product?
Each of these planned interventions or manipulation of your business, your pricing policy,
manufacturing process, or your complex machinery changes the way the process of interest changes
because you change the data generation mechanism by placing in a new regime.
Thinking in terms of these business interventions and how they affect your operations is a natural process in all businesses, enterprises, and industries.
However, our common toolset of descriptive and predictive data analytics (machine learning) does, in most instances, not provide useful answers to these questions.
While machine learning methodologies are uniquely geared towards uncovering patterns in your observed data, they are limited to already observed patterns in your data.
So if you haven't yet tested the effects of that 10% discount on your sales, change in raw materials on your product's quality, or increase in stifness of that one spring on your machinery's vibrations then machine learning
won't be able to tell you.
## Prediction vs. explanation
You're the head of your sales department and need to figure out whether to write your customer
or client that e-mail either reminding them of your shop's product range or offering them a discount.
Essentially you're trying to predict effect of your e-mail intervention in the following causal model:
```
#hide_input
gv('''
"e-mail"->purchase
''')
```
There are at least two questions to ask regarding this model:
1. How will I affect the purchase likelihood of my customer / client if I send them an e-mail now?
2. My customer / client purchased after I sent them an e-mail. What would have happened had I not sent them that e-mail?
The first question asks for a prediction, and is referred to as hypothetical causation, while the second question
asks for an explanation, or counterfactual causation.
Prediction is more tractable than explanation and therefore the focus of this article.
## Seeing vs. doing
## References
- http://www.homepages.ucl.ac.uk/~ucgtrbd/talks/imperial_causality.pdf
| github_jupyter |
# Two-Qubit Characterization Sequences
Examples of two-qubit sequences, including CR gates
```
from QGL import *
```
See Auspex [example notebooks](https://github.com/BBN-Q/Auspex/tree/develop/doc/examples) on how to configure a channel library.
For the examples in this notebook, we will the channel library generated by running `ex1_QGL_basics.ipynb` in this same directory.
```
cl = ChannelLibrary("example")
q1 = cl["q1"]
# Repeat similar configuration for q2
q2 = cl.new_qubit("q2")
aps2_3 = cl.new_APS2("BBNAPS3", address="192.168.5.103")
aps2_4 = cl.new_APS2("BBNAPS4", address="192.168.5.104")
dig_2 = cl.new_X6("X6_2", address=0)
cl.set_control(q2, aps2_3)
cl.set_measure(q2, aps2_4, dig_2.ch(1))
```
One can define simultaneous operations on qubits using the `*` operator (indicating a tensor product), see [ex1_QGL_basics](./ex1_QGL_basics.ipynb).
Below is an example of QGL basic sequence for two qubits.
* The first argument (a tuple) selects the driven qubits
* The optional argument `measChans` selects which qubits to measure (default = all driven)
* The optional argument `add_cals` adds reference segments corresponding to the computational states at the end of the sequence, used to normalize the readout signals
```
RabiPoints = 101;
plot_pulse_files(RabiAmp_NQubits((q1,q2),np.linspace(0,1,RabiPoints), measChans=(q1,q2), add_cals=True))
```
### Two-qubit gates
To write a two-qubit gate in QGL, you must add to your channel library a logical channel
representing the coupling between qubits. In QGL terminology, this is known as
an `Edge`, and is a *directed* edge in the connectivity graph of your device.
QGL uses directed edges because certain two-qubit interactions have a preferred
ordering of the interaction. For instance, a cross resonance gate has a
preferred sign of the qubit-qubit detuning. By storing directed edges, we can
write two-qubit primitives that emit different pulses depending on whether the
(control, target) pair is aligned or anti-aligned with the underlying
interaction Hamiltonian.
The following examples declares that q1 and q2 are connected, and defines an edge
connecting from q1 to q2:
```
e = cl.new_edge(q1, q2)
```
We can now include `CNOT` gates in our sequences. In this example you can see the use of the two-qubit primitive `CNOT`.
The exact sequence will depend on the (source,
target) order you selected in creating the q1-q2 `Edge` and on the
chosen `cnot_implementation`.
You can select a
different default `CNOT` implementation by modifying the [cnot_implementation](https://github.com/BBN-Q/QGL/blob/3dce4ec0996ee010f8a80f3a64e585b1f7b9f7d3/QGL/config.py#L34) key
in your local QGL's `config.py` file.
In order to actually compile a CNOT, there needs to be a physical channel and generator associated with the edge, i.e.:
```
# Most calls required label and address. Let's define
# an AWG for control pulse generation
aps2_5 = cl.new_APS2("BBNAPS5", address="192.168.5.106")
cl.set_control(e, aps2_5)
seqs = [[Id(q1), CNOT(q1, q2)]] # use the default CNOT_simple implementation, where the CNOT is represented as an X pulse
mf = compile_to_hardware(seqs,'CNOT_simple')
plot_pulse_files(mf)
```
You can also explicitly call `CNOT_CR` to
use the CR decomposition, independently of the global configuration.
```
seqs = [[Id(q1), CNOT_CR(q1, q2)]] # use the CNOT_CR implementation, where the CNOT is decomposed
# into a sequence of single-qubit gates and a ZX90, as is appropriate for a cross-resonance interaction.
mf = compile_to_hardware(seqs,'CNOT_CR')
plot_pulse_files(mf)
```
Inverting the order of the `CNOT_CR` input will also produce a CNOT using the same directed edge (q1->q2), but with added single-qubit gates to invert the CNOT control and target.
```
seqs = [[Id(q1), CNOT_CR(q2, q1)]] # use the CNOT_CR implementation, where the CNOT is decomposed
# into a sequence of single-qubit gates and a ZX90, as is appropriate for a cross-resonance interaction.
mf = compile_to_hardware(seqs,'CNOT_CR_inv')
plot_pulse_files(mf)
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Eager Execution
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r1/guide/eager.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/eager.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
> Note: This is an archived TF1 notebook. These are configured
to run in TF2's
[compatbility mode](https://www.tensorflow.org/guide/migrate)
but will run in TF1 as well. To use TF1 in Colab, use the
[%tensorflow_version 1.x](https://colab.research.google.com/notebooks/tensorflow_version.ipynb)
magic.
TensorFlow's eager execution is an imperative programming environment that
evaluates operations immediately, without building graphs: operations return
concrete values instead of constructing a computational graph to run later. This
makes it easy to get started with TensorFlow and debug models, and it
reduces boilerplate as well. To follow along with this guide, run the code
samples below in an interactive `python` interpreter.
Eager execution is a flexible machine learning platform for research and
experimentation, providing:
* *An intuitive interface*—Structure your code naturally and use Python data
structures. Quickly iterate on small models and small data.
* *Easier debugging*—Call ops directly to inspect running models and test
changes. Use standard Python debugging tools for immediate error reporting.
* *Natural control flow*—Use Python control flow instead of graph control
flow, simplifying the specification of dynamic models.
Eager execution supports most TensorFlow operations and GPU acceleration. For a
collection of examples running in eager execution, see:
[tensorflow/contrib/eager/python/examples](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples).
Note: Some models may experience increased overhead with eager execution
enabled. Performance improvements are ongoing, but please
[file a bug](https://github.com/tensorflow/tensorflow/issues) if you find a
problem and share your benchmarks.
## Setup and basic usage
To start eager execution, add `` to the beginning of
the program or console session. Do not add this operation to other modules that
the program calls.
```
import tensorflow.compat.v1 as tf
```
Now you can run TensorFlow operations and the results will return immediately:
```
tf.executing_eagerly()
x = [[2.]]
m = tf.matmul(x, x)
print("hello, {}".format(m))
```
Enabling eager execution changes how TensorFlow operations behave—now they
immediately evaluate and return their values to Python. `tf.Tensor` objects
reference concrete values instead of symbolic handles to nodes in a computational
graph. Since there isn't a computational graph to build and run later in a
session, it's easy to inspect results using `print()` or a debugger. Evaluating,
printing, and checking tensor values does not break the flow for computing
gradients.
Eager execution works nicely with [NumPy](http://www.numpy.org/). NumPy
operations accept `tf.Tensor` arguments. TensorFlow
[math operations](https://www.tensorflow.org/api_guides/python/math_ops) convert
Python objects and NumPy arrays to `tf.Tensor` objects. The
`tf.Tensor.numpy` method returns the object's value as a NumPy `ndarray`.
```
a = tf.constant([[1, 2],
[3, 4]])
print(a)
# Broadcasting support
b = tf.add(a, 1)
print(b)
# Operator overloading is supported
print(a * b)
# Use NumPy values
import numpy as np
c = np.multiply(a, b)
print(c)
# Obtain numpy value from a tensor:
print(a.numpy())
# => [[1 2]
# [3 4]]
```
## Dynamic control flow
A major benefit of eager execution is that all the functionality of the host
language is available while your model is executing. So, for example,
it is easy to write [fizzbuzz](https://en.wikipedia.org/wiki/Fizz_buzz):
```
def fizzbuzz(max_num):
counter = tf.constant(0)
max_num = tf.convert_to_tensor(max_num)
for num in range(1, max_num.numpy()+1):
num = tf.constant(num)
if int(num % 3) == 0 and int(num % 5) == 0:
print('FizzBuzz')
elif int(num % 3) == 0:
print('Fizz')
elif int(num % 5) == 0:
print('Buzz')
else:
print(num.numpy())
counter += 1
fizzbuzz(15)
```
This has conditionals that depend on tensor values and it prints these values
at runtime.
## Build a model
Many machine learning models are represented by composing layers. When
using TensorFlow with eager execution you can either write your own layers or
use a layer provided in the `tf.keras.layers` package.
While you can use any Python object to represent a layer,
TensorFlow has `tf.keras.layers.Layer` as a convenient base class. Inherit from
it to implement your own layer:
```
class MySimpleLayer(tf.keras.layers.Layer):
def __init__(self, output_units):
super(MySimpleLayer, self).__init__()
self.output_units = output_units
def build(self, input_shape):
# The build method gets called the first time your layer is used.
# Creating variables on build() allows you to make their shape depend
# on the input shape and hence removes the need for the user to specify
# full shapes. It is possible to create variables during __init__() if
# you already know their full shapes.
self.kernel = self.add_variable(
"kernel", [input_shape[-1], self.output_units])
def call(self, input):
# Override call() instead of __call__ so we can perform some bookkeeping.
return tf.matmul(input, self.kernel)
```
Use `tf.keras.layers.Dense` layer instead of `MySimpleLayer` above as it has
a superset of its functionality (it can also add a bias).
When composing layers into models you can use `tf.keras.Sequential` to represent
models which are a linear stack of layers. It is easy to use for basic models:
```
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, input_shape=(784,)), # must declare input shape
tf.keras.layers.Dense(10)
])
```
Alternatively, organize models in classes by inheriting from `tf.keras.Model`.
This is a container for layers that is a layer itself, allowing `tf.keras.Model`
objects to contain other `tf.keras.Model` objects.
```
class MNISTModel(tf.keras.Model):
def __init__(self):
super(MNISTModel, self).__init__()
self.dense1 = tf.keras.layers.Dense(units=10)
self.dense2 = tf.keras.layers.Dense(units=10)
def call(self, input):
"""Run the model."""
result = self.dense1(input)
result = self.dense2(result)
result = self.dense2(result) # reuse variables from dense2 layer
return result
model = MNISTModel()
```
It's not required to set an input shape for the `tf.keras.Model` class since
the parameters are set the first time input is passed to the layer.
`tf.keras.layers` classes create and contain their own model variables that
are tied to the lifetime of their layer objects. To share layer variables, share
their objects.
## Eager training
### Computing gradients
[Automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation)
is useful for implementing machine learning algorithms such as
[backpropagation](https://en.wikipedia.org/wiki/Backpropagation) for training
neural networks. During eager execution, use `tf.GradientTape` to trace
operations for computing gradients later.
`tf.GradientTape` is an opt-in feature to provide maximal performance when
not tracing. Since different operations can occur during each call, all
forward-pass operations get recorded to a "tape". To compute the gradient, play
the tape backwards and then discard. A particular `tf.GradientTape` can only
compute one gradient; subsequent calls throw a runtime error.
```
w = tf.Variable([[1.0]])
with tf.GradientTape() as tape:
loss = w * w
grad = tape.gradient(loss, w)
print(grad) # => tf.Tensor([[ 2.]], shape=(1, 1), dtype=float32)
```
### Train a model
The following example creates a multi-layer model that classifies the standard
MNIST handwritten digits. It demonstrates the optimizer and layer APIs to build
trainable graphs in an eager execution environment.
```
# Fetch and format the mnist data
(mnist_images, mnist_labels), _ = tf.keras.datasets.mnist.load_data()
dataset = tf.data.Dataset.from_tensor_slices(
(tf.cast(mnist_images[...,tf.newaxis]/255, tf.float32),
tf.cast(mnist_labels,tf.int64)))
dataset = dataset.shuffle(1000).batch(32)
# Build the model
mnist_model = tf.keras.Sequential([
tf.keras.layers.Conv2D(16,[3,3], activation='relu'),
tf.keras.layers.Conv2D(16,[3,3], activation='relu'),
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(10)
])
```
Even without training, call the model and inspect the output in eager execution:
```
for images,labels in dataset.take(1):
print("Logits: ", mnist_model(images[0:1]).numpy())
```
While keras models have a builtin training loop (using the `fit` method), sometimes you need more customization. Here's an example, of a training loop implemented with eager:
```
optimizer = tf.train.AdamOptimizer()
loss_history = []
for (batch, (images, labels)) in enumerate(dataset.take(400)):
if batch % 10 == 0:
print('.', end='')
with tf.GradientTape() as tape:
logits = mnist_model(images, training=True)
loss_value = tf.losses.sparse_softmax_cross_entropy(labels, logits)
loss_history.append(loss_value.numpy())
grads = tape.gradient(loss_value, mnist_model.trainable_variables)
optimizer.apply_gradients(zip(grads, mnist_model.trainable_variables),
global_step=tf.train.get_or_create_global_step())
import matplotlib.pyplot as plt
plt.plot(loss_history)
plt.xlabel('Batch #')
plt.ylabel('Loss [entropy]')
```
### Variables and optimizers
`tf.Variable` objects store mutable `tf.Tensor` values accessed during
training to make automatic differentiation easier. The parameters of a model can
be encapsulated in classes as variables.
Better encapsulate model parameters by using `tf.Variable` with
`tf.GradientTape`. For example, the automatic differentiation example above
can be rewritten:
```
class Model(tf.keras.Model):
def __init__(self):
super(Model, self).__init__()
self.W = tf.Variable(5., name='weight')
self.B = tf.Variable(10., name='bias')
def call(self, inputs):
return inputs * self.W + self.B
# A toy dataset of points around 3 * x + 2
NUM_EXAMPLES = 2000
training_inputs = tf.random_normal([NUM_EXAMPLES])
noise = tf.random_normal([NUM_EXAMPLES])
training_outputs = training_inputs * 3 + 2 + noise
# The loss function to be optimized
def loss(model, inputs, targets):
error = model(inputs) - targets
return tf.reduce_mean(tf.square(error))
def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value = loss(model, inputs, targets)
return tape.gradient(loss_value, [model.W, model.B])
# Define:
# 1. A model.
# 2. Derivatives of a loss function with respect to model parameters.
# 3. A strategy for updating the variables based on the derivatives.
model = Model()
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
print("Initial loss: {:.3f}".format(loss(model, training_inputs, training_outputs)))
# Training loop
for i in range(300):
grads = grad(model, training_inputs, training_outputs)
optimizer.apply_gradients(zip(grads, [model.W, model.B]),
global_step=tf.train.get_or_create_global_step())
if i % 20 == 0:
print("Loss at step {:03d}: {:.3f}".format(i, loss(model, training_inputs, training_outputs)))
print("Final loss: {:.3f}".format(loss(model, training_inputs, training_outputs)))
print("W = {}, B = {}".format(model.W.numpy(), model.B.numpy()))
```
## Use objects for state during eager execution
With graph execution, program state (such as the variables) is stored in global
collections and their lifetime is managed by the `tf.Session` object. In
contrast, during eager execution the lifetime of state objects is determined by
the lifetime of their corresponding Python object.
### Variables are objects
During eager execution, variables persist until the last reference to the object
is removed, and is then deleted.
```
if tf.config.list_physical_devices('GPU'):
with tf.device("gpu:0"):
v = tf.Variable(tf.random_normal([1000, 1000]))
v = None # v no longer takes up GPU memory
```
### Object-based saving
`tf.train.Checkpoint` can save and restore `tf.Variable`s to and from
checkpoints:
```
x = tf.Variable(10.)
checkpoint = tf.train.Checkpoint(x=x)
x.assign(2.) # Assign a new value to the variables and save.
checkpoint_path = './ckpt/'
checkpoint.save('./ckpt/')
x.assign(11.) # Change the variable after saving.
# Restore values from the checkpoint
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_path))
print(x) # => 2.0
```
To save and load models, `tf.train.Checkpoint` stores the internal state of objects,
without requiring hidden variables. To record the state of a `model`,
an `optimizer`, and a global step, pass them to a `tf.train.Checkpoint`:
```
import os
import tempfile
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(16,[3,3], activation='relu'),
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(10)
])
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
checkpoint_dir = tempfile.mkdtemp()
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
root = tf.train.Checkpoint(optimizer=optimizer,
model=model,
optimizer_step=tf.train.get_or_create_global_step())
root.save(checkpoint_prefix)
root.restore(tf.train.latest_checkpoint(checkpoint_dir))
```
### Object-oriented metrics
`tf.metrics` are stored as objects. Update a metric by passing the new data to
the callable, and retrieve the result using the `tf.metrics.result` method,
for example:
```
m = tf.keras.metrics.Mean("loss")
m(0)
m(5)
m.result() # => 2.5
m([8, 9])
m.result() # => 5.5
```
#### Summaries and TensorBoard
[TensorBoard](https://tensorflow.org/tensorboard) is a visualization tool for
understanding, debugging and optimizing the model training process. It uses
summary events that are written while executing the program.
TensorFlow 1 summaries only work in eager mode, but can be run with the `compat.v2` module:
```
from tensorflow.compat.v2 import summary
global_step = tf.train.get_or_create_global_step()
logdir = "./tb/"
writer = summary.create_file_writer(logdir)
writer.set_as_default()
for _ in range(10):
global_step.assign_add(1)
# your model code goes here
summary.scalar('global_step', global_step, step=global_step)
!ls tb/
```
## Advanced automatic differentiation topics
### Dynamic models
`tf.GradientTape` can also be used in dynamic models. This example for a
[backtracking line search](https://wikipedia.org/wiki/Backtracking_line_search)
algorithm looks like normal NumPy code, except there are gradients and is
differentiable, despite the complex control flow:
```
def line_search_step(fn, init_x, rate=1.0):
with tf.GradientTape() as tape:
# Variables are automatically recorded, but manually watch a tensor
tape.watch(init_x)
value = fn(init_x)
grad = tape.gradient(value, init_x)
grad_norm = tf.reduce_sum(grad * grad)
init_value = value
while value > init_value - rate * grad_norm:
x = init_x - rate * grad
value = fn(x)
rate /= 2.0
return x, value
```
### Custom gradients
Custom gradients are an easy way to override gradients in eager and graph
execution. Within the forward function, define the gradient with respect to the
inputs, outputs, or intermediate results. For example, here's an easy way to clip
the norm of the gradients in the backward pass:
```
@tf.custom_gradient
def clip_gradient_by_norm(x, norm):
y = tf.identity(x)
def grad_fn(dresult):
return [tf.clip_by_norm(dresult, norm), None]
return y, grad_fn
```
Custom gradients are commonly used to provide a numerically stable gradient for a
sequence of operations:
```
def log1pexp(x):
return tf.log(1 + tf.exp(x))
class Grad(object):
def __init__(self, f):
self.f = f
def __call__(self, x):
x = tf.convert_to_tensor(x)
with tf.GradientTape() as tape:
tape.watch(x)
r = self.f(x)
g = tape.gradient(r, x)
return g
grad_log1pexp = Grad(log1pexp)
# The gradient computation works fine at x = 0.
grad_log1pexp(0.).numpy()
# However, x = 100 fails because of numerical instability.
grad_log1pexp(100.).numpy()
```
Here, the `log1pexp` function can be analytically simplified with a custom
gradient. The implementation below reuses the value for `tf.exp(x)` that is
computed during the forward pass—making it more efficient by eliminating
redundant calculations:
```
@tf.custom_gradient
def log1pexp(x):
e = tf.exp(x)
def grad(dy):
return dy * (1 - 1 / (1 + e))
return tf.log(1 + e), grad
grad_log1pexp = Grad(log1pexp)
# As before, the gradient computation works fine at x = 0.
grad_log1pexp(0.).numpy()
# And the gradient computation also works at x = 100.
grad_log1pexp(100.).numpy()
```
## Performance
Computation is automatically offloaded to GPUs during eager execution. If you
want control over where a computation runs you can enclose it in a
`tf.device('/gpu:0')` block (or the CPU equivalent):
```
import time
def measure(x, steps):
# TensorFlow initializes a GPU the first time it's used, exclude from timing.
tf.matmul(x, x)
start = time.time()
for i in range(steps):
x = tf.matmul(x, x)
# tf.matmul can return before completing the matrix multiplication
# (e.g., can return after enqueing the operation on a CUDA stream).
# The x.numpy() call below will ensure that all enqueued operations
# have completed (and will also copy the result to host memory,
# so we're including a little more than just the matmul operation
# time).
_ = x.numpy()
end = time.time()
return end - start
shape = (1000, 1000)
steps = 200
print("Time to multiply a {} matrix by itself {} times:".format(shape, steps))
# Run on CPU:
with tf.device("/cpu:0"):
print("CPU: {} secs".format(measure(tf.random_normal(shape), steps)))
# Run on GPU, if available:
if tf.config.list_physical_devices('GPU'):
with tf.device("/gpu:0"):
print("GPU: {} secs".format(measure(tf.random_normal(shape), steps)))
else:
print("GPU: not found")
```
A `tf.Tensor` object can be copied to a different device to execute its
operations:
```
if tf.config.list_physical_devices('GPU'):
x = tf.random_normal([10, 10])
x_gpu0 = x.gpu()
x_cpu = x.cpu()
_ = tf.matmul(x_cpu, x_cpu) # Runs on CPU
_ = tf.matmul(x_gpu0, x_gpu0) # Runs on GPU:0
```
### Benchmarks
For compute-heavy models, such as
[ResNet50](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/resnet50)
training on a GPU, eager execution performance is comparable to graph execution.
But this gap grows larger for models with less computation and there is work to
be done for optimizing hot code paths for models with lots of small operations.
## Work with graphs
While eager execution makes development and debugging more interactive,
TensorFlow graph execution has advantages for distributed training, performance
optimizations, and production deployment. However, writing graph code can feel
different than writing regular Python code and more difficult to debug.
For building and training graph-constructed models, the Python program first
builds a graph representing the computation, then invokes `Session.run` to send
the graph for execution on the C++-based runtime. This provides:
* Automatic differentiation using static autodiff.
* Simple deployment to a platform independent server.
* Graph-based optimizations (common subexpression elimination, constant-folding, etc.).
* Compilation and kernel fusion.
* Automatic distribution and replication (placing nodes on the distributed system).
Deploying code written for eager execution is more difficult: either generate a
graph from the model, or run the Python runtime and code directly on the server.
### Write compatible code
The same code written for eager execution will also build a graph during graph
execution. Do this by simply running the same code in a new Python session where
eager execution is not enabled.
Most TensorFlow operations work during eager execution, but there are some things
to keep in mind:
* Use `tf.data` for input processing instead of queues. It's faster and easier.
* Use object-oriented layer APIs—like `tf.keras.layers` and
`tf.keras.Model`—since they have explicit storage for variables.
* Most model code works the same during eager and graph execution, but there are
exceptions. (For example, dynamic models using Python control flow to change the
computation based on inputs.)
* Once eager execution is enabled with `tf.enable_eager_execution`, it
cannot be turned off. Start a new Python session to return to graph execution.
It's best to write code for both eager execution *and* graph execution. This
gives you eager's interactive experimentation and debuggability with the
distributed performance benefits of graph execution.
Write, debug, and iterate in eager execution, then import the model graph for
production deployment. Use `tf.train.Checkpoint` to save and restore model
variables, this allows movement between eager and graph execution environments.
See the examples in:
[tensorflow/contrib/eager/python/examples](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples).
### Use eager execution in a graph environment
Selectively enable eager execution in a TensorFlow graph environment using
`tfe.py_func`. This is used when `` has *not*
been called.
```
def my_py_func(x):
x = tf.matmul(x, x) # You can use tf ops
print(x) # but it's eager!
return x
with tf.Session() as sess:
x = tf.placeholder(dtype=tf.float32)
# Call eager function in graph!
pf = tf.py_func(my_py_func, [x], tf.float32)
sess.run(pf, feed_dict={x: [[2.0]]}) # [[4.0]]
```
| github_jupyter |
<img style="float: right;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOIAAAAjCAYAAACJpNbGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABR0RVh0Q3JlYXRpb24gVGltZQAzLzcvMTNND4u/AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAACMFJREFUeJztnD1y20gWgD+6nJtzAsPhRqKL3AwqwQdYDpXDZfoEppNNTaWbmD7BUEXmI3EPMFCR2YI1UDQpdAPqBNzgvRZA/BGUZEnk9FeFIgj0z2ugX7/XP+jGer2mLv/8b6d+4Efgf/8KG0+Zn8XyXLx+bgEslqegcfzxSY3Irrx6bgEsFssBWsRGowGufwHAYtq7u+H6fUCOxTTWax4wBAbr+SRqNDKesOv3gN/133sW0yh927j1mucIaFWINl7PJ+OcvMcfW8Bol3iN44+mLIOsTCp3UJFfAETr+WRQcG8EOJpunEnTyDlYzycbeWr5xxq3jOF6PglK8ix9buv5xCsrAzBkMV1l5OwD/aJ4BXzV3+8F9z4gz/hTSbz8cxc84FuNvDc4VIsYA7+qohmGwAnycA194G22YqUYlZxv4vpN4AuwBv4oON5m8k3TVLnK4sYFcRyN86dWvCwnlCvFCeUVvwX8CkSZZ5eWs5mLJWE/VZThBMgpfirPk5J4f1SU4QsQ6LNP4+j9OkSUKdRiGlD87CWe3PcyR5PFdAhc1cz/joOziMoIeVF95GX1EGVY6bWhvsAeZQrm+kON80PDneD6PRbTi4LQpmJfsZieFaR1qXlXURh3y2BaBPyG63sspv0t6e+CKJTrf2YxHe8Qr6z8AXBdGbMoHgCTshgr4AiItfxljenPJGv5roCi+rGVw1TExTTWl99ThRsglfYHUnF7SMv+Bhjn4idxbhFLGiAu6gjXD3LuUBF5VzWi3CoAfMP1kxe7mNYZMT5DLFgf13eAXi3ZtvMOsUb3V3J5/mmqy+/66RbnTC1LFdfIu/kd8Qx2bTQeg2GBTPfiUF1TgHNE0QaIq/JDX9RKr/WBy/V8EhfEHWncWMO2EKV8S7UypYnYdE2r+o8gyj5MHXVYsZh+JnG7A+3LPQxR5g9II/UJ148ockmrybqm2+Qapo6gppwB8J7EM6jqaz8u0lhfkXgB58BKPam6rvEdh2kRARbTMa7/HXEfVqnW8hxxWwE+5+JJRTYd9CM90gxw/XFuMKMo/yTNDzUkLnbr6rCYnuH6N8igQ3CvNPJproDPuH6MKMd4Z5kMUjnrh98tn1if72/Ie729Vzq708L0YV3/HGmgB4iHsjOProhhd1lrEr4zaz/FvM4lolTnqWum/6jKmeuDmFb1jHylNg96hPQbhcU0wPVBXESvQI4W5aNshsK4jeOPhSOcOaThMVb48dhU8m2UlR+29ZHzrqyhLL0EaTROteGt67EYIsT6F1HXC/ikcvS00dl51PRwLaIwQtzCxGWRFnRMkT8v/SyAy8I+iliHJtDUsHHq7imipE42GtJanxdcB6mgQcm9MmKNs1m5F9MI13+n+cXZSEpAeV8mQgZqNkmU/HsuT7kf4PrGhXcK0h1SXv7iPKsJKCrDYvoV17+meMqhiDFlll7GEb4U3iseAf+k7mqksmU9qUoaj73E7TEtol3iZnks7Moai8WylUN3TS0WANbzyYv2rqxFtFheANYi7iGNRoPOrO2QGTQIu8vhU8vSmbWNDAHQD7vLYWfWbgFx2F3ee3FBZ9ZuIgMpTWAQdpeRXm9pPoPOrD3UMCtkQM4BRmF3ubG6ZZdxkOfCWsT9pU96CuX56KfOjeIFVC8Ar8NI0xuyOQJsVkWl8xzptQGPNY/6xFiLuL+0gIu0FVTrNESmbK7C7tLrzNpmPW0EeGF32UyFN19UnCAT4ZHGWWnYqDNrB4jViZBK/kbD9sLuMiBZSD8AVp1Z+0LD/NmZta+BIzOS3pm1xwBhd9kvkeEGUbQeqSmIdHhkXnGs5fIQRUxPV1x0Zm2zMuoq7C69rU/yBWAt4v7iAd86s/ZaDweZP+wBvwBOZ9b2SCrrmPzk+AWizA09j1QxMK4gZumcWKUWMvkdA56mfxN2l7GmHWk6V2F32Qi7yxaIsmnYHvkJ9zEQqAwBotQXwK2m0c+EN/Kk8zPTZiOkIWrp/xNTnpeOtYh7iFauN+k5W+0vXab6UsbyecAw229SxWiG3aVZ7NBCKrGHuneazy2iyBeIuxkjk9UDE1bzOtJ4IzbdwysNN0D6dnf9Rk3/iKSBWOnhUbASSWW+DbvLWM+HKreZ3O/r77gza5u842w6LxFrEfcTj+Jv3mK4q7Co63hE+fI6E94hUaT0cry+XushSuvoNZO2CdsCrlXJHDYVMUIUJso2BmhfL+wuV6rMvVR6AXnS1428XupaE7Hwnrqkg4cMGD0lr3NfpVegrUw1m2sN0+crNirEX1uTqiPbPoyI/QSKKmqA9I9aer+fcR2zxIj7GiMV+EYVIkZc3r5eH2rYI+0vnpBYIE/vGwUCdYM7s3agbqXJu58VIOwug86sfd2ZtSPNKwi7S9PHy4UnscCmXKuUZQRdsqbPwCHp2754pKYnW0akcZBO/x2df29XnvA//6iV8T3TSluBmOQlR+v5JNvaHixlDZRalRZifbZaAg3vIIrkmP6YVu6owI1M9x2r0vVIFCBGXNLS96Ph45IGY2ey6e1DY20UMaLGItUXoIhVvCv5tvDg2MWLqYNaoKBKWe6Z7gBR8OwAzZOyD4poBmtidlwt/gIxw/QHz0+oWKIoj19fRz8p3YOjoV8195F5l31ltZ5PfnluISyW+/IK6SPstRIiH/FaLHvLa2R+6F6f978AVsD7v0vf0HK4vNK9VfbVojSBceP4o/PcglgsD8GMmjaRbRCc1PEQIrbv45nlIfleIrs778XkrcWSZXMcXPZyqbvfxy7ckuyqHJPslJzH9c3We2ZRbx1O/07ziJbDI1FE2Qwp4n4DNzHJhkZF16+3bnwrCmi40U2eWoj7KZvobn7+YtKO1vPJVyyWPSZrER1kNU0TqfienpvlaWZR7oX+3tba6lxcX7MK3tNfo2RlpNc8tthsIFbAKYtpsA+TtRbLNp5/H4/EFXX0MOfbOGUxvbCKaDkEnl8Rq0jc1ayFjhFFjKwiWg6B/wNk+JCXXNBIXQAAAABJRU5ErkJggg==">
# Getting Started with PCSE/WOFOST
This Jupyter notebook will introduce PCSE and explain the basics of running models with PCSE, taking WOFOST as an example.
Allard de Wit, March 2018
**Prerequisites for running this notebook**
Several packages need to be installed for running PCSE/WOFOST:
1. `PCSE` and its dependencies. See the [PCSE user guide](http://pcse.readthedocs.io/en/stable/installing.html) for more information;
2. `pandas` for processing and storing WOFOST output;
3. `matplotlib` for generating charts
## Importing the relevant modules
```
%matplotlib inline
import sys, os
import pcse
import pandas
import matplotlib
matplotlib.style.use("ggplot")
import matplotlib.pyplot as plt
print("This notebook was built with:")
print("python version: %s " % sys.version)
print("PCSE version: %s" % pcse.__version__)
```
## Starting from the internal demo database
For demonstration purposes, we can start WOFOST with a single function call. This function reads all relevant data from the internal demo databases. In the next notebook we will demonstrate how to read data from external sources.
The command below starts WOFOST in potential production mode for winter-wheat for a location in Southern Spain.
```
wofostPP = pcse.start_wofost(mode="pp")
```
You have just successfully initialized a PCSE/WOFOST object in the Python interpreter, which is in its initial state and waiting to do some simulation. We can now advance the model state for example with 1 day:
```
wofostPP.run()
```
Advancing the crop simulation with only 1 day, is often not so useful so the number of days to simulate can be specified as well:
```
wofostPP.run(days=10)
```
## Getting information about state and rate variables
Retrieving information about the calculated model states or rates can be done with the `get_variable()` method on a PCSE object. For example, to retrieve the leaf area index value in the current model state you can do:
```
wofostPP.get_variable("LAI")
wofostPP.run(days=50)
wofostPP.get_variable("LAI")
wofostPP.set_variable("LAI", 4.0)
```
Showing that after 11 days the LAI value is 0.287. When we increase time with another 25 days, the LAI increases to 1.528. The get_variable method can retrieve any state or rate variable that is defined somewhere in the model.
Finally, we can finish the crop season by letting it run until the model terminates because the crop reaches maturity or the harvest date:
```
wofostPP.run_till_terminate()
```
## Retrieving and displaying WOFOST output
We can retrieve the results of the simulation at each time step using `get_output()`. In python terms this returns a list of dictionaries, one dictionary for each time step of the the simulation results. Each dictionary contains the key:value pairs of the state or rate variables that were stored at that time step.
```
output = wofostPP.get_output()
```
The most convenient way to handle the output from WOFOST is to used the `pandas` module to convert it into a dataframe. Pandas DataFrames can be converted to a variety of formats including excel, CSV or database tables.
```
dfPP = pandas.DataFrame(output).set_index("day")
dfPP.head()
```
Besides the output at each time step, WOFOST also provides summary output which summarizes the crop cycle and provides you the total crop biomass, total yield, maximum LAI and other variables. In case of crop rotations, the summary output will consist of several sets of variables, one for each crop cycle.
```
summary_output = wofostPP.get_summary_output()
msg = "Reached maturity at {DOM} with total biomass {TAGP:.1f} kg/ha, " \
"a yield of {TWSO:.1f} kg/ha with a maximum LAI of {LAIMAX:.2f}."
for crop_cycle in summary_output:
print(msg.format(**crop_cycle))
```
## Visualizing output
The pandas module is also very useful for generating charts from simulation results. In this case we generate graphs of leaf area index and crop biomass including total biomass and grain yield.
```
fig, (axis1, axis2) = plt.subplots(nrows=1, ncols=2, figsize=(16,8))
dfPP.LAI.plot(ax=axis1, label="LAI")
dfPP.TAGP.plot(ax=axis2, label="Total biomass")
dfPP.TWSO.plot(ax=axis2, label="Yield")
axis1.set_title("Leaf Area Index")
axis2.set_title("Crop biomass")
fig.autofmt_xdate()
```
| github_jupyter |
# Week 10 - Programming Paradigms
## Learning Objectives
* List popular programming paradigms
* Demonstrate object oriented programming
* Compare procedural programming and object oriented programming
* Apply object oriented programming to solve sample problems
Computer programs and the elements they contain can be built in a variety of different ways. Several different styles, or paradigms, exist with differing popularity and usefulness for different tasks.
Some programming languages are designed to support a particular paradigm, while other languages support several different paradigms.
Three of the most commonly used paradigms are:
* Procedural
* Object oriented
* Functional
Python supports each of these paradigms.
## Procedural
You may not have realized it but the procedural programming paradigm is probably the approach you are currently taking with your programs.
Programs and functions are simply a series of steps to be performed.
For example:
```
primes = []
i = 2
while len(primes) < 25:
for p in primes:
if i % p == 0:
break
else:
primes.append(i)
i += 1
print(primes)
```
## Functional
Functional programming is based on the evaluation of mathematical functions. This is a more restricted form of function than you may have used previously - mutable data and changing state is avoided. This makes understanding how a program will behave more straightforward.
Python does support functional programming although it is not as widely used as procedural and object oriented programming. Some languages better known for supporting functional programming include Lisp, Clojure, Erlang, and Haskell.
### Functions - Mathematical vs subroutines
In the general sense, functions can be thought of as simply wrappers around blocks of code. In this sense they can also be thought of as subroutines. Importantly they can be written to fetch data and change the program state independently of the function arguments.
In functional programming the output of a function should depend solely on the function arguments.
There is an extensive howto in the [python documentation](https://docs.python.org/3.5/howto/functional.html).
[This presentation from PyCon US 2013](https://www.youtube.com/watch?v=Ta1bAMOMFOI) is also worth watching.
[This presentation from PyGotham 2014](https://www.youtube.com/watch?v=yW0cK3IxlHc) covers decorators specifically.
### List and generator comprehensions
```
def square(val):
print(val)
return val ** 2
squared_numbers = [square(i) for i in range(5)]
print('Squared from list:')
print(squared_numbers)
squared_numbers = (square(i) for i in range(5))
print('Squared from iterable:')
print(squared_numbers)
```
### Generators
```
def squared_numbers(num):
for i in range(num):
yield i ** 2
print('This is only printed after all the numbers output have been consumed')
print(squared_numbers(5))
for i in squared_numbers(5):
print(i)
import functools
def plus(val, n):
return val + n
f = functools.partial(plus, 5)
f(5)
```
### Decorators
```
def decorator(inner):
def inner_decorator():
print('before')
inner()
print('after')
return inner_decorator
def decorated():
print('decorated')
f = decorator(decorated)
f()
@decorator
def decorated():
print('decorated')
decorated()
import time
@functools.lru_cache()
def slow_compute(n):
time.sleep(1)
print(n)
start = time.time()
slow_compute(1)
print('First time function runs with these arguments takes ', time.time() - start)
start = time.time()
slow_compute(1)
print('Second time function runs with these arguments takes ', time.time() - start)
start = time.time()
slow_compute(2)
print('Changing the arguments causes slow_compute to be run again and takes ', time.time() - start)
```
## Object oriented
Object oriented programming is a paradigm that combines data with code into objects. The code can interact with and modify the data in an object. A program will be separated out into a number of different objects that interact with each other.
Object oriented programming is a widely used paradigm and a variety of different languages support it including Python, C++, Java, PHP, Ruby, and many others.
Each of these languages use slightly different syntax but the underlying design choices will be the same in each language.
Objects __are__ things, their names often recognise this and are nouns. These might be physical things like a chair, or concepts like a number.
While procedural programs make use of global information, object oriented design forgoes this global knowledge in favor of local knowledge. Objects contain information and can __do__ things. The information they contain are in attributes. The things they can do are in their methods (similar to functions, but attached to the object).
Finally, to achieve the objective of the program objects must interact.
We will look at the python syntax for creating objects later, first let's explore how objects might work in various scenarios.
## Designing Object Oriented Programs
These are the simple building blocks for classes and objects. Just as with the other programming constructs available in python, although the language is relatively simple if used effectively they are very powerful.
[Learn Python the Hard Way](http://learnpythonthehardway.org/book/ex43.html) has a very good description of how to design a program using the object oriented programming paradigm. The linked exercise particularly is worth reading.
The best place to start is describing the problem. What are you trying to do? What are the items involved?
### Example 1: A Laboratory Inventory
I would like to keep track of all the __items__ in the __laboratory__ so I can easily find them the next time I need them. Both __equipment__ and __consumables__ would be tracked. We have multiple __rooms__, and items can be on __shelves__, in __refrigerators__, in __freezers__, etc. Items can also be in __boxes__ containing other items in all these places.
The words in __bold__ would all be good ideas to turn into classes. Now we know some of the classes we will need we can start to think about what each of these classes should do, what the methods will be. Let's consider the consumables class:
For consumables we will need to manage their use so there should be an initial quantity and a quantity remaining that is updated every time we use some. We want to make sure that temperature sensitive consumables are always stored at the correct temperature, and that flammables are stored in a flammables cabinet etc.
The consumable class will need a number of attributes:
* Initial quantity
* Current quantity
* Storage temperature
* Flammability
The consumable class will need methods to:
* Update the quantity remaining
* Check for improper storage?
The consumable class might interact with the shelf, refrigerator, freezer, and/or box classes.
Reading back through our description of consumables there is reference to a flammables cabinet that was not mentioned in our initial description of the problem. This is an iterative design process so we should go back and add a flammables cabinet class.
### Exercise: A Chart
We have used matplotlib several times now to generate charts. If we were to create a charting library ourselves what are the objects we would use?
I would like to plot some data on a chart. The data, as a series of points and lines, would be placed on a set of x-y axes that are numbered and labeled to accurately describe the data. There should be a grid so that values can be easily read from the chart.
What are the classes you would use to create this plot?
Pick one class and describe the methods it would have, and the other classes it might interact with.
### Exercise 2: A Cookbook
A system to manage different recipes, with their ingredients, equipment needed and instructions. Recipes should be scalable to different numbers of servings with the amount of ingredients adjusted appropriately and viewable in metric and imperial units. Nutritional information should be tracked.
What are the classes you would use to create this system?
Pick one class and describe the methods it would have, and the other classes it might interact with.
[Building Skills in Object Oriented Design](http://www.itmaybeahack.com/homepage/books/oodesign.html) is a good resource to learn more about this process.
## Syntax
Now let's look at the syntax we use to work with objects in python.
There is a tutorial in the [python documentation](https://docs.python.org/3.5/tutorial/classes.html).
Before we use an object in our program we must first define it. Just as we define a function with the *def* keyword, we use *class* to define a class. What is a class? Think of it as the template, or blueprint from which our objects will be made.
Remember that in addition to code, objects can also contain data that can change so we may have many different instances of an object. Although each may contain different data they are all formed from the same class definition.
As an example:
```
class Person(object):
"""A class definition for a person. The following attributes are supported:
Attributes:
name: A string representing the person's name.
age: An integer representing the person's age."""
mammal = True
def __init__(self, name, age):
"""Return a Person object with name and age set to the values supplied"""
self.name = name
self.age = age
person1 = Person('Alice', 25)
person2 = Person('Bob', 30)
print(person1, person2)
```
There is a lot happening above.
__class Person(object):__ The *class* keyword begins the definition of our class. Here, we are naming the class *Person*. Next, *(object)* means that this class will inherit from the object class. This is not strictly necessary but is generally good practice. Inheritance will be discussed in greater depth next week. Finally, just as for a function definition we finish with a *colon*.
__"""Documentation"""__ Next, a docstring provides important notes on usage.
__mammal = True__ This is a class attribute. This is useful for defining data that our objects will need that is the same for all instances.
**def __init__(self, name, age):** This is a method definition. The *def* keyword is used just as for functions. The first parameter here is *self* which refers to the object this method will be part of. The double underscores around the method name signify that this is a special method. In this case the \_\_init\_\_ method is called when the object is first instantiated.
__self.name = name__ A common reason to define an \_\_init\_\_ method is to set instance attributes. In this class, name and age are set to the values supplied.
That is all there is to this class definition. Next, we create two instances of this class. The values supplied will be passed to the \_\_init\_\_ method.
Printing these objects don't provide a useful description of what they are. We can improve on this with another special method.
```
class Person(object):
"""A class definition for a person. The following attributes are supported:
Attributes:
name: A string representing the person's name.
age: An integer representing the person's age."""
mammal = True
def __init__(self, name, age):
"""Return a Person object with name and age set to the values supplied"""
self.name = name
self.age = age
def __str__(self):
return '{0} who is {1} years old.'.format(self.name, self.age)
person1 = Person('Alice', 25)
person2 = Person('Bob', 30)
print(person1, person2)
```
[There are many more special methods](https://docs.python.org/3.5/reference/datamodel.html#special-method-names).
Before we go on a note of caution is needed for class attributes. Do you remember the strange fibonacci sequence function from our first class?
```
def next_fibonacci(status=[]):
if len(status) < 2:
status.append(1)
return 1
status.append(status[-2] + status[-1])
return status[-1]
print(next_fibonacci(), next_fibonacci(), next_fibonacci(), next_fibonacci(), next_fibonacci(), next_fibonacci())
```
The same issue can happen with classes, only this is a much more common source of bugs.
If only using strings and numbers the behaviour will likely be much as you expect. However, if using a list, dictionary, or other similar type you may get a surprise.
```
class Person(object):
"""A class definition for a person. The following attributes are supported:
Attributes:
name: A string representing the person's name.
age: An integer representing the person's age."""
friends = []
def __init__(self, name, age):
"""Return a Person object with name and age set to the values supplied"""
self.name = name
self.age = age
def __str__(self):
return '{0} who is {1} years old'.format(self.name, self.age)
person1 = Person('Alice', 25)
person2 = Person('Bob', 30)
person1.friends.append('Charlie')
person2.friends.append('Danielle')
print(person1.friends, person2.friends)
```
Both of our objects point to the same instance of the list type so adding a new friend to either object shows up in both.
The solution to this is creating our *friends* attribute only at instantiation of the object. This can be done by creating it in the \_\_init\_\_ method.
```
class Person(object):
"""A class definition for a person. The following attributes are supported:
Attributes:
name: A string representing the person's name.
age: An integer representing the person's age."""
def __init__(self, name, age):
"""Return a Person object with name and age set to the values supplied"""
self.name = name
self.age = age
self.friends = []
def __str__(self):
return '{0} who is {1} years old'.format(self.name, self.age)
person1 = Person('Alice', 25)
person2 = Person('Bob', 30)
person1.friends.append('Charlie')
person2.friends.append('Danielle')
print(person1.friends, person2.friends)
```
Objects have their own namespace, although we have created variables called name, age, and friends they can only be accessed in the context of the object.
```
print('This works:', person1.friends)
print('This does not work:', friends)
```
We are not limited to special methods when creating classes. Standard functions, or in this context methods, are an integral part of object oriented programming. Their definition is identical to special methods and functions outside of classes.
```
class Person(object):
"""A class definition for a person. The following attributes are supported:
Attributes:
name: A string representing the person's name.
age: An integer representing the person's age."""
def __init__(self, name, age):
"""Return a Person object with name and age set to the values supplied"""
self.name = name
self.age = age
self.friends = []
def __str__(self):
"""Return a string representation of the object"""
return '{0} who is {1} years old'.format(self.name, self.age)
def add_friend(self, friend):
"""Add a friend"""
self.friends.append(friend)
person1 = Person('Alice', 25)
person2 = Person('Bob', 30)
person1.add_friend('Charlie')
person2.add_friend('Danielle')
print(person1.friends, person2.friends)
```
### Private vs Public
Some programming languages support hiding methods and attributes in an object. This can be useful to simplify the public interface someone using the class will see while still breaking up components into manageable blocks 'under-the-hood'. We will discuss designing the public interface in detail in future classes.
Python does not support private variables beyond convention. Names prefixed with a underscore are assumed to be private. This means they may be changed without warning between different versions of the package. For public attributes/methods this is highly discouraged.
### Glossary
__Class__: Our definition, or template, for an object.
__Object__: An instance of a class.
__Method__: A function that belongs to an object
__Attribute__: A characteristic of an object, these can be data attributes and methods.
# Assignments
1. Send in your final project ideas / contact me for suggestions if you don't have an idea. Email would be better for this than okpy. You don't need a polished idea, the intention is to start a conversation at this stage.
2. Considering exercise 2, list out the main classes. Pick two and list out the attributes and methods they will need. Treat this as a first, very rough, pass just as we did during class.
3. For one of the classes convert your list of attributes and methods to actual code. Provide a very short description of each method as a docstring.
**Assignment 1 should be emailed, and assignments 2 and 3 submitted through okpy.**
### Exercise 2: A Cookbook
A system to manage different recipes, with their ingredients, equipment needed and instructions. Recipes should be scalable to different numbers of servings with the amount of ingredients adjusted appropriately and viewable in metric and imperial units. Nutritional information should be tracked.
What are the classes you would use to create this system?
Pick one class and describe the methods it would have, and the other classes it might interact with.
| github_jupyter |
# Navigation
---
Congratulations for completing the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893)! In this notebook, you will learn how to control an agent in a more challenging environment, where it can learn directly from raw pixels! **Note that this exercise is optional!**
### 1. Start the Environment
We begin by importing some necessary packages. If the code cell below returns an error, please revisit the project instructions to double-check that you have installed [Unity ML-Agents](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md) and [NumPy](http://www.numpy.org/).
```
from unityagents import UnityEnvironment
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.
- **Mac**: `"path/to/VisualBanana.app"`
- **Windows** (x86): `"path/to/VisualBanana_Windows_x86/Banana.exe"`
- **Windows** (x86_64): `"path/to/VisualBanana_Windows_x86_64/Banana.exe"`
- **Linux** (x86): `"path/to/VisualBanana_Linux/Banana.x86"`
- **Linux** (x86_64): `"path/to/VisualBanana_Linux/Banana.x86_64"`
- **Linux** (x86, headless): `"path/to/VisualBanana_Linux_NoVis/Banana.x86"`
- **Linux** (x86_64, headless): `"path/to/VisualBanana_Linux_NoVis/Banana.x86_64"`
For instance, if you are using a Mac, then you downloaded `VisualBanana.app`. If this file is in the same folder as the notebook, then the line below should appear as follows:
```
env = UnityEnvironment(file_name="VisualBanana.app")
```
```
#env = UnityEnvironment(file_name="VisualBanana_Linux/Banana.x86_64")
env = UnityEnvironment(file_name="VisualBanana_Windows_x86_64/Banana.exe")
```
Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.
```
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
```
### 2. Examine the State and Action Spaces
The simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal:
- `0` - walk forward
- `1` - walk backward
- `2` - turn left
- `3` - turn right
The environment state is an array of raw pixels with shape `(1, 84, 84, 3)`. *Note that this code differs from the notebook for the project, where we are grabbing **`visual_observations`** (the raw pixels) instead of **`vector_observations`**.* A reward of `+1` is provided for collecting a yellow banana, and a reward of `-1` is provided for collecting a blue banana.
Run the code cell below to print some information about the environment.
```
from PIL import Image, ImageEnhance
def crop(state):
return state[:,42:,:,:]
def enhance_contrast(image_array):
image = Image.fromarray(np.squeeze(np.uint8(image_array * 255)))
image = ImageEnhance.Brightness(image).enhance(1.5)
image = ImageEnhance.Contrast(image).enhance(2.)
image_array = np.expand_dims(np.array(image) / 255, axis=0)
return image_array
def convert_rgb_to_grayscale(image):
return np.expand_dims(np.dot(image[...,:3], [0.2989, 0.5870, 0.1140]), axis=3)
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.visual_observations[0]
print('States look like:')
plt.imshow(np.squeeze(state))
#plt.show()
state_size = crop(state).shape
print('States have shape:', state.shape)
# crop
print('Cropped state look like:')
cropped_state = crop(state)
print('States have shape:', cropped_state.shape)
plt.imshow(np.squeeze(cropped_state))
plt.show()
# convert to grayscale
print('Grayscale state look like:')
grayscale_image = convert_rgb_to_grayscale(enhance_contrast(cropped_state))
plt.imshow(np.squeeze(grayscale_image), cmap='gray')
plt.show()
```
### 3. Implement an Agent
I extended `dqn_agent.py` by a parameter called `use_cnn`. If this parameter is set to `True` then the agent uses the neural network architecture with convolutional layers in `cnn_model.py` to map visual states to action values.
### 4. Train the Agent
```
from IPython.display import clear_output
from matplotlib import pyplot as plt
%matplotlib notebook
def init_plot():
fig,ax = plt.subplots(1,1)
ax.grid(True)
ax.set_xlabel('Episode #')
return fig, ax
def live_plot(fig, ax, data_dict, figsize=(7,5), title=''):
if ax.lines:
for line in ax.lines:
line.set_xdata(list(range(len(data_dict[line.get_label()]))))
line.set_ydata(data_dict[line.get_label()])
ax.set_xlim(0, len(data_dict[line.get_label()]))
else:
for label,data in data_dict.items():
line, = ax.plot(data)
line.set_label(label)
ax.legend()
ax.set_ylim(-5, 20)
fig.canvas.draw()
def preprocess(state):
return convert_rgb_to_grayscale(enhance_contrast(crop(state)))
import time
import torch
from collections import defaultdict, deque
from dqn_agent import Agent
def remove_actions_move_backward_and_turn_right(action):
# remove action 1 "walk backward" from actions
if action > 0:
# walk forward: action 0 --> 0
# turn left: action 1 --> 2
# turn right: action 2 --> 3
action += 1
return action
def train(agent, n_episodes=1400, eps_start=1.0, eps_end=0.01, eps_decay=0.995, episodes_per_print=100):
"""
Params
======
n_episodes (int): maximum number of training episodes
eps_start (float): starting value of epsilon, for epsilon-greedy action selection
eps_end (float): minimum value of epsilon
eps_decay (float): multiplicative factor (per episode) for decreasing epsilon
"""
scores = defaultdict(list) # list containing scores from each episode and average scores
scores_window = deque(maxlen=100) # last 100 scores
eps = eps_start # initialize epsilon
fig,ax = init_plot()
for i_episode in range(1, n_episodes+1):
episode_start = time.time()
# reset environment and score
env_info = env.reset(train_mode=True)[brain_name]
state = preprocess(env_info.visual_observations[0])
score = 0
# run for 1 episode
while True:
action = agent.act(state, eps)
env_info = env.step(remove_actions_move_backward_and_turn_right(action).astype(int))[brain_name]
next_state = preprocess(env_info.visual_observations[0])
reward = env_info.rewards[0]
done = env_info.local_done[0]
agent.step(state, action, reward, next_state - state, done)
# update score and state
score += reward
state = next_state
if done:
break
# save score
scores_window.append(score)
scores["score"].append(score)
scores["average score"].append(np.mean(scores_window))
# decrease epsilon
eps = max(eps_end, eps_decay*eps)
# print current performance
live_plot(fig, ax, scores)
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
if i_episode % episodes_per_print == 0:
print('\rEpisode {}\tAverage Score: {:.2f} \tDuration: {:.6f} Min'.format(i_episode,
np.mean(scores_window),
(time.time() - episode_start) / 60. * episodes_per_print
))
torch.save(agent.qnetwork_local.state_dict(), 'pixels_checkpoint.pth')
return scores
# remove action 1 "walk backward" and action 3 "turn right" from actions
action_size -= 1
agent = Agent(np.prod(state_size), action_size, seed=0, buffer_size=10000, batch_size=16, lr=0.0003,
scheduler_step_size=3000, scheduler_gamma=0.9, use_cnn=True)
scores = train(agent, eps_start=1.0, eps_end=0.1, eps_decay=0.999)
import torch
from dqn_agent import Agent
agent = Agent(state_size, action_size, seed=0, use_cnn=True)
# load the weights from file
agent.qnetwork_local.load_state_dict(torch.load('pixels_checkpoint.pth'))
# reset environment and score
env_info = env.reset(train_mode=False)[brain_name]
state = preprocess(env_info.visual_observations[0])
score = 0
# run for one episode
while True:
action = agent.act(state, eps=0.)
env_info = env.step(remove_actions_move_backward_and_turn_right(action.astype(int)))[brain_name]
next_state = preprocess(env_info.visual_observations[0])
reward = env_info.rewards[0]
done = env_info.local_done[0]
score += reward
state = next_state
if done:
break
print("Score: {}".format(score))
#env.close()
```
| github_jupyter |
# Lesson 4: Sorting, Aggregation, and Subsets
# Initial Setup
Import libraries and initialize variables to pick up where we left off in Lesson 3.
```
import pandas as pd
%matplotlib inline
weather_all = pd.read_csv('data/weather_airport_stations.csv')
```
# Sorting
- It's often convenient to have our data in a sorted form
- We can also use sorting to answer questions about the extreme (highest / lowest) values in our data
We can sort an entire DataFrame based on the values in a column using the `sort_values` method:
```
weather_sorted = weather_all.sort_values('Temperature (C)')
weather_sorted.head()
```
- The above code does not modify our original DataFrame `weather_all`
- Looking at `weather_sorted`, we can answer questions like:
- What station(s) and datetimes had the coldest temperatures?
- What were the weather conditions and other measurements (relative humidity, pressure, etc.) during these coldest temperatures?
- `sort_values` sorts in ascending order (lowest to highest) by default
- We can switch this using the `ascending` keyword argument:
```
column = 'Temperature (C)'
weather_all.sort_values(column, ascending=False).head()
```
# Aggregation
- So far we have looked at statistics for entire columns of a DataFrame
- With aggregation, we can answer questions about sub-groups within columns, such as:
- What are the mean, minimum, and maximum temperatures at each station in `weather_all`?
We can aggregate data with the `groupby` method chained with an aggregation method (e.g., `mean`, `sum`, `max`, `min`, `count`)
- For example, find the mean values for each station:
```
station_means = weather_all.groupby('Station Name').mean()
station_means
```
For more complex aggregations, there is a `pivot_table` method.
Create a bar chart of the mean temperature at each station:
```
temp_means = station_means['Temperature (C)']
temp_means
temp_means.plot(kind='bar', color='0.5', figsize=(12, 5));
```
We can use the `sort_values` method on the `temp_means` Series to find out which station had the highest mean temperature:
```
temp_means.sort_values(ascending=False)
```
# Data Subsets
- So far we've been working with entire DataFrames and individual columns
- We can also extract other subsets of a DataFrame:
- Multiple columns
- Select rows based on row numbers or row labels
- Select rows based on a criteria
## Selecting columns of a DataFrame
```
weather_all.head()
```
Get a subset of the DataFrame with only the columns `'Station Name'`, `'Wind Speed (km/hr)'` and `'Temperature (C)'`, in that order:
```
columns = ['Station Name', 'Wind Speed (km/hr)', 'Temperature (C)']
winds_temp = weather_all[columns]
winds_temp.head()
```
With a subset such as `winds_temp`, we can display summaries for just the columns we're interested in. For example, aggregate to find the maximum wind speed and temperature at each station:
```
winds_temp.groupby('Station Name').max()
```
## Selecting rows of a DataFrame
- Selecting rows based on position or row label is actually a fairly complex topic, which we won't cover today
- Let's look at how to select rows based on a criteria
- Similar to applying a filter in Excel
Where is it snowing?
- Use the string method `contains` on the `'Conditions'` column
```
snowing = weather_all['Conditions'].str.contains('Snow')
print(len(snowing))
snowing.head()
```
- `snowing` is a Boolean Series of length equal to the number of rows of `weather_all`
- The index of `snowing` is equal to the index of `weather_all`
- We can sum the Series to find out how many rows with snowing conditions are in our data:
```
num_snowing = snowing.sum()
num_snowing
```
Alternatively, we could also use `value_counts` to tally up the snowing conditions:
```
snowing.value_counts(dropna=False)
```
We can use `snowing` as a **filter** to extract the rows with snowing weather conditions
- However, our filter can only contain `True` or `False` values
- We need to fill the missing value (`NaN`)
- Use the `fillna` method to fill the missing with a value of `False`
```
snowing_filled = snowing.fillna(False)
snowing_filled.value_counts(dropna=False)
```
Now we're ready to apply our filter and find out where it's snowing:
```
weather_snowing = weather_all[snowing_filled]
weather_snowing
weather_snowing['Station Name'].unique()
```
It's snowing at one station—Iqaluit Airport!
- How many stations have temperatures greater than 20 C?
- Which station had the highest number of hours with temperatures greater than 20 C?
Use a comparison operator to create a filter:
```
temp_warm = weather_all['Temperature (C)'] > 20
temp_warm.head()
```
See how many `True` and `False` are in our filter, and check for missings:
```
temp_warm.value_counts(dropna=False)
```
Temperatures are greater than 20 C in 107 rows of our data, but this doesn't tell us the number of stations, since each station might have multiple rows (multiple hours) with temperatures greater than 20 C.
Use the filter `temp_warm` to extract the rows of `weather_all` which have temperatures greater than 20 C:
```
weather_warm = weather_all[temp_warm]
weather_warm.head(3)
```
The number of stations with temperature greater than 20 C is:
```
weather_warm['Station Name'].nunique()
```
List these stations and the number of hours at each station with temperatures greater than 20 C:
```
weather_warm['Station Name'].value_counts()
```
Winnipeg Richardson Int'l Airport had the highest occurrence (13 hours) of temperatures greater than 20 C
# Lesson 4 Recap
### Sorting
Sort a DataFrame based on the values in the column `'Column B'`:
```
df.sort_values('Column B')
```
To sort in descending order, use the keyword argument `ascending=False`
### Aggregation
For basic aggregation operations, use the `groupby` method chained with an aggregation method (e.g., `mean`, `sum`, `max`, `min`, `count`).
For example, to find the mean values for data grouped by `'Column B'`: `
```
df.groupby('Column B').mean()
```
### Subsets
#### Selecting Columns
To select a subset of columns from a DataFrame:
```
df_sub = df[['Column C', 'Column A', 'Column B']]
```
#### Selecting Rows with a Filter
To select a subset of rows with a filter:
- Create a filter (Boolean Series)
- Fill any missings in the filter using the `fillna` method (if necessary)
- Use the filter to extract the desired rows from the DataFrame
Filter Example 1: string method `contains` with text data
```
snowing = weather_all['Conditions'].str.contains('Snow')
snowing = snowing.fillna(False)
weather_snowing = weather_all[snowing]
```
Filter Example 2: comparison operator with numerical data
```
temp_warm = weather_all['Temperature (C)'] > 20
temp_warm = temp_warm.fillna(False)
weather_warm = weather_all[temp_warm]
```
# Exercise 4
a) What is the fastest wind speed in `weather_all`, and at what station and datetime did it occur? What were the wind direction, temperature, and weather conditions (raining / sunny / etc.) that accompanied this fastest wind speed?
b) How many stations had wind speeds greater than 30 km/hr? Which stations were they?
#### Bonus exercises
c) What were the top three windiest stations, based on their maximum wind speeds? What were the maximum wind speeds at each of these stations?
d) Do the top three stations from (c) change if you rank your stations based on mean wind speed instead of maximum wind speed?
| github_jupyter |
# Protein Folding with Pyrosetta
In this tutorial, we will fold a protein structure using a very simple algorithm in PyRosetta, and compare the folded structure with the solved crystal structure of the protein.
### Importing relevant libraries
We begin by importing the relevant libraries from Python. If running the following cell produces any errors or warnings, make sure you have followed all the steps in the "Setting up Pyrosetta" section.
```
import os
import glob
import shutil
import pandas as pd
import nglview as ngl
import pyrosetta as prs
prs.init()
from pyrosetta import rosetta
```
### Setting up score functions that will be used across parts
```
scorefxn_low = prs.create_score_function('score3')
scorefxn_high = prs.get_fa_scorefxn()
```
### Loading the native (solved crystal) structure
```
native_pose = prs.pose_from_pdb('data/1BL0/1BL0_chainA.pdb')
```
We can check the amino acid sequence of the structure with a very simple command.
```
native_pose.sequence()
```
We can also assign the correct secondary structure.
```
DSSP = prs.rosetta.protocols.moves.DsspMover()
DSSP.apply(native_pose) # populates the pose's Pose.secstruct
```
#### Hint: The amino acids are also called residues!
Let's view more information about the first residue of the protein.
```
print(native_pose.residue(1))
pose = prs.pose_from_sequence(native_pose.sequence())
test_pose = prs.Pose()
test_pose.assign(pose)
test_pose.pdb_info().name('Linearized Pose')
view = ngl.show_rosetta(test_pose)
view.add_ball_and_stick()
view # zoom in to see the atoms!
```
## Defining movers to switch from full-atom to centroid representation
We will be using the centroid representation to perform rough and fast scoring in the initial stages of the folding algorithm. Later on, we will switch to the full atom represenation to do accurate minimization and get the final structures.
```
to_centroid = prs.SwitchResidueTypeSetMover('centroid')
to_full_atom = prs.SwitchResidueTypeSetMover('fa_standard')
to_full_atom.apply(test_pose)
print('Full Atom Score:', scorefxn_high(test_pose))
to_centroid.apply(test_pose)
print('Centroid Score:', scorefxn_low(test_pose))
```
## Q: Visualize the centroid-only structure and see the difference with the full atom that we visualized above? Print again the information for the first residue and compare.
```
# here write the code to visualize the centroid only structure and print the information of the 1st residue
```
## Setting up the folding algorithm
```
# Loading the files with the pre-computed fragmets
long_frag_filename = 'data/1BL0/9_fragments.txt'
long_frag_length = 9
short_frag_filename = 'data/1BL0/3_fragments.txt'
short_frag_length = 3
# Defining parameters of the folding algorithm
long_inserts=5 # How many 9-fragment pieces to insest during the search
short_inserts=10 # How many 3-fragment pieces to insest during the search
kT = 3.0 # Simulated Annealing temperature
cycles = 1000 # How many cycles of Monte Carlo search to run
jobs = 50 # How many trajectories in parallel to compute.
job_output = 'outputs/1BL0/decoy' # The prefix of the filenames to store the results
```
#### Loading the fragmets
```
movemap = prs.MoveMap()
movemap.set_bb(True)
fragset_long = rosetta.core.fragment.ConstantLengthFragSet(long_frag_length, long_frag_filename)
long_frag_mover = rosetta.protocols.simple_moves.ClassicFragmentMover(fragset_long, movemap)
fragset_short = rosetta.core.fragment.ConstantLengthFragSet(short_frag_length, short_frag_filename)
short_frag_mover = rosetta.protocols.simple_moves.ClassicFragmentMover(fragset_short, movemap)
insert_long_frag = prs.RepeatMover(long_frag_mover, long_inserts)
insert_short_frag = prs.RepeatMover(short_frag_mover, short_inserts)
```
## Q: How many 9-mer and 3-mer fragmets do we have in our database?
#### Setting up the MonteCarlo search
```
# Making sure the structure is in centroid-only mode for the search
test_pose.assign(pose)
to_centroid.apply(test_pose)
# Defining what sequence of actions to do between each scoring step
folding_mover = prs.SequenceMover()
folding_mover.add_mover(insert_long_frag)
folding_mover.add_mover(insert_short_frag)
mc = prs.MonteCarlo(test_pose, scorefxn_low, kT)
trial = prs.TrialMover(folding_mover, mc)
# Setting up how many cycles of search to do in each trajectory
folding = prs.RepeatMover(trial, cycles)
```
#### Setting up the relax mover for the final stage
```
fast_relax_mover = prs.rosetta.protocols.relax.FastRelax(scorefxn_high)
```
### Running the folding algorithm!
```
scores = [0] * (jobs + 1)
scores[0] = scorefxn_low(test_pose)
if os.path.isdir(os.path.dirname(job_output)):
shutil.rmtree(os.path.dirname(job_output), ignore_errors=True)
os.makedirs(os.path.dirname(job_output))
jd = prs.PyJobDistributor(job_output, nstruct=jobs, scorefxn=scorefxn_high)
counter = 0
while not jd.job_complete:
# a. set necessary variables for the new trajectory
# -reload the starting pose
test_pose.assign(pose)
to_centroid.apply(test_pose)
# -change the pose's PDBInfo.name, for the PyMOL_Observer
counter += 1
test_pose.pdb_info().name(job_output + '_' + str(counter))
# -reset the MonteCarlo object (sets lowest_score to that of test_pose)
mc.reset(test_pose)
#### if you create a custom protocol, you may have additional
#### variables to reset, such as kT
#### if you create a custom protocol, this section will most likely
#### change, many protocols exist as single Movers or can be
#### chained together in a sequence (see above) so you need
#### only apply the final Mover
# b. apply the refinement protocol
folding.apply(test_pose)
####
# c. export the lowest scoring decoy structure for this trajectory
# -recover the lowest scoring decoy structure
mc.recover_low(test_pose)
# -store the final score for this trajectory
# -convert the decoy to fullatom
# the sidechain conformations will all be default,
# normally, the decoys would NOT be converted to fullatom before
# writing them to PDB (since a large number of trajectories would
# be considered and their fullatom score are unnecessary)
# here the fullatom mode is reproduced to make the output easier to
# understand and manipulate, PyRosetta can load in PDB files of
# centroid structures, however you must convert to fullatom for
# nearly any other application
to_full_atom.apply(test_pose)
fast_relax_mover.apply(test_pose)
scores[counter] = scorefxn_high(test_pose)
# -output the fullatom decoy structure into a PDB file
jd.output_decoy(test_pose)
# -export the final structure to PyMOL
test_pose.pdb_info().name(job_output + '_' + str(counter) + '_fa')
```
### Evaluating the folding results by getting the energies and RMSDs (distnace from the native pose) of each one of the predicted structures
```
decoy_poses = [prs.pose_from_pdb(f) for f in glob.glob(job_output + '*.pdb')]
def align_and_get_rmsds(native_pose, decoy_poses):
prs.rosetta.core.pose.full_model_info.make_sure_full_model_info_is_setup(native_pose)
rmsds = []
for p in decoy_poses:
prs.rosetta.core.pose.full_model_info.make_sure_full_model_info_is_setup(p)
rmsds += [prs.rosetta.protocols.stepwise.modeler.align.superimpose_with_stepwise_aligner(native_pose, p)]
return rmsds
rmsds = align_and_get_rmsds(native_pose, decoy_poses)
rmsd_data = []
for i in range(1, len(decoy_poses)): # print out the job scores
rmsd_data.append({'structure': decoy_poses[i].pdb_info().name(),
'rmsd': rmsds[i],
'energy_score': scores[i]})
rmsd_df = pd.DataFrame(rmsd_data)
rmsd_df.sort_values('rmsd')
```
### Q: Plot the energy_score VS rmsd. Are the lowest energy structures the closest to the native one?
| github_jupyter |
# Aula 8
## Exercícios do episódio 8
### Combinando Strings
```
def cercar(texto, cerca):
return cerca + texto + cerca
cercar('name', '*')
```
### Return versus print
```
def juntar(a, b):
return a + b
juntar('x', 'y')
resultado = juntar('x', 'y')
print(resultado)
def pontas(texto):
return texto[0] + texto[-1]
pontas('hélio')
```
### Normalizando um Array
```
import numpy as np
def reescalar(matriz):
'''Recebe um array como entrada e retorna um array correspondente
dimensionado para que 0 corresponda ao valor mínimo e 1 ao
valor máximo do array de entrada.
Exemplo:
>>> rescale(numpy.arange(10.0))
array([ 0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ])
>>> rescale(numpy.linspace(0, 100, 5))
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
'''
mínimo = np.min(matriz)
máximo = np.max(matriz)
return (matriz - mínimo) / (máximo - mínimo)
np.linspace(0, 20, 10)
reescalar(np.linspace(0, 20, 10))
reescalar?
```
### Definindo parâmatros padrão
```
def reescalar(matriz, arg_mín=0.0, arg_máx=1.0):
'''Recebe um array como entrada e retorna um array correspondente
dimensionado conforme os parâmetros especificados como mínimo e máximo.
'''
mínimo = np.min(matriz)
máximo = np.max(matriz)
temp = (matriz - mínimo) / (máximo - mínimo)
return temp * (arg_máx - arg_mín) + arg_mín
reescalar(np.linspace(0, 20, 10))
reescalar(np.linspace(0, 20, 10), 5, 50)
```
### Variáveis Internas e Externas da Função
```
f = 0
k = 0
def f2k(f):
k = ((f-32)*(5.0/9.0)) + 273.15
return k
print(f2k(8))
print(f2k(41))
print(f2k(32))
print(k)
```
### Mesclando parâmetros Padrão e Não-Padrão
### O Velho Troca Troca
```
a = 1
b = 2
a, b = b, a
a
b
```
### Código Legível
## Episódio 10: Programação defensiva
```
numbers = [1.5, 2.3, 0.7, -0.001, 4.4]
total = 0.0
for num in numbers:
assert num > 0.0, 'Data should only contain positive values'
total += num
print('total is:', total)
assert True
assert False, 'Isso é falso!'
def média(a, b):
res = (a + b) / 2
if a < b:
menor, maior = a, b
else:
menor, maior = b, a
assert res >= menor, res
assert res <= maior, res
return res
média(3, 4)
def média(lista):
assert len(lista) > 0, 'a lista não pode ser vazia'
res = sum(lista) / len(lista)
assert res >= min(lista), f'o resultado {res} deveria ser >= mínimo'
assert res <= max(lista), f'o resultado {res} deveria ser <= máximo'
return res
média([1])
def normalize_rectangle(rect):
'''Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis.
Input should be of the format (x0, y0, x1, y1).
(x0, y0) and (x1, y1) define the lower left and upper right corners
of the rectangle, respectively.'''
assert len(rect) == 4, 'Rectangles must contain 4 coordinates'
x0, y0, x1, y1 = rect
assert x0 < x1, 'Invalid X coordinates'
assert y0 < y1, 'Invalid Y coordinates'
dx = x1 - x0
dy = y1 - y0
if dx > dy:
scaled = dy / dx
upper_x, upper_y = 1.0, scaled
else:
scaled = dx / dy
upper_x, upper_y = scaled, 1.0
assert 0 < upper_x <= 1.0, f'Calculated upper X {upper_x} coordinate invalid'
assert 0 < upper_y <= 1.0, f'Calculated upper Y {upper_y} coordinate invalid'
return (0, 0, upper_x, upper_y)
normalize_rectangle((1, 2, 4, 6))
normalize_rectangle((1, 2, 6, 4))
```
## TDD
```
def test_sobreposição_um_dentro_do_outro():
faixa1 = (-3, 5)
faixa2 = (0, 4.5)
res = sobreposição(faixa1, faixa2)
assert res == faixa2
res = sobreposição(faixa2, faixa1)
assert res == faixa2
def test_sobreposição_parcial():
faixa1 = (-3, 3)
faixa2 = (0, 4.5)
esperado = (0, 3)
res = sobreposição(faixa1, faixa2)
assert res == esperado, f'{res} != {faixa2}'
res = sobreposição(faixa2, faixa1)
assert res == esperado
def test_sobreposição_inexistente():
faixa1 = (-3, 5)
faixa2 = (6, 10)
res = sobreposição(faixa1, faixa2)
assert res is None, f'esperava None, veio {res}'
def testar():
test_sobreposição_um_dentro_do_outro()
test_sobreposição_inexistente()
test_sobreposição_parcial()
print('OK')
def sobreposição(faixa1, faixa2):
inferior = max(faixa1[0], faixa2[0])
superior = min(faixa1[1], faixa2[1])
if inferior <= superior:
return (inferior, superior)
else:
return None
testar()
```
| github_jupyter |
# ML and AWS practical
You will have been sent an email with a login link to the amazon console.
## Logging in and the console
Once logged in, you will be be placed in the AWS management console.
<img src="aws1.png" />
A few things to note.
First, AWS is hosted in <a href="https://aws.amazon.com/about-aws/global-infrastructure/">multiple locations world-wide</a>.
<img src="aws2.png" />
From Amazon:
> These locations are composed of Regions and Availability Zones. Each Region is a separate geographic area. Each Region has multiple, isolated locations known as Availability Zones. Amazon EC2 provides you the ability to place resources, such as instances, and data in multiple locations. Although rare, failures can occur that affect the availability of instances that are in the same location. If you host all your instances in a single location that is affected by such a failure, none of your instances would be available.
We will just be using one region today, Ireland (eu-west-1). You can see (and select) the region from the drop down list in the top right of the console.
Under 'all services' one can select which tool of AWS one wishes to use. We will restrict ourselves for today to Elastic Compute Cloud (EC2), Simple Storage Service (S3) and Elastic Map Reduce (EMR).
First we'll explore EC2, set up an 'instance' (virtual machine) and connect to it.
- Click on EC2.
- Click on 'Instances' from the left pane. You will see an empty table and a big button 'Launch Instance' - click it!
#### Step 1: Choose AMI
The first step is deciding what machine image you want on your new instance. An easy start is to use one of the images created by Amazon. <span style="background-color: #FFFF00">Select the **Ubuntu Server 18.04 LTS (HVM)** machine image</span>.
<img src="aws4.png" />
In the future one could use an image already created with software or data already installed, for example.
#### Step 2: Choose Instance Type
The second step is selecting the (virtual) hardware the instance will run on. <span style="background-color: #FFFF00">For this practical **we ask that you use the t2.nano, t2.micro, t2.small or t2.medium instance type**</span> (as we have increased the limit on this account to allow you all to start one).
Click <span style="background-color: #FFFF00">Next: Configure Instance Details.</span>
#### Step 3: Configure Instance Details
**There is no need to modify any of this.** But a couple of items of interest:
**Autoscaling**: In the future, even for ML problems, it can be helpful to configure a load-balancer and autoscaling to increase or decrease the number of instances depending on the demand.
**Spot pricing** Typically AWS will not be using all its computational resources. To make use of this 'spare' hardware, AWS offer a service called 'spot pricing' which is typically considerably cheaper than the on-demand price, but comes at the cost of an instance that might be terminated with two minutes warning.
Click <span style="background-color: #FFFF00">Next: Add Storage</span>
#### Step 4: Add Storage
Simply leave it a 8Gb general purpose SSD.
A note here: There are many types of storage provided by AWS:
- Low cost, slow access: Amazon Glacier
- Elastic Block Store: This is the type of storage you need in your EC2 instance. (<a href="https://aws.amazon.com/ebs/features/#Amazon_EBS_volume_types">More info</a>) This comes in four flavours,
- slowest/cheapest: sc1 (cold HDD, solid state)
- still cheap: st1 (throughput-optimised HDD)
- solid-state: gp2 (general purpose SSD)
- fast/expensive: io1.
Click <span style="background-color: #FFFF00">Next: Add Tags</span>
#### Step 5: Add Tags
As everyone is using the same account it is very useful to **label your instance**, here it might be worth adding your id so you can find it again. For example, click *Add Tag* then use Key = "email" and Value = your email. Without this you might struggle to find your instance again!
Click <span style="background-color: #FFFF00">Next: Configure Security Group</span>
#### Step 6: Configure Security Group
Security groups are how EC2 organises access to the instances you create. I've already created one called "justssh" which gives access to the SSH port from anywhere. Typically one would restrict this to be from just your IP address, for example. Feel free to either use a security group that already exists or create a new one. You'll need to be able to SSH into the server later.
Click Review and Launch.
#### Step 7: Review and Launch
When you click 'launch' you'll be asked to Select or create a key pair.
A quick detour, from ssh.com:
> Each SSH key pair includes two keys:
> A **public key** that is copied to the SSH server(s). Anyone with a copy of the public key can encrypt data which can then only be read by the person who holds the corresponding private key. Once an SSH server receives a public key from a user and considers the key trustworthy, the server marks the key as authorized in its authorized_keys file. Such keys are called authorized keys.
> A **private key** that remains (only) with the user. The possession of this key is proof of the user's identity. Only a user in possession of a private key that corresponds to the public key at the server will be able to authenticate successfully. The private keys need to be stored and handled carefully, and no copies of the private key should be distributed. The private keys used for user authentication are called identity keys.
Previously, when connecting to SHARC or ICEBERG you were using a username/password. In this case AWS will be using a key pair. This is typically more secure and allows automation and is generally the standard method for secure communication.
<img src="aws6.png" />
So <span style="background-color: #FFFF00">click 'create a new key pair' and enter a **unique** key pair name, e.g. "mtsmithsecretkey".</a> Then click 'download key pair'. You'll receive a file called "mtsmithsecretkey.pem" (or whatever). You'll need this to SSH into this new instance. Depending on your operating system there are a few different things to do to achieve this (see next section).
Finally click 'Launch Instances'.
#### SSHing into your new instance
<img src="aws7.png" />
You'll be shown a summary stating your instances are launching. Either click the link to the instance
or return to the <a href="https://eu-west-1.console.aws.amazon.com/ec2/v2/home?region=eu-west-1#Instances:sort=instanceId">list of instances</a> and filter by the tag email address you entered.
You might need to wait a few seconds while the instance starts.
Click on the instance and then right click (or use the button at the top) select "Connect". This will give instructions on how to SSH in. In linux and iOS one needs to simply set the file's permissions to read only `chmod 400 filename.pem` then ssh:
ssh -i "mtsmithsecretkey.pem" ubuntu@ec2-34-243-65-51.eu-west-1.compute.amazonaws.com
In windows things are more complicated. <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html?icmpid=docs_ec2_console">AWS has instructions on how to get this working with putty</a>. Mike Croucher recommended <a href="https://mobaxterm.mobatek.net/">MobaXterm</a>. This works by default with the pem file. See <a href="https://angus.readthedocs.io/en/2016/amazon/log-in-with-mobaxterm-win.html">these instructions</a> if you need more help.
If you can't get that working there are <a href="https://www.bitvise.com/tunnelier">alternative SSH clients</a>.
# Elastic Map Reduce (EMR)
We'll now set up a cluster to run a simple Recommender system (a little like the one you set up earlier in the course). Here we're not interested in the algorithm, more in some of the aspects of the cloud.
Click on Services, and find "<a href="https://eu-west-1.console.aws.amazon.com/elasticmapreduce/home?region=eu-west-1#">EMR</a>" (under analytics), then click **Create cluster**. **Then choose Advanced Options.**
#### Step 1: Software and Steps
Here we get to select what software will be preinstalled on the cluster's nodes. In this case we just want hadoop and spark:
<img src="aws8.png" />
#### Step 2: Hardware
<span style="background-color: #FFFF00">**Edit the Master and Core to use the 'r5a.xlarge' instance type**</span> (we've increased the AWS limits on this type. You'll find that using other instance types will probably fail). Select about 3 instances for the core node set. You can save us money if you select "Spot" pricing, but there is a small risk your instacnces will get terminated by AWS during a spike in demand.
<img src="aws9.png" />
#### Step 3: General Cluster Settings
Name your cluster something sensible <span style="background-color: #FFFF00">and unique</span>, maybe the first part of your email address: "m.t.smith.cluster". Uncheck Logging, Debugging and Termination protections - as we won't be using these features. It might be worth adding the same tag you gave your instance before so you can find it.
<img src="aws10.png" />
#### Step 4: Security
Select the EC2 keypair you created previously. You could also try disabling 'cluster visible to all IAM users in account' to avoid clutter for other users. The default security groups are fine. Click **Create cluster**.
<img src="aws11.png" />
(note, I've added inbound SSH to the default security groups here - you'll need to do this if you work with this in the future).
#### Connecting
You will be able to select the cluster from the EMR <a href="https://eu-west-1.console.aws.amazon.com/elasticmapreduce/home?region=eu-west-1#">clusters page</a>, and click on the SSH button. You can ssh in the same way as before. Please be patient, it takes a while to get the cluster spun up. Initially ssh won't be available, and even when it is pyspark etc might not be installed when you first arrive - wait a minute and try again!
<img src="aws12.png" />
## The AWS command line interface
We now have a cluster running and ready for our commands.
Let's try out the AWS command line interface. It is often the case that one will want to perform a console operation repeatedly or describe a complex action programmatically to make it easy to see what has been done. To this end Amazon provide both a command line tool and an API. All the actions you can do with the console can be done via these alternative interfaces. As we're now logged into a machine that's got the AWS CLI installed, we could quickly try it out.
#### s3 access
First we're going to look at Amazon's simple storage service (s3). This has a <a href="https://s3.console.aws.amazon.com/s3/home?region=eu-west-1#">web interface</a>, but we'll be accessing it using the command line. On your new instance type:
aws s3 ls
This will list the bucket(s). To list the contents of the bucket;
aws s3 ls ml10m100k
Then to copy the data to our instance,
aws s3 cp s3://ml10m100k . --recursive
<img src="aws13.png" />
#### ec2 via the command line
Also try `aws ec2 describe-instances` to list all the instances currently in this account.
The command line interface allows you to also create and destroy instances, configure users, launch clusters, and do any other operation that you can also do with the web interface. You may find you don't have access to some of these commands however.
Be careful, you can terminate your fellow students' instances as you are all in the same account and have sufficient permissions. For more help on a particular aspect, you can type something like,
aws ec2 help
## Control via the API
We can also access AWS using the API, still logged into the cluster, on the command line, we need to install boto3, a library for accessing the AWS API from python. Type,
sudo pip install boto3
Then start a python terminal,
python
And then import boto3,
import boto3
We can then start a session connecting to the AWS API to control ec2,
sess = boto3.client('ec2')
reservations = sess.describe_instances()['Reservations']
for res in reservations:
for j in res['Instances']:
print(j['InstanceType'],j['PublicIpAddress'])
if 'Tags' in j: print(j['Tags'])
break
This will print out a list of all the instance types, and their tags.
# Using pyspark to make a recommendation
We need to put the datafiles we're going to use within reach of hadoop. For this we simply run
hadoop fs -put *.dat /
This copies the data to the <a href="https://www.aosabook.org/en/hdfs.html">Hadoop Distributed File System</a>.
Type `pyspark` to open the interactive python/spark command line.
We load the ratings data from the hadoop file system. This is a :: separated table of ratings. The lambda/map functions are to split by these :: and assign the types to the three columns.
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
data = sc.textFile('/ratings.dat')
ratings = data.map(lambda l: l.split('::')).map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))
This will be very quick as spark only runs things when it needs to (hence none of the above is run until the following lines are run...)
Let's ask for the first item, to check it's working:
ratings.first()
> Rating(user=1, product=122, rating=5.0)
Let's set up the model:
test, train = ratings.randomSplit(weights=[0.3, 0.7], seed=1)
rank = 10
numIterations = 10
model = ALS.train(train, rank, numIterations)
testdata = test.map(lambda p: (p[0],p[1]))
predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = test.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE))
> 0.7009719027724838
Finally, a quick look at the MSE on the training data;
traindata = train.map(lambda p: (p[0],p[1]))
predictionstrain = model.predictAll(traindata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = train.map(lambda r: ((r[0], r[1]), r[2])).join(predictionstrain)
print("Mean Squared Error = " + str(MSE))
How do these compare?
## Additional exercises
A global network of air pollution sensors is aggregated by openAQ. They archive this data on s3 (see here: https://openaq-data.s3.amazonaws.com/index.html)
We can copy one of these csv files to our instance from the command line using:
aws s3 cp s3://openaq-data/2019-01-01.csv .
Tip: This might be faster if the instance were in the same region as the data!
Or, from inside pyspark, can read the data directly:
df = spark.read.csv("s3a://openaq-data/2019-01-01.csv")
This could be improved by treating the headers properly for a start. Add options to do this (hint set `header=True`)
Feel free to try analysing this data. For example count the number of measurements in Uganda?
Hint the 'country' column would equal 'UG'...
df[df['country']=='UG'].count()
Note that without the `.count()` the result is immediate - spark doesn't do any computation until it has to.
You'll find the operation is far quicker the second time thanks to caching. Also look at `.persist()` <a href="https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html#rdd-persistence">here</a>.
#### Starting and stopping EC2 instances from the command line
Example code, modify to start an instance yourself.
aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
Think about where you can get the security-group-id. (hint: either from the webconsole, or for bonus credit from the command line interface! hint: `aws ec2 describe-security-groups`).
## Lambda Demo
This exercise is <span style="background-color: #FFFF00">**currently unavailable due to permission issues**</span>.
If you've time you could try using Lambda. This is a way of writing code that runs when triggered by a particular event, without needing to set up your own server.
### Lambda
1. Click on Services and find Lambda under 'Compute'.
2. Click 'Create a function'
3. Then 'Author from scratch', and select:
- A Function name (e.g. demofunction)
- Then runtime, I used python 3.7.
4. You'll want to 'Use an exsiting role' and select 'service-role/testfunction-role-np5tat7d' this gives the lambda functionn basic permission to upload logs to Amazon CloudWatch Logs. You won't be able to create a new role due to the restrictions placed on the student accounts we created.
<img src='aws14.png' />
5. Click Create function!
### The Lambda interface
This page is quite complicated. Make sure you're in the 'Configuration' section.
On the left of that panel you can select triggers - these are things that will trigger your lambda code to run. Why not choose API Gateway.
- Select your bucket as the trigger.
- Leave it as "All object creation events"
- Click Add.
At the moment there might be a permission issue with this activity.
## s3 Bucket
Visit the s3 page (via the Services tab). You'll be able to see the buckets we have, and create a new one.
<img src="aws15.png" />
<span style="background-color: #FFFF00">**Bucket names must be unique across all of Amazon S3 for everyone! So please prefix all our buckets with <span style="color: #444444">2018com6012yourbucketname</span> to try and avoid polluting the name space.**</span> You'll also need the region to be the same as the one you're going to be running the lambda function in! (keep it in Ireland). Click Next and leave all the other settings unchanged then Create Bucket!
You'll be able to see the bucket in the list now.
| github_jupyter |
# Predict state
Here is the current implementation of the `predict_state` function. It takes in a state (a Python list), and then separates those into position and velocity to calculate a new, predicted state. It uses a constant velocity motion model.
**In this exercise, we'll be improving this function, and using matrix multiplication to efficiently calculate the predicted state!**
```
# The current predict state function
# Predicts the next state based on a motion model
def predict_state(state, dt):
# Assumes a valid state had been passed in
x = state[0]
velocity = state[1]
# Assumes a constant velocity model
new_x = x + velocity*dt
# Create and return the new, predicted state
predicted_state = [new_x, velocity]
return predicted_state
```
## Matrix operations
You've been given a matrix class that can create new matrices and performs one operation: multiplication. In our directory this is called `matrix.py`.
Similar to the Car class, we can use this to initialize matrix objects.
```
# import the matrix file
import matrix
# Initialize a state vector
initial_position = 0 # meters
velocity = 50 # m/s
# Notice the syntax for creating a state column vector ([ [x], [v] ])
# Commas separate these items into rows and brackets into columns
initial_state = matrix.Matrix([ [initial_position],
[velocity] ])
```
### Transformation matrix
Next, define the state transformation matrix and print it out!
```
# Define the state transformation matrix
dt = 1
tx_matrix = matrix.Matrix([ [1, dt],
[0, 1] ])
print(tx_matrix)
```
### TODO: Modify the predict state function to use matrix multiplication
Now that you know how to create matrices, modify the `predict_state` function to work with them!
Note: you can multiply a matrix A by a matrix B by writing `A*B` and it will return a new matrix.
```
# The current predict state function
def predict_state_mtx(state, dt):
## Assume that the state passed in is a Matrix object
## Using a constant velocity model and a transformation matrix
## Create and return the new, predicted state!
predicted_state = tx_matrix*state
return predicted_state
```
### Test cell
Here is an initial state vector and dt to test your function with!
```
# initial state variables
initial_position = 10 # meters
velocity = 30 # m/s
# Initial state vector
initial_state = matrix.Matrix([ [initial_position],
[velocity] ])
print('The initial state is: ' + str(initial_state))
# after 2 seconds make a prediction using the new function
state_est1 = predict_state_mtx(initial_state, 2)
print('State after 2 seconds is: ' + str(state_est1))
# Make more predictions!
# after 3 more
state_est2 = predict_state_mtx(state_est1, 3)
print('State after 3 more seconds is: ' + str(state_est2))
# after 3 more
state_est3 = predict_state_mtx(state_est2, 3)
print('Final state after 3 more seconds is: ' + str(state_est3))
```
| github_jupyter |
```
%matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy import optimize
import optunity
```
# Search space
```
# range of possible lengths
L = np.linspace(0.01,3,200)
# physical angles for each length
theta_max = np.rad2deg(np.arctan(0.8/L))
theta_min = np.rad2deg(np.arctan(0.1/L))
def theta(beta, M1, gamma):
# function of the compressible flow theta-beta-Mach function to get theta
# constraints of the function to avoid angles outside range
if np.rad2deg(beta) < 0:
return 10
elif np.rad2deg(beta) > 90:
return 10
else:
# negative sign is used to minime the function
return -np.arctan(2*(M1**2*(np.sin(beta))**2-1)/((np.tan(beta))*(M1**2*(gamma+np.cos(2*beta))+2)))
# case boundary conditions
M1 = 2
gamma = 1.4
# minimum possible angle for detached oblique shock waves
minimum = optimize.fmin(theta, np.deg2rad(20), args=(M1, gamma))
detached = -np.rad2deg(theta(minimum[0],M1,gamma))
print('Detached oblique shock waves will occur if theta > %.4f deg' %detached)
def Lmin(x):
# difference between detached shock wave angle and the minimum geometrical angle for each x
# created to compute the length where maximum physical angle mets minimum geometrical angle
if x > 0.1:
return np.abs(detached - np.rad2deg(np.arctan(0.1/x)))
else:
return np.inf
minimum_L = optimize.fmin(Lmin, 0.25)
print('The length where minimum geometrical theta angle intersects maximum physical angle is %.4f' %minimum_L)
```
```
fig, ax = plt.subplots(1, figsize=(15,10))
ax.plot(L,theta_max,'b',linewidth=3,label=r'$\theta_{max} - geom$')
ax.plot(L,theta_min,'r',linewidth=3,label=r'$\theta_{min} - geom$')
ax.plot([0,3.0],[detached,detached],'k',linewidth=3,label=r'$\theta_{max} - phys$')
ax.plot([2.5,2.5],[0,45],'g',linewidth=3,label=r'$L_{max}$')
ax.set_xlim([L.min(),L.max()])
ax.set_ylim([1,45])
ax.fill_between(L,detached*np.ones(len(L)),color='k',alpha=0.2, label='Search space')
ax.fill_between(L,100*np.ones(len(L)),theta_max,color='w')
ax.fill_between(L,theta_min,color='w')
ax.fill_between([2.5,3.0],[45,45],color='w')
ax.set_xlabel('Length $L$ ($m$)',fontsize=30)
ax.set_ylabel(r'Angle $\theta$ ($deg$)',fontsize=30)
ax.legend(fontsize=28, loc='best', bbox_to_anchor=(1.02,0.7))
ax.tick_params(axis = 'both', labelsize = 28)
ax.set_title('Search space', fontsize = 40)
# plt.savefig('./SearchSpace.png', bbox_inches='tight')
```
# First population definition
```
def constraint(L,theta):
''' Function to test the length and angle constraints
INPUTS:
L: array with possible lengths
theta: array with possible angles theta
OUTPUTS:
boolMat: boolean matrix with 1 for the non valid points (constrained)'''
# space preallocation for boolean matrix
boolMat = np.zeros([len(L)])
# fill the boolean matrix
for i in range(len(L)):
# maximum allowable length
if L[i] > 2.5:
boolMat[i] = True
# angle for detached shock wave
elif theta[i] > detached:
boolMat[i] = True
# upper geometrical angle limit
elif L[i]*np.tan(np.deg2rad(theta[i])) > 0.8:
boolMat[i] = True
# lower geometrical angle limit
elif L[i]*np.tan(np.deg2rad(theta[i])) < 0.1:
boolMat[i] = True
else:
boolMat[i] = False
return boolMat
# get the limits of the x and y components of each individual
x_low = L[np.argwhere(theta_min < detached)[0][0]]
x_high = 2.5
y_low = theta_min[np.argwhere(L > 2.5)[0][0]]
y_high = detached
# Sobol sampling initialization
x1, x2 = zip(*optunity.solvers.Sobol.i4_sobol_generate(2, 128, int(np.sqrt(128))))
sobol = np.vstack(((x_high - x_low) * np.array([x1]) + x_low,
(y_high - y_low) * np.array([x2]) + y_low)).T
# unconstraint the Sobol initialization
while sum(constraint(sobol[:,0], sobol[:,1])) != 0:
boolMat = constraint(sobol[:,0], sobol[:,1])
for i in np.argwhere(boolMat == True):
sobol[i] = np.array([x_low+np.random.rand(1)*(x_high-x_low),y_low+np.random.rand(1)*(y_high-y_low)]).T
fig, ax = plt.subplots(1, figsize=(20,10))
ax.plot(L,theta_max,'b',linewidth=3,label=r'$\theta_{max}$ (geom)')
ax.plot(L,theta_min,'r',linewidth=3,label=r'$\theta_{min}$ (geom)')
ax.plot([0,3.0],[detached,detached],'k',linewidth=3,label=r'$\theta_{max}$ (phys)')
ax.plot([2.5,2.5],[0,45],'g',linewidth=3,label=r'$L_{max}$')
ax.set_xlim([L.min(),L.max()])
ax.set_ylim([0,45])
ax.fill_between(L,detached*np.ones(len(L)),color='k',alpha=0.3)
ax.fill_between(L,100*np.ones(len(L)),theta_max,color='w')
ax.fill_between(L,theta_min,color='w')
ax.fill_between([2.5,3.0],[45,45],color='w')
ax.set_xlabel('Parameter $L$',fontsize=16)
ax.set_ylabel(r'Parameter $\theta$',fontsize=18)
ax.tick_params(axis = 'both', labelsize = 14)
ax.set_title('Search space and first population (Sobol initialization)', fontsize = 22)
ax.plot(sobol[:,0],sobol[:,1],'k.',markersize=10,label='Population')
ax.legend(fontsize=16, loc='best')
```
| github_jupyter |
<a href="https://colab.research.google.com/github/GeorgeKMaina/Financial-Inclusion-East-Africa/blob/main/financial_inclusion_in_east_africa.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Defining the question
#### a) Specyfying the Data Analytic Question
What demographic factors can be used to establish whether an individual has acess to bank services
#### b) Metric of success
To identify the features that can help know whether an individual has acess to bank services using the chi squared test
#### c) Understanding the context
- Traditionally, access to bank accounts has been regarded as an indicator of financial inclusion. Despite the proliferation of mobile money in Africa and the growth of innovative fintech solutions, banks still play a pivotal role in facilitating access to financial services. Access to bank accounts enables households to save and facilitate payments while also helping businesses build up their credit-worthiness and improve their access to other financial services. Therefore, access to bank accounts is an essential contributor to long-term economic growth.
- The research problem is to figure out how we can predict which individuals are most likely to have or use a bank account.
#### d) Recording the experimental design
- The project entailed the use of pandas cross tabulations to get summaries of the different columns
- The project also used the chi2_contingency() function to get the chi squared statistics
- The chi squared statistic is used to determine whether two column features are independent
The null and alternative hypothesis for the chi square test is:
- Ho: The features are independnet
- Ha: There is a relationship between the features
-- null hypothesis is rejected when p-value is less than 0.05
#### e) Relevance of the data
- The data provided is relevant to our research question which was to establish what factors can help predict whether an individual has access to bank services
- from our analysis we were able to this
# Reading the Data
```
# we will import the necessary libraries for analysis
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
# we will read the dataset
fin=pd.read_csv(r'/content/Financial Dataset - 1.csv')
```
# Checking the Data
```
# we look at the first 5 rows
fin.head()
#we will look at the last 5 rows
fin.tail()
# we will check for the shape of the dataset
print('shape of dataset:', fin.shape)
print('Dataset has '+ str(fin.shape[0]) + ' rows and ' + str(fin.shape[1]) + ' columns')
# looking for the info of the dataset and the data types of the column
fin.dtypes
# we will need to convert the year column into datetime
# we will need to convert the gender of respondent into categorical data type
# we will need to convert the column Cell Phone Access into categorical data type
# we will need to convert the Has a Bank account into categorical data type
# we will need to convert the Has a marital_status categorical data type
fin.info()
# we can see that there are columns with missing values
```
# Tidying Up the Dataset
```
# we will start by looking for duplicated records in the dataset
fin.duplicated().sum()
cols=fin[['country','year','Has a Bank account','Type of Location','Cell Phone Access','household_size','gender_of_respondent','marital_status','Level of Educuation','Type of Job']]
for col in cols:
print ('\nlist of unique values in the column :%s'%col)
print(cols[col].unique())
# we can see that most columns contain nan values
# the column year has records of 2029,2039 and 2056
# we will first drop all the nan values
# then proceed to look at the rows with the years 2029,2039,2056
#checking for the number of missing values(null) in each column
missing=fin.isna().sum()
missing=missing[missing!=0]
print('number of columns with missing values:', len(missing))
#checking for the propotion of missing values in percentage
perc=(missing/len(fin))*100
missing_perc=pd.concat([missing,perc],axis=1)
missing_perc.rename(columns={0:'number of missing values',1:' percentage of missing values'},inplace=True)
missing_perc
# droping the null values will have no significant damage to our dataset
# we will drop all the rows with missing values
fin=fin.dropna()
# to check if all missing values have been dropped
fin.isna().sum()
#checking at this anomalies in years
fin[fin['year'].isin([2029,2056,2039])]
# we will drop this observations
#this are anomalies in the dataset
# there are only 3 rows that will be dropped
fin.drop(fin[fin['year']>2019].index,inplace=True)
#to confirm if the have beem dropped
fin.year.value_counts()
# we will look for outliers
# we only have 2 numerical columns
numerical=fin[['Respondent Age','household_size']]
numerical.describe().T
#the household size can not have 0 people
#the respondent age is not logical
#th avrage life expectancy of an individual in east africa is 68
#any age above this we will treated it as an outlier
plt.figure(figsize=(8,8))
numerical.boxplot()
plt.show()
#we will get all records of where the household size is less than 1
#we will drop this observations from our dataset
fin[fin['household_size']<1]
fin.drop(fin[fin['household_size']<1].index,inplace=True)
#we will also look for recordes where the family size is more than 10
fin[fin['household_size']>10]
#we will drop this records
fin.drop(fin[fin['household_size']>10].index,inplace=True)
# we will get all the valus where the age is more than 68
#this is the average life expectancy of the population in east africa
fin[fin['Respondent Age']>68]
#we will drop this values
fin.drop(fin[fin['Respondent Age']>68].index,inplace=True)
#looking at the subplots again
plt.figure(figsize=(8,8))
plt.title('boxplot')
plt.ylabel('scale')
fin[['Respondent Age','household_size']].boxplot()
plt.show()
fin[['Respondent Age','household_size']].describe()
fin.columns
#checking for anormalies
#we will first start with renaming some of the columns that were not gramatically correct
fin.rename(columns={'The relathip with head':'The relationship with household head','Level of Educuation':'Level of education'},inplace=True)
fin['Level of education'].value_counts()
# to have a loook at the rows where the level of education is 6 and 'Other/Dont know/RTA'
fin[fin['Level of education'].isin(['6','Other/Dont know/RTA'])]
fin.drop(fin[fin['Level of education'].isin(['6','Other/Dont know/RTA'])].index,inplace=True)
```
##univariate analysis
##### Has a Bank account
```
# this is our column of interest
plt.figure(figsize=(8,8))
plt.title('bar chart')
plt.ylabel('number of people')
color=['red','green']
fin['Has a Bank account'].value_counts().plot(kind='bar',color=color)
plt.show()
# we can see that most respondents did not have a bank account
```
##### Type of Location
```
plt.figure(figsize=(6,6))
plt.title('location of respondent residence')
explode=0.1,0
fin['Type of Location'].value_counts().plot(kind='pie',explode=explode, autopct='%1.3f%%')
plt.show()
#we can see most responddnents were in te rural areas
```
##### Cell Phone Acess
```
plt.figure(figsize=(6,6))
plt.title('whether respondent has a cell phone')
explode=0.1,0
color=['green','red']
fin['Cell Phone Access'].value_counts().plot(kind='pie',explode=explode, autopct='%1.3f%%',colors=color)
plt.show()
# most respondndetns have access to mobile phones
```
##### gender_of_respondent
```
plt.figure(figsize=(6,6))
plt.title('gender of the respondent')
explode=0.1,0
fin['gender_of_respondent'].value_counts().plot(kind='pie',explode=explode, autopct='%1.3f%%')
plt.show()
#most respondnents were female
```
##### The relationship with head
```
plt.figure(figsize=(8,8))
plt.title('The relationship with head')
plt.ylabel('count')
fin['The relationship with household head'].value_counts().plot(kind='bar')
plt.show()
```
##### marital_status
```
fin['marital_status'].value_counts()
#we will relabel the status 'Dont Know' into divorced or separated
fin['marital_status']=fin['marital_status'].replace('Dont know','Divorced/Seperated')
# we will make a plot to show the martial status
plt.figure(figsize=(8,8))
plt.title('marital status of respondent')
explode=0,0,0,0.1
fin['marital_status'].value_counts().plot(kind='pie',explode=explode,autopct='%1.3f%%')
plt.show()
#most respondnets were married/ living together
```
##### Type of Job
```
fin['Type of Job'].value_counts()
#we will combine the remintance dependnent and government dependent into one label known as dependnent
#those who refused to answer can be labelled into other income
fin["Type of Job"]= fin["Type of Job"].replace('Government Dependent', "dependent")
fin["Type of Job"]= fin["Type of Job"].replace('Remittance Dependent', "dependent")
fin["Type of Job"]= fin["Type of Job"].replace('Dont Know/Refuse to answer', "Other Income")
plt.figure(figsize=(8,8))
plt.title(' respondent job type')
plt.xlabel('count')
fin['Type of Job'].value_counts().plot(kind='barh')
plt.show()
```
## Bivariate Analysis
###### we will look at the relationship between 'Has a Bank account' and the other features
##### Has a Bank account and country
```
pd.crosstab(fin.country,fin['Has a Bank account'],margins=True,margins_name='Total')
# In Rwanda, most of the respondnents had bank accounts
#Uganda had the least
a=pd.crosstab(fin.country,fin['Has a Bank account'])
color=['red','green']
a.plot.bar(color=color)
plt.ylabel('count')
plt.title('bar chart of those with and without bank accounts')
plt.show()
```
- most people had no bank accounts in all the countries compared to those that had
```
stats.chi2_contingency(a)
#the chi2 statistic is 749, the degrees of freedom are 3 and the p-values is 4.3557
#the p-value is greater than the threshold of 0.05
#because of this we fail to reject the null hypothesis that the country and acess to bank services are independent
```
##### has bank account and location
```
pd.crosstab(fin['Type of Location'],fin['Has a Bank account'],margins=True,margins_name='Total')
#most respondnents in rural areas did not have bank accounts
# the proportion of those who had bank accounts in the urban and rural areas was not that different.
# this can imply if there were more respondnents from the urban areas aswell, then the number of those with accounts would be higher
loc_acc=pd.crosstab(fin['Type of Location'],fin['Has a Bank account'])
color=['red','green']
loc_acc.plot.bar(color=color)
plt.ylabel('count')
plt.show()
```
- Across all locations, the number of people without bank accounts is more than those with bank accounts
- The number of people with acess to bank services is slightly higher in urban areas than in rural areas
```
stats.chi2_contingency(loc_acc)
# we have a chi2 statistic of 200 and a pvalue that is less than the 0.05 threshold
#because of this we reject the null hypothesis that says there is no dependence between the location and accesibily of bank services
# this result implies that there is a relationship between the location of the respondent and the the accesibility of bank services
```
##### has bank account and has accesss to mobile phones
```
pd.crosstab(fin['Cell Phone Access'],fin['Has a Bank account'],margins=True,margins_name='Total')
#Most people who had acess to cell phones did not have bank accounts
#thos who had bank accounts and had cell phones were more than those who had bank accounts did not have cell phonescell
cell_acc=pd.crosstab(fin['Cell Phone Access'],fin['Has a Bank account'])
color=['red','green']
cell_acc.plot.bar(color=color)
plt.title('access to bank account and cell phone')
plt.ylabel('count')
plt.show()
```
- we can see that most people who had phone cell devices didn't have bank accounts
- We can se that most people who had bank accounts had phone cells services
```
#we will run a chi2 contignecy test to test for independnecy of the tow columns
stats.chi2_contingency(cell_acc)
```
- From the chi2_contingency() test, we had a chi2 statistic of 942 and a p-value that was less than the 0.05 thresshold
- because of this, we reject the null hypothesis which states that the two columns are independent
- By rejecting the null, we imply that there is an influence by phone cell acess to bank access.
#### has bank account and gender
```
pd.crosstab(fin['gender_of_respondent'],fin['Has a Bank account'],margins=True,margins_name='Total')
#most males had bank accounts than the females respondnents
#the number of females who did not have bank accounts were more than the male respondnets
gend_acc=pd.crosstab(fin['gender_of_respondent'],fin['Has a Bank account'])
color=['red','green']
gend_acc.plot.bar(stacked=True,color=color)
plt.title('bar chart')
plt.ylabel('count')
plt.show()
```
- we can see that most females did not have bank accounts
- we can also see that most males had bank accounts than their female counterparts
```
#we will run a chi squared test for independnence
stats.chi2_contingency(gend_acc)
```
- from the test above, we can see that the chi2 statistic is 279 while the p-value is less than the threshold of 0.05
- since the p-value is less than the 0.05 threshold, we fail to reject the null
- This implies that there is a relationship betwee the gender of the respondnent and them having a bank account
has bank account and household size
```
pd.crosstab(fin['household_size'],fin['Has a Bank account'],margins=True,margins_name='Total')
siz_acc=pd.crosstab(fin['household_size'],fin['Has a Bank account'])
color=['red','green']
siz_acc.plot.bar(color=color)
plt.ylabel('count')
plt.title('household size vs bank account status')
plt.show()
```
- at all household sizes, the number of those with no bank account is more than those with bank accounts
- Small sized families have more bank accounts than large families
- as the family size increase, the number of bank account decreases
```
#we will do a chi2 contigency test
stats.chi2_contingency(siz_acc)
```
- we have a chi2 test statistic of 76.88 and a p-value that is less than 0.05 threshold
- because of this we reject the null hypothesis that there is independnece between the two columns
- this implies that there is some level of influence that the family size has on access to bank services
#### has bank account and marital status
```
pd.crosstab(fin['marital_status'],fin['Has a Bank account'],margins=True,margins_name='Total')
marital_acc=pd.crosstab(fin['marital_status'],fin['Has a Bank account'])
color=['red','green']
marital_acc.plot.bar(color=color)
plt.title('marital status and bank account status')
plt.ylabel('count')
plt.show()
```
- we can see that in all the marital status groups, the number of people without bank accounts was more than those with bank accounts
- married/people living together had bank accounts
#### type respondnent job and bank account status
```
pd.crosstab(fin['Type of Job'],fin['Has a Bank account'],margins=True,margins_name='Total')
job_acc=pd.crosstab(fin['Type of Job'],fin['Has a Bank account'])
color=['red','green']
job_acc.plot.bar(color=color)
plt.title('job of respondnent vs bank account status')
plt.ylabel('count')
plt.show()
```
- we can see that individuals who are self employed have more bank accounts folowed by those that are formally employed in the private sector then farming and fishing follows
- those employed by government have more bank accounts
```
stats.chi2_contingency(job_acc)
```
- we have a chi squared statistic of 2898.176 and a p-value of 0.0
- the p-value is less than the p-value thresshold
- because of this we reject the null hypothesis
- this implies that there is no independence between the two columns
- therefore they do influence each other
#### bank account access and level of education of the respondent
```
pd.crosstab(fin['Level of education'],fin['Has a Bank account'],margins=True,margins_name='Total')
edu_acc=pd.crosstab(fin['Level of education'],fin['Has a Bank account'])
color=['red','green']
edu_acc.plot.bar()
plt.ylabel('count')
plt.title('level of education and bank account access')
plt.show()
```
- we can see that most people who attained the primary level of education do not have bank accounts
- Those with secondary education have the most acess to the banking services
```
# to look if the columns are independnet
#we will use the the chi square statistic
stats.chi2_contingency(edu_acc)
```
- the chi squared stat is 3388.22 while the pvalue is 0.0
- the pvalue is less than the threshold of 0.05
- this is to imply that the two column features are not independnent of each other
- in some way, the level of education influences whether an indiividual has a bank account or not
#### bank account acess with years
```
pd.crosstab(fin['year'],fin['Has a Bank account'],margins=True,margins_name='Total')
#the number of people with bank accounts dropped from the year 2016 to 2017
#the number of people with bank accounts was highest in 2018
year_acc=pd.crosstab(fin['year'],fin['Has a Bank account'])
color=['red','green']
year_acc.plot.bar(stacked=True,color=color)
plt.title('bank account status over the years')
plt.ylabel('count')
plt.show()
```
### bank account status with family head
```
pd.crosstab(fin['The relationship with household head'],fin['Has a Bank account'],margins=True,margins_name='Total')
head_acc=pd.crosstab(fin['The relationship with household head'],fin['Has a Bank account'])
color=['red','green']
head_acc.plot.bar(color=color)
plt.title('relationship with household head and bank account status')
plt.ylabel('count')
plt.show()
```
- we can see that most household head do not have access to bank accounts
- this is a worrying observation
- most parents did not have bank accounts
```
# we will calculate a chi square
stats.chi2_contingency(head_acc)
```
- the chi2 statistic is 344.75 while the p-value is less than 0.05 threshold
- we fail to reject the null hypothesis that states that there is independnece between the two features
- this implies that the feature relationship with head has an influence on whether there the respondent has a bank account or not
## Multivariate Analysis
We will look at the relationships between different features with 'has bank account' column
##### country, has bank account, location of respondent
```
pd.crosstab(index=[fin['country']],columns=[fin['Has a Bank account'],fin['Type of Location']],margins=True,margins_name='Total')
a=pd.crosstab(index=[fin['country']],columns=[fin['Has a Bank account'],fin['Type of Location']])
a.plot.bar()
plt.title('acsess to bank account vs location')
plt.ylabel('count')
plt.show()
```
- We can see that apart from Tanzania, most people in the rural areas had no bank accounts. In Tanzania we observe that most people in urban areas had no acess to bank services
- we can see that the number of people without bank accounts in the urban areas is more than those with bank account. this observation cuts across all the countries
- We can also see that the number of people without access to bank accounts are more in rural areas than in urban areas. This observation cuts across all the countries
- most people in rural areas have no bank accounts compared to those who have bank accounts in rural areas
##### country, type of job, has bank account, cell phone acesss and gender of respondnent
```
pd.crosstab(index=[fin['country'],fin['Type of Job']],columns=[fin['Has a Bank account'],fin['Cell Phone Access'],fin['gender_of_respondent']],margins=True,margins_name='Total')
```
- We can see that there are more males who have access to cell phones and bank accounts compared to their female counterparts
- This observation was across all types of job or income streams apart from dependent where the female population had the most bank accounts
- this can imply most females are dependnent on aid
- We can also see that there more females who have access to bank accounts but they do not have acesst o mobile phones
- this observation cuts across all countries and income streams
-In overall most females who had acess to bank services and acess to mobile phones aswell were more compared to the females who had acess to banks services but with no acess to mobile phones
- Also there were more males who had acess to bank accounts and acess to mobile phones than those who had acess to bank accounts but with no access to mobile phones
##### type of location, has a bank account, cell phone acesss
```
pd.crosstab(index=[fin['Type of Location']], columns=[fin['Has a Bank account'],fin['Cell Phone Access']],margins=True,margins_name='Total')
a=pd.crosstab(index=[fin['Type of Location']], columns=[fin['Has a Bank account'],fin['Cell Phone Access']])
plt.figure(figsize=(8,8))
a.plot.bar()
plt.title('has bank account, cell phone access')
plt.ylabel('count')
plt.show()
```
- We can see that most people in rural areas had acess to phone cells and but lacked acess to bank accounts than those in urban areas
- we can also see that the number of people who have neither bank accounts and phone cells are almost proportional in both urban and rural areas. Thos ein the rural areas are slightly more
- We can also see that there proportion of people who had access to bank accounts but no acess to cell phones were more in the urban areas
- We can also see that the number of people who had both acess to bank accounts and cell phones were more in urban areas.
##### level of education, has bank account and gender of respondent
```
pd.crosstab(index=[fin['Level of education']],columns=[fin['Has a Bank account'],fin['gender_of_respondent']],margins=True,margins_name='Total')
a=pd.crosstab(index=[fin['Level of education']],columns=[fin['Has a Bank account'],fin['gender_of_respondent']])
a.plot.bar()
plt.ylabel('count')
plt.title('bank account access and gender of respondent')
plt.show()
```
- Across all levels of education attained by respondnents, most males and females did not have acess to bank accounts
- Across all level of education, males counterparts had more bank accounts than the females
- For both males and females that only achieved primary scholl education, they did not have acess to bank services
- Most people who reached secondary school have acess to banks than the other people in the other levels of education
## Implementing the solution
- we have been able to establish that the columns that explain whether an individual has a bank account or not are the following
- - Type of Location
- - gender_of_respondent
-- Respondent Age
-- Level of education
-- Relationship with household head
-- respondent job
## Challenging the solution
- The data seams to be biased in the way that it was collected
- It would have been good if the number of respondents from the rural areas and urban areas were almost same(symetrical)
- Instead of looking at the type of employment, it would have been better if we had another column with amounts in income
- also more data was from Rwanda
- because of this, the rural areas received more weigh in the analysis. The results obtained might not really be a reflection of the reality
## Follow up questions
- In each household, howmany dependants are there( this are people who are below the age of 18 or people who can't work for other reason not including lack of job)
- of this people, who has a bank account
- and if they have, what would be the employment status or income level of the guardians
| github_jupyter |
```
# This notebook is to benchmark the model output following image distortions outlined in Extended Data Figure 3j,k,l
import os
import errno
import numpy as np
import deepcell
from deepcell_toolbox.multiplex_utils import multiplex_preprocess
# create folder for this set of experiments
experiment_folder = "image_distortion"
MODEL_DIR = os.path.join("/data/analyses", experiment_folder)
NPZ_DIR = "/data/npz_data/20201018_freeze/"
LOG_DIR = '/data/logs'
from deepcell.model_zoo.panopticnet import PanopticNet
model = PanopticNet(
backbone='resnet50',
input_shape=(256,256, 2),
norm_method=None,
num_semantic_heads=2,
num_semantic_classes=[1, 3], # inner distance, outer distance, fgbg, pixelwise
location=True, # should always be true
include_top=True,
use_imagenet=False)
from deepcell_toolbox.deep_watershed import deep_watershed_mibi
import scipy.ndimage as nd
metrics = {}
for model_split in ['1', '2', '3']:
print('analyzing split {}'.format(model_split))
weights = '/data/analyses/size_benchmarking/20201018_multiplex_seed_{}__subset_2665.h5'.format(model_split)
model.load_weights(weights)
test_dict = np.load(NPZ_DIR + "20201018_multiplex_seed_{}_test_256x256.npz".format(model_split))
X_test, y_test = test_dict['X'], test_dict['y']
tissue_list, platform_list = test_dict['tissue_list'], test_dict['platform_list']
current_dict = {}
print("smooth for loop")
for smooth_factor in np.arange(0, 5.5, 0.5):
print('smooth factor {}'.format(smooth_factor))
X_test_smooth = np.zeros_like(X_test)
for img in range(X_test.shape[0]):
for channel in [0, 1]:
X_test_smooth[img, :, :, channel] = nd.gaussian_filter(X_test[img, :, :, channel].astype('float32'),
smooth_factor)
X_test_processed = multiplex_preprocess(X_test_smooth)
print("creating predictions")
inner_distance, pixelwise = model.predict(X_test_processed)
print('postprocessing')
labeled_images = deep_watershed_mibi({'inner-distance': inner_distance[:, :, :, :],
'pixelwise-interior': pixelwise[:, :, :, 1:2]},
maxima_threshold=0.1, maxima_model_smooth=0,
interior_threshold=0.25, interior_model_smooth=2,
radius=3,
small_objects_threshold=10,
fill_holes_threshold=10)
print("calculating accuracy")
db = DatasetBenchmarker(y_true=y_test,
y_pred=labeled_images,
tissue_list=tissue_list,
platform_list=platform_list,
model_name='default_model')
tissue_stats, platform_stats = db.benchmark()
current_dict[str(smooth_factor)] = tissue_stats
metrics[model_split] = current_dict
np.savez_compressed(os.path.join(MODEL_DIR, 'blurring_metrics_triplicate.npz'), **metrics)
metrics['3']['1.0']['all']['f1']
np.savez_compressed(os.path.join(MODEL_DIR, 'blurring_metrics_triplicate.npz'), **metrics)
from deepcell_toolbox.deep_watershed import deep_watershed_mibi
from deepcell_toolbox.utils import resize
metrics = {}
for model_split in ['1', '2', '3']:
print('analyzing split {}'.format(model_split))
weights = '/data/analyses/size_benchmarking/20201018_multiplex_seed_{}__subset_2665.h5'.format(model_split)
model.load_weights(weights)
test_dict = np.load(NPZ_DIR + "20201018_multiplex_seed_{}_test_256x256.npz".format(model_split))
X_test, y_test = test_dict['X'], test_dict['y']
tissue_list, platform_list = test_dict['tissue_list'], test_dict['platform_list']
current_dict = {}
print("downsample for loop")
for downsample in np.arange(0.1, 1.1, .1):
pixel_size = int(256 * downsample)
print('downsample size {}'.format(pixel_size))
X_test_downsized = resize(X_test.astype('float32'), (pixel_size, pixel_size))
X_test_resized = resize(X_test_downsized, (256, 256))
X_test_processed = multiplex_preprocess(X_test_resized)
print("creating predictions")
inner_distance, pixelwise = model.predict(X_test_processed)
print('postprocessing')
labeled_images = deep_watershed_mibi({'inner-distance': inner_distance[:, :, :, :],
'pixelwise-interior': pixelwise[:, :, :, 1:2]},
maxima_threshold=0.1, maxima_model_smooth=0,
interior_threshold=0.25, interior_model_smooth=2,
radius=3,
small_objects_threshold=10,
fill_holes_threshold=10)
print("calculating accuracy")
db = DatasetBenchmarker(y_true=y_test,
y_pred=labeled_images,
tissue_list=tissue_list,
platform_list=platform_list,
model_name='default_model')
tissue_stats, platform_stats = db.benchmark()
current_dict[str(downsample)] = tissue_stats
metrics[model_split] = current_dict
np.savez_compressed(os.path.join(MODEL_DIR, 'resize_metrics_triplicate.npz'), **metrics)
np.savez_compressed(os.path.join(MODEL_DIR, 'resize_metrics.npz'), **metrics)
from deepcell_toolbox.deep_watershed import deep_watershed_mibi
metrics = {}
for model_split in ['1', '2', '3']:
print('analyzing split {}'.format(model_split))
weights = '/data/analyses/size_benchmarking/20201018_multiplex_seed_{}__subset_2665.h5'.format(model_split)
model.load_weights(weights)
test_dict = np.load(NPZ_DIR + "20201018_multiplex_seed_{}_test_256x256.npz".format(model_split))
X_test, y_test = test_dict['X'], test_dict['y']
tissue_list, platform_list = test_dict['tissue_list'], test_dict['platform_list']
current_dict = {}
print("smooth for loop")
for noise_max in np.arange(0, 0.2, .02):
noise = np.random.rand(X_test.shape[0], 256, 256, 2)
noise = noise * noise_max
print('noise_amount {}'.format(noise_max))
X_test_combined = X_test + noise
X_test_processed = multiplex_preprocess(X_test_combined)
print("creating predictions")
inner_distance, pixelwise = model.predict(X_test_processed)
print('postprocessing')
labeled_images = deep_watershed_mibi({'inner-distance': inner_distance[:, :, :, :],
'pixelwise-interior': pixelwise[:, :, :, 1:2]},
maxima_threshold=0.1, maxima_model_smooth=0,
interior_threshold=0.25, interior_model_smooth=2,
radius=3,
small_objects_threshold=10,
fill_holes_threshold=10)
print("calculating accuracy")
db = DatasetBenchmarker(y_true=y_test,
y_pred=labeled_images,
tissue_list=tissue_list,
platform_list=platform_list,
model_name='default_model')
tissue_stats, platform_stats = db.benchmark()
current_dict[str(noise_max)] = tissue_stats
metrics[model_split] = current_dict
np.savez_compressed(os.path.join(MODEL_DIR, 'noise_metrics_triplicate.npz'), **metrics)
metrics['0.18']['all']['f1']
np.savez_compressed(os.path.join(MODEL_DIR, 'noise_metrics.npz'), **metrics)
# Copyright 2016-2020 The Van Valen Lab at the California Institute of
# Technology (Caltech), with support from the Paul Allen Family Foundation,
# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.
# All rights reserved.
#
# Licensed under a modified Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.github.com/vanvalenlab/caliban-toolbox/LICENSE
#
# The Work provided may be used for non-commercial academic purposes only.
# For any other use of the Work, including commercial use, please contact:
# vanvalenlab@gmail.com
#
# Neither the name of Caltech nor the names of its contributors may be used
# to endorse or promote products derived from this software without specific
# prior written permission.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import numpy as np
from deepcell_toolbox.metrics import Metrics, stats_pixelbased
from scipy.stats import hmean
class DatasetBenchmarker(object):
"""Class to perform benchmarking across different tissue and platform types
Args:
y_true: true labels
y_pred: predicted labels
tissue_list: list of tissue names for each image
platform_list: list of platform names for each image
model_name: name of the model used to generate the predictions
metrics_kwargs: arguments to be passed to metrics package
Raises:
ValueError: if y_true and y_pred have different shapes
ValueError: if y_true and y_pred are not 4D
ValueError: if tissue_ids or platform_ids is not same length as labels
"""
def __init__(self,
y_true,
y_pred,
tissue_list,
platform_list,
model_name,
metrics_kwargs={}):
if y_true.shape != y_pred.shape:
raise ValueError('Shape mismatch: y_true has shape {}, '
'y_pred has shape {}. Labels must have the same'
'shape.'.format(y_true.shape, y_pred.shape))
if len(y_true.shape) != 4:
raise ValueError('Data must be 4D, supplied data is {}'.format(y_true.shape))
self.y_true = y_true
self.y_pred = y_pred
if len({y_true.shape[0], len(tissue_list), len(platform_list)}) != 1:
raise ValueError('Tissue_list and platform_list must have same length as labels')
self.tissue_list = tissue_list
self.platform_list = platform_list
self.model_name = model_name
self.metrics = Metrics(model_name, **metrics_kwargs)
def _benchmark_category(self, category_ids):
"""Compute benchmark stats over the different categories in supplied list
Args:
category_ids: list specifying which category each image belongs to
Returns:
stats_dict: dictionary of benchmarking results
"""
unique_ids = np.unique(category_ids)
# create dict to hold stats across each category
stats_dict = {}
for uid in unique_ids:
print("uid is {}".format(uid))
stats_dict[uid] = {}
category_idx = np.isin(category_ids, uid)
# sum metrics across individual images
for key in self.metrics.stats:
stats_dict[uid][key] = self.metrics.stats[key][category_idx].sum()
# compute additional metrics not produced by Metrics class
stats_dict[uid]['recall'] = \
stats_dict[uid]['correct_detections'] / stats_dict[uid]['n_true']
stats_dict[uid]['precision'] = \
stats_dict[uid]['correct_detections'] / stats_dict[uid]['n_pred']
stats_dict[uid]['f1'] = \
hmean([stats_dict[uid]['recall'], stats_dict[uid]['precision']])
pixel_stats = stats_pixelbased(self.y_true[category_idx] != 0,
self.y_pred[category_idx] != 0)
stats_dict[uid]['jaccard'] = pixel_stats['jaccard']
return stats_dict
def benchmark(self):
self.metrics.calc_object_stats(self.y_true, self.y_pred)
tissue_stats = self._benchmark_category(category_ids=self.tissue_list)
platform_stats = self._benchmark_category(category_ids=self.platform_list)
all_stats = self._benchmark_category(category_ids=['all'] * len(self.tissue_list))
tissue_stats['all'] = all_stats['all']
platform_stats['all'] = all_stats['all']
return tissue_stats, platform_stats
from skimage.exposure import rescale_intensity
from skimage.segmentation import find_boundaries
import copy
def make_color_overlay(input_data):
"""Create a color overlay from 2 channel image data
Args:
input_data: stack of input images
Returns:
numpy.array: color-adjusted stack of overlays in RGB mode
"""
RGB_data = np.zeros(input_data.shape[:3] + (3, ), dtype='float32')
# rescale channels to aid plotting
for img in range(input_data.shape[0]):
for channel in range(input_data.shape[-1]):
# get histogram for non-zero pixels
percentiles = np.percentile(input_data[img, :, :, channel][input_data[img, :, :, channel] > 0],
[5, 95])
rescaled_intensity = rescale_intensity(input_data[img, :, :, channel],
in_range=(percentiles[0], percentiles[1]),
out_range='float32')
RGB_data[img, :, :, channel + 1] = rescaled_intensity
# create a blank array for red channel
return RGB_data
def make_outline_overlay(RGB_data, predictions):
boundaries = np.zeros_like(predictions)
overlay_data = copy.copy(RGB_data)
for img in range(predictions.shape[0]):
boundary = find_boundaries(predictions[img], connectivity=1, mode='inner')
boundaries[img, boundary > 0] = 1
overlay_data[boundaries > 0, :] = 1
return overlay_data
```
| github_jupyter |
```
!apt-get install wget
!apt-get install tar
!apt-get install openjdk-8-jdk-headless -qq > /dev/null
!wget -q https://archive.apache.org/dist/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz
!tar xf spark-2.4.4-bin-hadoop2.7.tgz
!pip install h2o
!pip install findspark
!pip install pyarrow
!pip install pandas
!pip install numpy
import subprocess
cmd0 = "cat $HOME/.bashrc > mylog.txt "
returned_value0 = subprocess.call(cmd0, shell=True)
print("returned value:", returned_value0)
import subprocess
cmd1 = "echo 'export PATH=/tf/notebooks_h2o/spark-2.4.4-bin-hadoop2.7/bin:$PATH' >> $HOME/.bashrc "
returned_value1 = subprocess.call(cmd1, shell=True)
print("returned value1:", returned_value1)
import subprocess
cmd2 = "echo 'export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64' >> $HOME/.bashrc "
returned_value2 = subprocess.call(cmd2, shell=True)
print("returned value2:", returned_value2)
import subprocess
cmd3 = " echo 'export SPARK_HOME=/tf/notebooks_h2o/spark-2.4.4-bin-hadoop2.7' >> $HOME/.bashrc "
returned_value3 = subprocess.call(cmd3, shell=True)
print("returned value3:", returned_value3)
import subprocess
cmd4 = " echo 'export HADOOP_HOME=$SPARK_HOME' >> $HOME/.bashrc "
returned_value4 = subprocess.call(cmd4, shell=True)
print("returned value4:", returned_value4)
import subprocess
cmd5 = "echo 'export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64' >> $HOME/.bashrc "
returned_value5 = subprocess.call(cmd5, shell=True)
print("returned value5:", returned_value5)
import subprocess
cmd6 = " echo 'export PYSPARK_DRIVER_PYTHON=jupyter' >> $HOME/.bashrc "
returned_value6 = subprocess.call(cmd6, shell=True)
print("returned value5:", returned_value6)
import subprocess
cmd7 = " echo 'export PYSPARK_DRIVER_PYTHON_OPTS=notebook' >> $HOME/.bashrc "
returned_value7 = subprocess.call(cmd7, shell=True)
print("returned value7:", returned_value7)
import subprocess
cmd8 = " echo 'export PYSPARK_PYTHON=/usr/bin/python3' >> $HOME/.bashrc "
returned_value8 = subprocess.call(cmd8, shell=True)
print("returned value8:", returned_value8)
import subprocess
cmd9 = " echo 'export PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/build:$PYTHONPATH' >> $HOME/.bashrc "
returned_value9 = subprocess.call(cmd9, shell=True)
print("returned value9:", returned_value9)
import subprocess
cmd10 = " echo 'export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.10.7-src.zip:$PYTHONPATH' >> $HOME/.bashrc "
returned_value10 = subprocess.call(cmd10, shell=True)
print("returned value10:", returned_value10)
import subprocess
cmd11 = " echo 'export SPARK_LOCAL_IP=0.0.0.0' >> $HOME/.bashrc "
returned_value11 = subprocess.call(cmd11, shell=True)
print("returned value11:", returned_value11)
import subprocess
cmd12 = " echo 'export PACKAGES=\"io.delta:delta-core_2.11:0.3.0\"' >> $HOME/.bashrc "
returned_value12 = subprocess.call(cmd12, shell=True)
print("returned value12:", returned_value12)
import subprocess
cmd13 = " echo 'export PYSPARK_SUBMIT_ARGS=\"--packages ${PACKAGES} pyspark-shell\"' >> $HOME/.bashrc "
returned_value13 = subprocess.call(cmd13, shell=True)
print("returned value13:", returned_value13)
import subprocess
cmds1 = " source $HOME/.bashrc | echo done"
returned_value_s1 = subprocess.call(cmds1, shell=True)
print("returned value_s1:", returned_value_s1)
import subprocess
cmd0 = "cat $HOME/.bashrc >> mylog.txt "
returned_value0 = subprocess.call(cmd0, shell=True)
print("returned value0:", returned_value0)
import h2o
h2o.init()
exit()
import subprocess
cmd0 = " echo ' ${HOME} ' >> mylog.txt "
returned_value0 = subprocess.call(cmd0, shell=True)
print("returned value0:", returned_value0)
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.