code stringlengths 2.5k 150k | kind stringclasses 1 value |
|---|---|
# Dataframe basics
### Dr. Tirthajyoti Sarkar, Fremont, CA 94536
### Apache Spark
Apache Spark is one of the hottest new trends in the technology domain. It is the framework with probably the highest potential to realize the fruit of the marriage between Big Data and Machine Learning. It runs fast (up to 100x faster than traditional Hadoop MapReduce) due to in-memory operation, offers robust, distributed, fault-tolerant data objects (called RDD), and inte-grates beautifully with the world of machine learning and graph analytics through supplementary
packages like Mlib and GraphX.
Spark is implemented on Hadoop/HDFS and written mostly in Scala, a functional programming language, similar to Java. In fact, Scala needs the latest Java installation on your system and runs on JVM. However, for most of the beginners, Scala is not a language that they learn first to venture into the world of data science. Fortunately, Spark provides a wonderful Python integration, called PySpark, which lets Python programmers to interface with the Spark framework and
learn how to manipulate data at scale and work with objects and algorithms over a distributed file system.
### Dataframe
In Apache Spark, a DataFrame is a distributed collection of rows under named columns. It is conceptually equivalent to a table in a relational database, an Excel sheet with Column headers, or a data frame in R/Python, but with richer optimizations under the hood. DataFrames can be constructed from a wide array of sources such as: structured data files, tables in Hive, external databases, or existing RDDs. It also shares some common characteristics with RDD:
* Immutable in nature : We can create DataFrame / RDD once but can’t change it. And we can transform a DataFrame / RDD after applying transformations.
* Lazy Evaluations: Which means that a task is not executed until an action is performed.
* Distributed: RDD and DataFrame both are distributed in nature.
### Advantages of the DataFrame
* DataFrames are designed for processing large collection of structured or semi-structured data.
* Observations in Spark DataFrame are organised under named columns, which helps Apache Spark to understand the schema of a DataFrame. This helps Spark optimize execution plan on these queries.
* DataFrame in Apache Spark has the ability to handle petabytes of data.
* DataFrame has a support for wide range of data format and sources.
* It has API support for different languages like Python, R, Scala, Java.
```
import pyspark
from pyspark import SparkContext as sc
```
### Create a `SparkSession` app object
```
from pyspark.sql import SparkSession
spark1 = SparkSession.builder.appName('Basics').getOrCreate()
```
### Read in a JSON file and examine the data
```
df = spark1.read.json('Data/people.json')
```
#### Unlike Pandas DataFrame, it does not show itself when called
Instead, it just shows the Data types of the columns
```
df
```
#### You have to call show() method to evaluate it i.e. show it
```
df.show()
```
### The data schema
Use `printSchema()` to show he schema of the data. Note, how tightly it is integrated to the SQL-like framework. You can even see that the schema accepts `null` values because nullable property is set `True`.
```
df.printSchema()
```
#### Fortunately a simple `columns` method exists to get column names back as a Python list
```
df.columns
```
### The `describe` and `summary` methods
Similar to Pandas, the `describe` method is used for the statistical summary. But unlike Pandas, calling only `describe()` returns a DataFrame! This is due to the **[lazy evaluation](https://data-flair.training/blogs/apache-spark-lazy-evaluation/)** - the actual computation is delayed as much as possible.
```
df.describe()
```
#### We have to call `show` again
```
df.describe().show()
```
#### There is `summary` method for more stats
```
df.summary().show()
```
### The `take` and `collect` methods to read/collect rows
These methods return some or all rows as a Python list.
```
df.take(2)
df.collect()
```
### Defining your own Data Schema
Import data types and structure types to build the data schema yourself
```
from pyspark.sql.types import StructField, IntegerType, StringType, StructType
```
Define your data schema by supplying name and data types to the structure fields you will be importing. It will be a simple Python list of `StructField` objects. You have to use Spark data types like `IntegerType` and `StringType`.
```
data_schema = [StructField('age',IntegerType(),True),
StructField('name',StringType(),True)]
```
Now create a `StrucType` object called `final_struc` with this schema as field
```
final_struc = StructType(fields=data_schema)
```
Now read in the same old JSON with this new schema `final_struc`
```
df = spark1.read.json('Data/people.json',schema=final_struc)
df.show()
```
Now when you print the schema, **you will see that the `age` is read as `int` and not `long`**. By default Spark could not figure out for this column the exact data type that you wanted, so it went with `long`. But this is how you can build your own schema and instruct Spark to read the data accoridngly.
| github_jupyter |
```
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math
%matplotlib inline
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')
import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines, color=[255, 0, 0], thickness=10):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=0.8, β=1., γ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + γ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, γ)
import os
imgs = os.listdir("test_images/")
imgNum = len(imgs)
print(imgNum)
# TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images_output directory.
for File in imgs:
img = mpimg.imread('test_images/solidWhiteRight.jpg')
# Grab the x and y size and make a copy of the image
ysize = image.shape[0]
xsize = image.shape[1]
color_select = np.copy(image)
line_image = np.copy(image)
# Define color selection criteria
# MODIFY THESE VARIABLES TO MAKE YOUR COLOR SELECTION
red_threshold = 200
green_threshold = 200
blue_threshold = 200
rgb_threshold = [red_threshold, green_threshold, blue_threshold]
# Define the vertices of a triangular mask.
# Keep in mind the origin (x=0, y=0) is in the upper left
# MODIFY THESE VALUES TO ISOLATE THE REGION
# WHERE THE LANE LINES ARE IN THE IMAGE
left_bottom = [0, 539]
right_bottom = [950, 539]
apex = [480, 300]
# Perform a linear fit (y=Ax+B) to each of the three sides of the triangle
# np.polyfit returns the coefficients [A, B] of the fit
fit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)
fit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)
fit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)
# Mask pixels below the threshold
color_thresholds = (image[:,:,0] < rgb_threshold[0]) | \
(image[:,:,1] < rgb_threshold[1]) | \
(image[:,:,2] < rgb_threshold[2])
# Find the region inside the lines
XX, YY = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize))
region_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & \
(YY > (XX*fit_right[0] + fit_right[1])) & \
(YY < (XX*fit_bottom[0] + fit_bottom[1]))
# Mask color and region selection
color_select[color_thresholds | ~region_thresholds] = [0, 0, 0]
# Color pixels red where both color and region selections met
line_image[~color_thresholds & region_thresholds] = [255, 0, 0]
# Display the image and show region and color selections
plt.imshow(image)
x = [left_bottom[0], right_bottom[0], apex[0], left_bottom[0]]
y = [left_bottom[1], right_bottom[1], apex[1], left_bottom[1]]
plt.plot(x, y, 'b--', lw=4)
plt.imshow(color_select)
plt.imshow(line_image)
for File in imgs:
img = mpimg.imread('test_images/' + File)
imgray = grayscale(img)
imblur = gaussian_blur(imgray, 15)
edges = canny(imgray, 50, 150)
# This time we are defining a four sided polygon to mask
imshape = img.shape
vertices = np.array([[(0,imshape[0]),(480, 300), (490, 300), (imshape[1], imshape[0]), (imshape[1],imshape[0])]], dtype=np.int32)
masked_edges = region_of_interest(edges, vertices)
plt.imshow(masked_edges)
rho = 2 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 90 # minimum number of votes (intersections in Hough grid cell)
min_line_len = 40 #minimum number of pixels making up a line
max_line_gap = 20 # maximum gap in pixels between connectable line segments
line_img = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap)
# Create a "color" binary image to combine with line image
color_edges = np.dstack((edges, edges, edges))
# Draw the lines on the edge image
lines_edges = cv2.addWeighted(img, 0.8, line_img, 1, 0)
# plt.imshow(lines_edges)
# cv2.imwrite(os.path.join('output_images/') + File, lines_edges)
# plt.imshow(line_img ,cmap='gray')
```
| github_jupyter |
## Driver code for training models to learn pipeline 1 x pipeline 2 transform maps
- Note: currently using output after atlas-based grouping
- Atlas used: aparc (Freesurfer) DKT-31 Mindboggle (ANTs: https://mindboggle.readthedocs.io/en/latest/labels.html)
```
import sys
import numpy as np
import pandas as pd
import itertools
import seaborn as sns
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.manifold import TSNE
sys.path.append('../lib')
from data_handling import *
from data_stats import *
from deeplearning import *
```
### Data paths
```
proj_dir = '/home/nikhil/projects/CT_reproduce/code/compare-surf-tools/'
#proj_dir = '/Users/nikhil/projects/compare-surf-tools/'
data_dir = proj_dir + 'data/'
fs60_dir = data_dir + 'fs60_group_stats/'
qc_dir = '/home/nikhil/projects/CT_reproduce/data/QC/'
results_dir = data_dir + 'results/'
demograph_file = 'ABIDE_Phenotype.csv'
dkt_roi_names = 'DKT_parcel_map_FS_CIVET.csv'
ants_file = 'ABIDE_ants_thickness_data.csv' #uses modified (mindboggle) dkt atlas with 31 ROIs
civet_file = 'ABIDE_civet2.1_thickness_test1.csv'
fs53_file = 'ABIDE_fs5.3_thickness.csv'
fs51_file = 'cortical_fs5.1_measuresenigma_thickavg.csv'
fs60_lh_file = 'lh.aparc.thickness.table.test1' #'aparc_lh_thickness_table.txt' #'lh.aparc.thickness.table.test1'
fs60_rh_file = 'rh.aparc.thickness.table.test1' #'aparc_rh_thickness_table.txt' #'rh.aparc.thickness.table.test1'
```
### Global Vars
```
subject_ID_col = 'SubjID'
```
### Load data
```
# Demographics and Dx
demograph = pd.read_csv(data_dir + demograph_file)
demograph = demograph.rename(columns={'Subject_ID':subject_ID_col})
# ROI names
dkt_roi_map = pd.read_csv(data_dir + dkt_roi_names)
# CIVET 2.1
civet_data = pd.read_csv(data_dir + civet_file, dtype={subject_ID_col: str})
print('shape of civet data {}'.format(civet_data.shape))
civet_data_std = standardize_civet_data(civet_data, subject_ID_col, dkt_roi_map)
print('shape of stdized civet data {}'.format(civet_data_std.shape))
print('')
# ANTs
ants_data = pd.read_csv(data_dir + ants_file, header=2)
print('shape of ants data {}'.format(ants_data.shape))
ants_data_std = standardize_ants_data(ants_data, subject_ID_col)
print('shape of stdized ants data {}'.format(ants_data_std.shape))
print('')
# FS
fs53_data = pd.read_csv(data_dir + fs53_file)
print('shape of fs53 data {}'.format(fs53_data.shape))
fs53_data_std = standardize_fs_data(fs53_data, subject_ID_col)
print('shape of stdized fs53 data {}'.format(fs53_data_std.shape))
print('')
fs51_data = pd.read_csv(data_dir + fs51_file)
print('shape of fs51 data {}'.format(fs51_data.shape))
fs51_data_std = standardize_fs_data(fs51_data, subject_ID_col)
print('shape of stdized fs51 data {}'.format(fs51_data_std.shape))
print('')
fs60_lh_data = pd.read_csv(fs60_dir + fs60_lh_file, delim_whitespace=True)
fs60_rh_data = pd.read_csv(fs60_dir + fs60_rh_file, delim_whitespace=True)
print('shape of fs60 data l: {}, r: {}'.format(fs60_lh_data.shape,fs60_rh_data.shape))
fs60_data_std = standardize_fs60_data(fs60_lh_data, fs60_rh_data, subject_ID_col)
print('shape of stdized fs60 data {}'.format(fs60_data_std.shape))
```
### Create master dataframe
```
data_dict = {'civet': civet_data_std,
'fs60' : fs51_data_std}
na_action = 'drop' # options: ignore, drop; anything else will not use the dataframe for analysis.
master_df_raw, common_subs, common_roi_cols = combine_processed_data(data_dict, subject_ID_col, na_action)
# Add demographic columns to the master_df_raw
useful_demograph = demograph[[subject_ID_col,'SEX','AGE_AT_SCAN','DX_GROUP','SITE_ID']].copy()
# DX_GROUP: (orginal: 1:ASD, 2:Controls, after shift 0:ASD, 1:Controls)
# Shift to (0 and 1 instead of 1 and 2 for statsmodels)
useful_demograph['DX_GROUP'] = useful_demograph['DX_GROUP']-1
useful_demograph['SEX'] = useful_demograph['SEX']-1
_,useful_demograph[subject_ID_col] = useful_demograph[subject_ID_col].str.rsplit('_', 1).str
master_df_raw = pd.merge(master_df_raw, useful_demograph, how='left', on=subject_ID_col)
print('\nmaster df shape after adding demographic info {}'.format(master_df_raw.shape))
print('\nNumber of common subjects {}({}), ROIs {}'.format(len(common_subs), master_df_raw[master_df_raw['pipeline']=='fs60']['DX_GROUP'].value_counts().to_dict(),len(common_roi_cols)))
```
### QC filters
- Manual (Gleb or Maarten)
- Automatic (Amadou)
```
qc_type = 'maarten' #condition: master_df['QC_maarten']==0, master_df['QC_gleb'].isin['1','-+1']
if qc_type in ['maarten','gleb']:
qc_df = pd.read_csv(qc_dir + 'master_QC_table.csv',dtype={'SubjID': str})
master_df = pd.merge(master_df_raw, qc_df, how='left', on=subject_ID_col)
master_df = master_df[master_df['QC_maarten']==0]
print('Filtering based on {} QC. Resultant number of subjects {} ({}) (out of {})'.format(qc_type,len(master_df[subject_ID_col].unique()),master_df[master_df['pipeline']=='fs60']['DX_GROUP'].value_counts().to_dict(),len(common_subs)))
common_subs = master_df[subject_ID_col].unique()
else:
master_df = master_df_raw
print('No QC performed. master_df shape {}'.format(len(master_df[subject_ID_col].unique())))
```
### Create CV folds
```
n_splits = 1
test_size = 0.2
input_pipe = 'fs60'
output_pipe = 'civet'
ml_demograph = master_df[master_df['pipeline']=='fs60'][[subject_ID_col,'DX_GROUP','SEX','SITE_ID']]
X = master_df[master_df['pipeline']==input_pipe][[subject_ID_col] + common_roi_cols]
Y = master_df[master_df['pipeline']==output_pipe][[subject_ID_col] + common_roi_cols]
subject_idx = ml_demograph[subject_ID_col]
dx = ml_demograph['DX_GROUP']
print('Shape X {}, Y {}'.format(X.shape, Y.shape))
print('Shape subject_ids {}, dx {}'.format(subject_idx.shape, dx.shape))
# Use subject_ids for indexing to maintain correspondance between X and Y
# Use dx for stratification
sss = StratifiedShuffleSplit(n_splits=n_splits, test_size=test_size, random_state=0)
cv_list = []
for train_index, test_index in sss.split(subject_idx, dx):
subject_idx_train = subject_idx[train_index]
subject_idx_test = subject_idx[test_index]
X_train, X_test = X[X[subject_ID_col].isin(subject_idx_train)], X[X[subject_ID_col].isin(subject_idx_test)]
Y_train, Y_test = Y[Y[subject_ID_col].isin(subject_idx_train)], Y[Y[subject_ID_col].isin(subject_idx_test)]
cv_list.append((X_train,X_test,Y_train,Y_test))
print('')
print('Train Shapes X {}, Y {}'.format(X_train.shape, Y_train.shape))
print('Test Shapes X {}, Y {}'.format(X_test.shape, Y_test.shape))
print('\n number of CV folds {}'.format(len(cv_list)))
```
### Train model
```
# training params
lr = 0.001
n_epochs = 100
validate_after = 10
batch_size = 20
dropout = 1 #keep_prob
verbose = False # Do you want to print perf after every epoch??
save_model = False
save_model_path = './'
net_arch = {'input':62,'n_layers':4,'l1':10,'l2':10,'l3':10,'l4':10,'l5':10,'output':62,
'reg':0.1, 'loss_type':'corr'}
test_err_melt_concat = pd.DataFrame()
for fold in range(len(cv_list)):
print('\nStarting fold {}'.format(fold))
X_train,X_test,Y_train,Y_test = cv_list[fold]
tf.reset_default_graph()
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
# Train model
data = {'X':X_train[common_roi_cols].values,'y':Y_train[common_roi_cols].values}
simple_ae = pipeline_AE(net_arch)
optimizer = tf.train.AdamOptimizer(learning_rate = lr).minimize(simple_ae.loss)
tf.global_variables_initializer().run()
saver = tf.train.Saver()
cur_time = datetime.time(datetime.now())
print('\nStart training time: {}'.format(cur_time))
simple_ae, train_metrics = train_network(sess, simple_ae, data, optimizer, n_epochs,
batch_size, dropout,validate_after,verbose)
#Save trained model
if save_model:
print('saving model at {}'.format(save_model_path + 'simple_ae_example'))
saver.save(sess, save_model_path + 'simple_ae_example')
cur_time = datetime.time(datetime.now())
print('End training time: {}\n'.format(cur_time))
# Test model
print('Test perf')
data = {'X':X_test[common_roi_cols].values,'y':Y_test[common_roi_cols].values}
_,test_metrics = test_network(sess,simple_ae,data)
# Null Test: create fake output from output itself
# (Should be worse than actual performance)
print( '\nNull test perf')
data = {'X':Y_test[common_roi_cols].values,'y':Y_test[common_roi_cols].values}
_,test_metrics_null = test_network(sess,simple_ae,data)
# populate perf dataframe
test_err = pd.DataFrame()
test_err[subject_ID_col] = Y_test[subject_ID_col]
test_err[common_roi_cols] = Y_test[common_roi_cols] - test_metrics['test_preds']
test_err_melt = pd.melt(test_err, id_vars =[subject_ID_col], value_vars =common_roi_cols,
var_name ='ROI', value_name ='err')
test_err_melt['fold'] = np.tile(fold,len(test_err_melt))
test_err_melt['model'] = np.tile('real',len(test_err_melt))
test_err_melt_concat = test_err_melt_concat.append(test_err_melt)
# Null test
test_err_null = pd.DataFrame()
test_err_null[subject_ID_col] = Y_test[subject_ID_col]
test_err_null[common_roi_cols] = Y_test[common_roi_cols] - test_metrics_null['test_preds']
test_err_null_melt = pd.melt(test_err_null, id_vars=[subject_ID_col], value_vars=common_roi_cols,
var_name ='ROI', value_name ='err')
test_err_null_melt['fold'] = np.tile(fold,len(test_err_null_melt))
test_err_null_melt['model'] = np.tile('null',len(test_err_null_melt))
# Append to the same dataframe since subject IDs are the same
test_err_melt_concat = test_err_melt_concat.append(test_err_null_melt)
print('\nEnding fold {}'.format(fold))
train_loss = train_metrics['train_loss']
valid_loss = train_metrics['valid_loss']
test_loss = test_metrics['test_loss']
plt.figure(figsize=(10,5))
plt.style.use('seaborn-white')
sns.set(font_scale=1)
plt.plot(train_loss,label='train');
plt.plot(valid_loss,label='valid');
plt.plot(np.tile(test_loss,len(train_loss)),label='test');
plt.title('Loss')
plt.xlabel('number of epoch x{}'.format(validate_after))
plt.legend()
```
### Test Perf: MSE and Correlations between pipelines
```
# Before and after prediction
df1 = X_test
df2 = Y_test
df3 = pd.DataFrame(columns=common_roi_cols,data=test_metrics['test_preds'])
df3[subject_ID_col] = df1[subject_ID_col].values
df4 = pd.DataFrame(columns=common_roi_cols,data=test_metrics_null['test_preds'])
df4[subject_ID_col] = df1[subject_ID_col].values
pipeline_err = pd.DataFrame(columns=[subject_ID_col]+common_roi_cols)
model_err_null = pd.DataFrame(columns=[subject_ID_col]+common_roi_cols)
model_err = pd.DataFrame(columns=[subject_ID_col]+common_roi_cols)
pipeline_err[subject_ID_col] = df1[subject_ID_col].values
pipeline_err[common_roi_cols] = (df1[common_roi_cols].values - df2[common_roi_cols].values)**2
model_err[subject_ID_col] = df1[subject_ID_col].values
model_err[common_roi_cols] = (df3[common_roi_cols].values - df2[common_roi_cols].values)**2
model_err_null[subject_ID_col] = df1[subject_ID_col].values
model_err_null[common_roi_cols] = (df4[common_roi_cols].values - df2[common_roi_cols].values)**2
#MSE
print('pipeline 1 vs pipeline 2 MSE: {:4.2f}'.format(pipeline_err[common_roi_cols].values.mean()))
print('null model predictions vs pipeline 2 MSE: {:4.2f}'.format(model_err_null[common_roi_cols].values.mean()))
print('model predictions vs pipeline 2 MSE: {:4.2f}'.format(model_err[common_roi_cols].values.mean()))
#Corr
pipeline_xcorr_df = cross_correlations(df1,df2,subject_ID_col)
pipeline_xcorr_df['pair'] = np.tile('{} (orig),{}'.format(input_pipe,output_pipe),len(pipeline_xcorr_df))
print('pipeline 1 vs pipeline 2 correlation: {:4.2f}'.format(pipeline_xcorr_df['correlation'].mean()))
model_null_xcorr_df = cross_correlations(df4,df2,subject_ID_col)
model_null_xcorr_df['pair'] = np.tile('{}_pred (null),{}'.format(output_pipe,output_pipe),len(model_null_xcorr_df))
print('null model predictions vs pipeline 2 correlation: {:4.2f}'.format(model_null_xcorr_df['correlation'].mean()))
model_xcorr_df = cross_correlations(df3,df2,subject_ID_col)
model_xcorr_df['pair'] = np.tile('{}_pred (real),{}'.format(input_pipe,output_pipe),len(model_xcorr_df))
print('model predictions vs pipeline 2 correlation: {:4.2f}'.format(model_xcorr_df['correlation'].mean()))
xcorr_df_concat = pipeline_xcorr_df.append(model_null_xcorr_df).append(model_xcorr_df)
```
### Pearson's correlation (Test subset)
```
sns.set(font_scale=1)
with sns.axes_style("whitegrid"):
g = sns.catplot(x='correlation',y='ROI',hue='pair',order=common_roi_cols,
data=xcorr_df_concat,aspect=0.75,height=10,kind='strip')
```
### MSE distribution (Test subset)
```
plot_df = test_err_melt_concat
sns.set(font_scale=1)
with sns.axes_style("whitegrid"):
g = sns.catplot(x='err',y='ROI',order=common_roi_cols,col='model',
data=plot_df,aspect=0.75,height=10,kind='violin')
```
### TSNE
```
preds = train_metrics['train_preds']
tsne_embed = TSNE(n_components=2,init='pca').fit_transform(preds)
tsne_annot = ml_demograph[ml_demograph[subject_ID_col].isin(subject_idx_train)]['DX_GROUP'].values
plot_df = pd.DataFrame(columns=['x','y','annot','subset'])
plot_df['x'] = tsne_embed[:,0]
plot_df['y'] = tsne_embed[:,1]
plot_df['annot'] = tsne_annot
plot_df['subset'] = np.tile('train',len(tsne_annot))
with sns.axes_style("whitegrid"):
g = sns.lmplot(x='x',y='y',hue='annot',fit_reg=False, markers='o',data=plot_df,
height=6,scatter_kws={'alpha':0.5}); #x_jitter=20,y_jitter=20,
```
| github_jupyter |
# 基于 BipartiteGraphSage 的二部图无监督学习
二部图是电子商务推荐场景中很常见的一种图,GraphScope提供了针对二部图处理学习任务的模型。本次教程,我们将会展示GraphScope如何使用BipartiteGraphSage算法在二部图上训练一个无监督学习模型。
本次教程的学习任务是链接预测,通过计算在图中用户顶点和商品顶点之间存在边的概率来预测链接。
在这一任务中,我们使用GraphScope内置的BipartiteGraphSage算法在 [U2I](http://graph-learn-dataset.oss-cn-zhangjiakou.aliyuncs.com/u2i.zip) 数据集上训练一个模型,这一训练模型可以用来预测用户顶点和商品顶点之间的链接。这一任务可以被看作在一个异构链接网络上的无监督训练任务。
在这一任务中,BipartiteGraphSage算法会将图中的结构信息和属性信息压缩为每个节点上的低维嵌入向量,这些嵌入和表征可以进一步用来预测节点间的链接。
这一教程将会分为以下几个步骤:
- 启动GraphScope的学习引擎,并将图关联到引擎上
- 使用内置的GCN模型定义训练过程,并定义相关的超参
- 开始训练
```
# Install graphscope package if you are NOT in the Playground
!pip3 install graphscope
!pip3 uninstall -y importlib_metadata # Address an module conflict issue on colab.google. Remove this line if you are not on colab.
# Import the graphscope module.
import graphscope
graphscope.set_option(show_log=False) # enable logging
# Load u2i dataset
from graphscope.dataset import load_u2i
graph = load_u2i()
```
## Launch learning engine
然后,我们需要定义一个特征列表用于图的训练。训练特征集合必须从点的属性集合中选取。在这个例子中,我们选择了 "feature" 属性作为训练特征集,这一特征集也是 U2I 数据中用户顶点和商品顶点的特征集。
借助定义的特征列表,接下来,我们使用 [graphlearn](https://graphscope.io/docs/reference/session.html#graphscope.Session.graphlearn) 方法来开启一个学习引擎。
在这个例子中,我们在 "graphlearn" 方法中,指定在数据中 "u" 类型的顶点和 "i" 类型顶点和 "u-i" 类型边上进行模型训练。
```
# launch a learning engine.
lg = graphscope.graphlearn(
graph,
nodes=[("u", ["feature"]), ("i", ["feature"])],
edges=[(("u", "u-i", "i"), ["weight"]), (("i", "u-i_reverse", "u"), ["weight"])],
)
```
这里我们使用内置的`BipartiteGraphSage`模型定义训练过程。你可以在 [Graph Learning Model](https://graphscope.io/docs/learning_engine.html#data-model) 获取更多内置学习模型的信息。
在本次示例中,我们使用 tensorflow 作为神经网络后端训练器。
```
import numpy as np
import tensorflow as tf
import graphscope.learning
from graphscope.learning.examples import BipartiteGraphSage
from graphscope.learning.graphlearn.python.model.tf.optimizer import get_tf_optimizer
from graphscope.learning.graphlearn.python.model.tf.trainer import LocalTFTrainer
# Unsupervised GraphSage.
def train(config, graph):
def model_fn():
return BipartiteGraphSage(
graph,
config["batch_size"],
config["hidden_dim"],
config["output_dim"],
config["hops_num"],
config["u_neighs_num"],
config["i_neighs_num"],
u_features_num=config["u_features_num"],
u_categorical_attrs_desc=config["u_categorical_attrs_desc"],
i_features_num=config["i_features_num"],
i_categorical_attrs_desc=config["i_categorical_attrs_desc"],
neg_num=config["neg_num"],
use_input_bn=config["use_input_bn"],
act=config["act"],
agg_type=config["agg_type"],
need_dense=config["need_dense"],
in_drop_rate=config["drop_out"],
ps_hosts=config["ps_hosts"],
)
graphscope.learning.reset_default_tf_graph()
trainer = LocalTFTrainer(
model_fn,
epoch=config["epoch"],
optimizer=get_tf_optimizer(
config["learning_algo"], config["learning_rate"], config["weight_decay"]
),
)
trainer.train()
u_embs = trainer.get_node_embedding("u")
np.save("u_emb", u_embs)
i_embs = trainer.get_node_embedding("i")
np.save("i_emb", i_embs)
# Define hyperparameters
config = {
"batch_size": 128,
"hidden_dim": 128,
"output_dim": 128,
"u_features_num": 1,
"u_categorical_attrs_desc": {"0": ["u_id", 10000, 64]},
"i_features_num": 1,
"i_categorical_attrs_desc": {"0": ["i_id", 10000, 64]},
"hops_num": 1,
"u_neighs_num": [10],
"i_neighs_num": [10],
"neg_num": 10,
"learning_algo": "adam",
"learning_rate": 0.001,
"weight_decay": 0.0005,
"epoch": 5,
"use_input_bn": True,
"act": tf.nn.leaky_relu,
"agg_type": "gcn",
"need_dense": True,
"drop_out": 0.0,
"ps_hosts": None,
}
```
## 执行训练过程
在定义完训练过程和超参后,现在我们可以使用学习引擎和定义的超参开始训练过程。
```
train(config, lg)
```
| github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math as math
get_ipython().magic('matplotlib inline')
#Macrostate calculation
def macrostates(qt):
return qt+1
#Omega
def microstates(n, q):
omega = math.factorial(n+q-1)/(math.factorial(q)*math.factorial(n-1))
return omega
#Entropy
k = 1.38e-23
def entropy(n,q):
Sk = math.log(microstates(n,q)) #S in units of S/k
return Sk
#Temp calculation
def temp(N,q):
if(q!=0):
T = (2)/(entropy(N,q+1)-entropy(N,q-1))
else:
T = 0
return T
#Cv Calculation
def cv(N,q):
Cv = 2/(temp(N,q+1)-temp(N,q-1))
return Cv
# N = 50
# qt = 100
# q = 0
NA = 300
NB = 200
NT = NA+NB
qT = 100
qA = 0
qB = 0
#h = 6.626e-34
#U = qt*h*f
#elements1 = []
elements = []
while qA < macrostates(qT)-1:
if(qA!=0):
##Things for A
omegaA = microstates(NA,qA)
#q cannot equal 0 for the rest
SkA = entropy(NA,qA)
#q cannot equal the final value for the rest
TA = temp(NA,qA)
CvA = cv(NA,qA)
##Things for B
omegaB = microstates(NB,qT-qA)
#q cannot equal 0 for the rest
SkB = entropy(NB,qT-qA)
#q cannot equal the final value for the rest
TB = temp(NB,qT-qA)
CvB = cv(NB,qT-qA)
##Things for both
SkAB = SkA+SkB
elements.append([qA, omegaA, SkA, TA, CvA, qT-qA, omegaB, SkB, TB, CvB, SkAB])
else:
omegaA = microstates(NA,qA)
omegaB = microstates(NB, qT-qA)
elements.append([qA, omegaA, 0, 0, 0, qT-qA, omegaB, 0, 0, 0, 0])
qA = qA+1
print(elements)
dataFrame = pd.DataFrame(elements)
# while q < macrostates(qt):
# if(q!=0):
# omega = microstates(N,q)
# #q cannot equal 0 for the rest
# Sk = entropy(N,q)
# #q cannot equal the final value for the rest
# T = temp(N,q)
# Cv = cv(N,q)
# elements1.append([q, omega, Sk, T, Cv])
# else:
# omega = microstates(N,q)
# elements1.append([q, omega, 0, 0, 0])
# q = q+1
# print(elements1)
# dataFrame1 = pd.DataFrame(elements1)
#dataFrame1
dataFrame
##ENTROPY VS U
data = microstates(NA, qA)
qList = []
SkAList = []
SkBList = []
SkABList = []
for i in range(0, macrostates(qT)):
qList.append(i)
SkAList.append(entropy(NA,i))
SkBList.append(entropy(NB,qT-i))
SkABList.append(entropy(NA,i)+entropy(NB,qT-i))
yval1 = SkAList
yval2 = SkBList
yval3 = SkABList
xval = qList
fig = plt.figure(figsize=(10,10))
plt.plot(xval,yval1)
plt.plot(xval,yval2)
plt.plot(xval,yval3)
#plt.ylim(-0.5e-18,0.5e-18)
#plt.xlim(66400,70000)
##TEMPERATURE VS U
qList = []
TAList = []
TBList = []
#TABList = []
for i in range(0, macrostates(qT)):
qList.append(i)
TAList.append(temp(NA,i))
TBList.append(temp(NB,qT-i))
#SkABList.append(entropy(NA,i)+entropy(NB,qT-i))
yval4 = TAList
yval5 = TBList
#yval6 = SkABList
xval = qList
fig = plt.figure(figsize=(10,10))
plt.plot(xval,yval4)
plt.plot(xval,yval5)
#plt.plot(xval,yval6)
#plt.ylim(-0.5e-18,0.5e-18)
#plt.xlim(66400,70000)
##Cv VS U
qList = []
CvList = []
for i in range(0, macrostates(qt-2)):
qList.append(i)
if(i!=0):
CvList.append(cv(N,i))
else:
CvList.append(0)
yval7 = CvList
xval = qList
fig = plt.figure(figsize=(10,10))
plt.plot(xval,yval7)
##OMEGA VS U
#print(microstates(NA, 10))
#print(microstates(NB, qT))
qList = []
OAList = []
OBList = []
OABList = []
for i in range(0, macrostates(qT)):
qList.append(i)
print(microstates(NB,qT-i))
OAList.append(microstates(NA,i))
OBList.append(microstates(NB,qT-i))
OABList.append(microstates(NA,i)*microstates(NB,qT-i))
yval8 = OAList
yval9 = OBList
yval10 = OABList
xval = qList
fig = plt.figure(figsize=(10,10))
plt.plot(xval,yval8)
plt.plot(xval,yval9)
plt.plot(xval,yval10)
```
| github_jupyter |
```
from pyclustering.cluster.bsas import bsas
import numpy as np
import matplotlib.pyplot as plt
import cv2
fig_size =[12,9]
plt.rcParams["figure.figsize"] = fig_size
img = cv2.imread('faulty_image.jpg')
img_gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,img_thresh = cv2.threshold(img_gray,100,255,cv2.THRESH_TOZERO)
nonzro_samples = cv2.findNonZero(img_thresh).reshape(-1, 2).astype('float32')
plt.imshow(img_thresh,cmap='gray')
plt.show()
max_clusters = 8
threshold = 20
bsas_instance = bsas(nonzro_samples, max_clusters, threshold)
bsas_instance.process()
clusters = bsas_instance.get_clusters()
#representatives = bsas_instance.get_representatives()
cms=[]
ROIs=np.zeros((len(clusters),4))
for i,cluster in enumerate(clusters):
current_batch=nonzro_samples[cluster]
cms.append(np.sum(current_batch,axis=0)/current_batch.shape[0])
row_max=np.max(current_batch[:,1],axis=0)+6
row_min=np.min(current_batch[:,1],axis=0)-6
col_max=np.max(current_batch[:,0],axis=0)+6
col_min=np.min(current_batch[:,0],axis=0)-6
ROIs[i,:]=[row_min,row_max,col_min,col_max]
image_ROIs=[]
for roi in ROIs.astype('int32'):
print(roi)
image_ROIs.append(img_thresh.copy()[roi[0]:roi[1],roi[2]:roi[3]])
plt.imshow(image_ROIs[0],cmap='gray')
plt.show()
index=0 #Which ROI do you want to consider?
frame=image_ROIs[index]
roi_range=ROIs[index].astype('float32')
params = cv2.SimpleBlobDetector_Params()
params.minThreshold = 50;
params.maxThreshold = 255;
params.filterByArea = True
params.minArea = 0
params.filterByCircularity = True
params.minCircularity = 0.1
params.filterByConvexity = True
params.minConvexity = 0.1
params.filterByInertia = True
params.minInertiaRatio = 0.1
params.blobColor = 255
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
detector = cv2.SimpleBlobDetector(params)
else :
detector = cv2.SimpleBlobDetector_create(params)
keypoints = detector.detect(frame)
print(keypoints[0].pt)
print(roi_range)
frame_clr=cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)
im_with_keypoints = cv2.drawKeypoints(frame_clr, keypoints, np.array([]), (255,0,0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
plt.imshow(frame_clr)
for key in keypoints:
plt.plot(key.pt[0],key.pt[1],'r*')
plt.show()
img = cv2.imread('faulty_image.jpg')
# roi_range[2] corresponds to roi_x_min and keypoints[0].pt[0] corresponds to the x component of the keypoint
for key in keypoints:
cv2.circle(img,(int(round(key.pt[0]+roi_range[2])), int(round(key.pt[1]+roi_range[0]))), 2, (255,0,255), -1)
plt.imshow(img)
plt.show()
len(keypoints)
import cv2
import numpy as np
from pyclustering.cluster.bsas import bsas
class markerExteractor(object):
def __init__(self):
self.max_clusters = 8
self.threshold = 20
self.blubParams = cv2.SimpleBlobDetector_Params()
self.blubParams.minThreshold = 50;
self.blubParams.maxThreshold = 255;
self.blubParams.filterByArea = True
self.blubParams.minArea = 0
self.blubParams.filterByCircularity = True
self.blubParams.minCircularity = 0.3
self.blubParams.filterByConvexity = True
self.blubParams.minConvexity = 0.7
self.blubParams.filterByInertia = True
self.blubParams.minInertiaRatio = 0.1
self.blubParams.blobColor = 255
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
self.blubDetector = cv2.SimpleBlobDetector(self.blubParams)
else :
self.blubDetector = cv2.SimpleBlobDetector_create(self.blubParams)
def detect(self,frame):
self.cms=[]
self.image_ROIs=[]
self.keypoints=[]
img_gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret,img_thresh = cv2.threshold(img_gray,100,255,cv2.THRESH_TOZERO)
#Find the clusters
self.nonzro_samples = cv2.findNonZero(img_thresh)
if self.nonzro_samples is None:
return None
else:
self.nonzro_samples=self.nonzro_samples.reshape(-1, 2).astype('float32')
bsas_instance = bsas(self.nonzro_samples, self.max_clusters, self.threshold)
bsas_instance.process()
clusters = bsas_instance.get_clusters()
#Calculate the center of the clusters and the Regions of Interests
self.ROIs=np.zeros((len(clusters),4))
for i,cluster in enumerate(clusters):
current_batch=self.nonzro_samples[cluster]
self.cms.append(np.sum(current_batch,axis=0)/current_batch.shape[0])
row_max=np.max(current_batch[:,1],axis=0)+6
row_min=np.min(current_batch[:,1],axis=0)-6
col_max=np.max(current_batch[:,0],axis=0)+6
col_min=np.min(current_batch[:,0],axis=0)-6
self.ROIs[i,:]=[row_min,row_max,col_min,col_max]
for roi in self.ROIs.astype('int32'):
self.image_ROIs.append(img_thresh.copy()[roi[0]:roi[1],roi[2]:roi[3]])
#Return The Results
marker_points=[]
for i,roi in enumerate(self.image_ROIs):
keys_in_roi=self.blubDetector.detect(roi)
for key in keys_in_roi:
#Calculate the global coordinate of marker points. The points are returned in (X(Col),Y(Row)) coordinate.
marker_points.append([key.pt[0]+self.ROIs.astype('float32')[i,2],key.pt[1]+self.ROIs.astype('float32')[i,0]])
return np.array(marker_points)
img = cv2.imread('faulty_image.jpg')
markerExteractor_inst=markerExteractor()
points=markerExteractor_inst.detect(img)
for i in range(len(points)):
cv2.circle(img,(int(round(points[i,0])), int(round(points[i,1]))), 2, (255,0,255), -1)
plt.imshow(img)
plt.show()
cv2.imwrite('res.png',img)
#Testing the algorithm with a stream of images
markerExteractor_inst=markerExteractor()
cap=cv2.VideoCapture('/home/rouholla/Stereo_6DOF_Tracker/Marker_Extraction/output_rigt.avi')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output_debug.avi', fourcc, 30.0, (int(cap.get(3)),int(cap.get(4))))
while cap.isOpened():
ret,img=cap.read()
raw_img=img.copy()
if ret==True:
points=markerExteractor_inst.detect(img)
if points is not None:
for i in range(len(points)):
cv2.circle(img,(int(round(points[i,0])), int(round(points[i,1]))), 2, (255,0,255), -1)
cv2.imshow('Frame',img)
out.write(img)
if cv2.waitKey(20) & 0xFF == ord('q'):
cv2.imwrite('faulty_image.jpg',raw_img)
break
else:
break #Break the while loop if no frames could be captured
cv2.destroyAllWindows()
out.release()
cap.release()
import yaml
class undistrodMarkers:
def __init__(self,config_file_name):
with open(config_file_name, 'r') as f:
calib = yaml.safe_load(f.read())
self.K = np.array(calib['camera_matrix']['data']).reshape(calib['camera_matrix']['rows'],calib['camera_matrix']['cols'])
self.D = np.array(calib['distortion_coefficients']['data']).reshape(-1, 5)
self.P = np.array(calib['projection_matrix']['data']).reshape(3, 4)
self.R = np.array(calib['rectification_matrix']['data']).reshape(3, 3)
self.img_width = calib['image_width']
self.img_height = calib['image_height']
def process(self,points):
lpts_ud=cv2.undistortPoints(points.reshape(-1,1,2).astype(np.float32), self.K, self.D,P=self.P,R=self.R)
return cv2.convertPointsToHomogeneous(np.float32(lpts_ud))
leftUndist = undistrodMarkers('left.yml')
rightUndist = undistrodMarkers('right.yml')
```
## Phase 2
Now we use the tracker we just created to build our 6DOF tracker system
```
#Testing the algorithm with a stream of images
markerExteractor_inst=markerExteractor()
cap_right=cv2.VideoCapture('/home/rouholla/Stereo_6DOF_Tracker/Marker_Extraction/output_right_new.avi')
cap_left=cv2.VideoCapture('/home/rouholla/Stereo_6DOF_Tracker/Marker_Extraction/output_left_new.avi')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output_debug.avi', fourcc, 30.0, (int(cap_left.get(3)),int(cap_left.get(4))))
while cap_left.isOpened():
ret,img_left=cap_left.read()
ret,img_right=cap_right.read()
if ret==True:
points_left=markerExteractor_inst.detect(img_left)
points_right=markerExteractor_inst.detect(img_right)
if (points_left is not None) and (points_right is not None):
left_ud=leftUndist.process(points_left)
right_ud=rightUndist.process(points_right)
for i in range(min(len(points_left),len(points_right))):
cv2.circle(img_left,(int(round(points_left[i,0])), int(round(points_left[i,1]))), 2, (255,0,255), -1)
cv2.circle(img_right,(int(round(points_right[i,0])), int(round(points_right[i,1]))), 2, (255,0,255), -1)
cv2.imshow('Frame',np.hstack([img_left,img_right]))
out.write(img_left)
if cv2.waitKey(2) & 0xFF == ord('q'):
cv2.imwrite('faulty_image.jpg',img_right)
break
else:
break #Break the while loop if no frames could be captured
cv2.destroyAllWindows()
out.release()
cap_left.release()
cap_right.release()
cv2.destroyAllWindows()
#lpts=np.array([329.875, 378.875]).reshape(1,2)
#rpts=np.array([336.5, 334.5]).reshape(1,2)
#left_ud=leftUndist.process(lpts)
#right_ud=rightUndist.process(rpts)
print(left_ud.reshape(-1,3))
print ('right')
print(right_ud.reshape(-1,3))
left_ud-right_ud
left_ud.reshape(-1,3)[:,0:2]
#Create the corresponding matrix
def process_filtered_connection_matrix(connection_matrix):
m,n=connection_matrix.shape
matchesA=[]
matchesB=[]
for i in range(m):
if connection_matrix[i,:].any()==1:
matche=np.where((connection_matrix==connection_matrix[i,:]).all(axis=1))[0] #What rows are identical
if matche.tolist() not in matchesA:# if it's a new kind of row save the place where they exist
matchesA.append(matche.tolist())
matchesB.append(np.where(connection_matrix[i,:]==1)[0].tolist())
return matchesA,matchesB
def get_secondary_correspondings(matchesA,matchesB,points_left,points_right):
points_in_matchesA=[]
points_in_matchesB=[]
for clusters in matchesA:
points_in_cluster=points_left[clusters,:]
points_in_matchesA.append(points_in_cluster[points_in_cluster[:,0].argsort(),:].tolist())
for clusters in matchesB:
points_in_cluster=points_right[clusters,:]
points_in_matchesB.append(points_in_cluster[points_in_cluster[:,0].argsort(),:].tolist())
return np.array(points_in_matchesA,dtype='float32').reshape(-1,2),\
np.array(points_in_matchesB,dtype='float32').reshape(-1,2)
def filter_connection_matrix(connection_matrix,left_points,right_points):
new_connection_matrix=connection_matrix.copy()
progress=1
old_cost=np.sum(connection_matrix)
correspondings=[]
while progress>0:
m,n=connection_matrix.shape
for i in range(m):
if np.sum(connection_matrix[i,:],axis=0)==1: #left marker i is connected to just one right marker j
j=np.where(connection_matrix[i,:]==1)
connection_matrix[:,j]=0
new_connection_matrix[:,j]=0
connection_matrix[i,j]=1
if (i,j[0][0]) not in correspondings:
correspondings.append([i,j[0][0]])
for i in range(n):
if np.sum(connection_matrix[:,i],axis=0)==1: #left marker i in the right is connected to just one the left
j=np.where(connection_matrix[:,i]==1)
connection_matrix[j,:]=0
new_connection_matrix[j,:]=0
connection_matrix[j,i]=1
if [j[0][0],i] not in correspondings:
correspondings.append([j[0][0],i])
progress=old_cost-np.sum(connection_matrix)
old_cost=np.sum(connection_matrix)
correspondings=np.array(correspondings)
return new_connection_matrix,left_points[correspondings[:,0],:],right_points[correspondings[:,1],:]
def get_correspondings(left_points,right_points):
connection_matrix=calculate_connection_mateix(left_points,right_points)
new_cm,immediate_correspondings_left,immediate_correspondings_right=filter_connection_matrix(connection_matrix,left_points,right_points)
matchesLeft,matchesRight=process_filtered_connection_matrix(new_cm)
left_corr_sec,right_corr_sec=get_secondary_correspondings(matchesLeft,matchesRight,left_points,right_points)
return np.vstack([left_corr_sec,immediate_correspondings_left]),np.vstack([right_corr_sec,immediate_correspondings_right])
left_points=np.array([[104,110],[201,110],[200,100],[100,100],[202,120],[102,120],[10,100]]).reshape(-1,2)
right_points=np.array([[101,200],[202,220],[102,220],[103,210],[201,200],[203,210],[12,120]]).reshape(-1,2)
left_points[:,[0,1]]=left_points[:,[1,0]]
right_points[:,[0,1]]=right_points[:,[1,0]]
cm=np.array([[1,0,1,1,0,0],[0,1,0,0,1,1],[1,0,1,1,0,0],[0,1,0,0,1,1],[0,1,0,0,1,1],[1,0,1,1,0,0]])
#Test the corrosponding finder algorithm using dummy data
left_points=np.array([[104,110],[201,110],[200,100],[100,100],[202,120],[102,120],[10,100]]).reshape(-1,2)
right_points=np.array([[101,200],[202,220],[102,220],[103,210],[201,200],[203,210],[12,120]]).reshape(-1,2)
left_points[:,[0,1]]=left_points[:,[1,0]]
right_points[:,[0,1]]=right_points[:,[1,0]]
cm=np.array([[1,0,1,1,0,0],[0,1,0,0,1,1],[1,0,1,1,0,0],[0,1,0,0,1,1],[0,1,0,0,1,1],[1,0,1,1,0,0]])
get_correspondings(left_points,right_points)
#get the corrosponding points for the exteracted points from the camera frames
lpts_ud,rpts_ud=get_correspondings(left_ud.reshape(-1,3)[:,0:2],right_ud.reshape(-1,3)[:,0:2])
res=cv2.triangulatePoints(leftUndist.P,rightUndist.P,lpts_ud.reshape(-1,1,2).astype(np.float32),rpts_ud.reshape(-1,1,2).astype(np.float32))
points_3d=(res/res[-1,:])[0:3,:]
points_3d
```
## Les's test the Multi marker 3D point Tracker
```
#Testing the algorithm with a stream of images
markerExteractor_inst=markerExteractor()
cap_right=cv2.VideoCapture('/home/rouholla/Stereo_6DOF_Tracker/Marker_Extraction/output_right_new.avi')
cap_left=cv2.VideoCapture('/home/rouholla/Stereo_6DOF_Tracker/Marker_Extraction/output_left_new.avi')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output_debug.avi', fourcc, 30.0, (int(cap_left.get(3)),int(cap_left.get(4))))
while cap_left.isOpened():
ret,img_left=cap_left.read()
ret,img_right=cap_right.read()
if ret==True:
points_left=markerExteractor_inst.detect(img_left)
points_right=markerExteractor_inst.detect(img_right)
if (points_left is not None) and (points_right is not None):
left_ud=leftUndist.process(points_left)
right_ud=rightUndist.process(points_right)
for i in range(min(len(points_left),len(points_right))):
cv2.circle(img_left,(int(round(points_left[i,0])), int(round(points_left[i,1]))), 2, (255,0,255), -1)
cv2.circle(img_right,(int(round(points_right[i,0])), int(round(points_right[i,1]))), 2, (255,0,255), -1)
lpts_ud,rpts_ud=get_correspondings(left_ud.reshape(-1,3)[:,0:2],right_ud.reshape(-1,3)[:,0:2])
res=cv2.triangulatePoints(leftUndist.P,rightUndist.P,lpts_ud.reshape(-1,1,2).astype(np.float32),rpts_ud.reshape(-1,1,2).astype(np.float32))
points_3d=(res/res[-1,:])[0:3,:]
print(points_3d[-1,-1])
cv2.imshow('Frame',np.hstack([img_left,img_right]))
out.write(img_left)
if cv2.waitKey(2) & 0xFF == ord('q'):
cv2.imwrite('faulty_image.jpg',img_right)
break
else:
break #Break the while loop if no frames could be captured
cv2.destroyAllWindows()
out.release()
cap_left.release()
cap_right.release()
print(points_3d)
```
| 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 tensor slicing
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/tensor_slicing"><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/tensor_slicing.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/tensor_slicing.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/tensor_slicing.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
When working on ML applications such as object detection and NLP, it is sometimes necessary to work with sub-sections (slices) of tensors. For example, if your model architecture includes routing, where one layer might control which training example gets routed to the next layer. In this case, you could use tensor slicing ops to split the tensors up and put them back together in the right order.
In NLP applications, you can use tensor slicing to perform word masking while training. For example, you can generate training data from a list of sentences by choosing a word index to mask in each sentence, taking the word out as a label, and then replacing the chosen word with a mask token.
In this guide, you will learn how to use the TensorFlow APIs to:
* Extract slices from a tensor
* Insert data at specific indices in a tensor
This guide assumes familiarity with tensor indexing. Read the indexing sections of the [Tensor](https://www.tensorflow.org/guide/tensor#indexing) and [TensorFlow NumPy](https://www.tensorflow.org/guide/tf_numpy#indexing) guides before getting started with this guide.
## Setup
```
import tensorflow as tf
import numpy as np
```
## Extract tensor slices
Perform NumPy-like tensor slicing using `tf.slice`.
```
t1 = tf.constant([0, 1, 2, 3, 4, 5, 6, 7])
print(tf.slice(t1,
begin=[1],
size=[3]))
```
Alternatively, you can use a more Pythonic syntax. Note that tensor slices are evenly spaced over a start-stop range.
```
print(t1[1:4])
```
<img src="images/tf_slicing/slice_1d_1.png">
```
print(t1[-3:])
```
<img src="images/tf_slicing/slice_1d_2.png">
For 2-dimensional tensors,you can use something like:
```
t2 = tf.constant([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
print(t2[:-1, 1:3])
```
<img src="images/tf_slicing/slice_2d_1.png">
You can use `tf.slice` on higher dimensional tensors as well.
```
t3 = tf.constant([[[1, 3, 5, 7],
[9, 11, 13, 15]],
[[17, 19, 21, 23],
[25, 27, 29, 31]]
])
print(tf.slice(t3,
begin=[1, 1, 0],
size=[1, 1, 2]))
```
You can also use `tf.strided_slice` to extract slices of tensors by 'striding' over the tensor dimensions.
Use `tf.gather` to extract specific indices from a single axis of a tensor.
```
print(tf.gather(t1,
indices=[0, 3, 6]))
# This is similar to doing
t1[::3]
```
<img src="images/tf_slicing/slice_1d_3.png">
`tf.gather` does not require indices to be evenly spaced.
```
alphabet = tf.constant(list('abcdefghijklmnopqrstuvwxyz'))
print(tf.gather(alphabet,
indices=[2, 0, 19, 18]))
```
<img src="images/tf_slicing/gather_1.png">
To extract slices from multiple axes of a tensor, use `tf.gather_nd`. This is useful when you want to gather the elements of a matrix as opposed to just its rows or columns.
```
t4 = tf.constant([[0, 5],
[1, 6],
[2, 7],
[3, 8],
[4, 9]])
print(tf.gather_nd(t4,
indices=[[2], [3], [0]]))
```
<img src="images/tf_slicing/gather_2.png">
```
t5 = np.reshape(np.arange(18), [2, 3, 3])
print(tf.gather_nd(t5,
indices=[[0, 0, 0], [1, 2, 1]]))
# Return a list of two matrices
print(tf.gather_nd(t5,
indices=[[[0, 0], [0, 2]], [[1, 0], [1, 2]]]))
# Return one matrix
print(tf.gather_nd(t5,
indices=[[0, 0], [0, 2], [1, 0], [1, 2]]))
```
## Insert data into tensors
Use `tf.scatter_nd` to insert data at specific slices/indices of a tensor. Note that the tensor into which you insert values is zero-initialized.
```
t6 = tf.constant([10])
indices = tf.constant([[1], [3], [5], [7], [9]])
data = tf.constant([2, 4, 6, 8, 10])
print(tf.scatter_nd(indices=indices,
updates=data,
shape=t6))
```
Methods like `tf.scatter_nd` which require zero-initialized tensors are similar to sparse tensor initializers. You can use `tf.gather_nd` and `tf.scatter_nd` to mimic the behavior of sparse tensor ops.
Consider an example where you construct a sparse tensor using these two methods in conjunction.
```
# Gather values from one tensor by specifying indices
new_indices = tf.constant([[0, 2], [2, 1], [3, 3]])
t7 = tf.gather_nd(t2, indices=new_indices)
```
<img src="images/tf_slicing/gather_nd_sparse.png">
```
# Add these values into a new tensor
t8 = tf.scatter_nd(indices=new_indices, updates=t7, shape=tf.constant([4, 5]))
print(t8)
```
This is similar to:
```
t9 = tf.SparseTensor(indices=[[0, 2], [2, 1], [3, 3]],
values=[2, 11, 18],
dense_shape=[4, 5])
print(t9)
# Convert the sparse tensor into a dense tensor
t10 = tf.sparse.to_dense(t9)
print(t10)
```
To insert data into a tensor with pre-existing values, use `tf.tensor_scatter_nd_add`.
```
t11 = tf.constant([[2, 7, 0],
[9, 0, 1],
[0, 3, 8]])
# Convert the tensor into a magic square by inserting numbers at appropriate indices
t12 = tf.tensor_scatter_nd_add(t11,
indices=[[0, 2], [1, 1], [2, 0]],
updates=[6, 5, 4])
print(t12)
```
Similarly, use `tf.tensor_scatter_nd_sub` to subtract values from a tensor with pre-existing values.
```
# Convert the tensor into an identity matrix
t13 = tf.tensor_scatter_nd_sub(t11,
indices=[[0, 0], [0, 1], [1, 0], [1, 1], [1, 2], [2, 1], [2, 2]],
updates=[1, 7, 9, -1, 1, 3, 7])
print(t13)
```
Use `tf.tensor_scatter_nd_min` to copy element-wise minimum values from one tensor to another.
```
t14 = tf.constant([[-2, -7, 0],
[-9, 0, 1],
[0, -3, -8]])
t15 = tf.tensor_scatter_nd_min(t14,
indices=[[0, 2], [1, 1], [2, 0]],
updates=[-6, -5, -4])
print(t15)
```
Similarly, use `tf.tensor_scatter_nd_max` to copy element-wise maximum values from one tensor to another.
```
t16 = tf.tensor_scatter_nd_max(t14,
indices=[[0, 2], [1, 1], [2, 0]],
updates=[6, 5, 4])
print(t16)
```
## Further reading and resources
In this guide, you learned how to use the tensor slicing ops available with TensorFlow to exert finer control over the elements in your tensors.
* Check out the slicing ops available with TensorFlow NumPy such as `tf.experimental.numpy.take_along_axis` and `tf.experimental.numpy.take`.
* Also check out the [Tensor guide](https://www.tensorflow.org/guide/tensor) and the [Variable guide](https://www.tensorflow.org/guide/variable).
| github_jupyter |
# Object Detection @Edge with SageMaker Neo + Pytorch Yolov5
**SageMaker Studio Kernel**: Data Science
In this exercise you'll:
- Get a pre-trained model: Yolov5
- Prepare the model to compile it with Neo
- Compile the model for the target: **X86_64**
- Get the optimized model and run a simple local test
### install dependencies
```
!apt update -y && apt install -y libgl1
!pip install torch==1.7.0 torchvision==0.8.0 opencv-python dlr==1.8.0
```
## 1) Get a pre-trained model and export it to torchscript
-> SagMaker Neo expectes the model in the traced format
```
import os
import urllib.request
if not os.path.isdir('yolov5'):
!git clone https://github.com/ultralytics/yolov5 && \
cd yolov5 && git checkout v5.0 && \
git apply ../../models/01_YoloV5/01_Pytorch/yolov5_inplace.patch
if not os.path.exists('yolov5s.pt'):
urllib.request.urlretrieve('https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt', 'yolov5s.pt')
import torch.nn as nn
import torch
import sys
sys.path.insert(0, 'yolov5')
model = torch.load('yolov5s.pt')['model'].float().cpu()
## We need to replace these two activation functions to make it work with TVM.
# SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
class SiLU(nn.Module): # export-friendly version of nn.SiLU()
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
@staticmethod
def forward(x):
# return x * F.hardsigmoid(x) # for torchscript and CoreML
return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
for k,m in model.named_modules():
t = type(m)
layer_name = f"{t.__module__}.{t.__name__}"
if layer_name == 'models.common.Conv': # assign export-friendly activations
if isinstance(m.act, nn.Hardswish):
m.act = Hardswish()
elif isinstance(m.act, nn.SiLU):
m.act = SiLU()
img_size=640
inp = torch.rand(1,3,img_size,img_size).float().cpu()
model.eval()
p = model(inp)
model_trace = torch.jit.trace(model, inp, strict=False)
model_trace.save('model.pth')
```
## 2) Create a package with the model and upload to S3
```
import tarfile
import sagemaker
sagemaker_session = sagemaker.Session()
model_name='yolov5'
with tarfile.open("model.tar.gz", "w:gz") as f:
f.add("model.pth")
f.list()
s3_uri = sagemaker_session.upload_data('model.tar.gz', key_prefix=f'{model_name}/model')
print(s3_uri)
```
## 3) Compile the model with SageMaker Neo (X86_64)
```
import time
import boto3
import sagemaker
role = sagemaker.get_execution_role()
sm_client = boto3.client('sagemaker')
compilation_job_name = f'{model_name}-pytorch-{int(time.time()*1000)}'
sm_client.create_compilation_job(
CompilationJobName=compilation_job_name,
RoleArn=role,
InputConfig={
'S3Uri': s3_uri,
'DataInputConfig': f'{{"input": [1,3,{img_size},{img_size}]}}',
'Framework': 'PYTORCH'
},
OutputConfig={
'S3OutputLocation': f's3://{sagemaker_session.default_bucket()}/{model_name}-pytorch/optimized/',
'TargetPlatform': {
'Os': 'LINUX',
'Arch': 'X86_64'
}
},
StoppingCondition={ 'MaxRuntimeInSeconds': 900 }
)
while True:
resp = sm_client.describe_compilation_job(CompilationJobName=compilation_job_name)
if resp['CompilationJobStatus'] in ['STARTING', 'INPROGRESS']:
print('Running...')
else:
print(resp['CompilationJobStatus'], compilation_job_name)
break
time.sleep(5)
```
## 4) Download the compiled model
```
output_model_path = f's3://{sagemaker_session.default_bucket()}/{model_name}-pytorch/optimized/model-LINUX_X86_64.tar.gz'
!aws s3 cp $output_model_path /tmp/model.tar.gz
!rm -rf model_object_detection && mkdir model_object_detection
!tar -xzvf /tmp/model.tar.gz -C model_object_detection
```
## 5) Run the model locally
```
import urllib.request
urllib.request.urlretrieve('https://i2.wp.com/petcaramelo.com/wp-content/uploads/2020/05/doberman-cores.jpg', 'dogs.jpg')
%matplotlib inline
import numpy as np
import cv2
import matplotlib.pyplot as plt
import os
# Classes
labels= ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
'hair drier', 'toothbrush'] # class names
```
### load the model using the runtime DLR
```
import dlr
# load the model (CPU x86_64)
model = dlr.DLRModel('model_object_detection', 'cpu')
import sys
sys.path.insert(0,'../models/01_YoloV5/01_Pytorch')
from processing import Processor
proc = Processor(labels, threshold=0.25, iou_threshold=0.45)
img = cv2.imread('dogs.jpg')
x = proc.pre_process(img)
y = model.run(x)[0]
(bboxes, scores, cids), image = proc.post_process(y, img.shape, img.copy())
plt.figure(figsize=(10,10))
plt.imshow(image)
```
# Done! :)
| github_jupyter |
# K-Fold Cross Validation + Grid Search cv + Principal Componenet Analysis + Kernel SVM on Wine Dataset
GridSearchCV implements a “fit” method and a “predict” method like any classifier except that the parameters of the classifier used to predict is optimized by cross-validation. ... This enables searching over any sequence of parameter settings.
Cross-validation is a statistical method used to estimate the skill of machine learning models.
It is commonly used in applied machine learning to compare and select a model for a given predictive modeling problem because it is easy to understand, easy to implement, and results in skill estimates that generally have a lower bias than other methods.
In this tutorial, you will discover a gentle introduction to the k-fold cross-validation procedure for estimating the skill of machine learning models.
<ol>
<li>That k-fold cross validation is a procedure used to estimate the skill of the model on new data.
<li>There are common tactics that you can use to select the value of k for your dataset.
<li>There are commonly used variations on cross-validation such as stratified and repeated that are available in scikit-learn.
</ol>
```
import numpy as np
import pandas as pd
import time
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
fig = plt.figure(figsize=(10, 10))
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
# Importing the dataset into a pandas dataframe
df = pd.read_csv("Wine.csv")
df.describe()
df.info()
df.head(10)
df.tail(10)
```
<h4>So Dependent Variable of the dataset is splitted into 3 classes namely(1, 2, 3)</h4>
```
df.shape
#Spliting The dataset into Independent and Dependent Variable
X = df.iloc[:, 0:13].values
Y = df.iloc[:, 13].values
# Splitting the dataset into the Training set and Test set
X_train, X_test, Y_train, Y_test = train_test_split(X,
Y,
test_size = 0.2,
random_state = 0)
print("Size of X_train: {}".format(X_train.shape))
print("Size of X_test: {}".format(X_test.shape))
print("Size of Y_train: {}".format(Y_train.shape))
print("Size of Y_test: {}".format(Y_test.shape))
# Feature Scaling
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
```
#Applying Principal Component Analysis
#Commenting This out because we got out max variance and we could have
#Changed this block, but instead we are writing new section just to
#make others understand
"""pca = PCA(n_components = None)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)"""
We can see that First Two has the highest variance
So, we will set out n_components in PCA as 2
```
#Checking The Variances
Variances = pca.explained_variance_
Variances
# Applying PCA
pca = PCA(n_components = 2)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
# Fitting Logistic Regression to the Training set
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(X_train, Y_train)
#Predicting The Results
y_pred = classifier.predict(X_test)
y_pred
#Comparing the results
cm = confusion_matrix(Y_test, y_pred)
cm
#Checking The Accuracy score
acc = accuracy_score(Y_test, y_pred)
print("The Accuracy on the model is: {}%".format((acc*100).astype('int32')))
```
<h3>Building a text report showing the main classification metrics</h3>
```
cr = classification_report(Y_test, y_pred)
print(cr)
```
# Twerking The Hyper Parameters
```
#Applying KFold Cross Validation
fold = cross_val_score(estimator = classifier,
cv = 10,
X = X_train,
y = Y_train,
n_jobs = -1)
fold
print("Average Accuracy: {}%".format(((fold.mean())*100).astype('int32')))
print("Variance : {}".format(fold.std()))
```
Well the Cross_Val predicted just right 97% is what our classifier acvhieved without any hyper parameter optimization
<h4>Let's see what Grid Search CV can do</h4>
```
#Applying GridSearch Cv
params = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'kernel': ['rbf'], 'gamma': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]},
{'C': [1, 10, 100, 1000], 'kernel': ['poly'], 'gamma': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], 'degree': [2, 3, 4]},
{'C': [1, 10, 100, 1000], 'kernel': ['sigmoid'], 'gamma': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]}]
start = time.time()
gscv = GridSearchCV(estimator = classifier,
param_grid = params,
scoring= 'accuracy',
n_jobs= -1,
cv= 10)
gscv = gscv.fit(X_train, Y_train)
end = time.time()
tt = end - start
print(tt)
accuracy = gscv.best_score_
accuracy
best_parameters = gscv.best_params_
best_parameters
```
<h3>So according to grid sear best parameters for our model is {'C': 1, 'kernel': 'linear'}</h3>
Training The model with optimal parameters
```
classifier2 = SVC(kernel = 'rbf', random_state = 0)
classifier2.fit(X_train, Y_train)
y_pred2 = classifier2.predict(X_test)
cm = confusion_matrix(Y_test, y_pred2)
print("Average Accuracy: {}%".format(((fold.mean())*100).astype('int32')))
print("Variance : {}".format(fold.std()))
cm
# Visualising the Training set results
x_set, y_set = X_train, Y_train
#Creating the grid of Minimum and maximun values from X_train
X1, X2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1,
stop = x_set[:, 0].max() + 1,
step = 0.01),
np.arange(start = x_set[:, 1].min() - 1,
stop = x_set[:, 1].max() + 1,
step = 0.01))
#Plotting the line Classifier
plt.contourf(X1,
X2,
classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.4,
cmap = ListedColormap(('red', 'green', 'blue')))
#Plotting The Datapoint in red and gree color
for i,j in enumerate(np.unique(y_set)):
plt.scatter(x_set[y_set == j, 0],
x_set[y_set == j, 1],
c = ListedColormap(('red', 'green', 'blue'))(i),
label = j
)
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.title("PCA + Logistic Regression (Training Set)")
plt.xlabel('PCA1')
plt.ylabel('PCA2')
plt.legend()
# Visualising the Test set results
x_set, y_set = X_test, Y_test
#Creating the grid of Minimum and maximun values from X_train
X1, X2 = np.meshgrid(np.arange(start = x_set[:, 0].min() - 1,
stop = x_set[:, 0].max() + 1,
step = 0.01),
np.arange(start = x_set[:, 1].min() - 1,
stop = x_set[:, 1].max() + 1,
step = 0.01))
#Plotting the line Classifier
plt.contourf(X1,
X2,
classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.4,
cmap = ListedColormap(('red', 'green', 'blue')))
#Plotting The Datapoint in red and gree color
for i,j in enumerate(np.unique(y_set)):
plt.scatter(x_set[y_set == j, 0],
x_set[y_set == j, 1],
c = ListedColormap(('red', 'green', 'blue'))(i),
label = j
)
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.title("PCA + Logistic Regression (Test Set)")
plt.xlabel('PCA1')
plt.ylabel('PCA2')
plt.legend()
```
| github_jupyter |
Copyright (c) FLAML authors. All rights reserved.
Licensed under the MIT License.
# Zero-shot AutoML with FLAML
## Introduction
In this notebook, we demonstrate a basic use case of zero-shot AutoML with FLAML.
FLAML requires `Python>=3.7`. To run this notebook example, please install flaml and openml:
```
%pip install -U flaml openml;
```
## What is zero-shot AutoML?
Zero-shot automl means automl systems without expensive tuning. But it does adapt to data.
A zero-shot automl system will recommend a data-dependent default configuration for a given dataset.
Think about what happens when you use a `LGBMRegressor`. When you initialize a `LGBMRegressor` without any argument, it will set all the hyperparameters to the default values preset by the lightgbm library.
There is no doubt that these default values have been carefully chosen by the library developers.
But they are static. They are not adaptive to different datasets.
```
from lightgbm import LGBMRegressor
estimator = LGBMRegressor()
print(estimator.get_params())
```
It is unlikely that 100 trees with 31 leaves each is the best hyperparameter setting for every dataset.
So, we propose to recommend data-dependent default configurations at runtime.
All you need to do is to import the `LGBMRegressor` from flaml.default instead of from lightgbm.
```
from flaml.default import LGBMRegressor
```
Other parts of code remain the same. The new `LGBMRegressor` will automatically choose a configuration according to the training data.
For different training data the configuration could be different.
The recommended configuration can be either the same as the static default configuration from the library, or different.
It is expected to be no worse than the static default configuration in most cases.
For example, let's download [houses dataset](https://www.openml.org/d/537) from OpenML. The task is to predict median price of the house in the region based on demographic composition and a state of housing market in the region.
```
from flaml.data import load_openml_dataset
X_train, X_test, y_train, y_test = load_openml_dataset(dataset_id=537, data_dir='./')
print(X_train)
```
We fit the `flaml.default.LGBMRegressor` on this dataset.
```
estimator = LGBMRegressor() # imported from flaml.default
estimator.fit(X_train, y_train)
print(estimator.get_params())
```
The configuration is adapted as shown here.
The number of trees is 4797, the number of leaves is 122.
Does it work better than the static default configuration?
Let’s compare.
```
estimator.score(X_test, y_test)
```
The data-dependent configuration has a $r^2$ metric 0.8537 on the test data. What about static default configuration from lightgbm?
```
from lightgbm import LGBMRegressor
estimator = LGBMRegressor()
estimator.fit(X_train, y_train)
estimator.score(X_test, y_test)
```
The static default configuration gets $r^2=0.8296$, much lower than 0.8537 by the data-dependent configuration using `flaml.default`.
Again, the only difference in the code is from where you import the `LGBMRegressor`.
The adaptation to the training dataset is under the hood.
You might wonder, how is it possible to find the data-dependent configuration without tuning?
The answer is that,
flaml can recommend good data-dependent default configurations at runtime without tuning only because it mines the hyperparameter configurations across different datasets offline as a preparation step.
So basically, zero-shot automl shifts the tuning cost from online to offline.
In the offline preparation stage, we applied `flaml.AutoML`.
### Benefit of zero-shot AutoML
Now, what is the benefit of zero-shot automl? Or what is the benefit of shifting tuning from online to offline?
The first benefit is the online computational cost. That is the cost paid by the final consumers of automl. They only need to train one model.
They get the hyperparameter configuration right away. There is no overhead to worry about.
Another big benefit is that your code doesn’t need to change. So if you currently have a workflow without the setup for tuning, you can use zero-shot automl without breaking that workflow.
Compared to tuning-based automl, zero-shot automl requires less input. For example, it doesn’t need a tuning budget, resampling strategy, validation dataset etc.
A related benefit is that you don’t need to worry about holding a subset of the training data for validation, which the tuning process might overfit.
As there is no tuning, you can use all the training data to train your model.
Finally, you can customize the offline preparation for a domain, and leverage the past tuning experience for better adaptation to similar tasks.
## How to use at runtime
The easiest way to leverage this technique is to import a "flamlized" learner of your favorite choice and use it just as how you use the learner before.
The automation is done behind the scene.
The current list of “flamlized” learners are:
* LGBMClassifier, LGBMRegressor (inheriting LGBMClassifier, LGBMRegressor from lightgbm)
* XGBClassifier, XGBRegressor (inheriting LGBMClassifier, LGBMRegressor from xgboost)
* RandomForestClassifier, RandomForestRegressor (inheriting from scikit-learn)
* ExtraTreesClassifier, ExtraTreesRegressor (inheriting from scikit-learn)
They work for classification or regression tasks.
### What's the magic behind the scene?
`flaml.default.LGBMRegressor` inherits `lightgbm.LGBMRegressor`, so all the methods and attributes in `lightgbm.LGBMRegressor` are still valid in `flaml.default.LGBMRegressor`.
The difference is, `flaml.default.LGBMRegressor` decides the hyperparameter configurations based on the training data. It would use a different configuration if it is predicted to outperform the original data-independent default. If you inspect the params of the fitted estimator, you can find what configuration is used. If the original default configuration is used, then it is equivalent to the original estimator.
The recommendation of which configuration should be used is based on offline AutoML run results. Information about the training dataset, such as the size of the dataset will be used to recommend a data-dependent configuration. The recommendation is done instantly in negligible time. The training can be faster or slower than using the original default configuration depending on the recommended configuration.
### Can I check the configuration before training?
Yes. You can use `suggest_hyperparams()` method to find the suggested configuration.
For example, when you run the following code with the houses dataset, it will return the hyperparameter configuration instantly, without training the model.
```
from flaml.default import LGBMRegressor
estimator = LGBMRegressor()
hyperparams, _, _, _ = estimator.suggest_hyperparams(X_train, y_train)
print(hyperparams)
```
You can print the configuration as a dictionary, in case you want to check it before you use it for training.
This brings up an equivalent, open-box way for zero-shot AutoML if you would like more control over the training.
Import the function `preprocess_and_suggest_hyperparams` from `flaml.default`.
This function takes the task name, the training dataset, and the estimator name as input:
```
from flaml.default import preprocess_and_suggest_hyperparams
(
hyperparams,
estimator_class,
X_transformed,
y_transformed,
feature_transformer,
label_transformer,
) = preprocess_and_suggest_hyperparams("regression", X_train, y_train, "lgbm")
```
It outputs the hyperparameter configurations, estimator class, transformed data, feature transformer and label transformer.
```
print(estimator_class)
```
In this case, the estimator name is “lgbm”. The corresponding estimator class is `lightgbm.LGBMRegressor`.
This line initializes a LGBMClassifier with the recommended hyperparameter configuration:
```
model = estimator_class(**hyperparams)
```
Then we can fit the model on the transformed data.
```
model.fit(X_transformed, y_train)
```
The feature transformer needs to be applied to the test data before prediction.
```
X_test_transformed = feature_transformer.transform(X_test)
y_pred = model.predict(X_test_transformed)
```
These are automated when you use the "flamlized" learner. So you don’t need to know these details when you don’t need to open the box.
We demonstrate them here to help you understand what’s going on. And in case you need to modify some steps, you know what to do.
(Note that some classifiers like XGBClassifier require the labels to be integers, while others do not. So you can decide whether to use the transformed labels y_transformed and the label transformer label_transformer. Also, each estimator may require specific preprocessing of the data.)
## Combine Zero-shot AutoML and HPO
Zero Shot AutoML is fast and simple to use. It is very useful if speed and simplicity are the primary concerns.
If you are not satisfied with the accuracy of the zero shot model, you may want to spend extra time to tune the model.
You can use `flaml.AutoML` to do that. Everything is the same as your normal `AutoML.fit()`, except to set `starting_points="data"`.
This tells AutoML to start the tuning from the data-dependent default configurations. You can set the tuning budget in the same way as before.
Note that if you set `max_iter=0` and `time_budget=None`, you are effectively using zero-shot AutoML.
When `estimator_list` is omitted, the most promising estimator together with its hyperparameter configuration will be tried first, which are both decided by zero-shot automl.
```
from flaml import AutoML
automl = AutoML()
settings = {
"task": "regression",
"starting_points": "data",
"estimator_list": ["lgbm"],
"time_budget": 600,
}
automl.fit(X_train, y_train, **settings)
```
| github_jupyter |
# Transfer Learning
In this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html).
ImageNet is a massive dataset with over 1 million labeled images in 1000 categories. It's used to train deep neural networks using an architecture called convolutional layers. I'm not going to get into the details of convolutional networks here, but if you want to learn more about them, please [watch this](https://www.youtube.com/watch?v=2-Ol7ZB0MmU).
Once trained, these models work astonishingly well as feature detectors for images they weren't trained on. Using a pre-trained network on images not in the training set is called transfer learning. Here we'll use transfer learning to train a network that can classify our cat and dog photos with near perfect accuracy.
With `torchvision.models` you can download these pre-trained networks and use them in your applications. We'll include `models` in our imports now.
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
```
Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`.
```
torch.cuda.is_available()
data_dir = 'Cat_Dog_data'
# TODO: Define transforms for the training data and testing data
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
test_transforms = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
# Pass transforms in here, then run the next cell to see how the transforms look
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
test_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)
trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
testloader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=True)
images, labels = next(iter(testloader))
helper.imshow(images[0], normalize=False)
```
We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.html#id5). Let's print out the model architecture so we can see what's going on.
```
model = models.densenet121(pretrained=True)
model
```
This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. This layer was trained on the ImageNet dataset, so it won't work for our specific problem. That means we need to replace the classifier, but the features will work perfectly on their own. In general, I think about pre-trained networks as amazingly good feature detectors that can be used as the input for simple feed-forward classifiers.
```
# Freeze parameters so we don't backprop through them
for param in model.parameters():
param.requires_grad = False
from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(1024, 500)),
('relu', nn.ReLU()),
('fc2', nn.Linear(500, 2)),
('output', nn.LogSoftmax(dim=1))
]))
model.classifier = classifier
```
With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU leading to 100x increased training speeds. It's also possible to train on multiple GPUs, further decreasing training time.
PyTorch, along with pretty much every other deep learning framework, uses [CUDA](https://developer.nvidia.com/cuda-zone) to efficiently compute the forward and backwards passes on the GPU. In PyTorch, you move your model parameters and other tensors to the GPU memory using `model.to('cuda')`. You can move them back from the GPU with `model.to('cpu')` which you'll commonly do when you need to operate on the network output outside of PyTorch. As a demonstration of the increased speed, I'll compare how long it takes to perform a forward and backward pass with and without a GPU.
```
import time
for device in ['cpu', 'cuda']:
criterion = nn.NLLLoss()
# Only train the classifier parameters, feature parameters are frozen
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
model.to(device)
for ii, (inputs, labels) in enumerate(trainloader):
# Move input and label tensors to the GPU
inputs, labels = inputs.to(device), labels.to(device)
start = time.time()
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if ii==3:
break
print(f"Device = {device}; Time per batch: {(time.time() - start)/3:.3f} seconds")
```
You can write device agnostic code which will automatically use CUDA if it's enabled like so:
```python
# at beginning of the script
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
...
# then whenever you get a new Tensor or Module
# this won't copy if they are already on the desired device
input = data.to(device)
model = MyModule(...).to(device)
```
From here, I'll let you finish training the model. The process is the same as before except now your model is much more powerful. You should get better than 95% accuracy easily.
>**Exercise:** Train a pretrained models to classify the cat and dog images. Continue with the DenseNet model, or try ResNet, it's also a good model to try out first. Make sure you are only training the classifier and the parameters for the features part are frozen.
```
## TODO: Use a pretrained model to classify the cat and dog images
model = models.resnet50(pretrained=True)
model
for param in model.parameters(): #Turn off autograd for feature parameters
param.requires_grad = False
from collections import OrderedDict
fc = nn.Sequential(OrderedDict([ #Reaplce FC layer with a new one
('fc1', nn.Linear(2048, 512)),
('relu', nn.ReLU()),
('dropout', nn.Dropout(.2)),
('fc2', nn.Linear(512, 2)),
('output', nn.LogSoftmax(dim=1))
]))
model.fc = fc
model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.fc.parameters(), lr =0.003) #Set the opimizer to only train the fc layer that we made
model.to(device)
images, labels = next(iter(trainloader))
print(images[0].shape)
epochs =1
train_losses, test_losses = [], []
for ee in range(epochs):
running_loss = 0
for images, labels in trainloader:
images, labels = images.to(device), labels.to(device) #send values to cuda
optimizer.zero_grad() #zero out the gradients from the previosu batch
logps = model.forward(images) #send batch through model
loss = criterion(logps, labels) #calcualte the loss
loss.backward() #calcualte the gradients
optimizer.step() #step through the model and update weights
running_loss += loss.item()
else:
print('get here?')
test_loss = 0
accuracy = 0
model.eval()
with torch.no_grad():
for images, labels in testloader:
images, labels = images.to(device), labels.to(device) #send values to cuda
logps = model.forward(images) #get log probabilities for the test images
batch_loss = criterion(logps,labels) #get loss for test
test_loss += batch_loss.item()
ps = torch.exp(logps) #Get final probabilities
topP, topClass = ps.topk(1, dim=1) #get top 1 response
equals = topClass == labels.view(*topClass.shape) #check how many are right
accuracy += torch.mean(equals.type(torch.FloatTensor)).item() #calculate acc; equals needed to made into a flaot first
model.train() #set back to train mode
train_losses.append(running_loss/len(trainloader))
test_losses.append(test_loss/len(testloader))
print("Epoch: {}/{}.. ".format(ee+1, epochs),
"Training Loss: {:.3f}.. ".format(train_losses[-1]),
"Test Loss: {:.3f}.. ".format(test_losses[-1]),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)))
import helper
model.eval()
images, labels = next(iter(testloader))
img = images[2]
img = img.view(1, img.shape[0],img.shape[1], img.shape[2])
img = img.to(device)
with torch.no_grad():
output = model.forward(img)
ps = torch.exp(output)
topP, topClass = ps.topk(1, dim=1) #get top 1 response
#images[0] = images.cpu()
helper.imshow(images[2], normalize=False)
print(topClass, labels[2])
```
| github_jupyter |
# Clase!
## Contenidos:
* [Groupby](#groupby)
* [Merge](#merge)
* [Melt](#melt)
* [Sanity-Check](#sc)
## Motivación:
Manipular datos con pandas es sencillo, hacer agrupaciones, cruces y reformatos se logra de manera intuitiva. A continuación veremos un par de ejemplos de como hacer estas acciones.
OBS: Al contrario de NumPy, Pandas esta orientado a los datos (no a los algoritmos/calculos), por eso, las estructuras de datos que usan son distintas:
* Numpy: Usan array, lo que es equivalente a una matriz, su tamaño no es mutable y el tipo de data (*dtype*) debería ser única dentro del arreglo.
* Pandas: Usan Series y DataFrame (*a Series of Series*), estos pueden modificar su tamaño y pueden contener cualquier tipo de datos
Primero, Importamos las librerías correspondientes
```
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
```
Estos son los alias estandar para estas librerías
```
%matplotlib inline
#permite que los gráficos se muestren en el notebook
```
### Groupby: <a id = "groupby"></a>
Esta operación permite agrupar registros basados en distintas operaciones:
1. Conteo (*.count()*, *size()* )
2. Suma (*.sum()* )
3. Media (*.mean()* )
4. Desviación estandar (*.str()* (dentro de cada grupo))
5. Custom (revisar [documentación de los objetos DataFramegroupby y aggregate](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html))
Ahora generemos los datos:
```
n=1000 #cantidad de registros
edad = (np.random.randint(low=18,high=80,size=n)) #TIP: presione shift+tab dentro de una funcion para ver su *signature*
inc = np.random.normal(400e3,5e3,size=n)
reg = (np.random.randint(low=0,high=13,size=n))
df = pd.DataFrame({'edad':edad,
'income':inc,
'region':reg
}) # Creamos el pandas.DataFrame como un diccionario de listas o arreglos
```
Agreguemos alguna interacción para que no sea tan fome...
```
df = pd.DataFrame({'edad':edad,
'income':inc,
'region':reg
}) # Creamos el pandas.DataFrame como un diccionario de listas o arreglos
df.income = ((df.edad.values-55)*4)**2 + df.income.values - df.region*1e4
display(df.head(5)) # primeros 5 registros
display(df.tail(5)) # últimos 5 registros
def rango(edad): # TIP: Cualquier función que tenga un Docstring, se puede verificar con shift+tab
'''Calcula en que rango de edad cae un registro, toma un float.
Retorna: str
''' # <--- este es el Docstring
if edad<35:
return 'joven'
elif edad<55:
return 'menos joven'
else:
return 'mayor'
```
Aplica la funcion rango a toda la columna edad y se la asigna a la columna *rango edad*
```
df['rango edad'] = df.edad.apply(rango)
df.head(10)
```
Agrupemos el income por rango de edad, primero contemos cuantos registros hay en cada clase
```
df[['rango edad','income']].groupby('rango edad')
display(df[['rango edad','income']].groupby('rango edad').count())
```
veamos ahora el promedio y la desviación estandar por cada grupo
```
display(df[['rango edad','income']].groupby('rango edad').mean())
display(df[['rango edad','income']].groupby('rango edad').std())
df[['rango edad','region','income']].groupby(['rango edad','region']).mean()
grouped = df[['rango edad','region','income']].groupby(['rango edad','region']).std()
grouped
grouped.loc['menos joven',0]
df[(df.edad>30) & (df.edad<50) & (df.region == 2) ][['edad','income']].describe()
df[(df.edad>30) & (df.edad<50) & (df.region == 2) ][['edad','income']].hist()
```
### Merge <a id='merge'> </a>
Merge es la operación equivalente a los *join* en *SQL*, nos permite juntar dos dataframes basado en los valores de una columna.
Notemos que existen distintas maneras de hacer eso:
* Inner.
* Outer.
Para más detalles estudie la documentación en este [link](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html).
Ahora definamos un poco de metadata para pegarselo a nuestro dataframe original
```
df_meta = pd.DataFrame({'grupo etario':['menor de edad','joven','menos joven','mayor'],
'clasificacion':[0,1,2,3],
'ingreso_promedio':[352000, 343000, 347000,np.nan]
})
df_meta
```
Juntemos nuestro dataframe anterior con esta nueva información que tenemos...
```
merged = pd.merge(df,df_meta, # df es el left (izquierda de la coma) df_meta es el right (derecha de la coma)
left_on='rango edad', # nombre de la llave en el dataframe de la izquierda
right_on='grupo etario', # nombre de la llave en el dataframe de la izquierda
how='inner',
indicator=True # agrega una columna _merge, que dice que registros estaban en que dataframe
)
merged.head()
```
Veamos como difieren el income del del ingreso promedio
```
(merged.income - merged.ingreso_promedio).hist()
```
#### Ejemplo con dos llaves
En ciertos casos, necesitamos pegar DataFrames usando varias columnas, esta situación es trivial usando pd.merge.
Veamos un caso nuevo...
```
cuentas = np.random.randint(low=100,high=200,size=10000)*17000
opes = np.random.randint(low=100,high=200,size=10000)
df_registros = pd.DataFrame({'cuenta':cuentas,
'operacion':opes,
'moroso': np.random.binomial(1,0.05,size=10000)})
df_registros = df_registros[['cuenta',
'operacion',
'moroso']]
df_registros = df_registros.sort_values(['cuenta','operacion']) # así ordenamos un dataframe en base a una columna
df_llaves = df_registros[['cuenta','operacion']].drop_duplicates().copy()
df_llaves = df_llaves.reset_index()
df_llaves.head()
df_registros = df_registros.reset_index()
df_registros.pop('index')
df_registros.head()
```
Unamos la de registros, con su llave única, ¿Como haríamos esto?...
Necesitamos unir por cuenta y operación!
```
merged = pd.merge(df_registros,df_llaves,
how='inner',
left_on=['cuenta','operacion'],
right_on=['cuenta','operacion'])
merged.head()
```
De hecho, si los DataFrames contienen columnas con mismos nombres, el merge se hace sobre esas columnas, por lo que el código anterior se reduce a:
```
merged = pd.merge(df_registros,df_llaves,
how='inner',
)
merged.head()
```
### Melt <a id ='melt'> </a>
Esta operación permite reestructurar un Dataframe a un formato que sea más sencillo de manipular ([link a documentación](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html)).
Generemos datos para un ejemplo:
```
data = { i:[np.random.randint(low=1,high=11)
for j in range(7)
]
for i in range(10)
}
cols=['person {}'.format(i) for i in range(10)]
to_melt = pd.DataFrame(data)
to_melt.columns=cols
to_melt['year']= range(2010,2017)
to_melt
melted = pd.melt(to_melt, id_vars=['year'], var_name='Name')
melted.head()
```
### P:¿Qué pasó???!!!
R1:Magia.
R2: Pandas tomó todas las columnas que no estaban especificadas en el parámetros *id_vars* y los colocó en la columna **Name** (*var_name*) y por cada registro que existía en esa columna, creó un registro en el nuevo dataframe (*melted*), por lo que:
len(melted)=len(to_melt)x(len(to_melt.columns)-len(id_vars)).
A veces, tenemos que *derretir* un DataFrame basado en varias columnas, para eso tenemos el ejemplo siguiente:
**SPOILER-ALERT**: es tan sencillo como especificar las columnas en el parámetro *id_vars*
#### Ejemplo con dos columnas.
Generemos un DataFrame para el que tenga sentido hacer esta operación (por ejemplo, un dataframe con cuenta, operación y periodo mora...)
```
data = { i:[np.random.binomial(1,0.1)
for j in range(20)
]
for i in range(24)
}
cols=['periodo mora {}'.format(i) for i in range(24)]
to_melt = pd.DataFrame(data)
to_melt.columns=cols
to_melt['cuenta']= range(19,19+20)
to_melt['codigo']= np.random.randint(low=1000,high=2000,size=20)
to_melt = to_melt[list(to_melt.columns[-2:])
+list(to_melt.columns[:-2])
]
to_melt
```
Si quisieramos trabajar este dataframe como algo vertical, deberíamos usar la funcion *melt*.
```
id_vars=['cuenta','codigo']
melted = pd.melt(to_melt,
id_vars=id_vars, # así de sencillo!
var_name='Periodo Mora',
value_name='Flag mora'
)
melted_and_sorted = melted.sort_values(['cuenta',
'codigo']
) # ordenemos el DF segun cuenta y operación, para que sea más boni.
melted_and_sorted.head(24)
```
Si hubieramos olvidado agrega *'codigo'* al parámetro *id_vars* habríamos conseguido lo siguiente:
```
melted = pd.melt(to_melt, id_vars=['cuenta'], var_name='Mora')
melted_and_sorted = melted.sort_values(['cuenta'])
print(len(melted_and_sorted)) # Sobran valores!
melted_and_sorted.head(24)
```
Ahora en la columna mora, tenemos de vez en cuando un item con el valor "codigo", el cual debería ser otra columna!
# Sanity-Check <a id='sc'><a>
Como haríamos un Sanity-Check en python¿?
Revisaremos 3 pasos:
1. Validar DV.
2. Botar duplicados.
3. Contar difuntos/interdictos.
Primero hagamos un data set.
```
n = 1000000 #cantidad de registros
data = {'ID': [ ' persona {}'.format(i)
for i in range(n)], #TIP: las *list comprehension* permiten una escritura concisa de expresiones complejas
'rut': ['{}-{}'.format(i,np.random.randint(low=0,high=9))
for i in range(17000000,17000000+n)],
'difunto' : np.random.binomial(1,0.01,size=n),
'interdicto':np.random.binomial(1,0.005,size=n)
}
DF = pd.DataFrame(data)
DF.head()
def is_valid(rut,DV):
''' El primer argumento es la parte numerica del rut (float o str)
y DV es el digito verificador en formato string
'''
rut_reversed = str(rut)[::-1] #revertimos los ruts
rut_array = np.array(list(rut_reversed),dtype=int) #ahora lo guardamos en un array, como tipo numerico
coefs = np.arange(len(rut_array))%6+2 # generamos los coeficientes correspondientes
# print(rut_array)
# print(coefs)
suma = np.sum(coefs*rut_array)
# print(suma)
digit = 11 - suma%11 # calculamos el digito
# print(digit)
if digit == 10: # si es 10 lo reemplazamos por k
DV_calculado = 'k'
else:
DV_calculado = str(digit) # si no, lo convertimos el int a str
return DV == DV_calculado
```
Forma 1 (la mala (lenta))
```
DF['rut_sin_DV'] = DF.rut.apply(lambda x: int(x.split('-')[0]))
DF['DV'] = DF.rut.apply(lambda x: str(x.split('-')[1]))
```
la manera anterior no la usaremos porque me parece menos pythonista
Forma 2 (la no tan mala (menos lenta))
```
DF['Split'] = DF.rut.str.split('-')
#%%timeit
DF['is_valid'] = DF.Split.apply(lambda x: is_valid(int(x[0]),x[1]))
```
Veamos cuantos registros válidos tenemos... (usemos groupby?)
```
DF_valid = DF[DF.is_valid]
DF.groupby('is_valid').size()
```
Esa cantidad exagerada se debe a que agregamos el DV de manera aleatoria, por lo que era esperable.
Veamos ahora los duplicados, para eso existe el método *.drop_duplicates()*, recordemos además que queremos botar los duplicados en el rut, independiente de las otras columnas, para eso usemos el parámetros *subset*
```
DF_not_duplicates = DF_valid.drop_duplicates(subset=['rut'])
```
Por la manera en que generamos los registros, que podemos esperar de de esta operación?
Por último, verifiquemos los cuantos difuntos e interdictos tenemos (para variar, groupby...)
```
DF_not_duplicates[['difunto','ID']].groupby('difunto').count()
DF_not_duplicates[['interdicto','ID']].groupby('interdicto').count()
```
Ahora ambas clases juntas!
```
DF_not_duplicates[['difunto','interdicto','ID']].groupby(['difunto','interdicto']).count()
```
Seleccionemos los que no están difuntos ni interdictos: (usaremos la técnica llamada *masking*)
```
DF_clean = DF_not_duplicates[(DF_not_duplicates.difunto==0)
& (DF_not_duplicates.interdicto==0)]
print(len(DF_clean))
```
Del millón de registros, sobrevivieron como 80K~, pero estamos seguros que estos son válidos.
| github_jupyter |
```
from __future__ import print_function, division
import pickle
import torch
import sys
# sys.path.append('../../res/')
from loader import synthetic_loader
# from loader import city_scapes_loader
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import copy
import os
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import pickle
import sys
from PIL import Image
import torch.nn.functional as F
import math
from model import Unet
from model import FCN
from config_file import *
BATCH_SIZE = 2
CITYSCAPES = False
# TRAIN_DIR = '/data/graphics/'
VAL_DIR = '/data/graphics/toyota-pytorch/biased_dataset_generalization/datasets/test-set/val/'
data_transforms = {
'train': transforms.Compose([
transforms.Resize(IN_SIZE),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(IN_SIZE),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
}
label_transforms = {
'train': transforms.Compose([
transforms.Resize(IN_SIZE),
transforms.ToTensor()
]),
'val': transforms.Compose([
transforms.Resize(IN_SIZE),
transforms.ToTensor()
])
}
if CITYSCAPES:
# dset_train = city_scapes_loader.ImageFolder(TRAIN_DIR, data_transforms['train'])
dset_val = city_scapes_loader.ImageFolder(VAL_DIR, data_transforms['val'])
else:
# dset_train = synthetic_loader.ImageFolder(TRAIN_DIR, data_transforms['train'],target_transform=label_transforms['train'])
dset_val = synthetic_loader.ImageFolder(VAL_DIR, data_transforms['val'],target_transform=label_transforms['val'])
# train_loader = torch.utils.data.DataLoader(dset_train, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
val_loader = torch.utils.data.DataLoader(dset_val, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
dset_loaders = {'val':val_loader}
dset_sizes = {}
# dset_sizes['train'] = len(dset_train)
dset_sizes['val'] = len(dset_val)
def batch_iou_sum(labels, predictions):
iou_sum = 0
for i in range(len(labels)):
iou_sum += binary_iou(labels[i],predictions[i])
return iou_sum
def batch_ppa_sum(labels, predictions):
ppa_sum = 0
for i in range(len(labels)):
ppa_sum += per_pixel_acc(labels[i],predictions[i])
return ppa_sum
def binary_iou(l,p):
label = l.cpu().numpy().astype(int)
pred = p.detach().cpu().numpy().astype(int)
intersection = np.sum(np.bitwise_and(label,pred))
union = np.sum(np.bitwise_or(label,pred))
if union == 0:
return 0
else:
return intersection/union
def per_pixel_acc(l,p):
label = l.cpu().numpy().astype(int)
pred = p.detach().cpu().numpy().astype(int)
h,w = label.shape
intersection = np.sum(np.bitwise_xor(label,pred))
return ((h*w) - intersection)/(h*w)
def show_results(model_path,GPU=False):
total_iou = 0
total_ppa = 0
count = 0
if GPU == False:
model = torch.load(model_path,map_location='cpu')
model.cpu();
else:
model = torch.load(model_path)
for data in dset_loaders['val']:
inputs, labels = data
if GPU == False:
outputs = model(inputs)
else:
outputs = model(inputs.cuda())
predictions = torch.argmax(outputs,dim=1)
batch_iou = batch_iou_sum(labels,predictions)
batch_ppa = batch_ppa_sum(labels,predictions)
if math.isnan(batch_iou):
break
if math.isnan(batch_ppa):
break
else:
total_iou += batch_iou
total_ppa += batch_ppa
count += len(labels)
average_ppa = total_ppa/count
average_iou = total_iou/count
return average_iou, average_ppa
def evaluate_model(model_path,GPU=False):
total_iou = 0
total_ppa = 0
count = 0
if GPU == False:
model = torch.load(model_path,map_location='cpu')
model.cpu();
else:
model = torch.load(model_path)
for data in dset_loaders['val']:
inputs, labels = data
if GPU == False:
outputs = model(inputs)
else:
outputs = model(inputs.cuda())
predictions = torch.argmax(outputs,dim=1)
batch_iou = batch_iou_sum(labels,predictions)
batch_ppa = batch_ppa_sum(labels,predictions)
if math.isnan(batch_iou):
break
if math.isnan(batch_ppa):
break
else:
total_iou += batch_iou
total_ppa += batch_ppa
count += len(labels)
average_ppa = total_ppa/count
average_iou = total_iou/count
return average_iou, average_ppa
trained_models = {1:'../runs/2018-10-30_B6T5J8CG/saved_models/B6T5J8CG.pt',10:'../runs/2018-10-30_O1B5C4OH/saved_models/O1B5C4OH.pt',100:'../runs/2018-10-31_RM4WZDIP/saved_models/RM4WZDIP.pt'}
GPU = True
ious = {}
ppas = {}
for num in trained_models.keys():
print('working on %s car models'%num)
path = trained_models[num]
iou,ppa = evaluate_model(path,GPU=True)
print('Average IOU for %s models:'%num,iou)
print('Average PPA for %s models:'%num,ppa)
ious[num] = iou
ppas[num] = ppa
```
# Visualize random results
| github_jupyter |
# Building a Regression Model for a Financial Dataset
In this notebook, you will build a simple linear regression model to predict the closing AAPL stock price. The lab objectives are:
* Pull data from BigQuery into a Pandas dataframe
* Use Matplotlib to visualize data
* Use Scikit-Learn to build a regression model
```
%%bash
bq mk -d ai4f
bq load --autodetect --source_format=CSV ai4f.AAPL10Y gs://cloud-training/ai4f/AAPL10Y.csv
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
plt.rc('figure', figsize=(12, 8.0))
```
## Pull Data from BigQuery
In this section we'll use a magic function to query a BigQuery table and then store the output in a Pandas dataframe. A magic function is just an alias to perform a system command. To see documentation on the "bigquery" magic function execute the following cell:
```
%%bigquery?
```
The query below selects everything you'll need to build a regression model to predict the closing price of AAPL stock. The model will be very simple for the purposes of demonstrating BQML functionality. The only features you'll use as input into the model are the previous day's closing price and a three day trend value. The trend value can only take on two values, either -1 or +1. If the AAPL stock price has increased over any two of the previous three days then the trend will be +1. Otherwise, the trend value will be -1.
Note, the features you'll need can be generated from the raw table `ai4f.AAPL10Y` using Pandas functions. However, it's better to take advantage of the serverless-ness of BigQuery to do the data pre-processing rather than applying the necessary transformations locally.
```
%%bigquery df
WITH
raw AS (
SELECT
date,
close,
LAG(close, 1) OVER(ORDER BY date) AS min_1_close,
LAG(close, 2) OVER(ORDER BY date) AS min_2_close,
LAG(close, 3) OVER(ORDER BY date) AS min_3_close,
LAG(close, 4) OVER(ORDER BY date) AS min_4_close
FROM
`ai4f.AAPL10Y`
ORDER BY
date DESC ),
raw_plus_trend AS (
SELECT
date,
close,
min_1_close,
IF (min_1_close - min_2_close > 0, 1, -1) AS min_1_trend,
IF (min_2_close - min_3_close > 0, 1, -1) AS min_2_trend,
IF (min_3_close - min_4_close > 0, 1, -1) AS min_3_trend
FROM
raw ),
train_data AS (
SELECT
date,
close,
min_1_close AS day_prev_close,
IF (min_1_trend + min_2_trend + min_3_trend > 0, 1, -1) AS trend_3_day
FROM
raw_plus_trend
ORDER BY
date ASC )
SELECT
*
FROM
train_data
```
View the first five rows of the query's output. Note that the object `df` containing the query output is a Pandas Dataframe.
```
print(type(df))
df.dropna(inplace=True)
df.head()
```
## Visualize data
The simplest plot you can make is to show the closing stock price as a time series. Pandas DataFrames have built in plotting funtionality based on Matplotlib.
```
df.plot(x='date', y='close');
```
You can also embed the `trend_3_day` variable into the time series above.
```
start_date = '2018-06-01'
end_date = '2018-07-31'
plt.plot(
'date', 'close', 'k--',
data = (
df.loc[pd.to_datetime(df.date).between(start_date, end_date)]
)
)
plt.scatter(
'date', 'close', color='b', label='pos trend',
data = (
df.loc[df.trend_3_day == 1 & pd.to_datetime(df.date).between(start_date, end_date)]
)
)
plt.scatter(
'date', 'close', color='r', label='neg trend',
data = (
df.loc[(df.trend_3_day == -1) & pd.to_datetime(df.date).between(start_date, end_date)]
)
)
plt.legend()
plt.xticks(rotation = 90);
df.shape
```
## Build a Regression Model in Scikit-Learn
In this section you'll train a linear regression model to predict AAPL closing prices when given the previous day's closing price `day_prev_close` and the three day trend `trend_3_day`. A training set and test set are created by sequentially splitting the data after 2000 rows.
```
features = ['day_prev_close', 'trend_3_day']
target = 'close'
X_train, X_test = df.loc[:2000, features], df.loc[2000:, features]
y_train, y_test = df.loc[:2000, target], df.loc[2000:, target]
# Create linear regression object. Don't include an intercept,
# TODO
# Train the model using the training set
# TODO
# Make predictions using the testing set
# TODO
# Print the root mean squared error of your predictions
# TODO
# Print the variance score (1 is perfect prediction)
# TODO
# Plot the predicted values against their corresponding true values
# TODO
```
The model's predictions are more or less in line with the truth. However, the utility of the model depends on the business context (i.e. you won't be making any money with this model). It's fair to question whether the variable `trend_3_day` even adds to the performance of the model:
```
print('Root Mean Squared Error: {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, X_test.day_prev_close))))
```
Indeed, the RMSE is actually lower if we simply use the previous day's closing value as a prediction! Does increasing the number of days included in the trend improve the model? Feel free to create new features and attempt to improve model performance!
| github_jupyter |
# Weight Decay
:label:`sec_weight_decay`
Now that we have characterized the problem of overfitting,
we can introduce some standard techniques for regularizing models.
Recall that we can always mitigate overfitting
by going out and collecting more training data.
That can be costly, time consuming,
or entirely out of our control,
making it impossible in the short run.
For now, we can assume that we already have
as much high-quality data as our resources permit
and focus on regularization techniques.
Recall that in our
polynomial regression example
(:numref:`sec_model_selection`)
we could limit our model's capacity
simply by tweaking the degree
of the fitted polynomial.
Indeed, limiting the number of features
is a popular technique to mitigate overfitting.
However, simply tossing aside features
can be too blunt an instrument for the job.
Sticking with the polynomial regression
example, consider what might happen
with high-dimensional inputs.
The natural extensions of polynomials
to multivariate data are called *monomials*,
which are simply products of powers of variables.
The degree of a monomial is the sum of the powers.
For example, $x_1^2 x_2$, and $x_3 x_5^2$
are both monomials of degree 3.
Note that the number of terms with degree $d$
blows up rapidly as $d$ grows larger.
Given $k$ variables, the number of monomials
of degree $d$ (i.e., $k$ multichoose $d$) is ${k - 1 + d} \choose {k - 1}$.
Even small changes in degree, say from $2$ to $3$,
dramatically increase the complexity of our model.
Thus we often need a more fine-grained tool
for adjusting function complexity.
## Norms and Weight Decay
We have described
both the $L_2$ norm and the $L_1$ norm,
which are special cases of the more general $L_p$ norm
in :numref:`subsec_lin-algebra-norms`.
(***Weight decay* (commonly called $L_2$ regularization),
might be the most widely-used technique
for regularizing parametric machine learning models.**)
The technique is motivated by the basic intuition
that among all functions $f$,
the function $f = 0$
(assigning the value $0$ to all inputs)
is in some sense the *simplest*,
and that we can measure the complexity
of a function by its distance from zero.
But how precisely should we measure
the distance between a function and zero?
There is no single right answer.
In fact, entire branches of mathematics,
including parts of functional analysis
and the theory of Banach spaces,
are devoted to answering this issue.
One simple interpretation might be
to measure the complexity of a linear function
$f(\mathbf{x}) = \mathbf{w}^\top \mathbf{x}$
by some norm of its weight vector, e.g., $\| \mathbf{w} \|^2$.
The most common method for ensuring a small weight vector
is to add its norm as a penalty term
to the problem of minimizing the loss.
Thus we replace our original objective,
*minimizing the prediction loss on the training labels*,
with new objective,
*minimizing the sum of the prediction loss and the penalty term*.
Now, if our weight vector grows too large,
our learning algorithm might focus
on minimizing the weight norm $\| \mathbf{w} \|^2$
vs. minimizing the training error.
That is exactly what we want.
To illustrate things in code,
let us revive our previous example
from :numref:`sec_linear_regression` for linear regression.
There, our loss was given by
$$L(\mathbf{w}, b) = \frac{1}{n}\sum_{i=1}^n \frac{1}{2}\left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right)^2.$$
Recall that $\mathbf{x}^{(i)}$ are the features,
$y^{(i)}$ are labels for all data examples $i$, and $(\mathbf{w}, b)$
are the weight and bias parameters, respectively.
To penalize the size of the weight vector,
we must somehow add $\| \mathbf{w} \|^2$ to the loss function,
but how should the model trade off the
standard loss for this new additive penalty?
In practice, we characterize this tradeoff
via the *regularization constant* $\lambda$,
a non-negative hyperparameter
that we fit using validation data:
$$L(\mathbf{w}, b) + \frac{\lambda}{2} \|\mathbf{w}\|^2,$$
For $\lambda = 0$, we recover our original loss function.
For $\lambda > 0$, we restrict the size of $\| \mathbf{w} \|$.
We divide by $2$ by convention:
when we take the derivative of a quadratic function,
the $2$ and $1/2$ cancel out, ensuring that the expression
for the update looks nice and simple.
The astute reader might wonder why we work with the squared
norm and not the standard norm (i.e., the Euclidean distance).
We do this for computational convenience.
By squaring the $L_2$ norm, we remove the square root,
leaving the sum of squares of
each component of the weight vector.
This makes the derivative of the penalty easy to compute: the sum of derivatives equals the derivative of the sum.
Moreover, you might ask why we work with the $L_2$ norm
in the first place and not, say, the $L_1$ norm.
In fact, other choices are valid and
popular throughout statistics.
While $L_2$-regularized linear models constitute
the classic *ridge regression* algorithm,
$L_1$-regularized linear regression
is a similarly fundamental model in statistics, which is popularly known as *lasso regression*.
One reason to work with the $L_2$ norm
is that it places an outsize penalty
on large components of the weight vector.
This biases our learning algorithm
towards models that distribute weight evenly
across a larger number of features.
In practice, this might make them more robust
to measurement error in a single variable.
By contrast, $L_1$ penalties lead to models
that concentrate weights on a small set of features by clearing the other weights to zero.
This is called *feature selection*,
which may be desirable for other reasons.
Using the same notation in :eqref:`eq_linreg_batch_update`,
the minibatch stochastic gradient descent updates
for $L_2$-regularized regression follow:
$$
\begin{aligned}
\mathbf{w} & \leftarrow \left(1- \eta\lambda \right) \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \mathbf{x}^{(i)} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right).
\end{aligned}
$$
As before, we update $\mathbf{w}$ based on the amount
by which our estimate differs from the observation.
However, we also shrink the size of $\mathbf{w}$ towards zero.
That is why the method is sometimes called "weight decay":
given the penalty term alone,
our optimization algorithm *decays*
the weight at each step of training.
In contrast to feature selection,
weight decay offers us a continuous mechanism
for adjusting the complexity of a function.
Smaller values of $\lambda$ correspond
to less constrained $\mathbf{w}$,
whereas larger values of $\lambda$
constrain $\mathbf{w}$ more considerably.
Whether we include a corresponding bias penalty $b^2$
can vary across implementations,
and may vary across layers of a neural network.
Often, we do not regularize the bias term
of a network's output layer.
## High-Dimensional Linear Regression
We can illustrate the benefits of
weight decay
through a simple synthetic example.
```
%matplotlib inline
import torch
from torch import nn
from d2l import torch as d2l
```
First, we [**generate some data as before**]
(**$$y = 0.05 + \sum_{i = 1}^d 0.01 x_i + \epsilon \text{ where }
\epsilon \sim \mathcal{N}(0, 0.01^2).$$**)
We choose our label to be a linear function of our inputs,
corrupted by Gaussian noise with zero mean and standard deviation 0.01.
To make the effects of overfitting pronounced,
we can increase the dimensionality of our problem to $d = 200$
and work with a small training set containing only 20 examples.
```
n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5
true_w, true_b = torch.ones((num_inputs, 1)) * 0.01, 0.05
train_data = d2l.synthetic_data(true_w, true_b, n_train)
train_iter = d2l.load_array(train_data, batch_size)
test_data = d2l.synthetic_data(true_w, true_b, n_test)
test_iter = d2l.load_array(test_data, batch_size, is_train=False)
```
## Implementation from Scratch
In the following, we will implement weight decay from scratch,
simply by adding the squared $L_2$ penalty
to the original target function.
### [**Initializing Model Parameters**]
First, we will define a function
to randomly initialize our model parameters.
```
def init_params():
w = torch.normal(0, 1, size=(num_inputs, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
return [w, b]
```
### (**Defining $L_2$ Norm Penalty**)
Perhaps the most convenient way to implement this penalty
is to square all terms in place and sum them up.
```
def l2_penalty(w):
return torch.sum(w.pow(2)) / 2
```
### [**Defining the Training Loop**]
The following code fits a model on the training set
and evaluates it on the test set.
The linear network and the squared loss
have not changed since :numref:`chap_linear`,
so we will just import them via `d2l.linreg` and `d2l.squared_loss`.
The only change here is that our loss now includes the penalty term.
```
def train(lambd):
w, b = init_params()
net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss
num_epochs, lr = 100, 0.003
animator = d2l.Animator(xlabel='epochs', ylabel='loss', yscale='log',
xlim=[5, num_epochs], legend=['train', 'test'])
for epoch in range(num_epochs):
for X, y in train_iter:
# The L2 norm penalty term has been added, and broadcasting
# makes `l2_penalty(w)` a vector whose length is `batch_size`
l = loss(net(X), y) + lambd * l2_penalty(w)
l.sum().backward()
d2l.sgd([w, b], lr, batch_size)
if (epoch + 1) % 5 == 0:
animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss),
d2l.evaluate_loss(net, test_iter, loss)))
print('L2 norm of w:', torch.norm(w).item())
```
### [**Training without Regularization**]
We now run this code with `lambd = 0`,
disabling weight decay.
Note that we overfit badly,
decreasing the training error but not the
test error---a textbook case of overfitting.
```
train(lambd=0)
```
### [**Using Weight Decay**]
Below, we run with substantial weight decay.
Note that the training error increases
but the test error decreases.
This is precisely the effect
we expect from regularization.
```
train(lambd=3)
```
## [**Concise Implementation**]
Because weight decay is ubiquitous
in neural network optimization,
the deep learning framework makes it especially convenient,
integrating weight decay into the optimization algorithm itself
for easy use in combination with any loss function.
Moreover, this integration serves a computational benefit,
allowing implementation tricks to add weight decay to the algorithm,
without any additional computational overhead.
Since the weight decay portion of the update
depends only on the current value of each parameter,
the optimizer must touch each parameter once anyway.
In the following code, we specify
the weight decay hyperparameter directly
through `weight_decay` when instantiating our optimizer.
By default, PyTorch decays both
weights and biases simultaneously. Here we only set `weight_decay` for
the weight, so the bias parameter $b$ will not decay.
```
def train_concise(wd):
net = nn.Sequential(nn.Linear(num_inputs, 1))
for param in net.parameters():
param.data.normal_()
loss = nn.MSELoss(reduction='none')
num_epochs, lr = 100, 0.003
# The bias parameter has not decayed
trainer = torch.optim.SGD([
{"params":net[0].weight,'weight_decay': wd},
{"params":net[0].bias}], lr=lr)
animator = d2l.Animator(xlabel='epochs', ylabel='loss', yscale='log',
xlim=[5, num_epochs], legend=['train', 'test'])
for epoch in range(num_epochs):
for X, y in train_iter:
trainer.zero_grad()
l = loss(net(X), y)
l.mean().backward()
trainer.step()
if (epoch + 1) % 5 == 0:
animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss),
d2l.evaluate_loss(net, test_iter, loss)))
print('L2 norm of w:', net[0].weight.norm().item())
```
[**The plots look identical to those when
we implemented weight decay from scratch**].
However, they run appreciably faster
and are easier to implement,
a benefit that will become more
pronounced for larger problems.
```
train_concise(0)
train_concise(3)
```
So far, we only touched upon one notion of
what constitutes a simple linear function.
Moreover, what constitutes a simple nonlinear function
can be an even more complex question.
For instance, [reproducing kernel Hilbert space (RKHS)](https://en.wikipedia.org/wiki/Reproducing_kernel_Hilbert_space)
allows one to apply tools introduced
for linear functions in a nonlinear context.
Unfortunately, RKHS-based algorithms
tend to scale poorly to large, high-dimensional data.
In this book we will default to the simple heuristic
of applying weight decay on all layers of a deep network.
## Summary
* Regularization is a common method for dealing with overfitting. It adds a penalty term to the loss function on the training set to reduce the complexity of the learned model.
* One particular choice for keeping the model simple is weight decay using an $L_2$ penalty. This leads to weight decay in the update steps of the learning algorithm.
* The weight decay functionality is provided in optimizers from deep learning frameworks.
* Different sets of parameters can have different update behaviors within the same training loop.
## Exercises
1. Experiment with the value of $\lambda$ in the estimation problem in this section. Plot training and test accuracy as a function of $\lambda$. What do you observe?
1. Use a validation set to find the optimal value of $\lambda$. Is it really the optimal value? Does this matter?
1. What would the update equations look like if instead of $\|\mathbf{w}\|^2$ we used $\sum_i |w_i|$ as our penalty of choice ($L_1$ regularization)?
1. We know that $\|\mathbf{w}\|^2 = \mathbf{w}^\top \mathbf{w}$. Can you find a similar equation for matrices (see the Frobenius norm in :numref:`subsec_lin-algebra-norms`)?
1. Review the relationship between training error and generalization error. In addition to weight decay, increased training, and the use of a model of suitable complexity, what other ways can you think of to deal with overfitting?
1. In Bayesian statistics we use the product of prior and likelihood to arrive at a posterior via $P(w \mid x) \propto P(x \mid w) P(w)$. How can you identify $P(w)$ with regularization?
[Discussions](https://discuss.d2l.ai/t/99)
| github_jupyter |
<a href="https://colab.research.google.com/github/chemaar/python-programming-course/blob/master/Lab_5_Data_Structures_Lists_Strings_STUDENT.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Lab 5: Data structures: Lists and strings
In this notebook, we propose and solve some exercises about basic data structures implemented through Python lists and strings.
* **In these exercises, we can always proceed solving the problems in a generic way or taking advantage of Python capabilities. As a recommendation, first, try the generic way (applicable to any programming language) and, then, using Python**
* **As a good programming practice, our test cases should ensure that all branches of the code are executed at least once.**
## List of exercises
1. Write a a program that creates a list of $n$ numbers initializing each position with a value (the numeric value of such position). Display the list in the console.
* Input: 5
* Expected output:
```
[0,1,3,4,5]
```
2. Write a program that given a list of $n$ numbers, calculates and displays the length of the list.
* Input: [3,4,5,6]
* Expected output:
```
The length of the list is: 4
```
3. Write a program that given a list of $n$ numbers, calculates and displays the max value within the list and its position.
* Input: [8, 1, 9, 2]
* Expected output:
```
The max value is: 9 in position: 2.
```
4. Write a program that given a list of $n$ numbers, calculates and displays the min value within the list and its position.
* Input: [8, 1, 9, 2]
* Expected output:
```
The min value is: 1 in position: 1.
```
5. Write a program that given a list of $n$ numbers, calculates and displays the sum of its elements.
* Input: [8, 1, 9, 2]
* Expected output:
```
The sum is: 20.
```
6. Write a program that given a list of $n$ numbers and a target number $k$, counts the number of occurrences of $k$ in the list.
* Input: [8, 1, 9, 1], $k=1$
* Expected output:
```
The number 1 has 2 occurrences.
```
7. Write a program that given a list of $n$ numbers and a target number $k$, returns and displays the position of the first apparition of the number $k$.
* Input: [8, 1, 9, 1], $k=1$
* Expected output:
```
The number 1 occurs first in position 1.
```
8. Write a program that given a list of $n$ numbers and a target number $k$, returns and displays the position of the last apparition.
* Input: [8, 1, 9, 1], $k=1$
* Expected output:
```
The number 1 occurs last in position 3.
```
9. Write a program that given a list of $n$ numbers and a target number $k$, returns and displays a list of all positions in which the value $k$ occurs.
* Input: [8, 1, 9, 1], $k=1$
* Expected output:
```
The number 1 occurs in [1, 3].
```
10. Write a program that given a list of $n$ numbers, creates a new list in reverse order.
* Input: [7, 5, 9, 2]
* Expected output:
```
The reverse list is [2, 9, 5, 7].
```
11. **Benchmarking**: compare your previous code against the Python versions. See the next example.
```
#Module to use timers
import time
values = [8,1,9,2]
#Start the timer
t = time.time()
min_value = values[0]
position = 0
for i in range(1, len(values)):
if values [i] < min_value:
min_value = values [i]
position = i
print("\n\tMy min version-->time Taken: %.5f sec" % (time.time()-t))
#Python way to find the max value
#Start the timer
t = time.time()
min_value = min(values)
position = values.index(min_value)
print("\n\tPython version-->time Taken: %.5f sec" % (time.time()-t))
```
12. Write a program that given a list of $n$ numbers, $v$, and an scalar number $k$, returns and displays the scalar product of $k \cdot v$.
* Input: [7, 5, 9, 2], k = 3
* Expected output:
```
The scalar product of 3 and [7, 5, 9, 2] is [21, 15, 27, 6].
```
14. Write a program that given two lists of $n$ numbers, returns and displays the vector product of $l1 \cdot l2$.
* Input: [7, 5, 9, 2], [4, 5, 6, 7]
* Expected output:
```
The vector product of [7, 5, 9, 2] and [4, 5, 6, 7] is [28, 25, 54, 14].
```
15. Write a program that given two lists of $n$ numbers, returns all combination of pairs (cartesian product).
* Input: [7, 5, 9, 2], [4, 5, 6, 7]
* Expected output:
```
The cartesian product is: [[7, 4], [7, 5], [7, 6], [7, 7], [5, 4], [5, 5], [5, 6], [5, 7], [9, 4], [9, 5], [9, 6], [9, 7], [2, 4], [2, 5], [2, 6], [2, 7]].
```
16. Write a program that given a list of $n$ numbers, returns and displays the average of the list numbers.
* Input: [4, 5, 6, 7]
* Expected output:
```
The average of [4, 5, 6, 7] is 5.5.
```
17. Write a program that given a list of $n$ numbers and a number $k$, returns the first $k$ numbers.
* Input: [4, 5, 6, 7], k = 2
* Expected output:
```
[4,5]
```
18. Write a program that given a list of $n$ numbers and a number $k$, returns the last $k$ numbers.
* Input: [4, 5, 6, 7], k = 2
* Expected output:
```
[7,6]
```
19. Write a program that given a list of $n$ numbers, returns a new list containing in the same position the factorial of that value (if the value is < 0, the return value will be -1) .
* Input: [5, 0, 1, -1]
* Expected output:
```
[120, 1, 1, -1]
```
20. Write a program that given a list of $n$ numbers, returns a new list without the repeated numbers.
* Input: [4, 5, 5, 6, 6, 8]
* Expected output:
```
[4, 5, 6, 8]
```
21. Write a program that given two lists of $n$ numbers, returns the union of both lists.
* Input: [4,5,6] [5,7,8,9]
* Expected output:
```
[4, 5, 6, 7, 8, 9]
```
22. Write a program that given two lists of $n$ numbers, returns the intersection of both lists.
* Input: [4,5,6] [5,7,8,9]
* Expected output:
```
[5]
```
23. Write a program that asks the user for $n$ numbers and returns a sorted list.
* Use the function `insert(pos, value)`
* Input: 6, 4, 8
* Expected output:
```
[4, 6, 8]
```
24. Write a program that asks the user for $n$ numbers and returns a sorted list in descending order.
* Use the function `insert(pos, value)`
* Input: 6, 4, 8
* Expected output:
```
[8, 6, 4]
```
25. Write a program that given a list of $n$ numbers and a parameter $k$, creates chunks of $k$ elements.
* Input: [1,2,3,4,5,6,7,8,9], k = 3
* Expected output:
```
[ [1,2,3], [4,5,6], [7,8,9] ]
```
26. Write a program that given a number $n$ and an initial value $k$, creates a list of size $n$ with all positions having the initial value.
* Input: n = 10, k = -1
* Expected output:
```
[-1, -1, -1, -1, -1]
```
27. Write a program that given a string, displays the lenght of the string.
* Input: Hello
* Expected output:
```
The lenght of Hello is 5.
```
28. Explore the string object methods.
```
dir ("")
```
28. Write a program that given a string, displays the string in reverse order.
* Input: Hello
* Expected output:
```
Hello and olleH
```
29. Write a program that given a string, displays whether the string is a palindrome.
* Input: anna
* Expected output:
```
anna is a palindrome True.
```
30. Write a program that given a string, displays the string in uppercase letters.
* Make use of function `ord(char)`-->ASCII number of the char.
* Input: This is a string
* Expected output:
```
THIS IS A STRING
```
31. Write a program that given a string, displays the string in lowercase letters.
* Input: THIS IS A STRING
* Expected output:
```
this is a string
```
32. Write a program that given a string and a char separator, returns a list of the words. (Tokenizer)
* Input: Anna,21,Programming
* Expected output:
```
["Anna", "21", "Programming"]
```
33. Write a program that given a list of strings, returns a list with the size of each string.
* Input: ["Anna", "21", "Programming"]
* Expected output:
```
[4, 2, 11]
```
34. Write a program that given a string and a number $k$, returns a list of chunked strings of size $k$.
* Input: "This is a very looooong string" and $k=3$
* Expected output:
```
['Thi', 's i', 's a', ' ve', 'ry ', 'loo', 'ooo', 'ng ', 'str', 'ing']
```
35. Write a program that given a string, returns a trimmed string (removing blankspaces at the beginning and at the end) and separating words with just one blankspace.
* Input: " Hello Mary "
* Expected output:
```
Hello Mary has 18 characters.
Hello Mary has 10 characters.
```
36. Write a program that given a string, an input character and a replacement character, returns a string replacing all occurrences of input character by the replacement character.
* Input: "Hello", input = "l", replacement ="t"
* Expected output:
```
Hello is now Hetto.
```
37. Write a program that given a string, counts and displays the number of unique characters.
* Input: "Hello"
* Expected output:
```
The number of unique characters is 4.
```
38. Write a program that given a list of strings and a char separator, displays a message containing each string separated by separator.
* Input: ["Hello", "Mary,", "How", "are", "you?"], separator = "#"
* Expected output:
```
Hello#Mary,#How#are#you?
```
39. Write a program that given a string and and input pattern (another string), checks if the string starts with the input pattern.
* Input: "Hello", pattern="He"
* Expected output:
```
True
```
40. Write a program that given a string and and input pattern (another string), checks if the string ends with the input pattern.
* Input: "Hello", pattern="lo"
* Expected output:
```
True
```
41. Write a program that given a string, filters all characters that are not numbers.
* Use the function `value.isdigit()`
* Input: "He2l3l4o5"
* Expected output:
```
['2', '3', '4', '5']
```
42. Write a program that given a list of integers and a value $k$, filters all numbers that are less than $k$.
* Input: [4, 15, 9, 21], $k=10$
* Expected output:
```
[4, 9]
```
43. Write a program that given a list of integers and a value $k$, removes the first apparition of the value from the list.
* Input: [4, 15, 9, 21], $k=15$
* Expected output:
```
[4, 9, 21]
```
44. Write a program that asks the user for introducing $k$ numbers and creates a list following a LIFO (Last Input First Output) strategy. Then, the program must extract and remove the elements following this strategy
* Input: 4, 5, 6, 7 ($k=4$)
* Expected output:
```
Stack: [4, 5, 6, 7]
Extracting: 7, Stack: [4, 5, 6, 7]
Extracting: 6, Stack: [4, 5, 6]
Extracting: 5, Stack: [4, 5]
Extracting: 4, Stack: [4]
```
45. Write a program that asks the user for introducing $k$ numbers and creates a list following a FIFO (First Input First Output) strategy. Then, the program must extract and remove the elements following this strategy
* Input: 4, 5, 6, 7 ($k=4$)
* Expected output:
```
Stack: [4, 5, 6, 7]
Extracting: 4, Stack: [4, 5, 6, 7]
Extracting: 5, Stack: [5, 6, 7]
Extracting: 6, Stack: [6, 7]
Extracting: 7, Stack: [7]
```
## Quick questions
**1. Define the lists x and y as lists of numbers.**
* x = [2, 4, 6, 8]
* y = [1, 3, 5, 7]
* What is the value of 2*x?
* What is the result of x+y?
* What is the result of x-y?
* What is the value of x[1]?
* What is the value of x[-1]?
* What is the value of x[:]?
* What is the value of x[2:4]?
* What is the value of x[1:4:2]?
* What is the value of x[:2]?
* What is the value of x[::2]?
* What is the result of the following two expressions? x[3]=8
**2. Define a string x = "Hello"**
* What is the value of 4*x?
* What is the value of x[1]?
* What is the value of x[-1]?
* What is the value of x[::2]?
* What is the value of x[::-1]?
## Quick review of list and string methods
### List: some relevant methods
```
#Review of list methods
#Create a list
values = []
#Append an element
values.append(1)
print(values)
#Access an element
print(values[0])
#Get number of elements
len(values)
print(len(values))
#Count the number of elements
print(values.count(1))
#Slicing [start:end:step], default start = 0, end = len(list), step = 1
#First k elements, k = 1
print(values[:1])
#List sort
print(values.sort())
#List reverse
values.reverse()
#Remove an element
del values [0]
#Remove all elements
values.clear()
```
### String: some relevant methods
```
#Review of string methods
value = " Hello, Mary "
print(len(value))
#Accessing
print(value[5])
#Cleaning
print(value.strip())
#Modifying values
print(value.upper())
print(value.lower())
#Finding and replacing
print("Hello".startswith("He"))
print("Hello".endswith("lo"))
print(value.find("H"))
print(value.replace(" ","#"))
#Check values
print("1".isdigit())
print("a".isalpha())
#Tokenizing
print(value.split(","))
```
| github_jupyter |
---
_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._
---
## Assignment 4 - Understanding and Predicting Property Maintenance Fines
This assignment is based on a data challenge from the Michigan Data Science Team ([MDST](http://midas.umich.edu/mdst/)).
The Michigan Data Science Team ([MDST](http://midas.umich.edu/mdst/)) and the Michigan Student Symposium for Interdisciplinary Statistical Sciences ([MSSISS](https://sites.lsa.umich.edu/mssiss/)) have partnered with the City of Detroit to help solve one of the most pressing problems facing Detroit - blight. [Blight violations](http://www.detroitmi.gov/How-Do-I/Report/Blight-Complaint-FAQs) are issued by the city to individuals who allow their properties to remain in a deteriorated condition. Every year, the city of Detroit issues millions of dollars in fines to residents and every year, many of these fines remain unpaid. Enforcing unpaid blight fines is a costly and tedious process, so the city wants to know: how can we increase blight ticket compliance?
The first step in answering this question is understanding when and why a resident might fail to comply with a blight ticket. This is where predictive modeling comes in. For this assignment, your task is to predict whether a given blight ticket will be paid on time.
All data for this assignment has been provided to us through the [Detroit Open Data Portal](https://data.detroitmi.gov/). **Only the data already included in your Coursera directory can be used for training the model for this assignment.** Nonetheless, we encourage you to look into data from other Detroit datasets to help inform feature creation and model selection. We recommend taking a look at the following related datasets:
* [Building Permits](https://data.detroitmi.gov/Property-Parcels/Building-Permits/xw2a-a7tf)
* [Trades Permits](https://data.detroitmi.gov/Property-Parcels/Trades-Permits/635b-dsgv)
* [Improve Detroit: Submitted Issues](https://data.detroitmi.gov/Government/Improve-Detroit-Submitted-Issues/fwz3-w3yn)
* [DPD: Citizen Complaints](https://data.detroitmi.gov/Public-Safety/DPD-Citizen-Complaints-2016/kahe-efs3)
* [Parcel Map](https://data.detroitmi.gov/Property-Parcels/Parcel-Map/fxkw-udwf)
___
We provide you with two data files for use in training and validating your models: train.csv and test.csv. Each row in these two files corresponds to a single blight ticket, and includes information about when, why, and to whom each ticket was issued. The target variable is compliance, which is True if the ticket was paid early, on time, or within one month of the hearing data, False if the ticket was paid after the hearing date or not at all, and Null if the violator was found not responsible. Compliance, as well as a handful of other variables that will not be available at test-time, are only included in train.csv.
Note: All tickets where the violators were found not responsible are not considered during evaluation. They are included in the training set as an additional source of data for visualization, and to enable unsupervised and semi-supervised approaches. However, they are not included in the test set.
<br>
**File descriptions** (Use only this data for training your model!)
train.csv - the training set (all tickets issued 2004-2011)
test.csv - the test set (all tickets issued 2012-2016)
addresses.csv & latlons.csv - mapping from ticket id to addresses, and from addresses to lat/lon coordinates.
Note: misspelled addresses may be incorrectly geolocated.
<br>
**Data fields**
train.csv & test.csv
ticket_id - unique identifier for tickets
agency_name - Agency that issued the ticket
inspector_name - Name of inspector that issued the ticket
violator_name - Name of the person/organization that the ticket was issued to
violation_street_number, violation_street_name, violation_zip_code - Address where the violation occurred
mailing_address_str_number, mailing_address_str_name, city, state, zip_code, non_us_str_code, country - Mailing address of the violator
ticket_issued_date - Date and time the ticket was issued
hearing_date - Date and time the violator's hearing was scheduled
violation_code, violation_description - Type of violation
disposition - Judgment and judgement type
fine_amount - Violation fine amount, excluding fees
admin_fee - $20 fee assigned to responsible judgments
state_fee - $10 fee assigned to responsible judgments
late_fee - 10% fee assigned to responsible judgments
discount_amount - discount applied, if any
clean_up_cost - DPW clean-up or graffiti removal cost
judgment_amount - Sum of all fines and fees
grafitti_status - Flag for graffiti violations
train.csv only
payment_amount - Amount paid, if any
payment_date - Date payment was made, if it was received
payment_status - Current payment status as of Feb 1 2017
balance_due - Fines and fees still owed
collection_status - Flag for payments in collections
compliance [target variable for prediction]
Null = Not responsible
0 = Responsible, non-compliant
1 = Responsible, compliant
compliance_detail - More information on why each ticket was marked compliant or non-compliant
___
## Evaluation
Your predictions will be given as the probability that the corresponding blight ticket will be paid on time.
The evaluation metric for this assignment is the Area Under the ROC Curve (AUC).
Your grade will be based on the AUC score computed for your classifier. A model which with an AUROC of 0.7 passes this assignment, over 0.75 will recieve full points.
___
For this assignment, create a function that trains a model to predict blight ticket compliance in Detroit using `train.csv`. Using this model, return a series of length 61001 with the data being the probability that each corresponding ticket from `test.csv` will be paid, and the index being the ticket_id.
Example:
ticket_id
284932 0.531842
285362 0.401958
285361 0.105928
285338 0.018572
...
376499 0.208567
376500 0.818759
369851 0.018528
Name: compliance, dtype: float32
### Hints
* Make sure your code is working before submitting it to the autograder.
* Print out your result to see whether there is anything weird (e.g., all probabilities are the same).
* Generally the total runtime should be less than 10 mins. You should NOT use Neural Network related classifiers (e.g., MLPClassifier) in this question.
* Try to avoid global variables. If you have other functions besides blight_model, you should move those functions inside the scope of blight_model.
* Refer to the pinned threads in Week 4's discussion forum when there is something you could not figure it out.
```
import pandas as pd
import numpy as np
def blight_model():
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
df_train = pd.read_csv('train.csv', encoding='latin1')
df_pred = pd.read_csv('test.csv', encoding='latin1')
address = pd.read_csv('addresses.csv', encoding='latin1')
# Merge the addresses into the train and test DataFrames
df_train = pd.merge(df_train, address, how='inner', left_on='ticket_id', right_on='ticket_id')
df_pred = pd.merge(df_pred, address, how='inner', left_on='ticket_id', right_on='ticket_id')
#Delete data with NaN in Ylabels('compliance)
df_train = df_train.dropna(subset=['compliance'])
df_train['compliance'] = df_train['compliance'].astype(int)
#Define the columns to be used
df_train = df_train[['ticket_id', 'state', 'zip_code', 'non_us_str_code',
'country', 'discount_amount', 'judgment_amount', 'address',
'compliance']].set_index('ticket_id')
df_pred = df_pred[['ticket_id', 'state', 'zip_code', 'non_us_str_code',
'country', 'discount_amount', 'judgment_amount', 'address']].set_index('ticket_id')
#Make values->categories, give numbers to categories
columns = ['state', 'zip_code', 'non_us_str_code',
'country', 'discount_amount', 'address']
df_train[columns] = pd.Categorical(df_train[columns]).codes
df_pred[columns] = pd.Categorical(df_pred[columns]).codes
#Define X and Y datasets
Y = df_train['compliance']
X = df_train.drop(['compliance'], axis=1)
X_pred = df_pred
#Train model, predict_probabilities
clf = RandomForestClassifier().fit(X, Y)
y_pred = clf.predict_proba(X_pred)[:, 1]
#Results
results = pd.Series(y_pred, index=df_pred.index)
return results #df_train.corr()
blight_model()
```
| github_jupyter |
# AutoEncoders and Generative Models
**Autoencoder**
```
from keras.datasets import mnist
from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
(X_train, _), (X_test, _) = mnist.load_data()
X_train = X_train.astype('float32')/255
X_test = X_test.astype('float32')/255
X_train = X_train.reshape(len(X_train), np.prod(X_train.shape[1:]))
X_test = X_test.reshape(len(X_test), np.prod(X_test.shape[1:]))
print(X_train.shape)
print(X_test.shape)
input_img= Input(shape=(784,))
# Create simple autoencoder
# The size of our encoded representations
# 32 floats -> compression of factor 24.5, assuming the input is 784 floats
encoding_dim = 32
# "encoded" is the encoded representation of the input
encoded = Dense(encoding_dim, activation='relu')(input_img)
# "decoded" is the lossy reconstruction of the input
decoded = Dense(784, activation='sigmoid')(encoded)
# This model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
# This model maps an input to its encoded representation
encoder = Model(input_img, encoded)
autoencoder.summary()
encoder.summary()
# Compile the model
autoencoder.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['accuracy'])
# Fit the model
autoencoder.fit(X_train, X_train,
epochs=5,
batch_size=256,
shuffle=True,
validation_data=(X_test, X_test))
# Make predictions with the test data
encoded_imgs = encoder.predict(X_test)
predicted = autoencoder.predict(X_test)
# Plotting code from:
# https://medium.com/datadriveninvestor/deep-autoencoder-using-keras-b77cd3e8be95
# Plot the results
plt.figure(figsize=(40, 4))
for i in range(10):
# display original images
ax = plt.subplot(3, 20, i + 1)
plt.imshow(X_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display encoded images
ax = plt.subplot(3, 20, i + 1 + 20)
plt.imshow(encoded_imgs[i].reshape(8,4))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstructed images
ax = plt.subplot(3, 20, 2*20 +i+ 1)
plt.imshow(predicted[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show() # Uncomment to see the figure
# Clear the figure for proper Canvas formatting
plt.clf()
```
**for better results more hidden layers could be added**
```
# Deeper autoencoder
encoded = Dense(units=128, activation='relu')(input_img)
encoded = Dense(units=64, activation='relu')(encoded)
encoded = Dense(units=32, activation='relu')(encoded)
decoded = Dense(units=64, activation='relu')(encoded)
decoded = Dense(units=128, activation='relu')(decoded)
decoded = Dense(units=784, activation='sigmoid')(decoded)
```
**Recive similar images**
```
# Train an autoencoder
from keras.datasets import mnist
from keras.layers import Input, Dense, Flatten
from keras.models import Model
import numpy as np
import pandas as pd
(X_train, _), (X_test, _) = mnist.load_data()
X_train = X_train.astype('float32')/255
X_test = X_test.astype('float32')/255
X_train = X_train.reshape(len(X_train), np.prod(X_train.shape[1:]))
X_test = X_test.reshape(len(X_test), np.prod(X_test.shape[1:]))
print(X_train.shape)
print(X_test.shape)
input_img= Input(shape=(784,))
# Create simple autoencoder
# The size of our encoded representations
encoding_dim = 32
# "encoded" is the encoded representation of the input
encoded = Dense(encoding_dim, activation='relu')(input_img)
# "decoded" is the lossy reconstruction of the input
decoded = Dense(784, activation='sigmoid')(encoded)
# This model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
# This model maps an input to its encoded representation
encoder = Model(input_img, encoded)
# Compile the model
autoencoder.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['accuracy'])
# Fit the model
autoencoder.fit(X_train, X_train,
epochs=10,
batch_size=256,
shuffle=True,
validation_data=(X_test, X_test))
#import tensorflow as tf
#encoded = tf.keras.layers.Flatten()(encoded)
encoded = Flatten()(encoded)
encoder = Model(input_img, encoded)
encoded_imgs = encoder.predict(X_train)
# Let's plot!
import matplotlib.pyplot as plt
# Look up an image that corresponds to this code
query = 34534
plt.imshow(X_train[query].reshape(28, 28));
# Use the encoder model to create the encoded representation
query_encoding = encoder.predict(np.expand_dims(X_train[query],0))
# Use the nearest neighbors algorithm to look up the images
# that have the closest representation
from sklearn.neighbors import NearestNeighbors
# Instantiate the model and fit on the encoded images
nn = NearestNeighbors(n_neighbors=5, algorithm='ball_tree')
nn.fit(encoded_imgs)
# Find the result from the query encoding
results = nn.kneighbors(query_encoding)
# Select and plot the first of the images retrieved
results_loc = results[1][0][1:]
plt.imshow(X_train[results_loc[1]].reshape(28, 28));
```
| github_jupyter |
```
import gzip
try: import simplejson as json
except ImportError: import json
import codecs
import matplotlib.pyplot as plt
import numpy as np
def parse(filename):
#f = gzip.open(filename, 'r')
f = codecs.open(filename,encoding='latin-1')
entry = {}
for l in f:
l = l.strip()
colonPos = l.find(':')
if colonPos == -1:
yield entry
entry = {}
continue
eName = l[:colonPos]
rest = l[colonPos+2:]
entry[eName] = rest
yield entry
finefood_data = []
for e in parse("finefoods.txt"):
finefood_data.append(e)
print("Number of Amazon finefood reviews: {}".format(len(finefood_data)))
finefood_data[2]
#construct the reduced file with only productid, userid, rating
keep_property_arr =["product/productId", "review/userId", "review/score","review/time"]
finefood_reduced =[]
finefood_missingproperties = []
i=0
for review in finefood_data:
user_jsobobj = dict()
flag=0
for prop in keep_property_arr:
if prop not in review:
finefood_missingproperties.append(review)
flag=1
break
if flag==0:
for property in keep_property_arr:
if property =="review/score":
user_jsobobj[property] = float(review[property])
else:
user_jsobobj[property] = review[property]
finefood_reduced.append(user_jsobobj)
finefood_data[94197]
print("Number of 'clean' reviews: {}".format(len(finefood_reduced)))
print("Number of reviews with incomplete information: {}".format(len(finefood_missingproperties)))
Iu = dict() #set of products reviewed by users
qualified_review_count = 0
userproduct_dict = dict() #dictionary to find out review for particular user and item
train_data = [] #generate the qualified reviews
dup_ui_comb = []
ui_timestamp = dict()
count=0
mul_data = []
for review in finefood_reduced:
item = review["product/productId"]
user = review["review/userId"]
time = review["review/time"]
if user in Iu and item in Iu[user]:
if [user,item] not in dup_ui_comb:
dup_ui_comb.append([user,item])
continue;
if user in Iu:# and item not in Iu[user]:
Iu[user].append(item)
ui_timestamp["user"+"item"] = time;
else:
Iu[user] = [item]
ui_timestamp["user"+"item"] = time;
key = user+'-'+item
userproduct_dict[key] = review
train_data.append(review)
qualified_review_count+=1
# Dump all clean and unclean contents to separate files. These files are used for all further processing
print(qualified_review_count)
print(len(dup_ui_comb))
red_data = []
i=0
for user,item in dup_ui_comb:
for review in finefood_reduced:
if review["review/userId"] == user and review["product/productId"] == item:
red_data.append(review)
i+=1
if i==50:
break
two_data= []
for review in finefood_data:
try:
if review["review/userId"] == "A1CBNUBPZPWH5D" and review["product/productId"] == "B0016FY6H6":
two_data.append(review)
except Exception:
pass
two_data
with open("finefood_incompletedata.json",'w') as outfile:
for line in finefood_missingproperties:
json.dump(line,outfile)
outfile.write("\n")
print("File {} written".format("finefood_incompletedata.json"))
outfile.close()
with open("finefood_reduced_time_data.json",'w') as outfile:
json.dump(finefood_reduced,outfile)
print("File {} written".format("finefood_reduced_time_data.json"))
outfile.close()
```
## Exploratory analysis
```
user_set = set()
product_set = set()
scores =[]
for review in finefood_reduced:
if review["product/productId"] not in product_set:
product_set.add(review["product/productId"])
if review["review/userId"] not in user_set:
user_set.add(review["review/userId"])
scores.append(review["review/score"])
print("Number of products: {}".format(len(product_set)))
print("Number of users: {}".format(len(user_set)))
distinct_scores = dict()
for score in scores:
if score not in distinct_scores:
distinct_scores[score]=1
else:
distinct_scores[score]+=1
plt.scatter(list(distinct_scores.keys()),list(distinct_scores.values()))
plt.xlabel("Rating values")
plt.ylabel("Number of reviews")
plt.title(" Number of reviews per rating")
plt.show()
#figure out distribution of average rating of products / or ratings given by users
Iu = dict()
Ui = dict()
for review in finefood_reduced:
if review["product/productId"] in Ui:
Ui[review["product/productId"]].append(float(review["review/score"]))
else:
Ui[review["product/productId"]] = [float(review["review/score"])]
if review["review/userId"] in Iu:
Iu[review["review/userId"]].append(float(review["review/score"]))
else:
Iu[review["review/userId"]] = [float(review["review/score"])]
Iu_len = dict()
len_user = []
for key in Iu:
if len(Iu[key]) not in Iu_len:
Iu_len[len(Iu[key])]=1
else:
Iu_len[len(Iu[key])]+=1
len_user.append(len(Iu[key]))
len_user.sort()
plt.plot(len_user)
plt.xlabel("#users")
plt.ylabel("#reviews")
plt.show()
plt.scatter(list(Iu_len.keys()),list(Iu_len.values()))
plt.ylabel("#users")
plt.xlabel("#reviews")
plt.show()
review_cutoff = 10
count = 0
for key in Iu_len:
if key>review_cutoff:
count+= Iu_len[key]
print("Number of users who have written more than {} reviews is {}".format(review_cutoff,count))
avg_user_rating = dict()
for key in Iu:
if np.mean(Iu[key]) not in avg_user_rating:
avg_user_rating[np.mean(Iu[key])]=1
else:
avg_user_rating[np.mean(Iu[key])]+=1
x = sorted(list(avg_user_rating.keys()),reverse=True)
plt.scatter(list(avg_user_rating.keys()), list(avg_user_rating.values()))
plt.show()
```
| github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import sentencepiece as spm
sp_model = spm.SentencePieceProcessor()
sp_model.Load('prepare/sp10m.cased.ms-en.model')
import tensorflow as tf
import tensorflow_text
import struct
unknown = b'\xff\xff\xff\xff'
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())
for node in graph_def.node:
if node.op == 'RefSwitch':
node.op = 'Switch'
for index in xrange(len(node.input)):
if 'moving_' in node.input[index]:
node.input[index] = node.input[index] + '/read'
elif node.op == 'AssignSub':
node.op = 'Sub'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'AssignAdd':
node.op = 'Add'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'Assign':
node.op = 'Identity'
if 'use_locking' in node.attr: del node.attr['use_locking']
if 'validate_shape' in node.attr: del node.attr['validate_shape']
if len(node.input) == 2:
node.input[0] = node.input[1]
del node.input[1]
if 'Reshape/shape' in node.name or 'Reshape_1/shape' in node.name:
b = node.attr['value'].tensor.tensor_content
arr_int = [int.from_bytes(b[i:i + 4], 'little') for i in range(0, len(b), 4)]
if len(arr_int):
arr_byte = [unknown] + [struct.pack('<i', i) for i in arr_int[1:]]
arr_byte = b''.join(arr_byte)
node.attr['value'].tensor.tensor_content = arr_byte
if len(node.attr['value'].tensor.int_val):
node.attr['value'].tensor.int_val[0] = -1
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
import json
with open('prepare/test-set-segmentation.json') as fopen:
data = json.load(fopen)
X, Y = [], []
for x, y in data:
X.append(x)
Y.append(y)
g = load_graph('super-tiny-segmentation/frozen_model.pb')
x = g.get_tensor_by_name('import/inputs:0')
logits = g.get_tensor_by_name('import/SelectV2_3:0')
test_sess = tf.InteractiveSession(graph = g)
from tqdm import tqdm
batch_size = 10
results = []
for i in tqdm(range(0, len(X), batch_size)):
batch_x = X[i: i + batch_size]
batches = []
for b in batch_x:
batches.append(f'segmentasi: {b}')
g = test_sess.run(logits, feed_dict = {x:batches})
results.extend(g.tolist())
results_Y = [sp_model.DecodeIds(r) for r in results]
results_Y[0], Y[0]
def calculate_wer(actual, hyp):
"""
Calculate WER using `python-Levenshtein`.
"""
import Levenshtein as Lev
b = set(actual.split() + hyp.split())
word2char = dict(zip(b, range(len(b))))
w1 = [chr(word2char[w]) for w in actual.split()]
w2 = [chr(word2char[w]) for w in hyp.split()]
return Lev.distance(''.join(w1), ''.join(w2)) / len(actual.split())
wer = []
for i in tqdm(range(len(results_Y))):
wer.append(calculate_wer(Y[i], results_Y[i]))
import numpy as np
np.mean(wer)
```
| github_jupyter |
```
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras import Model
import tensorflow_probability as tfp
import matplotlib.pylab as plt
# Lets create some data
x = np.arange(-5,5, 0.1)
y = x+ x*np.sin(x)
plt.plot(x,y)
# but real data is never so perfect
# Lets add some noise
random_error = 0.5*np.random.rand(1000).reshape(1000,1)
x = np.arange(-5,5, 0.01).reshape(1000,1)
x_error = x+random_error
y=x_error+ x_error*np.sin(x_error)
#y = ((x+random_error)*np.sin(x+random_error)).reshape(1000,1)
plt.plot(x,y)
# We need to define some distribution for our model
class Gaussian(object):
def __init__(self, mu, **kwargs):
self.mu = mu
#sigma = log(1+e^rho)
rho = kwargs.get("rho", None)
sigma = kwargs.get("sigma", None)
if (rho is None) and (sigma is None):
assert "None of rho or sigma is specified"
elif rho is None:
self.sigma = sigma
self.rho = tf.math.log(tf.math.exp(self.sigma)-1)
elif sigma is None:
self.rho = rho
self.sigma = tf.math.log(1+ tf.math.exp(self.rho))
def sample(self):
epsilon = tf.random.normal(shape = self.mu.shape)
sample = self.mu+self.sigma*epsilon
return sample
def log_prob(self,x):
log_prob = tf.reduce_sum(tfp.distributions.Normal(loc = self.mu, scale = self.sigma).log_prob(x))
return log_prob
class ScaleMixtureGaussian(object):
def __init__(self, pi, sigma_1, sigma_2):
self.pi = pi
self.sigma_1 = sigma_1
self.sigma_2 = sigma_2
self.gaussian_1 = Gaussian(mu = 0.0, sigma = sigma_1)
self.gaussian_2 = Gaussian(mu = 0.0, sigma = sigma_2)
def log_prob(self,x):
prob_1 = tf.clip_by_value(tf.math.exp(self.gaussian_1.log_prob(x)), clip_value_min= 1e-10, clip_value_max= 1.)
prob_2 = tf.clip_by_value(tf.math.exp(self.gaussian_2.log_prob(x)), clip_value_min = 1e-10, clip_value_max = 1.)
return tf.math.log(self.pi*prob_1+(1-self.pi)*prob_2)
# Now lets create our Bayesian Layer
class BayesianDense(Layer):
def __init__(self, units = 4, activation = None, **kwargs):
super(BayesianDense, self).__init__(**kwargs)
self.units = units
prior_pi = 0.5
prior_sigma_1 = tf.math.exp(1.0)
prior_sigma_2 = tf.math.exp(-1.0)
self.activation = tf.keras.activations.get(activation)
self.prior = ScaleMixtureGaussian(prior_pi, prior_sigma_1, prior_sigma_2)
self.log_prior = 0
self.log_posterior = 0
def build(self, input_shape):
w_init = tf.random_uniform_initializer(-2.0, 2.0)
b_init = tf.zeros_initializer()
self.w_mu = tf.Variable(name='w_mu',
initial_value= w_init(shape=(input_shape[-1], self.units),
dtype = 'float32'), trainable = True)
self.w_rho = tf.Variable(name='w_rho',
initial_value= w_init(shape=(input_shape[-1], self.units),
dtype = 'float32'), trainable = True)
self.b_mu = tf.Variable(name='b_mu',
initial_value= b_init(shape=(self.units,),
dtype = 'float32'), trainable = True)
self.b_rho = tf.Variable(name='b_rho',
initial_value= b_init(shape=(self.units,),
dtype = 'float32'), trainable = True)
def call(self, inputs, training=None):
'''This is where all the computation takes place.'''
self.w_dist = Gaussian(self.w_mu, rho = self.w_rho)
self.b_dist = Gaussian(self.b_mu, rho = self.b_rho)
if training:
self.w = self.w_dist.sample()
self.b = self.b_dist.sample()
else:
self.w = self.w_dist.mu
self.b = self.b_dist.mu
self.log_prior = self.prior.log_prob(self.w) + \
self.prior.log_prob(self.b)
self.log_posterior = self.w_dist.log_prob(self.w) + \
self.b_dist.log_prob(self.b)
#print(self.log_prior)
#print(f' This is posterior {self.log_posterior}')
o = self.activation(tf.matmul(inputs,self.w)+self.b)
return o
class BayesianModel(Model):
def __init__(self):
super(BayesianModel, self).__init__()
self.l1 = BayesianDense(input_shape = (1,) , units = 8, activation='relu', name = 'bayesian_dense_1')
self.l2 = BayesianDense(units = 4, activation='relu', name = 'bayesian_dense_2')
self.l3 = BayesianDense(units = 1, activation='relu', name = 'bayesian_dense_3')
#self.l4 = BayesianDense(units = 1, name = 'bayesian_dense_3')
def log_prior(self):
return self.l1.log_prior + self.l2.log_prior + self.l3.log_prior # +self.l4.log_prior
def log_posterior(self):
return self.l1.log_posterior + self.l2.log_posterior + self.l3.log_posterior # + self.l4.log_posterior
def sample_elbo(self, x_val, y_true):
samples = 20
log_priors = []
log_posteriors = []
log_likelihoods = []
for i in range(samples):
output = self(x_val)
log_priors.append(self.log_prior())
log_posteriors.append(self.log_posterior())
log_likelihoods.append(Gaussian(mu = output, sigma = 5.0).log_prob(y_true))
log_prior = tf.math.reduce_mean(tf.stack(log_priors))
log_posterior = tf.math.reduce_mean(tf.stack(log_posteriors))
log_likelihood = tf.math.reduce_mean(tf.stack(log_likelihoods))
elbo = log_posterior-log_prior-log_likelihood
print(f'This is log posterior {log_posterior}')
print(f'This is log prior {log_prior}')
print(f'This is log likelihood {log_likelihood}')
return elbo
def call(self, inputs):
x = self.l1(inputs)
x = self.l2(x)
x = self.l3(x)
# x = self.l4(x)
return x
model = BayesianModel()
model.build(input_shape = (1000,1))
model.summary()
tf.random.set_seed(
1
)
epochs = 10
optimizer = tf.keras.optimizers.Adam(lr=1)
loss_list= []
# Iterate over epochs.
for epoch in range(epochs):
with tf.GradientTape() as tape:
y_pred = model(x, training= True)
# Compute reconstruction loss
loss = model.sample_elbo(x_val=x, y_true = y)
grads = tape.gradient(loss, model.trainable_weights)
loss_list.append(loss)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
plt.plot(loss_list)
plt.plot(x,model(x))
```
| github_jupyter |
```
from preamble import *
%matplotlib inline
```
# Algorithm Chains and Pipelines
```
from sklearn.svm import SVC
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# load and split the data
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
cancer.data, cancer.target, random_state=0)
# compute minimum and maximum on the training data
scaler = MinMaxScaler().fit(X_train)
# rescale training data
X_train_scaled = scaler.transform(X_train)
svm = SVC()
# learn an SVM on the scaled training data
svm.fit(X_train_scaled, y_train)
# scale test data and score the scaled data
X_test_scaled = scaler.transform(X_test)
svm.score(X_test_scaled, y_test)
```
### Parameter Selection with Preprocessing
```
from sklearn.model_selection import GridSearchCV
# illustration purposes only, don't use this code
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100],
'gamma': [0.001, 0.01, 0.1, 1, 10, 100]}
grid = GridSearchCV(SVC(), param_grid=param_grid, cv=5)
grid.fit(X_train_scaled, y_train)
print("best cross-validation accuracy:", grid.best_score_)
print("test set score: ", grid.score(X_test_scaled, y_test))
print("best parameters: ", grid.best_params_)
mglearn.plots.plot_improper_processing()
```
### Building Pipelines
```
from sklearn.pipeline import Pipeline
pipe = Pipeline([("scaler", MinMaxScaler()), ("svm", SVC())])
pipe.fit(X_train, y_train)
pipe.score(X_test, y_test)
```
### Using Pipelines in Grid-searches
```
param_grid = {'svm__C': [0.001, 0.01, 0.1, 1, 10, 100],
'svm__gamma': [0.001, 0.01, 0.1, 1, 10, 100]}
grid = GridSearchCV(pipe, param_grid=param_grid, cv=5)
grid.fit(X_train, y_train)
print("best cross-validation accuracy:", grid.best_score_)
print("test set score: ", grid.score(X_test, y_test))
print("best parameters: ", grid.best_params_)
mglearn.plots.plot_proper_processing()
rnd = np.random.RandomState(seed=0)
X = rnd.normal(size=(100, 10000))
y = rnd.normal(size=(100,))
from sklearn.feature_selection import SelectPercentile, f_regression
select = SelectPercentile(score_func=f_regression, percentile=5).fit(X, y)
X_selected = select.transform(X)
print(X_selected.shape)
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import Ridge
np.mean(cross_val_score(Ridge(), X_selected, y, cv=5))
pipe = Pipeline([("select", SelectPercentile(score_func=f_regression, percentile=5)), ("ridge", Ridge())])
np.mean(cross_val_score(pipe, X, y, cv=5))
```
### The General Pipeline Interface
```
def fit(self, X, y):
X_transformed = X
for step in self.steps[:-1]:
# iterate over all but the final step
# fit and transform the data
X_transformed = step[1].fit_transform(X_transformed, y)
# fit the last step
self.steps[-1][1].fit(X_transformed, y)
return self
def predict(self, X):
X_transformed = X
for step in self.steps[:-1]:
# iterate over all but the final step
# transform the data
X_transformed = step[1].transform(X_transformed)
# fit the last step
return self.steps[-1][1].predict(X_transformed)
```

### Convenient Pipeline creation with ``make_pipeline``
```
from sklearn.pipeline import make_pipeline
# standard syntax
pipe_long = Pipeline([("scaler", MinMaxScaler()), ("svm", SVC(C=100))])
# abbreviated syntax
pipe_short = make_pipeline(MinMaxScaler(), SVC(C=100))
pipe_short.steps
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
pipe = make_pipeline(StandardScaler(), PCA(n_components=2), StandardScaler())
pipe.steps
```
#### Accessing step attributes
```
# fit the pipeline defined above to the cancer dataset
pipe.fit(cancer.data)
# extract the first two principal components from the "pca" step
components = pipe.named_steps["pca"].components_
print(components.shape)
```
#### Accessing attributes in grid-searched pipeline.
```
pipe.named_steps.pca.components_
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(StandardScaler(), LogisticRegression())
param_grid = {'logisticregression__C': [0.01, 0.1, 1, 10, 100]}
X_train, X_test, y_train, y_test = train_test_split(
cancer.data, cancer.target, random_state=4)
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
print(grid.best_estimator_)
print(grid.best_estimator_.named_steps["logisticregression"])
print(grid.best_estimator_.named_steps["logisticregression"].coef_)
```
### Grid-searching preprocessing steps and model parameters
```
from sklearn.datasets import load_boston
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=0)
from sklearn.preprocessing import PolynomialFeatures
pipe = make_pipeline(
StandardScaler(),
PolynomialFeatures(),
Ridge())
param_grid = {'polynomialfeatures__degree': [1, 2, 3],
'ridge__alpha': [0.001, 0.01, 0.1, 1, 10, 100]}
grid = GridSearchCV(pipe, param_grid=param_grid, cv=5, n_jobs=-1)
grid.fit(X_train, y_train)
res = pd.DataFrame(grid.cv_results_)
res = pd.pivot_table(res, index=['param_polynomialfeatures__degree', 'param_ridge__alpha'],
values=['mean_train_score', 'mean_test_score'])
res['mean_train_score'].unstack()
print(grid.best_params_)
grid.score(X_test, y_test)
from sklearn.linear_model import Lasso
pipe = Pipeline([('scaler', StandardScaler()), ('regressor', Ridge())])
param_grid = {'scaler': [StandardScaler(), MinMaxScaler(), None],
'regressor': [Ridge(), Lasso()],
'regressor__alpha': np.logspace(-3, 3, 7)}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
grid.score(X_test, y_test)
grid.best_params_
```
# Exercise
Load the boston housing dataset using ``sklearn.datasets.load_boston``. Create a pipline using scaling, polynomial features and a linear regression model (like ridge or lasso).
Search over the best options for the polynomial features together with the regularization of a linear model.
```
# Come back at 4:30
# Book signing tomorrow at 11:30
# office hours at 11am
```
| github_jupyter |
# Laboratorio 4 - Parte 1
### Redes Neuronales Artificiales: MLP
### 2018-II
#### Profesor: Julián D. Arias Londoño
#### julian.ariasl@udea.edu.co
## Guía del laboratorio
En esta archivo va a encontrar tanto celdas de código cómo celdas de texto con las instrucciones para desarrollar el laboratorio.
Lea atentamente las instrucciones entregadas en las celdas de texto correspondientes y proceda con la solución de las preguntas planteadas.
Nota: no olvide ir ejecutando las celdas de código de arriba hacia abajo para que no tenga errores de importación de librerías o por falta de definición de variables.
#### Primer Integrante:
Deiry Sofia Navas Muriel
#### Segundo Integrante:
David Alejandro Marin alzate
```
%matplotlib inline
import numpy as np
import math
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPRegressor
from __future__ import division
#Algunas advertencias que queremos evitar
import warnings
warnings.filterwarnings("always")
```
## Indicaciones
Este ejercicio tiene como objetivo implementar una red neuronal artificial de tipo perceptrón multicapa (MLP) para resolver un problema de regresión. Usaremos la librería sklearn. Consulte todo lo relacionado con la definición de hiperparámetros, los métodos para el entrenamiento y la predicción de nuevas muestras en el siguiente enlace: http://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html#sklearn.neural_network.MLPRegressor
Para este ejercicio usaremos la base de datos sobre calidad del aire, que ha sido usada en laboratorios previos, pero en este caso trataremos de predecir dos variables en lugar de una, es decir, abordaremos un problema de múltiples salidas.
```
#cargamos la bd que está en un archivo .data y ahora la podemos manejar de forma matricial
db = np.loadtxt('DB/AirQuality.data',delimiter='\t') # Assuming tab-delimiter
#Esta es la base de datos AirQuality del UCI Machine Learning Repository. En la siguiente URL se encuentra toda
#la descripción de la base de datos y la contextualización del problema.
#https://archive.ics.uci.edu/ml/datasets/Air+Quality#
X = db[:,0:11]
Y = db[:,11:13]
#Mean Absolute Percentage Error para los problemas de regresión
def MAPE(Y_est,Y):
N = np.size(Y)
mape = np.sum(abs((Y_est.reshape(N,1) - Y.reshape(N,1))/Y.reshape(N,1)))/N
return mape
```
## Ejercicio 1
Complete el script siguiente con el código necesario para usar una red neuronal tipo MLP para solucionar el problema de regresión propuesto. Como función de activación en las capas ocultas use la función 'tanh'. Ajuste el número máximo de épocas a 500.
```
from numpy import random
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import ShuffleSplit
from sklearn import preprocessing
#Validamos el modelo
def main(hidden = (28,)):
Folds = 4
random.seed(19680801)
ErrorY1 = np.zeros(Folds)
ErrorY2 = np.zeros(Folds)
ErrorT = np.zeros(Folds)
ss = ShuffleSplit(n_splits=Folds, test_size=0.3)
j = 0
for train, test in ss.split(X):
Xtrain = X[train,:]
Ytrain = Y[train,:]
Xtest = X[test,:]
Ytest = Y[test,:]
#Normalizamos los datos
media = np.mean(Xtrain,axis=0)
desvia = np.std(Xtrain,axis=0)
Xtrain = preprocessing.scale(Xtrain)
Xtest = (Xtest - np.matlib.repmat(media, Xtest.shape[0], 1))/np.matlib.repmat(desvia, Xtest.shape[0], 1)
#Haga el llamado a la función para crear y entrenar el modelo usando los datos de entrenamiento
mlp = MLPRegressor(hidden_layer_sizes= hidden, activation='tanh', max_iter= 500)
mlp.fit(Xtrain,Ytrain)
#Use para el modelo para hacer predicciones sobre el conjunto Xtest
Yest = mlp.predict(Xtest)
#Mida el error MAPE para cada una de las dos salidas
ErrorY1[j] = MAPE(Yest[:,0], Ytest[:,0])
ErrorY2[j] = MAPE(Yest[:,1], Ytest[:,1])
ErrorT[j] = (ErrorY1[j] + ErrorY2[j])/2
j += 1
mean1 = round(np.mean(ErrorY1),5)
std1 = round(np.std(np.std(ErrorY1)),5)
mean2 = round(np.mean(ErrorY2),5)
std2 = round(np.std(ErrorY2),5)
meanT = round(np.mean(ErrorT),5)
stdT = round(np.std(ErrorT),5)
return mean1,std1,mean2,std2,meanT,stdT
mean1,std1,mean2,std2,meanT,stdT = main(hidden= (28,))
print('MAPE salida 1 = ' + str(mean1) + '+-' + str(std1))
print('MAPE salida 2 = ' + str(mean2) + '+-' + str(std2))
print('MAPE total = ' + str(meanT) + '+-' + str(stdT))
num_layers = [1,1,1,1,1,2,2,2,2,2]
num_neurons_per_layer = [20,24,28,32,36,20,24,28,32,36]
mape_1 = np.zeros(10)
mape_ic_1 = np.zeros(10)
mape_2 = np.zeros(10)
mape_ic_2 = np.zeros(10)
for i in range(0,10):
if(num_layers[i] == 1):
mape_1[i],mape_ic_1[i],mape_2[i],mape_ic_2[i],meanT,stdT = main(hidden= (num_neurons_per_layer[i]))
elif(num_layers[i] == 2):
mape_1[i],mape_ic_1[i],mape_2[i],mape_ic_2[i],meanT,stdT = main(hidden= (num_neurons_per_layer[i],num_neurons_per_layer[i]))
print(i)
print('MAPE salida 1 = ' + str(mape_1[i]) + '+-' + str(mape_ic_1[i]))
print('MAPE salida 2 = ' + str(mape_2[i]) + '+-' + str(mape_ic_2[i]))
print('MAPE total = ' + str(meanT) + '+-' + str(stdT))
```
## Ejercicio 2
Una vez completado el código anterior. Realice los experimentos necesarios para completar la tabla siguiente:
```
import pandas as pd
import qgrid
df_types = pd.DataFrame({
'N. de capas ocultas' : pd.Series([1,1,1,1,1,2,2,2,2,2]),
'Neuronas por capa' : pd.Series([20,24,28,32,36,20,24,28,32,36])})
df_types["MAPE salida 1"] = mape_1
df_types["IC MAPE salida 1"] = mape_ic_1
df_types["MAPE salida 2"] = mape_2
df_types["IC MAPE salida 2"] = mape_ic_2
df_types.set_index(['N. de capas ocultas','Neuronas por capa'], inplace=True)
#df_types.sort_index(inplace=True)
qgrid_widget = qgrid.show_grid(df_types, show_toolbar=False)
qgrid_widget
```
Ejecute la siguiente instrucción para dejar guardados en el notebook los resultados de las pruebas.
```
qgrid_widget.get_changed_df()
```
<b>Responda</b>:
2.1 ¿Qué tipo de función de activación usa el modelo en la capa de salida?:
En este caso la red neuronal para regresión utliza la funcion de activación "identity", en realidad no corresponde a ninguna funcion de activación sino es el mismo valor de entrada $f(x)=x$
## Ejercicio 3.
A continuación se leen los datos de un problema de clasificación. El problema corresponde a la clasifiación de dígitos escritos a mano. Usaremos únicamente 4 de las 10 clases disponibles. Los datos fueron preprocesados para reducir el número de características. La técnica usada será analizada más adelante en el curso.
```
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
digits = load_digits(n_class=4)
#--------- preprocesamiento--------------------
pca = PCA(0.99, whiten=True)
data = pca.fit_transform(digits.data)
#---------- Datos a usar ----------------------
X = data
Y = digits.target
```
Este ejercicio tiene como objetivo implementar una red neuronal artificial de tipo perceptrón multicapa (MLP) para resolver un problema de clasificación. Usaremos la librería sklearn. Consulte todo lo relacionado con la definición de hiperparámetros, los métodos para el entrenamiento y la predicción de nuevas muestras en el siguiente enlace: http://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html#sklearn.neural_network.MLPClassifier
Complete el script siguiente con el código necesario para usar una red neuronal tipo MLP para solucionar el problema de clasificación propuesto. Como función de activación en las capas ocultas use la función 'tanh'. Ajuste el número máximo de épocas a 500.
```
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import StratifiedKFold
def mainClassifier(hidden = (24)):
Folds = 4
random.seed(19680801)
EficienciaTrain = np.zeros(Folds)
EficienciaVal = np.zeros(Folds)
skf = StratifiedKFold(n_splits=Folds)
j = 0
for train, test in skf.split(X, Y):
Xtrain = X[train,:]
Ytrain = Y[train]
Xtest = X[test,:]
Ytest = Y[test]
#Normalizamos los datos
media = np.mean(Xtrain)
desvia = np.std(Xtrain)
Xtrain = preprocessing.scale(Xtrain)
Xtest = (Xtest - np.matlib.repmat(media, Xtest.shape[0], 1))/np.matlib.repmat(desvia, Xtest.shape[0], 1)
#Haga el llamado a la función para crear y entrenar el modelo usando los datos de entrenamiento
mlp = MLPClassifier(activation='tanh', hidden_layer_sizes=hidden, max_iter=500 )
mlp.fit(Xtrain,Ytrain)
#Validación con las muestras de entrenamiento
Ytrain_pred = mlp.predict(Xtrain)
#Validación con las muestras de test
Yest = mlp.predict(Xtest)
#Evaluamos las predicciones del modelo con los datos de test
EficienciaTrain[j] = np.mean(Ytrain_pred == Ytrain)
EficienciaVal[j] = np.mean(Yest == Ytest)
j += 1
mean = round(np.mean(EficienciaTrain),5)
std = round(np.std(EficienciaTrain),5)
meanVal = round(np.mean(EficienciaVal),5)
stdVal = round(np.std(EficienciaVal),5)
return mean,std,meanVal,stdVal
#mean,std,meanVal,stdVal,mainClassifier()
#print('Eficiencia durante el entrenamiento = ' + str(mean) + '+-' + str(std))
#print('Eficiencia durante la validación = ' + str(np.mean(EficienciaVal)) + '+-' + str(np.std(EficienciaVal)))
num_layers = [1,1,1,1,1,2,2,2,2,2]
num_neurons_per_layer = [20,24,28,32,36,20,24,28,32,36]
mean = np.zeros(10)
std = np.zeros(10)
meanVal = np.zeros(10)
stdVal = np.zeros(10)
for i in range(0,10):
if(num_layers[i] == 1):
mean[i], std[i], meanVal[i], stdVal[i]= mainClassifier(hidden= (num_neurons_per_layer[i]))
elif(num_layers[i] == 2):
mean[i], std[i], meanVal[i], stdVal[i]= mainClassifier(hidden= (num_neurons_per_layer[i],num_neurons_per_layer[i]))
print('Eficiencia durante el entrenamiento = ' + str(mean[i]) + '+-' + str(std[i]))
print('Eficiencia durante la validación = ' + str(meanVal[i]) + '+-' + str(stdVal[i]))
```
## Ejercicio 4
Una vez completado el código realice los experimentos necesarios para llenar la siguiente tabla:
```
df_types = pd.DataFrame({
'N. de capas ocultas' : pd.Series([1,1,1,1,1,2,2,2,2,2]),
'Neuronas por capa' : pd.Series([20,24,28,32,36,20,24,28,32,36])})
df_types["Eficiencia en validacion"] = meanVal
df_types["Intervalo de confianza"] = stdVal
df_types.set_index(['N. de capas ocultas','Neuronas por capa'], inplace=True)
#df_types.sort_index(inplace=True)
qgrid_widget = qgrid.show_grid(df_types, show_toolbar=False)
qgrid_widget
```
Ejecute la siguiente instrucción para dejar guardados en el notebook los resultados de las pruebas.
```
qgrid_widget.get_changed_df()
```
<b>Responda</b>:
4.1 ¿Qué tipo de función de activación usa el modelo en la capa de salida?:
En la capa de la salida la función de activación es "softmax", se utliza el atributo del MLPRegressor out_activation_
4.2 ¿Cuántas neuronas en la capa de salida tiene el modelo?¿Porqué debe tener ese número?
Hay 4 neuronas en la capa de salida que corresponde a las 4 clases del problema de clasificación, se utiliza el atributo n_outputs_
| github_jupyter |
<a href="https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# `RoBERTa` --> `Longformer`: build a "long" version of pretrained models
This notebook replicates the procedure descriped in the [Longformer paper](https://arxiv.org/abs/2004.05150) to train a Longformer model starting from the RoBERTa checkpoint. The same procedure can be applied to build the "long" version of other pretrained models as well.
### Data, libraries, and imports
Our procedure requires a corpus for pretraining. For demonstration, we will use Wikitext103; a corpus of 100M tokens from wikipedia articles. Depending on your application, consider using a different corpus that is a better match.
```
!wget https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-raw-v1.zip
!unzip wikitext-103-raw-v1.zip
!pip install transformers==3.0.1
import logging
import os
import math
from dataclasses import dataclass, field
from transformers import RobertaForMaskedLM, RobertaTokenizerFast, TextDataset, DataCollatorForLanguageModeling, Trainer
from transformers import TrainingArguments, HfArgumentParser
from transformers.modeling_longformer import LongformerSelfAttention
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
```
### RobertaLong
`RobertaLongForMaskedLM` represents the "long" version of the `RoBERTa` model. It replaces `BertSelfAttention` with `RobertaLongSelfAttention`, which is a thin wrapper around `LongformerSelfAttention`.
```
class RobertaLongSelfAttention(LongformerSelfAttention):
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=False,
):
return super().forward(hidden_states, attention_mask=attention_mask, output_attentions=output_attentions)
class RobertaLongForMaskedLM(RobertaForMaskedLM):
def __init__(self, config):
super().__init__(config)
for i, layer in enumerate(self.roberta.encoder.layer):
# replace the `modeling_bert.BertSelfAttention` object with `LongformerSelfAttention`
layer.attention.self = RobertaLongSelfAttention(config, layer_id=i)
```
Starting from the `roberta-base` checkpoint, the following function converts it into an instance of `RobertaLong`. It makes the following changes:
- extend the position embeddings from `512` positions to `max_pos`. In Longformer, we set `max_pos=4096`
- initialize the additional position embeddings by copying the embeddings of the first `512` positions. This initialization is crucial for the model performance (check table 6 in [the paper](https://arxiv.org/pdf/2004.05150.pdf) for performance without this initialization)
- replaces `modeling_bert.BertSelfAttention` objects with `modeling_longformer.LongformerSelfAttention` with a attention window size `attention_window`
The output of this function works for long documents even without pretraining. Check tables 6 and 11 in [the paper](https://arxiv.org/pdf/2004.05150.pdf) to get a sense of the expected performance of this model before pretraining.
```
def create_long_model(save_model_to, attention_window, max_pos):
model = RobertaForMaskedLM.from_pretrained('roberta-base')
tokenizer = RobertaTokenizerFast.from_pretrained('roberta-base', model_max_length=max_pos)
config = model.config
# extend position embeddings
tokenizer.model_max_length = max_pos
tokenizer.init_kwargs['model_max_length'] = max_pos
current_max_pos, embed_size = model.roberta.embeddings.position_embeddings.weight.shape
max_pos += 2 # NOTE: RoBERTa has positions 0,1 reserved, so embedding size is max position + 2
config.max_position_embeddings = max_pos
assert max_pos > current_max_pos
# allocate a larger position embedding matrix
new_pos_embed = model.roberta.embeddings.position_embeddings.weight.new_empty(max_pos, embed_size)
# copy position embeddings over and over to initialize the new position embeddings
k = 2
step = current_max_pos - 2
while k < max_pos - 1:
new_pos_embed[k:(k + step)] = model.roberta.embeddings.position_embeddings.weight[2:]
k += step
model.roberta.embeddings.position_embeddings.weight.data = new_pos_embed
# replace the `modeling_bert.BertSelfAttention` object with `LongformerSelfAttention`
config.attention_window = [attention_window] * config.num_hidden_layers
for i, layer in enumerate(model.roberta.encoder.layer):
longformer_self_attn = LongformerSelfAttention(config, layer_id=i)
longformer_self_attn.query = layer.attention.self.query
longformer_self_attn.key = layer.attention.self.key
longformer_self_attn.value = layer.attention.self.value
longformer_self_attn.query_global = layer.attention.self.query
longformer_self_attn.key_global = layer.attention.self.key
longformer_self_attn.value_global = layer.attention.self.value
layer.attention.self = longformer_self_attn
logger.info(f'saving model to {save_model_to}')
model.save_pretrained(save_model_to)
tokenizer.save_pretrained(save_model_to)
return model, tokenizer
```
Pretraining on Masked Language Modeling (MLM) doesn't update the global projection layers. After pretraining, the following function copies `query`, `key`, `value` to their global counterpart projection matrices.
For more explanation on "local" vs. "global" attention, please refer to the documentation [here](https://huggingface.co/transformers/model_doc/longformer.html#longformer-self-attention).
```
def copy_proj_layers(model):
for i, layer in enumerate(model.roberta.encoder.layer):
layer.attention.self.query_global = layer.attention.self.query
layer.attention.self.key_global = layer.attention.self.key
layer.attention.self.value_global = layer.attention.self.value
return model
```
### Pretrain and Evaluate on masked language modeling (MLM)
The following function pretrains and evaluates a model on MLM.
```
def pretrain_and_evaluate(args, model, tokenizer, eval_only, model_path):
val_dataset = TextDataset(tokenizer=tokenizer,
file_path=args.val_datapath,
block_size=tokenizer.max_len)
if eval_only:
train_dataset = val_dataset
else:
logger.info(f'Loading and tokenizing training data is usually slow: {args.train_datapath}')
train_dataset = TextDataset(tokenizer=tokenizer,
file_path=args.train_datapath,
block_size=tokenizer.max_len)
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15)
trainer = Trainer(model=model, args=args, data_collator=data_collator,
train_dataset=train_dataset, eval_dataset=val_dataset, prediction_loss_only=True,)
eval_loss = trainer.evaluate()
eval_loss = eval_loss['eval_loss']
logger.info(f'Initial eval bpc: {eval_loss/math.log(2)}')
if not eval_only:
trainer.train(model_path=model_path)
trainer.save_model()
eval_loss = trainer.evaluate()
eval_loss = eval_loss['eval_loss']
logger.info(f'Eval bpc after pretraining: {eval_loss/math.log(2)}')
```
**Training hyperparameters**
- Following RoBERTa pretraining setting, we set number of tokens per batch to be `2^18` tokens. Changing this number might require changes in the lr, lr-scheudler, #steps and #warmup steps. Therefor, it is a good idea to keep this number constant.
- Note that: `#tokens/batch = batch_size x #gpus x gradient_accumulation x seqlen`
- In [the paper](https://arxiv.org/pdf/2004.05150.pdf), we train for 65k steps, but 3k is probably enough (check table 6)
- **Important note**: The lr-scheduler in [the paper](https://arxiv.org/pdf/2004.05150.pdf) is polynomial_decay with power 3 over 65k steps. To train for 3k steps, use a constant lr-scheduler (after warmup). Both lr-scheduler are not supported in HF trainer, and at least **constant lr-scheduler** will need to be added.
- Pretraining will take 2 days on 1 x 32GB GPU with fp32. Consider using fp16 and using more gpus to train faster (if you increase `#gpus`, reduce `gradient_accumulation` to maintain `#tokens/batch` as mentioned earlier).
- As a demonstration, this notebook is training on wikitext103 but wikitext103 is rather small that it takes 7 epochs to train for 3k steps Consider doing a single epoch on a larger dataset (800M tokens) instead.
- Set #gpus using `CUDA_VISIBLE_DEVICES`
```
@dataclass
class ModelArgs:
attention_window: int = field(default=512, metadata={"help": "Size of attention window"})
max_pos: int = field(default=4096, metadata={"help": "Maximum position"})
parser = HfArgumentParser((TrainingArguments, ModelArgs,))
training_args, model_args = parser.parse_args_into_dataclasses(look_for_args_file=False, args=[
'--output_dir', 'tmp',
'--warmup_steps', '500',
'--learning_rate', '0.00003',
'--weight_decay', '0.01',
'--adam_epsilon', '1e-6',
'--max_steps', '3000',
'--logging_steps', '500',
'--save_steps', '500',
'--max_grad_norm', '5.0',
'--per_gpu_eval_batch_size', '8',
'--per_gpu_train_batch_size', '2', # 32GB gpu with fp32
'--gradient_accumulation_steps', '32',
'--evaluate_during_training',
'--do_train',
'--do_eval',
])
training_args.val_datapath = 'wikitext-103-raw/wiki.valid.raw'
training_args.train_datapath = 'wikitext-103-raw/wiki.train.raw'
# Choose GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
```
### Put it all together
1) Evaluating `roberta-base` on MLM to establish a baseline. Validation `bpc` = `2.536` which is higher than the `bpc` values in table 6 [here](https://arxiv.org/pdf/2004.05150.pdf) because wikitext103 is harder than our pretraining corpus.
```
roberta_base = RobertaForMaskedLM.from_pretrained('roberta-base')
roberta_base_tokenizer = RobertaTokenizerFast.from_pretrained('roberta-base')
logger.info('Evaluating roberta-base (seqlen: 512) for refernece ...')
pretrain_and_evaluate(training_args, roberta_base, roberta_base_tokenizer, eval_only=True, model_path=None)
```
2) As descriped in `create_long_model`, convert a `roberta-base` model into `roberta-base-4096` which is an instance of `RobertaLong`, then save it to the disk.
```
model_path = f'{training_args.output_dir}/roberta-base-{model_args.max_pos}'
if not os.path.exists(model_path):
os.makedirs(model_path)
logger.info(f'Converting roberta-base into roberta-base-{model_args.max_pos}')
model, tokenizer = create_long_model(
save_model_to=model_path, attention_window=model_args.attention_window, max_pos=model_args.max_pos)
```
3) Load `roberta-base-4096` from the disk. This model works for long sequences even without pretraining. If you don't want to pretrain, you can stop here and start finetuning your `roberta-base-4096` on downstream tasks 🎉🎉🎉
```
logger.info(f'Loading the model from {model_path}')
tokenizer = RobertaTokenizerFast.from_pretrained(model_path)
model = RobertaLongForMaskedLM.from_pretrained(model_path)
```
4) Pretrain `roberta-base-4096` for `3k` steps, each steps has `2^18` tokens. Notes:
- The `training_args.max_steps = 3 ` is just for the demo. **Remove this line for the actual training**
- Training for `3k` steps will take 2 days on a single 32GB gpu with `fp32`. Consider using `fp16` and more gpus to train faster.
- Tokenizing the training data the first time is going to take 5-10 minutes.
- MLM validation `bpc` **before** pretraining: **2.652**, a bit worse than the **2.536** of `roberta-base`. As discussed in [the paper](https://arxiv.org/pdf/2004.05150.pdf) this is expected because the model didn't learn yet to work with the sliding window attention.
- MLM validation `bpc` after pretraining for a few number of steps: **2.628**. It is quickly getting better. By 3k steps, it should be better than the **2.536** of `roberta-base`.
```
logger.info(f'Pretraining roberta-base-{model_args.max_pos} ... ')
training_args.max_steps = 3 ## <<<<<<<<<<<<<<<<<<<<<<<< REMOVE THIS <<<<<<<<<<<<<<<<<<<<<<<<
pretrain_and_evaluate(training_args, model, tokenizer, eval_only=False, model_path=training_args.output_dir)
```
5) Copy global projection layers. MLM pretraining doesn't train global projections, so we need to call `copy_proj_layers` to copy the local projection layers to the global ones.
```
logger.info(f'Copying local projection layers into global projection layers ... ')
model = copy_proj_layers(model)
logger.info(f'Saving model to {model_path}')
model.save_pretrained(model_path)
```
🎉🎉🎉🎉 **DONE**. 🎉🎉🎉🎉
`model` can now be used for finetuning on downstream tasks after loading it from the disk.
```
logger.info(f'Loading the model from {model_path}')
tokenizer = RobertaTokenizerFast.from_pretrained(model_path)
model = RobertaLongForMaskedLM.from_pretrained(model_path)
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
# Distributed Tensorflow with Horovod
In this tutorial, you will train a word2vec model in TensorFlow using distributed training via [Horovod](https://github.com/uber/horovod).
## Prerequisites
* Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning (AML)
* Go through the [configuration notebook](../../../configuration.ipynb) to:
* install the AML SDK
* create a workspace and its configuration file (`config.json`)
* Review the [tutorial](../train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb) on single-node TensorFlow training using the SDK
```
# Check core SDK version number
import azureml.core
print("SDK version:", azureml.core.VERSION)
```
## Diagnostics
Opt-in diagnostics for better experience, quality, and security of future releases.
```
from azureml.telemetry import set_diagnostics_collection
set_diagnostics_collection(send_diagnostics=True)
```
## Initialize workspace
Initialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#workspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`.
```
from azureml.core.workspace import Workspace
ws = Workspace.from_config()
print('Workspace name: ' + ws.name,
'Azure region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep='\n')
```
## Create or Attach existing AmlCompute
You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.
**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.
As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota.
```
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# choose a name for your cluster
cluster_name = "gpucluster"
try:
compute_target = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing compute target')
except ComputeTargetException:
print('Creating a new compute target...')
compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_NC6',
max_nodes=4)
# create the cluster
compute_target = ComputeTarget.create(ws, cluster_name, compute_config)
compute_target.wait_for_completion(show_output=True)
# use get_status() to get a detailed status for the current cluster.
print(compute_target.get_status().serialize())
```
The above code creates a GPU cluster. If you instead want to create a CPU cluster, provide a different VM size to the `vm_size` parameter, such as `STANDARD_D2_V2`.
## Upload data to datastore
To make data accessible for remote training, AML provides a convenient way to do so via a [Datastore](https://docs.microsoft.com/azure/machine-learning/service/how-to-access-data). The datastore provides a mechanism for you to upload/download data to Azure Storage, and interact with it from your remote compute targets.
If your data is already stored in Azure, or you download the data as part of your training script, you will not need to do this step. For this tutorial, although you can download the data in your training script, we will demonstrate how to upload the training data to a datastore and access it during training to illustrate the datastore functionality.
First, download the training data from [here](http://mattmahoney.net/dc/text8.zip) to your local machine:
```
import os
import urllib
os.makedirs('./data', exist_ok=True)
download_url = 'http://mattmahoney.net/dc/text8.zip'
urllib.request.urlretrieve(download_url, filename='./data/text8.zip')
```
Each workspace is associated with a default datastore. In this tutorial, we will upload the training data to this default datastore.
```
ds = ws.get_default_datastore()
print(ds.datastore_type, ds.account_name, ds.container_name)
```
Upload the contents of the data directory to the path `./data` on the default datastore.
```
ds.upload(src_dir='data', target_path='data', overwrite=True, show_progress=True)
```
For convenience, let's get a reference to the path on the datastore with the zip file of training data. We can do so using the `path` method. In the next section, we can then pass this reference to our training script's `--input_data` argument.
```
path_on_datastore = 'data/text8.zip'
ds_data = ds.path(path_on_datastore)
print(ds_data)
```
## Train model on the remote compute
### Create a project directory
Create a directory that will contain all the necessary code from your local machine that you will need access to on the remote resource. This includes the training script, and any additional files your training script depends on.
```
project_folder = './tf-distr-hvd'
os.makedirs(project_folder, exist_ok=True)
```
Copy the training script `tf_horovod_word2vec.py` into this project directory.
```
import shutil
shutil.copy('tf_horovod_word2vec.py', project_folder)
```
### Create an experiment
Create an [Experiment](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#experiment) to track all the runs in your workspace for this distributed TensorFlow tutorial.
```
from azureml.core import Experiment
experiment_name = 'tf-distr-hvd'
experiment = Experiment(ws, name=experiment_name)
```
### Create a TensorFlow estimator
The AML SDK's TensorFlow estimator enables you to easily submit TensorFlow training jobs for both single-node and distributed runs. For more information on the TensorFlow estimator, refer [here](https://docs.microsoft.com/azure/machine-learning/service/how-to-train-tensorflow).
```
from azureml.train.dnn import TensorFlow
script_params={
'--input_data': ds_data
}
estimator= TensorFlow(source_directory=project_folder,
compute_target=compute_target,
script_params=script_params,
entry_script='tf_horovod_word2vec.py',
node_count=2,
process_count_per_node=1,
distributed_backend='mpi',
use_gpu=True)
```
The above code specifies that we will run our training script on `2` nodes, with one worker per node. In order to execute a distributed run using MPI/Horovod, you must provide the argument `distributed_backend='mpi'`. Using this estimator with these settings, TensorFlow, Horovod and their dependencies will be installed for you. However, if your script also uses other packages, make sure to install them via the `TensorFlow` constructor's `pip_packages` or `conda_packages` parameters.
Note that we passed our training data reference `ds_data` to our script's `--input_data` argument. This will 1) mount our datastore on the remote compute and 2) provide the path to the data zip file on our datastore.
### Submit job
Run your experiment by submitting your estimator object. Note that this call is asynchronous.
```
run = experiment.submit(estimator)
print(run)
```
### Monitor your run
You can monitor the progress of the run with a Jupyter widget. Like the run submission, the widget is asynchronous and provides live updates every 10-15 seconds until the job completes.
```
from azureml.widgets import RunDetails
RunDetails(run).show()
```
Alternatively, you can block until the script has completed training before running more code.
```
run.wait_for_completion(show_output=True)
```
| github_jupyter |
# Imports
```
import sys
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.externals import joblib
import torch
import torchvision
import torchvision.transforms as transforms
import pickle
import pandas as pd
import os
sys.path.append('../../Utils')
from SVC_Utils import *
```
# Load CIFAR100
```
def unpickle(file):
with open(file, 'rb') as fo:
res = pickle.load(fo, encoding='bytes')
return res
transform = transforms.Compose(
[transforms.ToTensor()])
#training data;
trainset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transforms.ToTensor())
trainloader = torch.utils.data.DataLoader(trainset, batch_size=int((trainset.__len__())/2), shuffle=True, num_workers=2)
trainloader_final=torch.utils.data.DataLoader(trainset, batch_size=trainset.__len__(), shuffle=True, num_workers=2)
#test data
testset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transforms.ToTensor())
testloader = torch.utils.data.DataLoader(testset, batch_size=testset.__len__(),shuffle=False, num_workers=2)
classes=None
traininputs, traintargets=load(trainloader)
testinputs, testtargets=load(testloader)
ftraininputs, ftraintargets=load(trainloader_final)
```
# Model Training
```
n_components=180
C_range=np.logspace(0,1,2)
gamma_range=np.logspace(-2,-1,2)
clfs=hp_grid(n_components=n_components, C_range=C_range, gamma_range=gamma_range)
#fitted_clfs=train_grid(clfs, traininputs, traintargets)
fitted_clfs=joblib.load('fclfs')
```
# Model Testing/Evaluation
```
#Stores training and testing accuracies in matrices (Rows: C_range, Cols: gamma_range)
train_accs=np.random.randn(len(C_range),len(gamma_range))
test_accs=np.random.randn(len(C_range),len(gamma_range))
test_preds=[]
k=0;
for i in range(len(C_range)):
for j in range(len(gamma_range)):
train_accs[i,j]=predict_eval(fitted_clfs[k], traininputs, traintargets, training=True)[1]
preds, test_accs[i,j]=predict_eval(fitted_clfs[k], testinputs, testtargets)
test_preds.append(preds)
k+=1
idx=['C = 1','C = 10']
cols=['gamma = .01','gamma = .1']
trainacc_df=pd.DataFrame(data=train_accs, index=idx, columns=cols)
testacc_df=pd.DataFrame(data=test_accs, index=idx, columns=cols)
#training accuracy for C/gamma grid
trainacc_df.style.background_gradient(cmap='GnBu')
#test accuracy for C/gamma grid
testacc_df.style.background_gradient(cmap='GnBu')
```
# Save Model
```
maxacc, gen=maxacc_gen(test_accs, train_accs, clfs)
fn_max_acc = 'SVMCIFAR100_maxacc_proba.pkl'
fn_gen = 'SVMCIFAR100_gen_proba.pkl'
print(maxacc)
save_proba(fn_max_acc, maxacc, traininputs, traintargets)
save_proba(fn_gen, gen, traininputs, traintargets)
```
| github_jupyter |
```
import pandas as pd
import sys
sys.path.insert(0, '../../../')
from notebooks.utils import load_node_features, get_referral_sites_edges, export_model_as_feature
from train import run_experiment
```
# Load referral sites edges for level 1
```
level = 1
referral_sites_NODES = get_referral_sites_edges(data_year=2020, level=level)
print(referral_sites_NODES[:5])
edge_df = pd.DataFrame(referral_sites_NODES, columns=['source', 'target'])
edge_df.head()
```
### Find all unique nodes in edges
```
nodes_in_edges = list(set(edge_df.source.unique().tolist() + edge_df.target.unique().tolist()))
print('Number of unique nodes in edges:', len(nodes_in_edges), 'Sample:', nodes_in_edges[:5])
```
### 1. Load all node features
```
node_features_df = load_node_features()
node_features_df = node_features_df.set_index('site')
node_features_df.head()
```
# Subset node_features
```
node_features_df = node_features_df.loc[nodes_in_edges]
node_features_df.info()
```
### 2. Fill all missing alexa_rank and total_sites_linking_in with 0
```
node_features_df.alexa_rank = node_features_df.alexa_rank.fillna(0)
node_features_df.total_sites_linking_in = node_features_df.total_sites_linking_in.fillna(0)
node_features_df.info()
```
### 3. Normalizing features
```
import math
node_features_df['normalized_alexa_rank'] = node_features_df['alexa_rank'].apply(lambda x: 1/x if x else 0)
node_features_df['normalized_total_sites_linked_in'] = node_features_df['total_sites_linking_in'].apply(lambda x: math.log2(x) if x else 0)
```
# Create Graph
```
import stellargraph as sg
G = sg.StellarGraph(node_features_df[['normalized_alexa_rank', 'normalized_total_sites_linked_in']], edge_df)
print(G.info())
```
# Unsupervised Deep Graph Infomax
```
from stellargraph.mapper import (
CorruptedGenerator,
FullBatchNodeGenerator
)
from stellargraph.layer import GCN, DeepGraphInfomax
from tensorflow.keras import Model
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping
# 1. Specify the other optional parameter values: root nodes, the number of walks to take per node, the length of each walk, and random seed.
nodes = list(G.nodes())
number_of_walks = 1
length = 5
# 2. Create the UnsupervisedSampler instance with the relevant parameters passed to it.
fullbatch_generator = FullBatchNodeGenerator(G, sparse=False)
gcn_model = GCN(layer_sizes=[128], activations=["relu"], generator=fullbatch_generator)
corrupted_generator = CorruptedGenerator(fullbatch_generator)
gen = corrupted_generator.flow(G.nodes())
# 3. Create a node pair generator:
infomax = DeepGraphInfomax(gcn_model, corrupted_generator)
x_in, x_out = infomax.in_out_tensors()
deep_graph_infomax_model = Model(inputs=x_in, outputs=x_out)
deep_graph_infomax_model.compile(loss=tf.nn.sigmoid_cross_entropy_with_logits, optimizer=Adam(lr=1e-3))
from stellargraph.utils import plot_history
epochs = 100
es = EarlyStopping(monitor="loss", min_delta=0, patience=20)
history = deep_graph_infomax_model.fit(gen, epochs=epochs, verbose=0, callbacks=[es])
plot_history(history)
x_emb_in, x_emb_out = gcn_model.in_out_tensors()
# for full batch models, squeeze out the batch dim (which is 1)
x_out = tf.squeeze(x_emb_out, axis=0)
emb_model = Model(inputs=x_emb_in, outputs=x_out)
node_features_fullbactch_generator = fullbatch_generator.flow(node_features_df.index)
node_embeddings = emb_model.predict(node_features_fullbactch_generator)
embeddings_wv = dict(zip(node_features_df.index.tolist(), node_embeddings.tolist()))
print('Sample:', embeddings_wv['crooked.com'][:10])
```
# Export embeddings as feature
```
export_model_as_feature(embeddings_wv, f'deep_graph_infomax_referral_sites_level_{level}_epochs_{epochs}')
run_experiment(features=f'deep_graph_infomax_referral_sites_level_{level}_epochs_{epochs}')
run_experiment(features=f'deep_graph_infomax_referral_sites_level_{level}_epochs_{epochs}', task='bias')
```
| github_jupyter |
```
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import os
import librosa
import librosa.display
import wave
import cv2
import random
import tensorflow as tf
import tensorflow.keras as keras
%matplotlib inline
```
Récuperer les chemins des audios
```
import glob
import os.path
def listdirectory(path):
fichier=[]
l = glob.glob(path+'\\*')
for i in l:
if os.path.isdir(i): fichier.extend(listdirectory(i))
else: fichier.append(i)
return fichier
#load blues
path_blues='C:\\Users\\USER\\Desktop\\Audio\\genres\\blues'
blues=listdirectory(path_blues)
#load classical
path_classical='C:\\Users\\USER\\Desktop\\Audio\\genres\\classical'
classical=listdirectory(path_classical)
#load country
path_country='C:\\Users\\USER\\Desktop\\Audio\\genres\\country'
country=listdirectory(path_country)
#load disco
path_disco='C:\\Users\\USER\\Desktop\\Audio\\genres\\disco'
disco=listdirectory(path_disco)
#load hiphop
path_hiphop='C:\\Users\\USER\\Desktop\\Audio\\genres\\hiphop'
hiphop=listdirectory(path_hiphop)
#load jazz
path_jazz='C:\\Users\\USER\\Desktop\\Audio\\genres\\jazz'
jazz=listdirectory(path_jazz)
#load metal
path_metal='C:\\Users\\USER\\Desktop\\Audio\\genres\\metal'
metal=listdirectory(path_metal)
#load pop
path_pop='C:\\Users\\USER\\Desktop\\Audio\\genres\\pop'
pop=listdirectory(path_pop)
#load reggae
path_reggae='C:\\Users\\USER\\Desktop\\Audio\\genres\\reggae'
reggae=listdirectory(path_reggae)
#load rock
path_rock='C:\\Users\\USER\\Desktop\\Audio\\genres\\rock'
rock=listdirectory(path_rock)
import pandas
lab=np.arange(10)
colmn = ['0']
for i in range(1, 100):
colmn.append(str(i))
spect_ = ([blues, classical, country, disco, hiphop, jazz, metal, pop, reggae, rock])
df_x = pandas.DataFrame(spect_, index = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock'], columns= colmn)
df_x
```
Segmentation des audios pour augmenter la base des mfcc
```
def segmentation_mfcc(chemin,label):
a=0
labels=[]
mfcc=[]
duree=30
y, sr = librosa.load(chemin)
max_len=int(duree*sr/10)
for i in range(10):
lmin=max_len*i
lmax=lmin + max_len
mfcc_ = librosa.feature.mfcc(y=y[lmin:lmax] , sr=sr, n_mfcc=13, n_fft=2048, hop_length=512)
mfcc_ = mfcc_.T
if (len(mfcc_)==130):
mfcc.append(mfcc_ )
labels.append(label)
mfcc=np.array(mfcc)
return mfcc,labels
```
Segmentation des audios pour augmenter la base des mel
```
def segmentation_mel(chemin,label):
a=0
k=0
labels=[]
mel=[]
duree=30
y, sr = librosa.load(chemin)
max_len=int(duree*sr/10)
for i in range(10):
lmin=max_len*i
lmax=lmin + max_len
mel_ = librosa.feature.melspectrogram(y=y[lmin:lmax] , sr=sr, n_mels=13,n_fft=1024,hop_length=512)
mel_ = mel_.T
if (len(mel_)==130):
mel.append(mel_ )
a=a+1
labels.append(label)
mel=np.array(mel)
return mel,labels
```
creation de la base mfcc
```
base_mfcc=np.zeros((9996, 130, 13))
labels_mfcc=np.zeros(9996)
k=0
for i in range(np.shape(df_x)[0]):
for j in range(np.shape(df_x)[1]):
mfcc,lab=segmentation_mfcc(df_x.iloc[i,j],i)
for l in range( mfcc.shape[0]):
base_mfcc[k,:,:]=mfcc[l,:,:]
labels_mfcc[k]=lab[l]
k+=1
print("base mfcc chargée")
```
creation de la base mel spectrogram
```
base_mel=np.zeros((9996, 130, 13))
labels_mel=np.zeros(9996)
k=0
for i in range(np.shape(df_x)[0]):
for j in range(np.shape(df_x)[1]):
mel,lab=segmentation_mel(df_x.iloc[i,j],i)
for l in range( mel.shape[0]):
base_mel[k,:,:]=mel[l,:,:]
labels_mel[k]=lab[l]
k+=1
print("base mel chargée")
# visualiser une image pour chaque genre
plt.figure(figsize=(20,10))
for i in range(10):
plt.subplot(1,10,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(base_mfcc[1000*i])
plt.xlabel([labels_mfcc[1000*i]])
plt.show()
# visualiser une image pour chaque genre
plt.figure(figsize=(20,10))
for i in range(10):
plt.subplot(1,10,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(base_mel[1000*i])
plt.xlabel([labels_mel[1000*i]])
plt.show()
```
separation des données en base d apprentissage et de tests
```
X_train_mfcc, X_test_mfcc, y_train_mfcc, y_test_mfcc = train_test_split(base_mfcc, labels_mfcc, test_size=0.3)
X_train_mel, X_test_mel, y_train_mel, y_test_mel = train_test_split(base_mel, labels_mel, test_size=0.3)
print(X_train_mfcc.shape)
print(y_train_mfcc.shape)
print(X_test_mfcc.shape)
print(y_test_mfcc.shape)
print(X_train_mel.shape)
print(y_train_mel.shape)
print(X_test_mel.shape)
print(y_test_mel.shape)
```
Model simple avec des couches dense
```
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(X_train_mfcc.shape[1], X_train_mfcc.shape[2])))
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dense(256, activation='relu'))
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
# compile model
optimiser = tf.keras.optimizers.Adam(learning_rate=0.0001)
model.compile(optimizer=optimiser,loss='sparse_categorical_crossentropy',metrics=['accuracy'])
model.summary()
```
Apprentissage sur la base mfcc
```
history = model.fit(X_train_mfcc, y_train_mfcc, validation_split=0.3, batch_size=32, epochs=50)
```
fonction pour afficher la figure de l'accuracy
```
def affiche_acc(history):
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
```
fonction pour afficher la figure de l'erreur
```
def affiche_loss(history):
# summarize history for accuracy
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
```
figure de l'accuracy
```
affiche_acc(history)
```
figure de l'erreur
```
affiche_loss(history)
```
Evaluation sur la base de test mfcc
```
test_loss, test_acc = model.evaluate(X_test_mfcc,y_test_mfcc)
print('Test accuracy:', test_acc)
```
redimensionner la base mfcc pour un model CNN
```
X_train_mfcc_2 = X_train_mfcc.reshape(X_train_mfcc.shape[0],X_train_mfcc.shape[1],X_train_mfcc.shape[2],1)
X_test_mfcc_2 = X_test_mfcc.reshape(X_test_mfcc.shape[0],X_test_mfcc.shape[1],X_test_mfcc.shape[2],1)
input_shape_mfcc = (X_train_mfcc_2.shape[1], X_train_mfcc_2.shape[2], 1)
print(X_train_mfcc_2.shape)
print(X_test_mfcc_2.shape)
```
architecture avec des CNN pour les mfcc
```
model_CNN_mfcc = keras.Sequential()
# 1st conv layer
model_CNN_mfcc.add(keras.layers.Conv2D(256, (3, 3), activation='relu', input_shape=input_shape_mfcc))
model_CNN_mfcc.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
model_CNN_mfcc.add(keras.layers.BatchNormalization())
# 2nd conv layer
model_CNN_mfcc.add(keras.layers.Conv2D(256, (3, 3), activation='relu'))
model_CNN_mfcc.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
model_CNN_mfcc.add(keras.layers.BatchNormalization())
# 3rd conv layer
model_CNN_mfcc.add(keras.layers.Conv2D(128, (2, 2), activation='relu'))
model_CNN_mfcc.add(keras.layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'))
model_CNN_mfcc.add(keras.layers.BatchNormalization())
# flatten output and feed it into dense layer
model_CNN_mfcc.add(keras.layers.Flatten())
model_CNN_mfcc.add(keras.layers.Dense(256, activation='relu'))
model_CNN_mfcc.add(keras.layers.Dense(128, activation='relu'))
model_CNN_mfcc.add(keras.layers.Dense(64, activation='tanh'))
model_CNN_mfcc.add(keras.layers.Dense(32, activation='tanh'))
model_CNN_mfcc.add(keras.layers.Dropout(0.5))
# output layer
model_CNN_mfcc.add(keras.layers.Dense(10, activation='softmax'))
optimiser = tf.keras.optimizers.Adam(learning_rate=0.0001)
model_CNN_mfcc.compile(optimizer=optimiser,loss='sparse_categorical_crossentropy',metrics=['accuracy'])
model_CNN_mfcc.summary()
```
apprentissage avec le model CNN sur la base mfcc
```
history_CNN_mfcc = model_CNN_mfcc.fit(X_train_mfcc_2, y_train_mfcc, batch_size=32, validation_split = 0.3, epochs=50)
affiche_acc(history_CNN_mfcc)
affiche_loss(history_CNN_mfcc)
```
evaluation du model CNN sur la base mfcc
```
test_loss, test_acc = model_CNN_mfcc.evaluate(X_test_mfcc_2,y_test_mfcc)
print('Test accuracy:', test_acc)
```
matrice de confusion
```
prediction_mfcc=model_CNN_mfcc.predict(X_test_mfcc_2,batch_size=32)
prediction_mfcc.shape
y_pred_mfcc=[]
for i in range(len(prediction_mfcc)) :
y_pred_mfcc.append(np.argmax(prediction_mfcc[i,:]))
confusion_metrics_mfcc=tf.math.confusion_matrix(y_test_mfcc,y_pred_mfcc)
print(np.round(np.array((confusion_metrics_mfcc/sum(confusion_metrics_mfcc))*100), 0))
```
redimensionner la base mel pour un model CNN
```
X_train_mel_2 = X_train_mel.reshape(X_train_mel.shape[0],X_train_mel.shape[1],X_train_mel.shape[2],1)
X_test_mel_2 = X_test_mel.reshape(X_test_mel.shape[0],X_test_mel.shape[1],X_test_mel.shape[2],1)
input_shape_mel = (X_train_mel_2.shape[1], X_train_mel_2.shape[2], 1)
```
architecture avec des CNN pour les mel
```
model_CNN_mel = keras.Sequential()
# 1st conv layer
model_CNN_mel.add(keras.layers.Conv2D(256, (3, 3), activation='relu', input_shape=input_shape_mel))
model_CNN_mel.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
model_CNN_mel.add(keras.layers.BatchNormalization())
# 2nd conv layer
model_CNN_mel.add(keras.layers.Conv2D(256, (3, 3), activation='relu'))
model_CNN_mel.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
model_CNN_mel.add(keras.layers.BatchNormalization())
# 3rd conv layer
model_CNN_mel.add(keras.layers.Conv2D(128, (2, 2), activation='relu'))
model_CNN_mel.add(keras.layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'))
model_CNN_mel.add(keras.layers.BatchNormalization())
# flatten output and feed it into dense layer
model_CNN_mel.add(keras.layers.Flatten())
model_CNN_mel.add(keras.layers.Dense(256, activation='relu'))
model_CNN_mel.add(keras.layers.Dense(128, activation='relu'))
model_CNN_mel.add(keras.layers.Dense(64, activation='tanh'))
model_CNN_mel.add(keras.layers.Dense(32, activation='tanh'))
model_CNN_mel.add(keras.layers.Dropout(0.5))
# output layer
model_CNN_mel.add(keras.layers.Dense(10, activation='softmax'))
optimiser = tf.keras.optimizers.Adam(learning_rate=0.0001)
model_CNN_mel.compile(optimizer=optimiser,loss='sparse_categorical_crossentropy',metrics=['accuracy'])
model_CNN_mel.summary()
```
apprentissage avec le model CNN sur la base mel
```
history_CNN_mel = model_CNN_mel.fit(X_train_mel_2, y_train_mel, batch_size=32, validation_split = 0.3, epochs=50)
affiche_acc(history_CNN_mel)
affiche_loss(history_CNN_mel)
```
evaluation du model CNN sur la base mel
```
test_loss_mel, test_acc_mel = model_CNN_mel.evaluate(X_test_mel_2,y_test_mel)
print('Test accuracy:', test_acc)
```
matrice de confusion
```
prediction_mel=model_CNN_mel.predict(X_test_mel_2,batch_size=32)
prediction_mel.shape
y_pred_mel=[]
for i in range(len(prediction_mel)) :
y_pred_mel.append(np.argmax(prediction_mel[i,:]))
confusion_metrics_mel=tf.math.confusion_matrix(y_test_mel,y_pred_mel)
print(np.round(np.array((confusion_metrics_mel/sum(confusion_metrics_mel))*100), 0))
```
| github_jupyter |
# Table of Contents
<p><div class="lev1 toc-item"><a href="#Initialize-Environment" data-toc-modified-id="Initialize-Environment-1"><span class="toc-item-num">1 </span>Initialize Environment</a></div><div class="lev1 toc-item"><a href="#Load-Toy-Data" data-toc-modified-id="Load-Toy-Data-2"><span class="toc-item-num">2 </span>Load Toy Data</a></div><div class="lev1 toc-item"><a href="#Measure-Functional-Connectivity" data-toc-modified-id="Measure-Functional-Connectivity-3"><span class="toc-item-num">3 </span>Measure Functional Connectivity</a></div><div class="lev1 toc-item"><a href="#Optimize-Dynamic-Subgraphs-Parameters" data-toc-modified-id="Optimize-Dynamic-Subgraphs-Parameters-4"><span class="toc-item-num">4 </span>Optimize Dynamic Subgraphs Parameters</a></div><div class="lev2 toc-item"><a href="#Generate-Cross-Validation-Parameter-Sets" data-toc-modified-id="Generate-Cross-Validation-Parameter-Sets-41"><span class="toc-item-num">4.1 </span>Generate Cross-Validation Parameter Sets</a></div><div class="lev2 toc-item"><a href="#Run-NMF-Cross-Validation-Parameter-Sets" data-toc-modified-id="Run-NMF-Cross-Validation-Parameter-Sets-42"><span class="toc-item-num">4.2 </span>Run NMF Cross-Validation Parameter Sets</a></div><div class="lev2 toc-item"><a href="#Visualize-Quality-Measures-of-Search-Space" data-toc-modified-id="Visualize-Quality-Measures-of-Search-Space-43"><span class="toc-item-num">4.3 </span>Visualize Quality Measures of Search Space</a></div><div class="lev1 toc-item"><a href="#Detect-Dynamic-Subgraphs" data-toc-modified-id="Detect-Dynamic-Subgraphs-5"><span class="toc-item-num">5 </span>Detect Dynamic Subgraphs</a></div><div class="lev2 toc-item"><a href="#Stochastic-Factorization-with-Consensus" data-toc-modified-id="Stochastic-Factorization-with-Consensus-51"><span class="toc-item-num">5.1 </span>Stochastic Factorization with Consensus</a></div><div class="lev2 toc-item"><a href="#Plot--Subgraphs-and-Spectrotemporal-Dynamics" data-toc-modified-id="Plot--Subgraphs-and-Spectrotemporal-Dynamics-52"><span class="toc-item-num">5.2 </span>Plot Subgraphs and Spectrotemporal Dynamics</a></div>
# Initialize Environment
```
from __future__ import division
import os
os.environ['MKL_NUM_THREADS'] = '1'
os.environ['NUMEXPR_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import sys
# Data manipulation
import numpy as np
import scipy.io as io
import NMF
# Echobase
sys.path.append('../Echobase/')
import Echobase
# Plotting
import matplotlib.pyplot as plt
import seaborn as sns
```
# Load Toy Data
```
# df contains the following keys:
# -- evData contains ECoG with dims: n_sample x n_channels
# -- Fs contains sampling frequency: 1 x 1
# -- channel_lbl contains strings of channel labels with dims: n_channels
# -- channel_ix_soz contains indices of seizure-onset channels: n_soz
df = io.loadmat('./ToyData/Seizure_ECoG.mat')
evData = df['evData']
fs = int(df['Fs'][0,0])
n_sample, n_chan = evData.shape
```
# Measure Functional Connectivity
```
def compute_dynamic_windows(n_sample, fs, win_dur=1.0, win_shift=1.0):
"""
Divide samples into bins based on window duration and shift.
Parameters
----------
n_sample: int
Number of samples
fs: int
Sampling frequency
win_dur: float
Duration of the dynamic window
win_shift: float
Shift of the dynamic window
Returns
-------
win_ix: ndarray with dims: (n_win, n_ix)
"""
n_samp_per_win = int(fs * win_dur)
n_samp_per_shift = int(fs * win_shift)
curr_ix = 0
win_ix = []
while (curr_ix+n_samp_per_win) <= n_sample:
win_ix.append(np.arange(curr_ix, curr_ix+n_samp_per_win))
curr_ix += n_samp_per_shift
win_ix = np.array(win_ix)
return win_ix
# Transform to a configuration matrix (n_window x n_connection)
triu_ix, triu_iy = np.triu_indices(n_chan, k=1)
n_conn = len(triu_ix)
# Measure dynamic functional connectivity using Echobase
#win_bin = compute_dynamic_windows(n_sample, fs)
win_bin = compute_dynamic_windows(fs*100, fs)
n_win = win_bin.shape[0]
n_fft = win_bin.shape[1] // 2
# Notch filter the line-noise
fft_freq = np.linspace(0, fs // 2, n_fft)
notch_60hz = ((fft_freq > 55.0) & (fft_freq < 65.0))
notch_120hz = ((fft_freq > 115.0) & (fft_freq < 125.0))
notch_180hz = ((fft_freq > 175.0) & (fft_freq < 185.0))
fft_freq_ix = np.setdiff1d(np.arange(n_fft),
np.flatnonzero(notch_60hz | notch_120hz | notch_180hz))
fft_freq = fft_freq[fft_freq_ix]
n_freq = len(fft_freq_ix)
# Compute dFC
A_tensor = np.zeros((n_win, n_freq, n_conn))
for w_ii, w_ix in enumerate(win_bin):
evData_hat = evData[w_ix, :]
evData_hat = Echobase.Sigproc.reref.common_avg_ref(evData_hat)
for tr_ii, (tr_ix, tr_iy) in enumerate(zip(triu_ix, triu_iy)):
out = Echobase.Pipelines.ecog_network.coherence.mt_coherence(
df=1.0/fs, xi=evData_hat[:, tr_ix], xj=evData_hat[:, tr_iy],
tbp=5.0, kspec=9, nf=n_fft,
p=0.95, iadapt=1,
cohe=True, freq=True)
A_tensor[w_ii, :, tr_ii] = out['cohe'][fft_freq_ix]
A_hat = A_tensor.reshape(-1, n_conn)
```
# Optimize Dynamic Subgraphs Parameters
## Generate Cross-Validation Parameter Sets
```
def generate_folds(n_win, n_fold):
"""
Generate folds for cross-validation by randomly dividing the windows
into different groups for train/test-set.
Parameters
----------
n_win: int
Number of windows (observations) in the configuration matrix
n_fold: int
Number of folds desired
Returns
-------
fold_list: list[list]
List of index lists that can be further divided into train
and test sets
"""
# discard incomplete folds
n_win_per_fold = int(np.floor(n_win / n_fold))
win_list = np.arange(n_win)
win_list = np.random.permutation(win_list)
win_list = win_list[:(n_win_per_fold*n_fold)]
win_list = win_list.reshape(n_fold, -1)
fold_list = [list(ff) for ff in win_list]
return fold_list
fold_list = generate_folds(n_win, n_fold=5)
# Set the bounds of the search space
# Random sampling scheme
param_search_space = {'rank_range': (2, 20),
'alpha_range': (0.01, 1.0),
'beta_range': (0.01, 1.0),
'n_param': 20}
# Get parameter search space
# Each sampled parameter set will be evaluated n_fold times
param_list = NMF.optimize.gen_random_sampling_paramset(
fold_list=fold_list,
**param_search_space)
```
## Run NMF Cross-Validation Parameter Sets
```
# **This cell block should be parallelized. Takes time to run**
# Produces a list of quality measures for each parameter set in param_list
qmeas_list = [NMF.optimize.run_xval_paramset(A_hat, pdict)
for pdict in param_list]
```
## Visualize Quality Measures of Search Space
```
all_param, opt_params = NMF.optimize.find_optimum_xval_paramset(param_list, qmeas_list, search_pct=5)
# Generate quality measure plots
for qmeas in ['error', 'pct_sparse_subgraph', 'pct_sparse_coef']:
for param in ['rank', 'alpha', 'beta']:
param_unq = np.unique(all_param[param])
qmeas_mean = [np.mean(all_param[qmeas][all_param[param]==pp]) for pp in param_unq]
ax_jp = sns.jointplot(all_param[param], all_param[qmeas], kind='kde',
space=0, n_levels=60, shade_lowest=False)
ax = ax_jp.ax_joint
ax.plot([opt_params[param], opt_params[param]],
[ax.get_ylim()[0], ax.get_ylim()[1]],
lw=1.0, alpha=0.75, linestyle='--')
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.set_xlabel(param)
ax.set_ylabel(qmeas)
plt.show()
plt.close()
```
# Detect Dynamic Subgraphs
## Stochastic Factorization with Consensus
```
def refactor_connection_vector(conn_vec):
n_node = int(np.ceil(np.sqrt(2*len(conn_vec))))
triu_ix, triu_iy = np.triu_indices(n_node, k=1)
adj = np.zeros((n_node, n_node))
adj[triu_ix, triu_iy] = conn_vec[...]
adj += adj.T
return adj
fac_subgraph, fac_coef, err = NMF.optimize.consensus_nmf(A_hat, n_seed=2, n_proc=1,
opt_alpha=opt_params['alpha'],
opt_beta=opt_params['beta'],
opt_rank=opt_params['rank'])
fac_subgraph = np.array([refactor_connection_vector(subg)
for subg in fac_subgraph])
fac_coef = fac_coef.reshape(-1, n_win, n_freq)
```
## Plot Subgraphs and Spectrotemporal Dynamics
```
n_row = fac_subgraph.shape[0]
n_col = 2
plt.figure(figsize=(12,36))
for fac_ii in xrange(fac_subgraph.shape[0]):
ax = plt.subplot(n_row, n_col, 2*fac_ii+1)
ax.matshow(fac_subgraph[fac_ii, ...] / fac_subgraph.max(), cmap='viridis')
ax.set_axis_off()
ax = plt.subplot(n_row, n_col, 2*fac_ii+2)
ax.matshow(fac_coef[fac_ii, ...].T / fac_coef.max(), aspect=n_win/n_freq, cmap='inferno')
plt.show()
```
| github_jupyter |
```
import os
import shutil
from functools import reduce
from glob import glob
import geopandas as gpd
import numpy as np
```
## Constant Definition
```
data_raw = "../data/raw"
sealing_raw = os.path.join(data_raw, "sealing")
district_raw = os.path.join(data_raw, "district")
ground_level_raw = os.path.join(data_raw, "ground_level")
data_interim = "../data/interim"
sealing_interim = os.path.join(data_interim, "sealing")
district_interim = os.path.join(data_interim, "district")
ground_level_interim = os.path.join(data_interim, "ground_level")
district_url = "https://opendata.arcgis.com/datasets/9f5d82911d4545c4be1da8cab89f21ae_0.geojson"
x_coordinate_start = 390
y_coordinate_start = 5818
number_of_tiles = 2
# first, setup all directories
for directory in [
sealing_raw,
district_raw,
ground_level_raw,
sealing_interim,
district_interim,
ground_level_interim
]:
if not os.path.exists(directory):
os.makedirs(directory)
```
# Ground Level of Berlin
Uses the `berlin-opendata-downloader`: https://github.com/se-jaeger/berlin-gelaendemodelle-downloader
Compress the data on the fly to a tile size of `5x5`.
```
!pip install berlin-opendata-downloader
!berlin_downloader download {ground_level_raw} --compress 5 --file-format geojson
# move the downloaded files to a more appropriate directory
files = glob(os.path.join(ground_level_raw, "compressed", "geojson", "*"))
for file in files:
shutil.move(file, ground_level_raw)
# delete empty directories
shutil.rmtree(os.path.join(ground_level_raw, "compressed"))
```
Computing gradients on each tile separately creates errors on the borders of the tiles but would be necessary,
if the whole data shall be use because the current approach assumes the input of gradient computing is rectangular.
Use a subset of the data because it is
1. easier to use because of the dataset size
2. more accurate
```
file_names = []
for x_offset in range(number_of_tiles):
for y_offset in range(number_of_tiles):
x = x_coordinate_start + x_offset * 2
y = y_coordinate_start + y_offset * 2
file_names.append(os.path.join(ground_level_raw, f"{x}_{y}.geojson"))
# read the subset of tiles and create one Data Frame
data_frames_ground_level = [gpd.read_file(file) for file in file_names]
df_ground_level_subset = reduce(lambda a, b: a.append(b), data_frames_ground_level)
# some column selection
df_ground_level_subset.drop(columns=["x", "y"], inplace=True)
# compute gradients of the ground levels
x_size = y_size = int(np.sqrt(df_ground_level_subset.shape[0]))
ground_level_matrix = df_ground_level_subset["height"].values.reshape((x_size, y_size))
ground_level_gradients = np.gradient(ground_level_matrix)
df_ground_level_subset["y gradient"] = ground_level_gradients[0].flatten()
df_ground_level_subset["x gradient"] = ground_level_gradients[1].flatten()
# save the preprocessed DataFrame
df_ground_level_subset.to_file(os.path.join(ground_level_interim, "ground_level_subset.geojson"), driver="GeoJSON")
df_ground_level_subset.head()
```
# Districts of Berlin
```
# get and save the raw data
df_district = gpd.read_file(district_url)
df_district.to_crs(crs={"init": "epsg:25833"}, inplace=True)
df_district.to_file(os.path.join(district_raw, "district.geojson"), driver="GeoJSON")
# drop some columns, rename the rest, and save the data
df_district = df_district[["Gemeinde_n", "geometry"]]
df_district.columns = ["district", "geometry"]
df_district.to_file(os.path.join(district_interim, "district.geojson"), driver="GeoJSON")
df_district.head()
```
# Level of Sealing
Used the software [QGIS](https://www.qgis.org/en/site/) to download
the data `geojson` dump to `../data/raw/sealing/sealing.geojson`.
- The original map: https://fbinter.stadt-berlin.de/fb/index.jsp?loginkey=showMap&mapId=wmsk01_02versieg2016@senstadt
- WFS: https://fbinter.stadt-berlin.de/fb/berlin/service_intern.jsp?id=sach_nutz2015_nutzsa@senstadt&type=WFS
```
df_sealing = gpd.read_file(os.path.join(sealing_raw, "sealing.geojson"))
df_sealing = df_sealing[["VG_0", "geometry"]]
df_sealing.columns = ["sealing", "geometry"]
df_sealing.to_file(os.path.join(sealing_interim, "sealing.geojson"), driver="GeoJSON")
df_sealing.head()
```
| github_jupyter |
## Exercise L3 - 1: Diagnose Dataset Level and Select Last Encounter
### Instructions
- Given the dataset, convert the dataset to a longitudinal level but select only the last encounter for each patient.
- Assume that that the order of encounter IDs is indicative of the time for encounter. In other words a lower number encounter will come before a higher numbered encounter.
```
import pandas as pd
import numpy as np
ehr_level_dataset_path = "./data/ehr_level_exercise_dataset.csv"
```
### Level of Dataset
What level is the dataset at? Is at the line or encounter level?
### Solution
```
ehr_level_df = pd.read_csv(ehr_level_dataset_path)
ehr_level_df.head()
```
**Tests**
- Line: Total number of rows > Number of Unique Encounters
- Encounter level: Total Number of Rows = Number of Unique Encounters
```
# Line Test
try:
assert len(ehr_level_df) > ehr_level_df['ENCOUNTER_ID'].nunique()
print("Dataset could be at the line level")
except:
print("Dataset is not at the line level")
# Encounter Test
try:
assert len(ehr_level_df) == ehr_level_df['ENCOUNTER_ID'].nunique()
print("Dataset could be at the encounter level")
except:
print("Dataset is not at the encounter level")
```
**Answer:** Dataset is at the encounter level and you can probably guess by seeing the arrays for the code sets but we did a few simple tests to confirm.
### Select Last Encounter for each Patient
So in many cases you may only want a snapshot of a patient's history for your modeling objective. In some cases it might be important to see the changes over time but in other cases you only want the most recent case or depending on the model the first case could also be used. Really important to know how the context for how the model will be deployed in production and the time state you will be getting data.
```
# select last encounter for each patient
#convert encounter id column to a numerical value
def convert_encounter_id_to_number(df, encounter_id):
df["ENCOUNTER_ID_NUMBER"] = df[encounter_id].str.replace('udacity_health_encounter_id_', '').astype(int)
return df
def select_last_encounter(df, patient_id, encounter_id):
df = df.sort_values(encounter_id)
last_encounter_values = df.groupby(patient_id)[encounter_id].tail(1).values
return df[df[encounter_id].isin(last_encounter_values)]
ehr_encounter_number_df = convert_encounter_id_to_number(ehr_level_df, "ENCOUNTER_ID")
last_encounter_df = select_last_encounter(ehr_encounter_number_df, "PATIENT_ID", "ENCOUNTER_ID_NUMBER" )
#take subset of output
test_last_encounter_df = last_encounter_df[['ENCOUNTER_ID', 'ENCOUNTER_ID_NUMBER', 'PATIENT_ID']]
```
### Test cases
- PATIENT_IDS - udacity_health_patient_id_309, udacity_health_patient_id_418, udacity_health_patient_id_908
```
ehr_level_df[ehr_level_df['PATIENT_ID']=='udacity_health_patient_id_309']
```
For patient id 309, the selected encounter should be 7772.
```
test_last_encounter_df[test_last_encounter_df['PATIENT_ID']=='udacity_health_patient_id_309']
ehr_level_df[ehr_level_df['PATIENT_ID']=='udacity_health_patient_id_418']
```
For patient id 418, the selected encounter should be 3362.
```
test_last_encounter_df[test_last_encounter_df['PATIENT_ID']=='udacity_health_patient_id_418']
ehr_level_df[ehr_level_df['PATIENT_ID']=='udacity_health_patient_id_908']
```
For patient id 908, the selected encounter should be 6132.
```
test_last_encounter_df[test_last_encounter_df['PATIENT_ID']=='udacity_health_patient_id_908']
```
## Exercise L3 - 2: Dataset Splitting
### Instructions
- Split the provided dataset into a train and test split but be sure not to mix patient encounter records across the two partitions
- Be sure to run the following three tests
- Patient data in only one partition
- Total unique number of patients across all partitions = total number unique patients in original full dataset
- Total number of rows original dataset = sum of rows across splits
```
splitting_exercise_dataset_path = "./data/SYNTHETIC_EHR_DATASET.csv"
```
### Solution
This is largely a review of two parts in this lesson and you can use most of the same code for each step. The key is to identify the level of the dataset and then to convert it to the encounter level before you do your splits. Then perform the splitting and run the tests.
#### Convert to Encounter Level
```
# convert to encounter and then split but make sure
ehr_pre_split_df = pd.read_csv(splitting_exercise_dataset_path)
grouping_field_list = ['ENCOUNTER_ID', 'PATIENT_ID', 'PRINCIPAL_DIAGNOSIS_CODE']
non_grouped_field_list = [c for c in ehr_pre_split_df.columns if c not in grouping_field_list]
ehr_encounter_df = ehr_pre_split_df.groupby(grouping_field_list)[non_grouped_field_list].agg(lambda x:
list([y for y in x if y is not np.nan ] ) ).reset_index()
```
#### Split at Patient Level
```
PATIENT_ID_FIELD = 'PATIENT_ID'
TEST_PERCENTAGE = 0.2
def split_dataset_patient_level(df, key, test_percentage=0.2):
df = df.iloc[np.random.permutation(len(df))]
unique_values = df[key].unique()
total_values = len(unique_values)
sample_size = round(total_values * (1 - test_percentage ))
train = df[df[key].isin(unique_values[:sample_size])].reset_index(drop=True)
test = df[df[key].isin(unique_values[sample_size:])].reset_index(drop=True)
return train, test
train_df, test_df = split_dataset_patient_level(ehr_encounter_df, PATIENT_ID_FIELD, TEST_PERCENTAGE)
assert len(set(train_df[PATIENT_ID_FIELD].unique()).intersection(set(test_df[PATIENT_ID_FIELD].unique()))) == 0
print("Test passed for patient data in only one partition")
assert (train_df[PATIENT_ID_FIELD].nunique() + test_df[PATIENT_ID_FIELD].nunique()) == ehr_encounter_df[PATIENT_ID_FIELD].nunique()
print("Test passed for number of unique patients being equal!")
assert len(train_df) + len(test_df) == len(ehr_encounter_df)
print("Test passed for number of total rows equal!")
```
#### Optional
- Check label distribution and use scikitlearn - https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html#sphx-glr-auto-examples-model-selection-plot-cv-indices-py
## Exercise L3 - 3: Build Bucketed Numeric Feature with TF
### Instructions
- Given the Swiss heart disease dataset that we worked with earlier, build a bucketed numeric feature from the age feature.
- For this exercise, use the Tensorflow csv function for loading the dataset directly into a TF tensor -https://www.tensorflow.org/api_docs/python/tf/data/experimental/make_csv_dataset. This approach will be useful for when you have much larger datasets and also allows you to bypass loading the dataset in Pandas.
- More information on the Tensorflow bucketized feature can be found here https://www.tensorflow.org/api_docs/python/tf/feature_column/bucketized_column. Bucketed features take as input the numeric feature that we covered in the lesson. For the numeric feature, you do not need to normalize it like we did in the lesson.
```
import tensorflow as tf
swiss_dataset_path = "./data/lesson_exercise_swiss_dataset.csv"
BATCH_SIZE =128
PREDICTOR_FIELD = 'num_label'
```
### Solution
```
# ETL with TF dataset make csv function
swiss_tf_dataset = tf.data.experimental.make_csv_dataset( swiss_dataset_path, batch_size=BATCH_SIZE,
num_epochs=1, label_name=PREDICTOR_FIELD, header=True)
swiss_dataset_batch = next(iter(swiss_tf_dataset))[0]
swiss_dataset_batch
# create TF numeric feature
tf_numeric_age_feature = tf.feature_column.numeric_column(key='age', default_value=0, dtype=tf.float64)
#boundaries for the different age buckets
b_list = [ 0, 18, 25, 40, 55, 65, 80, 100]
#create TF bucket feature from numeric feature
tf_bucket_age_feature = tf.feature_column.bucketized_column(source_column=tf_numeric_age_feature, boundaries= b_list)
def demo(feature_column, example_batch):
feature_layer = tf.keras.layers.DenseFeatures(feature_column)
print(feature_layer(example_batch))
print("\nExample of one transformed row:")
print(feature_layer(example_batch).numpy()[0])
print("Example bucket field:\n{}\n".format(tf_bucket_age_feature))
demo(tf_bucket_age_feature, swiss_dataset_batch)
```
## Exercise L3 - 4: Build Embedding Categorical Feature with TF
### Instructions
- Build a 10 dimension embedding feature for the PRINCIPAL_DIAGNOSIS_CODE field
- Here is the link to the Tensorflow Embedding column documentation -https://www.tensorflow.org/api_docs/python/tf/feature_column/embedding_column
- Some functions provided below to assist
```
ehr_line_df = pd.read_csv("./data/SYNTHETIC_EHR_DATASET.csv")
cat_example_df = ehr_line_df[['ENCOUNTER_ID', 'PRINCIPAL_DIAGNOSIS_CODE', 'LABEL']]
#adapted from https://www.tensorflow.org/tutorials/structured_data/feature_columns
def df_to_dataset(df, predictor, batch_size=32):
df = df.copy()
labels = df.pop(predictor)
ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
ds = ds.shuffle(buffer_size=len(df))
ds = ds.batch(batch_size)
return ds
BATCH_SIZE = 64
PREDICTOR_FIELD = 'LABEL'
categorical_tf_ds = df_to_dataset(cat_example_df, PREDICTOR_FIELD, batch_size=BATCH_SIZE)
# build vocab for categorical features
def write_vocabulary_file(vocab_list, field_name, default_value, vocab_dir='./vocab/'):
output_file_path = os.path.join(vocab_dir, str(field_name) + "_vocab.txt")
# put default value in first row as TF requires
vocab_list = np.insert(vocab_list, 0, default_value, axis=0)
df = pd.DataFrame(vocab_list).to_csv(output_file_path, index=None, header=None)
return output_file_path
def build_vocab_files(df, categorical_column_list, default_value='00'):
vocab_files_list = []
for c in categorical_column_list:
v_file = write_vocabulary_file(df[c].unique(), c, default_value)
vocab_files_list.append(v_file)
return vocab_files_list
```
### Solution
```
import os
# add logic to add if not exist
#os.mkdir("./vocab/")
categorical_field_list = ["PRINCIPAL_DIAGNOSIS_CODE"]
vocab_files_list = build_vocab_files(cat_example_df, categorical_field_list)
vocab_files_list[0]
principal_diagnosis_vocab = tf.feature_column.categorical_column_with_vocabulary_file(
key="PRINCIPAL_DIAGNOSIS_CODE", vocabulary_file = vocab_files_list[0], num_oov_buckets=1)
dims = 10
cat_embedded = tf.feature_column.embedding_column(principal_diagnosis_vocab, dimension=dims)
categorical_tf_ds_batch = next(iter(categorical_tf_ds))[0]
demo(cat_embedded, categorical_tf_ds_batch)
```
| github_jupyter |
Generalized Method of Moments
=============================
*Generalized method of moments* (GMM) is an estimation principle that
extends *method of moments*. It seeks the parameter that minimizes a
quadratic form of the moments. It is particularly useful in estimating
structural models in which moment conditions can be derived from
economic theory. GMM emerges as one of the most popular estimators in
modern econometrics, and it includes conventional methods like the
two-stage least squares (2SLS) and the three-stage least square as
special cases.
**R Example**
The CRAN packge [gmm](http://cran.r-project.org/web/packages/gmm/index.html) provides an interface for GMM estimation. In this document we demonstrate it in a nonlinear model.
[Bruno Rodrigues](http://www.brodrigues.co/pages/aboutme.html) shared [his example](http://www.brodrigues.co/blog/2013-11-07-gmm-with-rmd/) with detailed instruction and discussion.
(update: as Aug 19, 2018, his linked data no longer works. I track to the original dataset and do the conversion to make it work.)
Unfortunately, I find his example cannot reflect the essence of GMM. The blunder was that he took the *method of moments* as the *generalized method of moments*. He worked with a just-identified model, in which the choices of **type** and **wmatrix** in his call
```
my_gmm <- gmm(moments, x = dat, t0 = init, type = "iterative", crit = 1e-25, wmatrix = "optimal", method = "Nelder-Mead", control = list(reltol = 1e-25, maxit = 20000))
```
is simplily irrelevant. Experimenting with different options of **type** and **wmatrix**, we will find exactly the same point estimates and variances.
Below I illustrate the nonlinear GMM in an over-identified system. First we import the data and add a constant.
```
# load the data
library(Ecdat, quietly = TRUE, warn.conflicts = FALSE)
data(Benefits)
g = Benefits
g$const <- 1 # add the constant
g1 <- g[, c("ui", "const", "age", "dkids", "dykids", "head", "sex", "married", "rr") ]
head(g)
# to change the factors into numbers
for (j in c(1, 4, 5, 6, 7, 8) ){
g1[,j] = as.numeric( g1[,j] ) -1
}
```
R's OLS function **lm** adds the intercept in the default setting. In contrast,we have to specify the moments from scratch in **gmm**. The constant, a column of ones, must be included explicitly in the data matrix.
Next, we define the logistic function and the moment conditions.
```
logistic <- function(theta, data) {
return(1/(1 + exp(-data %*% theta)))
}
moments <- function(theta, data) {
y <- as.numeric(data[, 1])
x <- data.matrix(data[, c(2:3, 6:8)])
z <- data.matrix( data[, c(2,4, 5:9) ] ) # more IVs than the regressors. Over-identified.
m <- z * as.vector((y - logistic(theta, x)))
return(cbind(m))
}
```
Here I naively adapt Bruno Rodrigues's example and specify the momemts as
$$
E[z_i \epsilon_i] = E[ z_i ( y_i - \mathrm{ logistic }(x_i \beta ) )] = 0
$$
However, such a specification is almost impossible to be motivated from the economic theory of random utility models.
Eventually, we call the GMM function and display the results. An initial value must be provided for a numerical optimization algorithm. It is recommended to try at least dozens of initial values in general unless one can show that the minimizer is unique in the model.
```
library(gmm) # load the library "gmm"
init <- (lm(ui ~ age + dkids + head + sex, data = g1 ))$coefficients
my_gmm <- gmm(moments, x = g1, t0 = init, type = "twoStep", wmatrix = "optimal")
summary(my_gmm)
```
In the summary, the $J$ statistics indicates that the moment conditions are unlikely to hold. The model requires further modification.
P.S.: According to my personal experience, caution must be executed when using **gmm** in R for nonlinear models. Sometimes the estimates can be unreliable, perhaps due to the shape of the criterion function in several parameters. Simulation experiments are highly suggested before we believe the estimates.
| github_jupyter |

<div class = 'alert alert-block alert-info'
style = 'background-color:#4c1c84;
color:#eeebf1;
border-width:5px;
border-color:#4c1c84;
font-family:Comic Sans MS;
border-radius: 50px 50px'>
<p style = 'font-size:24px'>Exp 033</p>
<a href = "#Config"
style = "color:#eeebf1;
font-size:14px">1.Config</a><br>
<a href = "#Settings"
style = "color:#eeebf1;
font-size:14px">2.Settings</a><br>
<a href = "#Data-Load"
style = "color:#eeebf1;
font-size:14px">3.Data Load</a><br>
<a href = "#Pytorch-Settings"
style = "color:#eeebf1;
font-size:14px">4.Pytorch Settings</a><br>
<a href = "#Training"
style = "color:#eeebf1;
font-size:14px">5.Training</a><br>
</div>
<p style = 'font-size:24px;
color:#4c1c84'>
実施したこと
</p>
<li style = "color:#4c1c84;
font-size:14px">使用データ:Jigsaw-Classification</li>
<li style = "color:#4c1c84;
font-size:14px">使用モデル:unitary/toxic-bert</li>
<li style = "color:#4c1c84;
font-size:14px">Attentionの可視化</li>
<br>
<h1 style = "font-size:45px; font-family:Comic Sans MS ; font-weight : normal; background-color: #4c1c84 ; color : #eeebf1; text-align: center; border-radius: 100px 100px;">
Config
</h1>
<br>
```
import sys
sys.path.append("../src/utils/iterative-stratification/")
sys.path.append("../src/utils/detoxify")
sys.path.append("../src/utils/coral-pytorch/")
sys.path.append("../src/utils/pyspellchecker")
import warnings
warnings.simplefilter('ignore')
import os
import gc
gc.enable()
import sys
import glob
import copy
import math
import time
import random
import string
import psutil
import pathlib
from pathlib import Path
from contextlib import contextmanager
from collections import defaultdict
from box import Box
from typing import Optional
from pprint import pprint
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import japanize_matplotlib
from tqdm.auto import tqdm as tqdmp
from tqdm.autonotebook import tqdm as tqdm
tqdmp.pandas()
## Model
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import StratifiedKFold, KFold
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from transformers import AutoTokenizer, AutoModel, AdamW, AutoModelForSequenceClassification
from transformers import RobertaModel, RobertaForSequenceClassification
from transformers import RobertaTokenizer
from transformers import LukeTokenizer, LukeModel, LukeConfig
from transformers import get_linear_schedule_with_warmup, get_cosine_schedule_with_warmup
from transformers import BertTokenizer, BertForSequenceClassification, BertForMaskedLM
from transformers import RobertaTokenizer, RobertaForSequenceClassification
from transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification
from transformers import DebertaTokenizer, DebertaModel
# Pytorch Lightning
import pytorch_lightning as pl
from pytorch_lightning.utilities.seed import seed_everything
from pytorch_lightning import callbacks
from pytorch_lightning.callbacks.progress import ProgressBarBase
from pytorch_lightning import LightningDataModule, LightningDataModule
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.loggers.csv_logs import CSVLogger
from pytorch_lightning.callbacks import RichProgressBar
from sklearn.linear_model import Ridge
from sklearn.svm import SVC, SVR
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.stats import rankdata
from cuml.svm import SVR as cuml_SVR
from cuml.linear_model import Ridge as cuml_Ridge
import cudf
from detoxify import Detoxify
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
from ast import literal_eval
from nltk.tokenize import TweetTokenizer
import spacy
from scipy.stats import sem
from copy import deepcopy
from spellchecker import SpellChecker
from typing import Text, Set, List
import torch
config = {
"exp_comment":"Jigsaw-Classification をHateBERTで学習",
"seed": 42,
"root": "/content/drive/MyDrive/kaggle/Jigsaw/raw",
"n_fold": 5,
"epoch": 5,
"max_length": 256,
"environment": "AWS",
"project": "Jigsaw",
"entity": "dataskywalker",
"exp_name": "032_exp",
"margin": 0.5,
"train_fold": [0, 1, 2, 3, 4],
"trainer": {
"gpus": 1,
"accumulate_grad_batches": 8,
"progress_bar_refresh_rate": 1,
"fast_dev_run": True,
"num_sanity_val_steps": 0,
},
"train_loader": {
"batch_size": 8,
"shuffle": True,
"num_workers": 1,
"pin_memory": True,
"drop_last": True,
},
"valid_loader": {
"batch_size": 8,
"shuffle": False,
"num_workers": 1,
"pin_memory": True,
"drop_last": False,
},
"test_loader": {
"batch_size": 8,
"shuffle": False,
"num_workers": 1,
"pin_memory": True,
"drop_last": False,
},
"backbone": {
"name": "GroNLP/hateBERT",
"output_dim": 1,
},
"optimizer": {
"name": "torch.optim.AdamW",
"params": {
"lr": 1e-6,
},
},
"scheduler": {
"name": "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts",
"params": {
"T_0": 20,
"eta_min": 0,
},
},
"loss": "nn.MSELoss",
}
config = Box(config)
config.tokenizer = AutoTokenizer.from_pretrained(config.backbone.name)
config.model = BertForMaskedLM.from_pretrained(config.backbone.name)
# pprint(config)
config.tokenizer.save_pretrained(f"../data/processed/{config.backbone.name}")
pretrain_model = BertForMaskedLM.from_pretrained(config.backbone.name)
pretrain_model.save_pretrained(f"../data/processed/{config.backbone.name}")
# 個人的にAWSやKaggle環境やGoogle Colabを行ったり来たりしているのでまとめています
import os
import sys
from pathlib import Path
if config.environment == 'AWS':
INPUT_DIR = Path('/mnt/work/data/kaggle/Jigsaw/')
MODEL_DIR = Path(f'../models/{config.exp_name}/')
OUTPUT_DIR = Path(f'../data/interim/{config.exp_name}/')
UTIL_DIR = Path('/mnt/work/shimizu/kaggle/PetFinder/src/utils')
os.makedirs(MODEL_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
print(f"Your environment is 'AWS'.\nINPUT_DIR is {INPUT_DIR}\nMODEL_DIR is {MODEL_DIR}\nOUTPUT_DIR is {OUTPUT_DIR}\nUTIL_DIR is {UTIL_DIR}")
elif config.environment == 'Kaggle':
INPUT_DIR = Path('../input/*****')
MODEL_DIR = Path('./')
OUTPUT_DIR = Path('./')
print(f"Your environment is 'Kaggle'.\nINPUT_DIR is {INPUT_DIR}\nMODEL_DIR is {MODEL_DIR}\nOUTPUT_DIR is {OUTPUT_DIR}")
elif config.environment == 'Colab':
INPUT_DIR = Path('/content/drive/MyDrive/kaggle/Jigsaw/raw')
BASE_DIR = Path("/content/drive/MyDrive/kaggle/Jigsaw/interim")
MODEL_DIR = BASE_DIR / f'{config.exp_name}'
OUTPUT_DIR = BASE_DIR / f'{config.exp_name}/'
os.makedirs(MODEL_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
if not os.path.exists(INPUT_DIR):
print('Please Mount your Google Drive.')
else:
print(f"Your environment is 'Colab'.\nINPUT_DIR is {INPUT_DIR}\nMODEL_DIR is {MODEL_DIR}\nOUTPUT_DIR is {OUTPUT_DIR}")
else:
print("Please choose 'AWS' or 'Kaggle' or 'Colab'.\nINPUT_DIR is not found.")
# Seed固定
seed_everything(config.seed)
## 処理時間計測
@contextmanager
def timer(name:str, slack:bool=False):
t0 = time.time()
p = psutil.Process(os.getpid())
m0 = p.memory_info()[0] / 2. ** 30
print(f'<< {name} >> Start')
yield
m1 = p.memory_info()[0] / 2. ** 30
delta = m1 - m0
sign = '+' if delta >= 0 else '-'
delta = math.fabs(delta)
print(f"<< {name} >> {m1:.1f}GB({sign}{delta:.1f}GB):{time.time() - t0:.1f}sec", file=sys.stderr)
```
<br>
<h1 style = "font-size:45px; font-family:Comic Sans MS ; font-weight : normal; background-color: #4c1c84 ; color : #eeebf1; text-align: center; border-radius: 100px 100px;">
Data Load
</h1>
<br>
```
## Data Check
for dirnames, _, filenames in os.walk(INPUT_DIR):
for filename in filenames:
print(f'{dirnames}/{filename}')
val_df = pd.read_csv("/mnt/work/data/kaggle/Jigsaw/validation_data.csv")
test_df = pd.read_csv("/mnt/work/data/kaggle/Jigsaw/comments_to_score.csv")
display(val_df.head())
display(test_df.head())
```
<br>
<h2 style = "font-size:45px;
font-family:Comic Sans MS ;
font-weight : normal;
background-color: #eeebf1 ;
color : #4c1c84;
text-align: center;
border-radius: 100px 100px;">
Jigsaw Classification
</h2>
<br>
```
train_df = pd.read_csv("../data/external/jigsaw-classification/train.csv.zip")
display(train_df.head(10))
display(train_df.shape)
train_df["is_colon"] = train_df["comment_text"].progress_apply(lambda x:1 if ":" in x else 0)
def preprocess_text(txt:str) -> str:
new_texts = txt
new_texts = new_texts.replace(":", ",")
return new_texts
train_df["text"] = train_df["comment_text"].progress_apply(preprocess_text)
test_df["text"] = test_df["text"].progress_apply(preprocess_text)
val_df["less_toxic"] = val_df["less_toxic"].progress_apply(preprocess_text)
val_df["more_toxic"] = val_df["more_toxic"].progress_apply(preprocess_text)
import re
spell = SpellChecker(distance=1)
def misspelt_words_fn(dataframe: pd.DataFrame, col="text") -> Set[Text]:
misspelt_words = set()
for tweet in dataframe[col].str.casefold():
[misspelt_words.add(word) for word in spell.unknown(tweet.split())]
return misspelt_words
WORD = re.compile(r'\w+')
def reTokenize(tweet: Text) -> List[Text]:
return WORD.findall(tweet.casefold())
PATTERN = re.compile(r"(.)\1{2,}")
def reduce_lengthening(text: Text) -> Text:
return PATTERN.sub(r"\1\1", text)
def spell_correction(text: Text) -> Text:
return ' '.join([spell.correction(word)
if word in misspelt_words else word
for word in reTokenize(reduce_lengthening(text))])
misspelt_words = misspelt_words_fn(train_df, "text")
train_df["text"] = train_df["text"].progress_apply(spell_correction)
misspelt_words = misspelt_words_fn(test_df, "text")
test_df["text"] = test_df["text"].progress_apply(spell_correction)
misspelt_words = misspelt_words_fn(val_df, "less_toxic")
val_df["less_toxic"] = val_df["less_toxic"].progress_apply(spell_correction)
misspelt_words = misspelt_words_fn(val_df, "more_toxic")
val_df["more_toxic"] = val_df["more_toxic"].progress_apply(spell_correction)
target_cols = [
"toxic",
"severe_toxic",
"obscene",
"threat",
"insult",
"identity_hate"
]
plt.figure(figsize=(12, 5))
sns.histplot(train_df["toxic"], color="#4c1c84")
plt.grid()
plt.show()
train_df.head()
```
<br>
<h1 style = "font-size:45px; font-family:Comic Sans MS ; font-weight : normal; background-color: #4c1c84 ; color : #eeebf1; text-align: center; border-radius: 100px 100px;">
Pytorch Dataset
</h1>
<br>
```
class JigsawDataset:
def __init__(self, df, tokenizer, max_length, mode, target_cols):
self.df = df
self.max_len = max_length
self.tokenizer = tokenizer
self.mode = mode
self.target_cols = target_cols
if self.mode == "train":
self.text = df["text"].values
self.target = df[target_cols].values
elif self.mode == "valid":
self.more_toxic = df["more_toxic"].values
self.less_toxic = df["less_toxic"].values
else:
self.text = df["text"].values
def __len__(self):
return len(self.df)
def __getitem__(self, index):
if self.mode == "train":
text = self.text[index]
target = self.target[index]
inputs_text = self.tokenizer.encode_plus(
text,
truncation=True,
return_attention_mask=True,
return_token_type_ids=True,
max_length = self.max_len,
padding="max_length",
)
text_ids = inputs_text["input_ids"]
text_mask = inputs_text["attention_mask"]
text_token_type_ids = inputs_text["token_type_ids"]
return {
'text_ids': torch.tensor(text_ids, dtype=torch.long),
'text_mask': torch.tensor(text_mask, dtype=torch.long),
'text_token_type_ids': torch.tensor(text_token_type_ids, dtype=torch.long),
'target': torch.tensor(target, dtype=torch.float)
}
elif self.mode == "valid":
more_toxic = self.more_toxic[index]
less_toxic = self.less_toxic[index]
inputs_more_toxic = self.tokenizer.encode_plus(
more_toxic,
truncation=True,
return_attention_mask=True,
return_token_type_ids=True,
max_length = self.max_len,
padding="max_length",
)
inputs_less_toxic = self.tokenizer.encode_plus(
less_toxic,
truncation=True,
return_attention_mask=True,
return_token_type_ids=True,
max_length = self.max_len,
padding="max_length",
)
target = 1
more_toxic_ids = inputs_more_toxic["input_ids"]
more_toxic_mask = inputs_more_toxic["attention_mask"]
more_token_type_ids = inputs_more_toxic["token_type_ids"]
less_toxic_ids = inputs_less_toxic["input_ids"]
less_toxic_mask = inputs_less_toxic["attention_mask"]
less_token_type_ids = inputs_less_toxic["token_type_ids"]
return {
'more_toxic_ids': torch.tensor(more_toxic_ids, dtype=torch.long),
'more_toxic_mask': torch.tensor(more_toxic_mask, dtype=torch.long),
'more_token_type_ids': torch.tensor(more_token_type_ids, dtype=torch.long),
'less_toxic_ids': torch.tensor(less_toxic_ids, dtype=torch.long),
'less_toxic_mask': torch.tensor(less_toxic_mask, dtype=torch.long),
'less_token_type_ids': torch.tensor(less_token_type_ids, dtype=torch.long),
'target': torch.tensor(target, dtype=torch.float)
}
else:
text = self.text[index]
inputs_text = self.tokenizer.encode_plus(
text,
truncation=True,
return_attention_mask=True,
return_token_type_ids=True,
max_length = self.max_len,
padding="max_length",
)
text_ids = inputs_text["input_ids"]
text_mask = inputs_text["attention_mask"]
text_token_type_ids = inputs_text["token_type_ids"]
return {
'text_ids': torch.tensor(text_ids, dtype=torch.long),
'text_mask': torch.tensor(text_mask, dtype=torch.long),
'text_token_type_ids': torch.tensor(text_token_type_ids, dtype=torch.long),
}
```
<br>
<h2 style = "font-size:45px;
font-family:Comic Sans MS ;
font-weight : normal;
background-color: #eeebf1 ;
color : #4c1c84;
text-align: center;
border-radius: 100px 100px;">
DataModule
</h2>
<br>
```
class JigsawDataModule(LightningDataModule):
def __init__(self, train_df, valid_df, test_df, cfg):
super().__init__()
self._train_df = train_df
self._valid_df = valid_df
self._test_df = test_df
self._cfg = cfg
def train_dataloader(self):
dataset = JigsawDataset(
df=self._train_df,
tokenizer=self._cfg.tokenizer,
max_length=self._cfg.max_length,
mode="train",
target_cols=target_cols
)
return DataLoader(dataset, **self._cfg.train_loader)
def val_dataloader(self):
dataset = JigsawDataset(
df=self._valid_df,
tokenizer=self._cfg.tokenizer,
max_length=self._cfg.max_length,
mode="valid",
target_cols=target_cols
)
return DataLoader(dataset, **self._cfg.valid_loader)
def test_dataloader(self):
dataset = JigsawDataset(
df=self._test_df,
tokenizer = self._cfg.tokenizer,
max_length=self._cfg.max_length,
mode="test",
target_cols=target_cols
)
return DataLoader(dataset, **self._cfg.test_loader)
## DataCheck
seed_everything(config.seed)
sample_dataloader = JigsawDataModule(train_df, val_df, test_df, config).train_dataloader()
for data in sample_dataloader:
break
print(data["text_ids"].size())
print(data["text_mask"].size())
print(data["text_token_type_ids"].size())
print(data["target"].size())
print(data["target"])
output = config.model(
data["text_ids"],
data["text_mask"],
data["text_token_type_ids"],
output_hidden_states=True,
output_attentions=True,
)
print(output["hidden_states"][-1].size(), output["attentions"][-1].size())
print(output["hidden_states"][-1][:, 0, :].size(), output["attentions"][-1].size())
```
<br>
<h2 style = "font-size:45px;
font-family:Comic Sans MS ;
font-weight : normal;
background-color: #eeebf1 ;
color : #4c1c84;
text-align: center;
border-radius: 100px 100px;">
LigitningModule
</h2>
<br>
```
class JigsawModel(pl.LightningModule):
def __init__(self, cfg, fold_num):
super().__init__()
self.cfg = cfg
self.__build_model()
self.criterion = eval(self.cfg.loss)()
self.save_hyperparameters(cfg)
self.fold_num = fold_num
def __build_model(self):
self.base_model = BertForMaskedLM.from_pretrained(
self.cfg.backbone.name
)
print(f"Use Model: {self.cfg.backbone.name}")
self.norm = nn.LayerNorm(768)
self.drop = nn.Dropout(p=0.3)
self.head = nn.Linear(768, self.cfg.backbone.output_dim)
def forward(self, ids, mask, token_type_ids):
output = self.base_model(
input_ids=ids,
attention_mask=mask,
token_type_ids=token_type_ids,
output_hidden_states=True,
output_attentions=True
)
feature = self.norm(output["hidden_states"][-1][:, 0, :])
out = self.drop(feature)
out = self.head(out)
return {
"logits":out,
"feature":feature,
"attention":output["attentions"],
"mask":mask,
}
def training_step(self, batch, batch_idx):
text_ids = batch["text_ids"]
text_mask = batch['text_mask']
text_token_type_ids = batch['text_token_type_ids']
targets = batch['target']
outputs = self.forward(text_ids, text_mask, text_token_type_ids)
loss = torch.sqrt(self.criterion(outputs["logits"], targets))
return {
"loss":loss,
"targets":targets,
}
def training_epoch_end(self, training_step_outputs):
loss_list = []
for out in training_step_outputs:
loss_list.extend([out["loss"].cpu().detach().tolist()])
meanloss = sum(loss_list)/len(loss_list)
logs = {f"train_loss/fold{self.fold_num+1}": meanloss,}
self.log_dict(
logs,
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True
)
def validation_step(self, batch, batch_idx):
more_toxic_ids = batch['more_toxic_ids']
more_toxic_mask = batch['more_toxic_mask']
more_text_token_type_ids = batch['more_token_type_ids']
less_toxic_ids = batch['less_toxic_ids']
less_toxic_mask = batch['less_toxic_mask']
less_text_token_type_ids = batch['less_token_type_ids']
targets = batch['target']
more_outputs = self.forward(
more_toxic_ids,
more_toxic_mask,
more_text_token_type_ids
)
less_outputs = self.forward(
less_toxic_ids,
less_toxic_mask,
less_text_token_type_ids
)
more_outputs = torch.sum(more_outputs["logits"], 1)
less_outputs = torch.sum(less_outputs["logits"], 1)
outputs = more_outputs - less_outputs
logits = outputs.clone()
logits[logits > 0] = 1
loss = self.criterion(logits, targets)
return {
"loss":loss,
"pred":outputs,
"targets":targets,
}
def validation_epoch_end(self, validation_step_outputs):
loss_list = []
pred_list = []
target_list = []
for out in validation_step_outputs:
loss_list.extend([out["loss"].cpu().detach().tolist()])
pred_list.append(out["pred"].detach().cpu().numpy())
target_list.append(out["targets"].detach().cpu().numpy())
meanloss = sum(loss_list)/len(loss_list)
pred_list = np.concatenate(pred_list)
pred_count = sum(x>0 for x in pred_list)/len(pred_list)
logs = {
f"valid_loss/fold{self.fold_num+1}":meanloss,
f"valid_acc/fold{self.fold_num+1}":pred_count,
}
self.log_dict(
logs,
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True
)
def configure_optimizers(self):
optimizer = eval(self.cfg.optimizer.name)(
self.parameters(), **self.cfg.optimizer.params
)
self.scheduler = eval(self.cfg.scheduler.name)(
optimizer, **self.cfg.scheduler.params
)
scheduler = {"scheduler": self.scheduler, "interval": "step",}
return [optimizer], [scheduler]
```
<br>
<h2 style = "font-size:45px;
font-family:Comic Sans MS ;
font-weight : normal;
background-color: #eeebf1 ;
color : #4c1c84;
text-align: center;
border-radius: 100px 100px;">
Training
</h2>
<br>
```
skf = KFold(
n_splits=config.n_fold,
shuffle=True,
random_state=config.seed
)
for fold, (_, val_idx) in enumerate(skf.split(X=train_df, y=train_df["toxic"])):
train_df.loc[val_idx, "kfold"] = int(fold)
train_df["kfold"] = train_df["kfold"].astype(int)
train_df.head()
## Debug
config.trainer.fast_dev_run = True
config.backbone.output_dim = len(target_cols)
for fold in config.train_fold:
print("★"*25, f" Fold{fold+1} ", "★"*25)
df_train = train_df[train_df.kfold != fold].reset_index(drop=True)
datamodule = JigsawDataModule(df_train, val_df, test_df, config)
sample_dataloader = JigsawDataModule(df_train, val_df, test_df, config).train_dataloader()
config.scheduler.params.T_0 = config.epoch * len(sample_dataloader)
model = JigsawModel(config, fold)
lr_monitor = callbacks.LearningRateMonitor()
loss_checkpoint = callbacks.ModelCheckpoint(
filename=f"best_acc_fold{fold+1}",
monitor=f"valid_acc/fold{fold+1}",
save_top_k=1,
mode="max",
save_last=False,
dirpath=MODEL_DIR,
save_weights_only=True,
)
wandb_logger = WandbLogger(
project=config.project,
entity=config.entity,
name = f"{config.exp_name}",
tags = ['Hate-BERT', "Jigsaw-Classification"]
)
lr_monitor = LearningRateMonitor(logging_interval='step')
trainer = pl.Trainer(
max_epochs=config.epoch,
callbacks=[loss_checkpoint, lr_monitor, RichProgressBar()],
# deterministic=True,
logger=[wandb_logger],
**config.trainer
)
trainer.fit(model, datamodule=datamodule)
## Training
config.trainer.fast_dev_run = False
config.backbone.output_dim = len(target_cols)
for fold in config.train_fold:
print("★"*25, f" Fold{fold+1} ", "★"*25)
df_train = train_df[train_df.kfold != fold].reset_index(drop=True)
datamodule = JigsawDataModule(df_train, val_df, test_df, config)
sample_dataloader = JigsawDataModule(df_train, val_df, test_df, config).train_dataloader()
config.scheduler.params.T_0 = config.epoch * len(sample_dataloader)
model = JigsawModel(config, fold)
lr_monitor = callbacks.LearningRateMonitor()
loss_checkpoint = callbacks.ModelCheckpoint(
filename=f"best_acc_fold{fold+1}",
monitor=f"valid_acc/fold{fold+1}",
save_top_k=1,
mode="max",
save_last=False,
dirpath=MODEL_DIR,
save_weights_only=True,
)
wandb_logger = WandbLogger(
project=config.project,
entity=config.entity,
name = f"{config.exp_name}",
tags = ['Hate-BERT', "Jigsaw-Classification"]
)
lr_monitor = LearningRateMonitor(logging_interval='step')
trainer = pl.Trainer(
max_epochs=config.epoch,
callbacks=[loss_checkpoint, lr_monitor, RichProgressBar()],
# deterministic=True,
logger=[wandb_logger],
**config.trainer
)
trainer.fit(model, datamodule=datamodule)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config.backbone.output_dim = len(target_cols)
print(f"Device == {device}")
MORE = np.zeros((len(val_df), config.backbone.output_dim))
LESS = np.zeros((len(val_df), config.backbone.output_dim))
PRED = np.zeros((len(test_df), config.backbone.output_dim))
attention_array = np.zeros((len(val_df), 256)) # attention格納
mask_array = np.zeros((len(val_df), 256)) # mask情報格納,後でattentionと掛け合わせる
for fold in config.train_fold:
pred_list = []
print("★"*25, f" Fold{fold+1} ", "★"*25)
valid_dataloader = JigsawDataModule(train_df, val_df, test_df, config).val_dataloader()
model = JigsawModel(config, fold)
loss_checkpoint = callbacks.ModelCheckpoint(
filename=f"best_acc_fold{fold+1}",
monitor=f"valid_acc/fold{fold+1}",
save_top_k=1,
mode="max",
save_last=False,
dirpath="../input/toxicroberta/",
)
model = model.load_from_checkpoint(MODEL_DIR/f"best_acc_fold{fold+1}-v1.ckpt", cfg=config, fold_num=fold)
model.to(device)
model.eval()
more_list = []
less_list = []
for step, data in tqdm(enumerate(valid_dataloader), total=len(valid_dataloader)):
more_toxic_ids = data['more_toxic_ids'].to(device)
more_toxic_mask = data['more_toxic_mask'].to(device)
more_text_token_type_ids = data['more_token_type_ids'].to(device)
less_toxic_ids = data['less_toxic_ids'].to(device)
less_toxic_mask = data['less_toxic_mask'].to(device)
less_text_token_type_ids = data['less_token_type_ids'].to(device)
more_outputs = model(
more_toxic_ids,
more_toxic_mask,
more_text_token_type_ids,
)
less_outputs = model(
less_toxic_ids,
less_toxic_mask,
less_text_token_type_ids
)
more_list.append(more_outputs["logits"].detach().cpu().numpy())
less_list.append(less_outputs["logits"].detach().cpu().numpy())
MORE += np.concatenate(more_list)/len(config.train_fold)
LESS += np.concatenate(less_list)/len(config.train_fold)
# PRED += pred_list/len(config.train_fold)
plt.figure(figsize=(12, 5))
plt.scatter(LESS, MORE)
plt.xlabel("less-toxic")
plt.ylabel("more-toxic")
plt.grid()
plt.show()
val_df["less_attack"] = LESS.sum(axis=1)
val_df["more_attack"] = MORE.sum(axis=1)
val_df["diff_attack"] = val_df["more_attack"] - val_df["less_attack"]
attack_score = val_df[val_df["diff_attack"]>0]["diff_attack"].count()/len(val_df)
print(f"exp033 Score: {attack_score:.6f}")
```
<br>
<h2 style = "font-size:45px;
font-family:Comic Sans MS ;
font-weight : normal;
background-color: #eeebf1 ;
color : #4c1c84;
text-align: center;
border-radius: 100px 100px;">
Attention Visualize
</h2>
<br>
```
text_df = pd.DataFrame()
text_df["text"] = list(set(val_df["less_toxic"].unique().tolist() + val_df["more_toxic"].unique().tolist()))
display(text_df.head())
display(text_df.shape)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config.backbone.output_dim = len(target_cols)
print(f"Device == {device}")
attention_array = np.zeros((len(text_df), config.max_length)) # attention格納
mask_array = np.zeros((len(text_df), config.max_length)) # mask情報格納,後でattentionと掛け合わせる
feature_array = np.zeros((len(text_df), 768))
PRED = np.zeros((len(text_df), config.backbone.output_dim))
for fold in config.train_fold:
pred_list = []
print("★"*25, f" Fold{fold+1} ", "★"*25)
test_dataloader = JigsawDataModule(train_df, val_df, text_df, config).test_dataloader()
model = JigsawModel(config, fold)
loss_checkpoint = callbacks.ModelCheckpoint(
filename=f"best_acc_fold{fold+1}",
monitor=f"valid_acc/fold{fold+1}",
save_top_k=1,
mode="max",
save_last=False,
dirpath="../input/toxicroberta/",
)
model = model.load_from_checkpoint(MODEL_DIR/f"best_acc_fold{fold+1}-v1.ckpt", cfg=config, fold_num=fold)
model.to(device)
model.eval()
attention_list = []
feature_list = []
mask_list = []
pred_list = []
for step, data in tqdm(enumerate(test_dataloader), total=len(test_dataloader)):
text_ids = data["text_ids"].to(device)
text_mask = data["text_mask"].to(device)
text_token_type_ids = data["text_token_type_ids"].to(device)
mask_list.append(text_mask.detach().cpu().numpy())
outputs = model(
text_ids,
text_mask,
text_token_type_ids,
)
## Last LayerのCLS Tokenに対するAttention
last_attention = outputs["attention"][-1].detach().cpu().numpy()
total_attention = np.zeros((last_attention.shape[0], config.max_length))
for batch in range(last_attention.shape[0]):
for n_head in range(12):
total_attention[batch, :] += last_attention[batch, n_head, 0, :]
attention_list.append(total_attention)
pred_list.append(outputs["logits"].detach().cpu().numpy())
feature_list.append(outputs["feature"].detach().cpu().numpy())
attention_array += np.concatenate(attention_list)/config.n_fold
mask_array += np.concatenate(mask_list)/config.n_fold
feature_array += np.concatenate(feature_list)/config.n_fold
PRED += np.concatenate(pred_list)/len(config.train_fold)
text_df["target"] = PRED[:, 0]
text_df.to_pickle(OUTPUT_DIR/"text_df.pkl")
np.save(OUTPUT_DIR/'toxic-bert-exp033-attention.npy', attention_array)
np.save(OUTPUT_DIR/'toxic-bert-exp033-mask.npy', mask_array)
np.save(OUTPUT_DIR/'toxic-bert-exp033-feature.npy', feature_array)
plt.figure(figsize=(12, 5))
sns.histplot(text_df["target"], color="#4c1c84")
plt.grid()
plt.show()
```
<br>
<h2 style = "font-size:45px;
font-family:Comic Sans MS ;
font-weight : normal;
background-color: #eeebf1 ;
color : #4c1c84;
text-align: center;
border-radius: 100px 100px;">
Attention Load
</h2>
<br>
```
text_df = pd.read_pickle(OUTPUT_DIR/"text_df.pkl")
attention_array = np.load(OUTPUT_DIR/'toxic-bert-exp033-attention.npy')
mask_array = np.load(OUTPUT_DIR/'toxic-bert-exp033-mask.npy')
feature_array = np.load(OUTPUT_DIR/'toxic-bert-exp033-feature.npy')
from IPython.display import display, HTML
def highlight_r(word, attn):
html_color = '#%02X%02X%02X' % (255, int(255*(1 - attn)), int(255*(1 - attn)))
return '<span style="background-color: {}">{}</span>'.format(html_color, word)
num = 12
ids = config.tokenizer(text_df.loc[num, "text"])["input_ids"]
tokens = config.tokenizer.convert_ids_to_tokens(ids)
attention = attention_array[num, :][np.nonzero(mask_array[num, :])]
html_outputs = []
for word, attn in zip(tokens, attention):
html_outputs.append(highlight_r(word, attn))
print(f"Offensive Score is {PRED[num, 0]}")
display(HTML(' '.join(html_outputs)))
display(text_df.loc[num, "text"])
text_df.sort_values("target", ascending=False).head(20)
high_score_list = text_df.sort_values("target", ascending=False).head(20).index.tolist()
for num in high_score_list:
ids = config.tokenizer(text_df.loc[num, "text"])["input_ids"]
tokens = config.tokenizer.convert_ids_to_tokens(ids)
attention = attention_array[num, :][np.nonzero(mask_array[num, :])]
html_outputs = []
for word, attn in zip(tokens, attention):
html_outputs.append(highlight_r(word, attn))
print(f"Offensive Score is {PRED[num, 0]}")
display(HTML(' '.join(html_outputs)))
display(text_df.loc[num, "text"])
```
| github_jupyter |
## Week 2: Logging - Assignment
**by Sarthak Niwate (Intern at Chistats)**
```
import logging
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='assignment.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)
logger.setLevel(logging.INFO)
logging.error('hello!')
logging.debug('This is a debug message')
logging.info('this is an info message')
logging.warning('tbllalfhldfhd, warning')
import numpy as np
```
#### 1. List down as much as possible buildin functions of python
```
for e in __builtins__.__dict__:
logger.info(e)
```
#### 2. Write down the skeleton of a function with optionals
This is what the simplest function definition looks like:
def functionName():
functionBody
return statement
- It starts with the keyword def (for defining the function)
- Then we give the name of the function (we should follow the rules of naming variables which applicable to function names too)
- Then there comes a bracket/paranthesis. That can be empty or we can pass no. of parameters to it.
- This whol expression should end with a colon.
- Then on the next line at tab space we start writing the body of the function which has expressions, operations, loops which will execute when we invoke the function in the program.
- There are two different variants for return statement at the end of the function body.
- return statement without an expression: if a function is not intended to produce a result, using the return instruction is not obligatory, it will be executed implicitly at the end of the function.
- return statement without the function will evaluate the expression's value and will return it as the function's result.
#### 3. WAF to print "Hello World"
```
def welcome():
logger.info("Hello World")
# calling function
welcome()
```
#### 4. WAF which takes name as parameter and prints it
```
def greetingsName(name):
result = "Have a good day " + name
logger.info(result)
greetingsName('Sarthak')
```
#### 5. WAF which takes number as parameter and prints the square of it
```
def squareNumber(x):
logger.info("The square of a number: "+ str(x**2))
squareNumber(10)
```
#### 6. WAF which takes two number as parameter, calculates the sum of square of the parameters and returns it
```
def sumSquares(x,y):
result = (x**2 + y**2)
logger.info("The sum of squares of two numbers is: " + str(result))
sumSquares(10,5)
```
#### 7. WAF to find factorial of given number
```
def factorialN(N):
fact = 1
if N < 0:
logger.info("Sorry, factorial does not exist for negative numbers")
elif N == 0:
logger.info("The factorial of 0 is 1")
else:
for i in range(1,N + 1):
fact = fact*i
logger.info("The factorial of " + str(N) + " is " + str(fact))
factorialN(4)
```
#### 8. WAF which takes two paramaters, camculates the sum and product of them and returns.
```
def sumProduct(x,y):
a = x+y
b = x*y
logging.info(str(a) + "," + str(b))
sumProduct(5,5)
```
9. List down the types of arguments and explain those in with example.
1. Keyword Arguments:
- We can pass arguments using keywords which used to define the element which is essential for our function for execution. For example, all the functions written above are used this method.
2. Default Argument:
- We can define a default value for an argument while defining a function.
3. Arbitary Argument:
- We can pass a iterable object as argument in a function using * (asterisk). *args is used when we directly pass those values as argument. And **kwargs is used when we pass defined values as the arguments to the function.
```
def keywordArg(x):
logger.info(str(x**3))
def defaultArg(x=5):
logger.info(str(x**3))
def arbitaryArg(*args):
result = 0
for x in args:
result += x
logger.info(str(result))
print("Cube of x is: ", keywordArg(5))
print("Cube of default arguments is: ", defaultArg())
print("Sum of seuqence is: ", arbitaryArg(1, 2, 3))
```
10. WAF to get variable length argument and caculate the sum of square of those numbers
```
def sumSquares(*args):
result = 0
for i in args:
result += i**2
logger.info("The sum of squares of 10,20,30 is: "+str(result))
sumSquares(10,20,30)
```
11. WAF to get two parameters as input 1. variable length argument of integers 2. positional parameter and identify whether second parameter is available in the variable length argument
12. Function
def fun(arg1, arg2, arg3=4, arg4=8):
print(arg1, arg2,arg3,arg4)
```
def fun(arg1, arg2, arg3=4, arg4=8):
logger.info(str(arg1)+","+str(arg2)+","+str(arg3)+","+str(arg4))
fun(3,2)
fun(10, 20, 30, 40)
fun(25, 50, arg4=10)
fun(arg4=4, arg1=3, arg2=4)
fun()
fun(arg3=10, arg4=20, 30, 40)
fun(4, 5, arg2=6)
fun(4, 5, arg3=5, arg5=6)
```
#### 13. Short note on function vs module vs library
#### What is a function in Python?
In Python, function is a group of related statements that perform a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes code reusable.
#### Python Modules
Modules refer to a file containing Python statements and definitions. A file containing Python code, for e.g.: example.py, is called a module and its module name would be example. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs.
As I said above, for example.py
```
# Python Module example
def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
logger.info(str(result))
add(3,4)
```
1.Created a file called example.py in the current folder with above definition
2.Now we can import this moudle into our python notebook
```
from arithmetic import addition
add(4,5.5)
# import statement example
# to import standard module math
import math
logger.info("The value of pi is "+str(math.pi))
# Import with renaming
import math as m
logger.info("The value of pi is "+str(m.pi))
#Python from...import statement
from math import pi
logger.info("The value of pi is "+str(pi))
#Import all names
from math import *
logger.info("The value of pi is "+ str(pi))
```
#### Python Packages
Suppose you have developed a very large application that includes many modules. As the number of modules grows, it becomes difficult to keep track of them all if they are dumped into one location. This is particularly so if they have similar names or functionality. You might wish for a means of grouping and organizing them. Packages allow for a hierarchical structuring of the module namespace using dot notation. In the same way that modules help avoid collisions between global variable names, packages help avoid collisions between module names. Creating a package is quite straight forward, since it makes use of the operating system’s inherent hierarchical file structure. Consider the following arrangement:
```
import arithmetic
from arithmetic.addition import add
from arithmetic.subtract import sub
add(9,3)
sub(9,8)
```
#### 14 and 15. Short note on global variables and on local variables
#### Global Variables
In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
```
x = "global"
def example():
logger.info("x inside : "+str(x))
example()
logger.info("x outside : "+str(x))
```
#### Local Variables
A variable declared inside the function's body or in the local scope is known as local variable.
```
def example():
l = "local"
logger.info(l)
example()
```
Let's take a look to the earlier problem where x was a global variable and we wanted to modify x inside example() function.
```
x = "global"
def example():
global x
y = "local"
x = x * 2
logger.info(str(x))
logger.info(str(y))
example()
# What if global and local variable has same name?
x = 5
def example():
x = 10
logger.info("local x: "+str(x))
example()
logger.info("global x: "+str(x))
```
#### Rules of global Keyword
1.The basic rules for global keyword in Python are:
2.When we create a variable inside a function, it’s local by default.
3.When we define a variable outside of a function, it’s global by default. You don’t have to use global keyword.
4.We use global keyword to read and write a global variable inside a function.
5.Use of global keyword outside a function has no effect
#### 16. WAF to caculate factorial of number using recursion
```
def factorialRec(num):
if num == 1:
return num
else:
return num*factorialRec(num-1)
num=int(input("Enter the number: "))
logger.info("factorial of "+str(num)+" is: ")
print(factorialRec(num))
```
#### 17. What is lambda function. SHort not with example
Anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
#Syntax:
lambda arguments: expression
Note: Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
```
# Program to show the use of lambda functions
double = lambda x: x * 2
# Output: 10
output = double(5)
logger.info(str(output))
#above is eqivalent to below code
# def double(x):
# return x * 2
```
#### Use of Lambda Function in python
We use lambda functions when we require a nameless function for a short period of time.
In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map() etc.
#### 18. Write a lambda function to get square of given number
```
double = lambda x: x ** 2
output_18 = double(5)
logger.info(str(output_18))
```
#### 19. Write a lambda function to get sum of two given numbers
```
add = lambda x,y: x+y
output_19 = add(5,5)
logger.info(str(output_19))
```
#### 20. Write a lambda function to get max of given values.
```
maxi = lambda *args: max(args)
output_20 = maxi(1,2,3)
logger.info(str(output_20))
```
#### 21. WAP to filter even numbers from list by using filter() function.
```
list_21 = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , list_21))
logger.info(str(new_list))
```
#### 22. WAP to filter students whoes name starts with "a" by using filter() function
```
list_22 = ['amar', 'Ajay', 'mukesh', 'neel', 'gauri', 'arya']
new = list(filter(lambda x: x.lower()[0]=='a',list_22))
logger.info(str(new))
```
#### 23. WAP to get list of integers as input and generate another list containing the square of all integers from list one. Write using lambda function and also without using lambda function
Ex. Input = [1,2,3,4,5], Output = [1,4,9,16,25]
```
numbers = int(input("How many numbers are in your list: "))
nums = []
for i in range(numbers):
num = int(input("Enter the number: "))
nums.append(num)
print(nums)
logger.info("The list of sqaures is: "+str(list(map(lambda n: n ** 2, nums))))
```
#### 24. WAP to calculate the sum of all numbers present in the list using reduce()
```
from functools import reduce
l = [1,2,3]
logger.info(str(reduce(lambda x,y: x+y,l)))
```
#### 25. Prove that everything in python is an object
Python is Object Oriented Programming. It supports user defined classes and functions. We can not only create custom objects, but every pre-exisiting thing available in python is object.
We can check type of python objects using type() function.
```
nums = [1,2,3]
logger.info(str(type(nums)))
num = 1
logger.info(str(type(num)))
boolean = False
logger.info(str(type(boolean)))
def exampleFun():
pass
logger.info(str(type(exampleFun)))
```
The output is <class 'list'> which means the num is an object that is instantiated from the list class.
The same applies for rest of the results we have got.
We can extract the list of all the available methods of a particular python object using dir().
```
logger.info(str(dir(nums)))
# These are all methods of lists or we can say attributes.
```
The most important thing to understand the python objects is when every python object is defined the pyton heap space allocated a space to store that variable and passes a id to the python interpreter to access the defined objects whenever it is invoked.
```
logger.info(str(id(nums)))
```
#### 26. Create the alias of the function defined in the Que 12, print the id of both functions and perform the same set of operations
```
def fun(arg1, arg2, arg3=4, arg4=8):
logger.info(str(arg1)+","+str(arg2)+","+str(arg3)+","+str(arg4))
alias_fun = fun
logger.info(str(id(fun)))
logger.info(str(id(alias_fun)))
alias_fun(3,2)
alias_fun(10, 20, 30, 40)
alias_fun(25, 50, arg4=10)
alias_fun(arg4=4, arg1=3, arg2=4)
alias_fun()
alias_fun(arg3=10, arg4=20, 30, 40)
alias_fun(4, 5, arg2=6)
alias_fun(4, 5, arg3=5, arg5=6)
```
#### 27. Nested function: Create a function which takes the list of numbers as parameter, calculates the square of every number in the nexted function and returns the final list of squares.
```
def listGet(*args):
def squareit():
new = [i*i for i in args]
logger.info(str(new))
logger.info(str(squareit))
listGet(1,2,3)
```
#### 28. What is the main() function in Python
```
def main():
logger.info("I will be skipped")
logger.info("I know, I will be considered")
```
#### 29. What is __name__ in Python, what are the ways to execute python file differently in different contexts. Ref. https://www.programiz.com/python-programming/main-function
**1. Running file on command line**
We can run our python scripts on command line with some instructions.
$python3 filename.py
The output will be displayed in the command line console. If this give a error, we should check our given PATH which assigned while installation of python. We redirect this output to a output.txt file by using two forward signs like this >>
$python3 filename.py >> output.txt
**2. Running file on Windows Console or Shell**
Currently in newer versions it is possible to run the python file on windows console or shell. It behaves in same manner as running a file in command line. In this me just a open that file through the console having the python script.
**3. Running python file using import**
In one of the questions from this assignment, I have created two modules as addition and subtract and created a package of them as examplepackage. It clearly shows how we can run python files using import (Question No. 13)
#### 30. What will be the output of below
```
logger.info(str(abs(-7.25)))
logger.info(str(abs(3+5j)))
logger.info(str(abs(3 - 4j)))
logger.info(str(round(5.76543, 2)))
logger.info(str(round(5.76543)))
round(-1.2)
arr = np.array([-0.341111, 1.455098989, 4.232323, -0.3432326, 7.626632, 5.122323])
print(round(arr, 2)) # Note: Use numpy to create an array
```
#### 31. Print values of all below
round_num = 15.456
final_val = round(round_num, 2)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_CEILING)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_DOWN)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_FLOOR)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_DOWN)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_EVEN)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)
val1=decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)
```
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='assignment_log2.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(message)s - %(name)s - %(funcName)s - %(lineno)d')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)
logger.setLevel(logging.INFO)
import decimal
round_num = 15.456
final_val = round(round_num, 2)
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_CEILING)))
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_DOWN)))
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_FLOOR)))
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_DOWN)))
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_EVEN)))
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)))
logger.info(str(decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)))
```
#### 32. WAP to create a sequence of numbers from 3 to 5 using range()
```
logger.info(str(list(range(3,6))))
```
#### 33. WAP to create a sequence of numbers from 3 to 19, but increment by 2 instead of 1
```
logger.info(str(list(range(3,20,2))))
```
#### 34. WAP to create a list of even number between the given numbers using range()
```
logger.info(str(list(range(0,201,2))))
```
#### 35. What will be the output of range(2, -14, -2)
```
logger.info(str(list(range(2,-14,-2))))
```
#### 36. Identify the time taken by Que 7 and Que 16 to excute using timeit
```
import timeit
import time
# define the sum , and multiplication functions
def sumSquares(x,y):
result = (x**2 + y**2)
return result
def factorialN(N):
fact = 1
# check if the number is negative, positive or zero
if N < 0:
print("Sorry, factorial does not exist for negative numbers")
elif N == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,N + 1):
fact = fact*i
print("The factorial of",N,"is",fact)
# test how fast the sum function is
sumTimingResult = timeit.timeit(
globals=globals(), # access the global variables in this scope
setup='xData= range(0,100); yData = range(220 , 320)',
stmt='[ sumSquares(x,yData[index]) for index , x in enumerate(xData)]',
number=10000,
timer=time.perf_counter)
logger.info(str(sumTimingResult))
# test the mul function
mulTimingResult = timeit.timeit(
globals=globals(), # access the global variables in this scope
setup='',
stmt='[ factorialN(index) for index in range(10)]',
number=30,
timer=time.perf_counter)
mulTimingResult
```
#### 37. Short note on return vs yield with example
1. return
The return statement is used inside a function to exit it an return a value. If we do not return a value explicitly, None is returned automatically.
2. yield
It is used inside a function lik a return statement, but yield returns a generator. Generator is an iterator that generates one item at a time instead of storing all the values in the memory.
#### 38. WAP to get all square numbers from 1 to 100 using yield. Ex. 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
```
def generator():
for i in range(100):
yield i*i
g = generator()
for i in g:
logger.info(str(i))
```
#### 39. WAP to create digital clock usinf time.sleep. Clock should print the output in hh:mm:ss AM/PM format
```
import time
logger.info(str(time.strftime("%I:%M:%S %p", time.localtime())))
import time
for i in range(10):
logger.info(str(time.strftime("%I:%M:%S %p", time.localtime())))
time.sleep(1)
```
#### 40. WAP to print the number from list with pause of 5 seconds
```
import time
num = input('Pause for how many seconds: ')
logger.info('Starting at: '+str(time.ctime()))
time.sleep(float(num))
logger.info('Stops at: '+str(time.ctime()))
```
#### 41. WAP to create the queue using collections.dequeue and perform all the queue operations like append, popleft
```
from collections import deque
numbers = deque()
numbers.append(12)
numbers.append(15)
numbers.append(12)
numbers.append(50)
numbers.append(127)
numbers.append(12)
numbers.append(15)
numbers.append(12)
numbers.append(50)
numbers.append(127)
numbers.append(12)
numbers.pop()
logger.info(str(numbers))
numbers.popleft()
logger.info(str(numbers))
logger.info(str(numbers.count(12)))
numbers.appendleft(25)
logger.info(str(numbers))
numbers.extend([100,200,400])
logger.info(str(numbers))
numbers.reverse()
logger.info(str(numbers))
numbers.extendleft([100,200])
logger.info(str(numbers))
```
#### 42. WAP to create queue using using queue. Queue andperform below operations on it
1. maxsize
2. empty()
3. full()
4. get()
5. get_nowait()
6. put(item)
7. put_nowait(item)
8. qsize()
```
from queue import Queue
q = Queue()
logger.info(str(q.empty())) # returns True if empty, False otherwise
logger.info(str(q.put(4)))
logger.info(str(q.get()))
logger.info(str(q.put_nowait(6)))
logger.info(str(q.maxsize))
logger.info(str(q.full()))
```
#### 43. What is Python Counter and why to use it
- Python counter is a container that keeps the count of each element present in the container. It is a part of the collections module. It is an unordered collection of items where items are stored as dictionary key-value pairs.
- We can use counter with strings, list tuples. The behaviour of counter is like, if we apply the counter on a string it will return us the frequency of each element as the dictionary of letter:frequency pairs in the output.
- Same in a list it will return the frequency.
```
from collections import Counter
list_43 = [1,2,3,1,2,3,1,2,3,4,5,6,4,5,6,1,2,4,5,6,1,2]
logger.info(str(Counter(list_43)))
```
#### 44. Using Counter: WAP to get the count of number of occurences of alphabet present in the list1 = ['x','y','z','x','x','x','y', 'z'] hint : from collections import Counter
```
from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
logger.info(str(Counter(list1)))
```
#### 45. What will be the output of below
```
my_str = "Welcome to python world!"
logger.info(str(Counter(my_str)))
dict1 = {'x': 4, 'y': 2, 'z': 2, 'z': 2}
logger.info(str(Counter(dict1)))
tuple1 = ('x','y','z','x','x','x','y','z')
logger.info(str(Counter(tuple1)))
```
#### 46. Update the value of the counter
```
_count = Counter()
_count.update('Welcome to python world!')
logger.info(str(_count))
```
#### 47. WAP to print the counter generated in Que 43 sequentially
```
c_43 = Counter(list_43)
logger.info(str(c_43))
```
#### 48. WAP to delete element from counter generated in Que 43
```
c_43.popitem()
logger.info(str(c_43))
```
#### 49. SUppoer we have two counter mentioned below
```
counter1 = Counter({'x': 4, 'y': 2, 'z': -2})
counter2 = Counter({'x1': -12, 'y': 5, 'z':4 })
logger.info("Addition: "+str(counter1 + counter2))
logger.info("Subtraction: "+str(counter1 - counter2))
logger.info("Intersection: "+str(counter1&counter2))
logger.info("Union: "+str(counter1|counter2))
```
#### 50. WAP to get the most common elements from the counter
```
logger.info(str(c_43.most_common(n=2)))
```
#### 51. WAP to get all elements with positive value and count>0 from counter
```
ele = c_43.elements() # doesn't return elements with count 0 or less
logger.info(str([i for i in ele]))
```
#### 52. WAP to get count of specific element from counter
```
logger.info(str(c_43[2]))
```
#### 53. WAP to set count of specific element from counter
#### 54. Iterate on the below using enumerate() function
```
dictionary= {'my_list' : ["eat","sleep","repeat"],'my_str' : "chistats",
'my_tuple' : ("A", "B", "C", "D", "E"), 'my_dict' : {"a": "PHP", "b":"JAVA", "c":"PYTHON", "d":"NODEJS"}}
for i in dictionary:
for x in enumerate(dictionary[i]):
logger.info(str(x))
print()
```
## Thank You
| github_jupyter |
```
import torch
import time
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset,DataLoader
import pandas as pd
import numpy as np
!pip install transformers==3.3.1
!pip install sentencepiece
import sentencepiece
from transformers import AutoModel, AutoTokenizer
from torch import cuda
device = 'cuda' if torch.cuda.is_available() else 'cpu'
from google.colab import drive
drive.mount('/content/drive')
train = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/kannada_offensive_train (1).csv', delimiter='\t', names=['text','label','nan'])
train = train.drop(columns=['nan'])
train.label = train.label.apply({'Not_offensive':0,'Offensive_Untargetede':1,'Offensive_Targeted_Insult_Group':2,'Offensive_Targeted_Insult_Individual':3,'not-Kannada':4, 'Offensive_Targeted_Insult_Other':5}.get)
train.head(9)
val = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/kannada_offensive_dev.csv', delimiter='\t', names=['text','label','nan'])
val = val.drop(columns=['nan'])
val.label = val.label.apply({'Not_offensive':0,'Offensive_Untargetede':1,'Offensive_Targeted_Insult_Group':2,'Offensive_Targeted_Insult_Individual':3,'not-Kannada':4, 'Offensive_Targeted_Insult_Other':5}.get)
from numpy import random
test = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/kannada_offensive_test.csv',delimiter='\t',names=['text','label'])
def addLabel():
test['label'] = [random.choice([0, 1, 2, 3, 4, 5]) for text in test.text]
addLabel()
test.head(9)
import re
def clean(df):
df['text'] = df['text'].apply(lambda x: x.lower())
df['text'] = df['text'].apply(lambda x: re.sub(r' +', ' ',x))
df['text'] = df['text'].apply(lambda x: re.sub("[!@#$+%*:()'-]", ' ',x))
df['text'] = df['text'].str.replace('\d+', '')
clean(train)
clean(val)
clean(test)
import pandas as pd
from torch.utils.data import Dataset,DataLoader
class RFDataset(Dataset):
def __init__(self,text,label,tokenizer,max_len):
self.text = text
self.label = label
self.tokenizer = tokenizer
self.max_len = max_len
def __len__(self):
return len(self.text)
def __getitem__(self,item):
text = str(self.text[item])
label = self.label[item]
encoding = self.tokenizer.encode_plus(
text,
add_special_tokens=True,
max_length = self.max_len,
return_token_type_ids = False,
padding = 'max_length',
return_attention_mask= True,
return_tensors='pt',
truncation=True
)
return {
'text' : text,
'input_ids' : encoding['input_ids'].flatten(),
'attention_mask' : encoding['attention_mask'].flatten(),
'label' : torch.tensor(label,dtype=torch.long)
}
def create_data_loader(df,tokenizer,max_len,batch_size):
ds = RFDataset(
text = df.text.to_numpy(),
label = df.label.to_numpy(),
tokenizer = tokenizer,
max_len = max_len
)
return DataLoader(ds,
batch_size = batch_size,
shuffle = True,
num_workers=4)
MODEL_TYPE = 'xlm-roberta-base'
tokenizer = AutoTokenizer.from_pretrained(MODEL_TYPE)
BATCH_SIZE = 32
MAX_LEN = 128
train_data_loader = create_data_loader(train,tokenizer,MAX_LEN,BATCH_SIZE)
val_data_loader = create_data_loader(val,tokenizer,MAX_LEN,BATCH_SIZE)
def create_dataloader(df,tokenizer,max_len,batch_size):
ds = RFDataset(
text = df.text.to_numpy(),
label = df.label.to_numpy(),
tokenizer = tokenizer,
max_len = max_len
)
return DataLoader(ds,
batch_size = batch_size,
shuffle = False,
num_workers=4)
test_data_loader = create_dataloader(test,tokenizer,MAX_LEN,BATCH_SIZE)
print('Training set size:',train.shape)
print('validation set size:',val.shape)
print('Testing set size:',test.shape)
import torch.nn as nn
class XLMRobertaclass(nn.Module):
def __init__(self, n_classes):
super(XLMRobertaclass, self).__init__()
self.auto = AutoModel.from_pretrained('xlm-roberta-base')
self.drop = nn.Dropout(p=0.4)
self.out1 = nn.Linear(self.auto.config.hidden_size, 128)
self.drop1 = nn.Dropout(p=0.4)
self.relu = nn.ReLU()
self.out = nn.Linear(128, n_classes)
def forward(self, input_ids, attention_mask):
_,pooled_output = self.auto(
input_ids=input_ids,
attention_mask=attention_mask
)
output = self.drop(pooled_output)
output = self.out1(output)
output = self.relu(output)
output = self.drop1(output)
return self.out(output)
model = XLMRobertaclass(6)
model = model.to(device)
from transformers import AdamW,get_linear_schedule_with_warmup
EPOCHS = 10
optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False)
total_steps = len(train_data_loader) * EPOCHS
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=0,
num_training_steps=total_steps
)
loss_fn = nn.CrossEntropyLoss().to(device)
def train_epoch(model,data_loader,loss_fn,optimizer,device,scheduler,n_examples):
model = model.train()
losses = []
correct_predictions = 0
for data in data_loader:
input_ids = data['input_ids'].to(device)
attention_mask = data['attention_mask'].to(device)
label = data['label'].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
_, preds = torch.max(outputs, dim=1)
loss = loss_fn(outputs,label)
correct_predictions += torch.sum(preds == label)
losses.append(loss.item())
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
return correct_predictions.double() / n_examples, np.mean(losses)
def eval_model(model, data_loader, loss_fn, device, n_examples):
model = model.eval()
losses = []
correct_predictions = 0
with torch.no_grad():
for d in data_loader:
input_ids = d["input_ids"].to(device)
attention_mask = d["attention_mask"].to(device)
label = d["label"].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
_, preds = torch.max(outputs, dim=1)
loss = loss_fn(outputs, label)
correct_predictions += torch.sum(preds == label)
losses.append(loss.item())
return correct_predictions.double() / n_examples, np.mean(losses)
import time
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
from collections import defaultdict
import torch
history = defaultdict(list)
best_accuracy = 0
for epoch in range(EPOCHS):
start_time = time.time()
train_acc,train_loss = train_epoch(
model,
train_data_loader,
loss_fn,
optimizer,
device,
scheduler,
len(train)
)
val_acc,val_loss = eval_model(
model,
val_data_loader,
loss_fn,
device,
len(val)
)
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
print(f'Train Loss {train_loss} accuracy {train_acc}')
print(f'Val Loss {val_loss} accuracy {val_acc}')
print()
history['train_acc'].append(train_acc)
history['train_loss'].append(train_loss)
history['val_acc'].append(val_acc)
history['val_loss'].append(val_loss)
if train_acc > best_accuracy:
torch.save(model.state_dict(),'xlm-roberta-base.bin')
best_accuracy = train_acc
import matplotlib.pyplot as plt
plt.plot(history['train_acc'], label='train accuracy')
plt.plot(history['val_acc'], label='validation accuracy')
plt.title('Training history')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend()
# plt.ylim([0, 1]);
val_acc.item()
def get_predictions(model, data_loader):
model = model.eval()
sentence = []
predictions = []
prediction_probs = []
real_values = []
with torch.no_grad():
for d in data_loader:
text = d["text"]
input_ids = d["input_ids"].to(device)
attention_mask = d["attention_mask"].to(device)
label = d["label"].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
_, preds = torch.max(outputs, dim=1)
sentence.extend(text)
predictions.extend(preds)
prediction_probs.extend(outputs)
real_values.extend(label)
predictions = torch.stack(predictions).cpu()
prediction_probs = torch.stack(prediction_probs).cpu()
real_values = torch.stack(real_values).cpu()
return sentence, predictions, prediction_probs, real_values
y_review_texts, y_pred, y_pred_probs, y_test = get_predictions(
model,
test_data_loader
)
a = {'id':[i for i in range(778)]}
a = pd.DataFrame(a)
df = pd.DataFrame({'id':a.id,'text':y_review_texts,'label':y_pred.tolist()})
df.label = df.label.apply({0:'Not_offensive',1:'Offensive_Untargetede',2:'Offensive_Targeted_Insult_Group',3:'Offensive_Targeted_Insult_Individual',4:'not-Kannada', 5:'Offensive_Targeted_Insult_Other'}.get)
df
df.to_csv('XLMRoberta_Kannada_submission.csv',index=False)
from google.colab import files
files.download("XLMRoberta_Kannada_submission.csv")
```
| github_jupyter |
## Automation of the PathLinker App paper Lovastatin Analysis
## Yihang Xin and Alex Pico
## 2021-01-05
## Installation
The following chunk of code installs the `py4cytoscape` module.
```
%%capture
!python3 -m pip install python-igraph requests pandas networkx
!python3 -m pip install py4cytoscape
```
## Setup Cytoscape
* Launch Cytoscape on your local machine. If you haven't already installed Cytoscape, then download the latest version from http://cytoscape.org.
* Install the filetransfer app from https://apps.cytoscape.org/apps/filetransfer
* Install the PathLinker app from http://apps.cytoscape.org/apps/pathlinker
* Leave Cytoscape running in the background during the remainder of the tutorial.
* Check cytoscape connection.
You can also install app inside Python notebook by running "py4cytoscape.install_app('Your App')"
## Import the required packages
```
import sys
import py4cytoscape as p4c
import networkx as nx
import pandas as pd
import json
import requests
p4c.cytoscape_version_info() # Check cytoscape connection.
```
## Create network using networkx
The PathLinker app paper uses the same interactome as the original PathLinker pap (available on the [PathLinker supplementary website](http://bioinformatics.cs.vt.edu/~murali/supplements/2016-sys-bio-applications-pathlinker/) here: [background-interactome-pathlinker-2015.txt](https://raw.githubusercontent.com/Murali-group/PathLinker-Cytoscape/master/src/test/resources/input/graph-dir_human-interactome.txt)).
```
url = "https://raw.githubusercontent.com/Murali-group/PathLinker-Cytoscape/master/src/test/resources/input/graph-dir_human-interactome.txt"
r = requests.get(url, allow_redirects=True)
open('background-interactome-pathlinker-2015.txt', 'wb').write(r.content)
# Import/Create the network that PathLinker will run on
network_file = 'background-interactome-pathlinker-2015.txt'
# create a new network by importing the data from a sample using pandas
df = pd.read_csv(network_file, header=None, sep='\t', lineterminator='\n',
names=["source", 'target', 'weight', 'evidence'])
# and create the networkx Graph from the pandas dataframe
# this is a directed network, so I'm using the networkx DiGraph instead of the default undirected Graph
G = nx.from_pandas_edgelist(df, "source", "target", edge_attr=['weight'], create_using=nx.MultiDiGraph())
p4c.create_network_from_networkx(G) # Take a while
```
## Run PathLinker using the API function
The function takes user sources, targets, and a set of parameters, and computes the k shortest paths. The function returns the paths in JSON format. Based on the user input, the function could generate a subnetwork (and view) containing those paths, and returns the computed paths and subnetwork/view SUIDs.
Additional description of the parameters are available in the PathLinker app [documentation](https://pathlinker-cytoscape-app.readthedocs.io/en/latest/PathLinker_Cytoscape.html#sources-and-targets).
The sources, targets and parameters used below are the same parameters used to run PathLinker in the paper "The PathLinker app: Connect the dots in protein interaction networks".
```
# Construct input data to pass to PathLinker API function
# construct PathLinker input data parameters for API request
params = {}
# the node names for the sources and targets are space separated
# and must match the "name" column in the Node Table in Cytoscape
params["sources"] = "P35968 P00533 Q02763"
params["targets"] = "Q15797 Q14872 Q16236 P14859 P36956"
# the number of shortest path to compute, must be greater than 0
# Default: 50
params["k"] = 50
# Edge weight type, must be one of the three: [UNWEIGHTED, ADDITIVE, PROBABILITIES]
params["edgeWeightType"] = "PROBABILITIES"
# Edge penalty. Not needed for UNWEIGHTED
# Must be 0 or greater for ADDITIVE, and 1 or greater for PROBABILITIES
params["edgePenalty"] = 1
# The column name in the Edge Table in Cytoscape containing edge weight property,
# column type must be numerical type
params["edgeWeightColumnName"] = "weight"
# The option to ignore directionality of edges when computing paths
# Default: False
params["treatNetworkAsUndirected"] = False
# Allow source/target nodes to appear as intermediate nodes in computed paths
# Default: False
params["allowSourcesTargetsInPaths"] = False
# Include more than k paths if the path length/score is equal to kth path length/score
# Default: False
params["includeTiedPaths"] = False
# Option to disable the generation of the subnetwork/view, path rank column, and result panel
# and only return the path result in JSON format
# Default: False
params["skipSubnetworkGeneration"] = False
cy_network_suid = p4c.get_network_suid()
# perform REST API call
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
# construct REST API request url
url = "http://localhost:1234/pathlinker/v1/" + str(cy_network_suid) + "/run"
# to just run on the network currently in view on cytoscape, use the following:
#url = "http://localhost:1234/pathlinker/v1/currentView/run"
# store request output
result_json = requests.request("POST",
url,
data = json.dumps(params),
params = None,
headers = headers)
#print(json.loads(result_json.content))
```
## Output
The following section stores the subnetwork/view references and prints out the path output returned by the run function.
The output consist of path result in JSON format, and based on user input: subnetwork SUID, subnetwork view SUID, and path rank column name.
```
# Store result, parse, and print
results = json.loads(result_json.content)
print("Output:\n")
# access the suid, references, and path rank column name
subnetwork_suid = results["subnetworkSUID"]
subnetwork_view_suid = results["subnetworkViewSUID"]
# The path rank column shows for each edge, the rank of the first path in which it appears
path_rank_column_name = results["pathRankColumnName"]
print("subnetwork SUID: %s" % (subnetwork_suid))
print("subnetwork view SUID: %s" % (subnetwork_view_suid))
print("Path rank column name: %s" % (path_rank_column_name))
print("")
# access the paths generated by PathLinker
paths = results["paths"]
# print the first 10 paths out of 50 paths
for path in paths[:3]:
print("path rank: %d" % (path['rank']))
print("path score: %s" % (str(path['score'])))
print("path: %s" % ("|".join(path['nodeList'])))
# write the paths to a file
paths_file = "pathlinker-50-paths.txt"
print("Writing paths to %s" % (paths_file))
with open(paths_file, 'w') as out:
out.write("path rank\tpath score\tpath\n")
for path in paths:
out.write('%d\t%s\t%s\n' % (path['rank'], str(path['score']), "|".join(path['nodeList'])))
```
## View the subnetwork and store the image
```
p4c.fit_content()
p4c.export_image('pathlinker-50-paths', type='PNG')
p4c.sandbox_get_from("pathlinker-50-paths.png")
from IPython.display import Image
Image('pathlinker-50-paths.png')
```
| github_jupyter |
# `It-Follows`
## Followup Observations of exoplanets (and beyond)
### 1. Exploratory analysis of the ExoFOP metadata
Michael Gully-Santiago
Wednesday, July 5, 2017
In this exploratory notebook, we will simply fetch metadata from the ExoFOP, read it in, and see what we find out.
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
```
You can download a CSV of all the K2 ExoFOP metadata here:
https://exofop.ipac.caltech.edu/k2/targets.php?sort=target&ipp1=1000&page1=1&camp=All
Navigate to:
> `Download as:` Text **CSV**
Select the CSV link. You will automatically download a file, which you can save to the `data/` directory in this repo to replicate the work here.
```
! ls ../data/
! head -n 15 ../data/exofop_targets.csv
efop_all = pd.read_csv('../data/exofop_targets.csv', true_values='Y', false_values='N', dtype={'Poss_pc':bool},
comment='\\', parse_dates=['Last Mod'])
efop_all.head()
```
From the [ExoFOP Help Page](https://exofop.ipac.caltech.edu/k2/help.php):
> Description of column headers:
- EPIC ID: Identification number from the Ecliptic Plane Input Catalog (EPIC).
- RA: Right Ascension
- Dec: Declination
- Kep mag: Kepler magnitude in EPIC.
- Ks mag: 2MASS K_short magnitude.
- Num Confirmed Planets: number of confirmed planets (if any).
- Possible PC? Indicates if a target has a possible planetary candidate (PC)
- Number of spectroscopy observations
- Number of imaging observations
- Last Modified: date of last modification of any parameters or observing notes of the target along with user name.
```
efop_all.shape
```
There are 287,309 targets and 10 columns.
```
efop_all.count()
```
What is the typical number of spectroscopic/imaging observations?
```
efop_all.Num_spec.describe()[['min', 'max']]
sns.distplot(efop_all.Num_spec, kde=False)
plt.yscale('log')
```
The vast majority of EPIC targets have no spectroscopic observations available on ExoFOP.
```
(efop_all.Num_spec > 0).sum(), (efop_all.Num_spec > 1).sum(), efop_all.Num_spec.sum()
```
Only 451 targets have spectra, with 108 possessing multi-epoch spectra. A total of 706 spectroscopic observations are available for K2 ExoFOP, which is identical to the number on the homepage accessed on 5 July, 2017.
## Spectroscopy
We can examine the metadata on the spectroscopic observations by navigating to the [Spectroscopy Portal](https://exofop.ipac.caltech.edu/k2/view_spect.php?sort=id&ipp1=500&page1=1)
```
! ls ../data/
! head -n 3 ../data/exofop_spectroscopy.csv
efop_spec = pd.read_csv('../data/exofop_spectroscopy.csv', false_values='No', true_values='Yes',
parse_dates=['Obs date'])
efop_spec.head()
```
Some boiler plate columns are the same for all instruments, and are therefore not very informative.
```
boiler_plate = ('SNR wavelength', 'Flux calib', 'Wave calib', 'RV type', 'Notes')
for key in boiler_plate:
print("{:.<20} ".format(key), efop_spec[key].unique())
efop_spec.Telescope.unique(), efop_spec.Instrument.unique(), efop_spec['Spectral resolution'].unique()
efop_spec.groupby('Instrument').count()['Unique ID']
```
There are 5 unique telescopes and 5 unique instruments populated in the K2 ExoFOP. Who is uploading this data?
```
efop_spec.groupby('User').count()['Unique ID']
```
Only 4 people have uploaded spectroscopy to the K2 ExoFOP.
```
vec = efop_spec['SNR/resolution']
sns.distplot(vec[vec.notnull()]);
```
I assume this label refers to SNR per resolution element (e.g., not "per pixel").
## The end for now!
| github_jupyter |
<small><i>This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).</i></small>
# Solution Notebook
## Problem: Implement n stacks using a single array.
* [Constraints](#Constraints)
* [Test Cases](#Test-Cases)
* [Algorithm](#Algorithm)
* [Code](#Code)
* [Unit Test](#Unit-Test)
## Constraints
* Are the stacks and array a fixed size?
* Yes
## Test Cases
* Test the following on the three stacks:
* Push to full stack -> Exception
* Push to non-full stack
* Pop on empty stack -> Exception
* Pop on non-empty stack
## Algorithm
### Absolute Index
* return stack size * stack index + stack pointer
Complexity:
* Time: O(1)
* Space: O(1)
### Push
* If stack is full, throw exception
* Else
* Increment stack pointer
* Get the absolute array index
* Insert the value to this index
Complexity:
* Time: O(1)
* Space: O(1)
### Pop
* If stack is empty, throw exception
* Else
* Store the value contained in the absolute array index
* Set the value in the absolute array index to None
* Decrement stack pointer
* return value
Complexity:
* Time: O(1)
* Space: O(1)
## Code
```
class Stacks(object):
def __init__(self, num_stacks, stack_size):
self.num_stacks = num_stacks
self.stack_size = stack_size
self.stack_pointers = [-1] * num_stacks
self.stack_array = [None] * num_stacks * stack_size
def abs_index(self, stack_index):
return stack_index * self.stack_size + self.stack_pointers[stack_index]
def push(self, stack_index, data):
if self.stack_pointers[stack_index] == self.stack_size - 1:
raise Exception('Stack is full')
else:
self.stack_pointers[stack_index] += 1
array_index = self.abs_index(stack_index)
self.stack_array[array_index] = data
def pop(self, stack_index):
if self.stack_pointers[stack_index] == -1:
raise Exception('Stack is empty')
else:
array_index = self.abs_index(stack_index)
data = self.stack_array[array_index]
self.stack_array[array_index] = None
self.stack_pointers[stack_index] -= 1
return data
```
## Unit Test
```
%%writefile test_n_stacks.py
from nose.tools import assert_equal
from nose.tools import raises
class TestStacks(object):
@raises(Exception)
def test_pop_on_empty(self, num_stacks, stack_size):
print('Test: Pop on empty stack')
stacks = Stacks(num_stacks, stack_size)
stacks.pop(0)
@raises(Exception)
def test_push_on_full(self, num_stacks, stack_size):
print('Test: Push to full stack')
stacks = Stacks(num_stacks, stack_size)
for i in range(0, stack_size):
stacks.push(2, i)
stacks.push(2, stack_size)
def test_stacks(self, num_stacks, stack_size):
print('Test: Push to non-full stack')
stacks = Stacks(num_stacks, stack_size)
stacks.push(0, 1)
stacks.push(0, 2)
stacks.push(1, 3)
stacks.push(2, 4)
print('Test: Pop on non-empty stack')
assert_equal(stacks.pop(0), 2)
assert_equal(stacks.pop(0), 1)
assert_equal(stacks.pop(1), 3)
assert_equal(stacks.pop(2), 4)
print('Success: test_stacks\n')
def main():
num_stacks = 3
stack_size = 100
test = TestStacks()
test.test_pop_on_empty(num_stacks, stack_size)
test.test_push_on_full(num_stacks, stack_size)
test.test_stacks(num_stacks, stack_size)
if __name__ == '__main__':
main()
run -i test_n_stacks.py
```
| github_jupyter |
```
# Copyright 2022 Google LLC
#
# 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 align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/notebook_template.ipynb"">
<img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
</a>
</td>
<td>
<a href="https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/notebook_template.ipynb">
<img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
View on GitHub
</a>
</td>
</table> -->
# Orchestrating ML workflow to Train and Deploy a PyTorch Text Classification Model on [Vertex AI Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/introduction)
## Overview
This notebook is an extension to the [previous notebook](./pytorch-text-classification-vertex-ai-train-tune-deploy.ipynb) to fine-tune and deploy a [pre-trained BERT model from HuggingFace Hub](https://huggingface.co/bert-base-cased) for sentiment classification task. This notebook shows how to automate and monitor a PyTorch based ML workflow by orchestrating the pipeline in a serverless manner using [Vertex AI Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/introduction).
The notebook defines a pipeline using [Kubeflow Pipelines v2 (`kfp.v2`) SDK](https://www.kubeflow.org/docs/components/pipelines/sdk-v2/) and submits the pipeline to Vertex AI Pipelines services.
### Dataset
The notebook uses [IMDB movie review dataset](https://huggingface.co/datasets/imdb) from [Hugging Face Datasets](https://huggingface.co/datasets).
### Objective
How to **orchestrate PyTorch ML workflows on [Vertex AI](https://cloud.google.com/vertex-ai)** and emphasize first class support for training, deploying and orchestrating PyTorch workflows on Vertex AI.
### Table of Contents
This notebook covers following sections:
---
- [High Level Flow of Building a Pipeline](#High-Level-Flow-of-Building-a-Pipeline): Understand pipeline concepts and pipeline schematic
- [Define the Pipeline Components](#Define-the-Pipeline-Components-for-PyTorch-based-ML-Workflow): Authoring custom pipeline components for PyTorch based ML Workflow
- [Define Pipeline Specification](#Define-Pipeline-Specification): Author pipeline specification using KFP v2 SDK for PyTorch based ML workflow
- [Submit Pipeline](#Submit-Pipeline): Compile and execute pipeline on Vertex AI Pipelines
- [Monitoring the Pipeline](#Monitoring-the-Pipeline): Monitor progress of pipeline and view logs, lineage, artifacts and pipeline runs
---
### Costs
This tutorial uses billable components of Google Cloud Platform (GCP):
* [Vertex AI Workbench](https://cloud.google.com/vertex-ai-workbench)
* [Vertex AI Training](https://cloud.google.com/vertex-ai/docs/training/custom-training)
* [Vertex AI Predictions](https://cloud.google.com/vertex-ai/docs/predictions/getting-predictions)
* [Vertex AI Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/introduction)
* [Cloud Storage](https://cloud.google.com/storage)
* [Container Registry](https://cloud.google.com/container-registry)
* [Cloud Build](https://cloud.google.com/build) *[Optional]*
Learn about [Vertex AI Pricing](https://cloud.google.com/vertex-ai/pricing), [Cloud Storage Pricing](https://cloud.google.com/storage/pricing) and [Cloud Build Pricing](https://cloud.google.com/build/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage.
***
**NOTE:** This notebook does not require a GPU runtime. However, you must have GPU quota for running the jobs with GPUs launched by pipelines. Check the [quotas](https://console.cloud.google.com/iam-admin/quotas) page to ensure that you have enough GPUs available in your project. If GPUs are not listed on the quotas page or you require additional GPU quota, [request a quota increase](https://cloud.google.com/compute/quotas#requesting_additional_quota). Free Trial accounts do not receive GPU quota by default.
***
### Set up your local development environment
**If you are using Colab or Google Cloud Notebooks**, your environment already meets
all the requirements to run this notebook. You can skip this step.
**Otherwise**, make sure your environment meets this notebook's requirements.
You need the following:
* The Google Cloud SDK
* Git
* Python 3
* virtualenv
* Jupyter notebook running in a virtual environment with Python 3
The Google Cloud guide to [Setting up a Python development
environment](https://cloud.google.com/python/setup) and the [Jupyter
installation guide](https://jupyter.org/install) provide detailed instructions
for meeting these requirements. The following steps provide a condensed set of
instructions:
1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)
2. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)
3. [Install virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv) and create a virtual environment that uses Python 3. Activate the virtual environment.
4. To install Jupyter, run `pip3 install jupyter` on the command-line in a terminal shell.
5. To launch Jupyter, run `jupyter notebook` on the command-line in a terminal shell.
6. Open this notebook in the Jupyter Notebook Dashboard.
### Install additional packages
Following are the Python dependencies required for this notebook and will be installed in the Notebooks instance itself.
- [Kubeflow Pipelines v2 SDK](https://pypi.org/project/kfp/)
- [Google Cloud Pipeline Components](https://pypi.org/project/google-cloud-pipeline-components/)
- [Vertex AI SDK for Python](https://pypi.org/project/google-cloud-aiplatform/)
---
The notebook has been tested with the following versions of Kubeflow Pipelines SDK and Google Cloud Pipeline Components
```
kfp version: 1.8.10
google_cloud_pipeline_components version: 0.2.2
```
---
```
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
!pip -q install {USER_FLAG} --upgrade kfp
!pip -q install {USER_FLAG} --upgrade google-cloud-pipeline-components
```
#### Install Vertex AI SDK for Python
The notebook uises [Vertex AI SDK for Python](https://cloud.google.com/vertex-ai/docs/start/client-libraries#python) to interact with Vertex AI services. The high-level `google-cloud-aiplatform` library is designed to simplify common data science workflows by using wrapper classes and opinionated defaults.
```
!pip -q install {USER_FLAG} --upgrade google-cloud-aiplatform
```
### Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
```
# Automatically restart kernel after installs
import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
```
Check the versions of the packages you installed. The KFP SDK version should be >=1.6.
```
!python3 -c "import kfp; print('kfp version: {}'.format(kfp.__version__))"
!python3 -c "import google_cloud_pipeline_components; print('google_cloud_pipeline_components version: {}'.format(google_cloud_pipeline_components.__version__))"
```
## Before you begin
This notebook does not require a GPU runtime.
### Set up your Google Cloud project
**The following steps are required, regardless of your notebook environment.**
1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.
1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).
1. Enable following APIs in your project required for running the tutorial
- [Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)
- [Cloud Storage API](https://console.cloud.google.com/flows/enableapi?apiid=storage.googleapis.com)
- [Container Registry API](https://console.cloud.google.com/flows/enableapi?apiid=containerregistry.googleapis.com)
- [Cloud Build API](https://console.cloud.google.com/flows/enableapi?apiid=cloudbuild.googleapis.com)
1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).
1. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook.
**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.
#### Set your project ID
**If you don't know your project ID**, you may be able to get your project ID using `gcloud`.
```
PROJECT_ID = "[your-project-id]" # <---CHANGE THIS TO YOUR PROJECT
import os
# Get your Google Cloud project ID using google.auth
if not os.getenv("IS_TESTING"):
import google.auth
_, PROJECT_ID = google.auth.default()
print("Project ID: ", PROJECT_ID)
# validate PROJECT_ID
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
print(
f"Please set your project id before proceeding to next step. Currently it's set as {PROJECT_ID}"
)
```
#### Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial.
```
from datetime import datetime
def get_timestamp():
return datetime.now().strftime("%Y%m%d%H%M%S")
TIMESTAMP = get_timestamp()
print(f"TIMESTAMP = {TIMESTAMP}")
```
### Authenticate your Google Cloud account
---
**If you are using Google Cloud Notebooks**, your environment is already authenticated. Skip this step.
---
**If you are using Colab**, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
**Otherwise**, follow these steps:
1. In the Cloud Console, go to the [**Create service account key** page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).
2. Click **Create service account**.
3. In the **Service account name** field, enter a name, and click **Create**.
4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type "Vertex AI" into the filter box, and select **Vertex AI Administrator**. Type "Storage Object Admin" into the filter box, and select **Storage Object Admin**.
5. Click *Create*. A JSON file that contains your key downloads to your local environment.
6. Enter the path to your service account key as the `GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell.
```
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# If on Google Cloud Notebooks, then don't execute this code
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this notebook locally, replace the string below with the
# path to your service account key and run this cell to authenticate your GCP
# account.
elif not os.getenv("IS_TESTING"):
%env GOOGLE_APPLICATION_CREDENTIALS ''
```
### Create a Cloud Storage bucket
**The following steps are required, regardless of your notebook environment.**
When you submit a training job using the Cloud SDK, you upload a Python package containing your training code to a Cloud Storage bucket. Vertex AI runs the code from this package. In this tutorial, Vertex AI also saves the trained model that results from your job in the same bucket. Using this model artifact, you can then create Vertex AI model and endpoint resources in order to serve online predictions.
Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.
You may also change the `REGION` variable, which is used for operations throughout the rest of this notebook. Make sure to [choose a region where Vertex AI services are available](https://cloud.google.com/vertex-ai/docs/general/locations#available_regions). You may not use a Multi-Regional Storage bucket for training with Vertex AI.
```
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
REGION = "us-central1" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
```
---
**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.
---
```
! gsutil mb -l $REGION $BUCKET_NAME
```
Finally, validate access to your Cloud Storage bucket by examining its contents:
```
! gsutil ls -al $BUCKET_NAME
```
### Import libraries and define constants
Import python libraries required to run the pipeline and define constants.
```
%load_ext autoreload
%autoreload 2
import os
from typing import NamedTuple
import google_cloud_pipeline_components
import kfp
from google.cloud import aiplatform
from google.cloud.aiplatform import gapic as aip
from google.cloud.aiplatform import pipeline_jobs
from google.protobuf.json_format import MessageToDict
from google_cloud_pipeline_components import aiplatform as aip_components
from google_cloud_pipeline_components.experimental import custom_job
from kfp.v2 import compiler, dsl
from kfp.v2.dsl import Input, Metrics, Model, Output, component
APP_NAME = "finetuned-bert-classifier"
PATH = %env PATH
%env PATH={PATH}:/home/jupyter/.local/bin
# Pipeline root is the GCS path to store the artifacts from the pipeline runs
PIPELINE_ROOT = f"{BUCKET_NAME}/pipeline_root/{APP_NAME}"
print(f"Kubeflow Pipelines SDK version = {kfp.__version__}")
print(
f"Google Cloud Pipeline Components version = {google_cloud_pipeline_components.__version__}"
)
print(f"Pipeline Root = {PIPELINE_ROOT}")
```
## High Level Flow of Building a Pipeline
Following is the high level flow to define and submit a pipeline on Vertex AI Pipelines:
1. Define pipeline components involved in training and deploying a PyTorch model
2. Define a pipeline by stitching the components in the workflow including pre-built [Google Cloud pipeline components](https://cloud.google.com/vertex-ai/docs/pipelines/components-introduction) and custom components
3. Compile and submit the pipeline to Vertex AI Pipelines service to run the workflow
4. Monitor the pipeline and analyze the metrics and artifacts generated

This notebook builds on the training and serving code developed in previously this [notebook](../pytorch-text-classification-vertex-ai-train-tune-deploy.ipynb).
---
### Concepts of a Pipeline
Let's look at the terminology and concepts used in [Kubeflow Pipelines SDK v2](https://www.kubeflow.org/docs/components/pipelines/sdk-v2/).

- **Component:** A component is a self-contained set of code performing a single task in a ML workflow, for example, training a model. A component interface is composed of inputs, outputs and a container image that the component’s code runs in - including an executable code and environment definition.
- **Pipeline:** A pipeline is composed of modular tasks defined as components that are chained together via inputs and outputs. Pipeline definition includes configuration such as parameters required to run the pipeline. Each component in a pipeline executes independently and the data (inputs and outputs) is passed between the components in a serialized format.
- **Inputs & Outputs:** Component’s inputs and outputs must be annotated with data type, which makes input or output a parameter or an artifact.
- **Parameters:** Parameters are inputs or outputs to support simple data types such as `str`, `int`, `float`, `bool`, `dict`, `list`. Input parameters are always passed by value between the components and are stored in the [Vertex ML Metadata](https://cloud.google.com/vertex-ai/docs/ml-metadata/introduction) service.
- **Artifacts:** Artifacts are references to the objects or files produced by pipeline runs that are passed as inputs or outputs. Artifacts support rich or larger data types such as datasets, models, metrics, visualizations that are written as files or objects. Artifacts are defined by name, uri and metadata which is stored automatically in the Vertex ML Metadata service and the actual content of artifacts is referred to a path in Cloud Storage bucket. Input artifacts are always passed by reference.
Learn more about KFP SDK v2 concepts [here](https://www.kubeflow.org/docs/components/pipelines/sdk-v2/).
---
### Pipeline schematic
Following is the high level pipeline schematic with tasks involved in the pipeline for the PyTorch based text classification model including input and outputs:

- **Build custom training image:** This step builds a custom training container image from the training application code and associated Dockerfile with the dependencies. The output from this step is the Container or Artifact registry URI of the custom training container.
- **Run the custom training job to train and evaluate the model:** This step downloads and preprocesses training data from IMDB sentiment classification dataset on HuggingFace, then trains and evaluates a model on the custom training container from the previous step. The step outputs Cloud Storage path to the trained model artifacts and the model performance metrics.
- **Package model artifacts:** This step packages trained model artifacts including custom prediction handler to create a model archive (.mar) file using Torch Model Archiver tool. The output from this step is the location of model archive (.mar) file on GCS.
- **Build custom serving image:** The step builds a custom serving container running TorchServe HTTP server to serve prediction requests for the models mounted. The output from this step is the Container or Artifact registry URI to the custom serving container.
- **Upload model with custom serving container:** This step creates a model resource using the custom serving image and MAR file from the previous steps.
- **Create an endpoint:** This step creates a Vertex AI Endpoint to provide a service URL where the prediction requests are sent.
- **Deploy model to endpoint for serving:** This step deploys the model to the endpoint created that creates necessary compute resources (based on the machine spec configured) to serve online prediction requests.
- **Validate deployment:** This step sends test requests to the endpoint and validates the deployment.
## Define the Pipeline Components for PyTorch based ML Workflow
The pipeline uses a mix of pre-built components from [Google Cloud Pipeline Components SDK](https://cloud.google.com/vertex-ai/docs/pipelines/components-introduction) to interact with Google Cloud services such as Vertex AI and define custom components for some steps in the pipeline. This section of the notebook defines custom components to perform the tasks in the pipeline using [KFP SDK v2 component spec](https://www.kubeflow.org/docs/components/pipelines/sdk-v2/component-development/).
**Create pipeline directory locally to save the component and pipeline specifications**
```
!mkdir -p ./pipelines
```
### 1. Component: Build Custom Training Container Image
This step builds a custom training container image using Cloud Build. The build job pulls the training application code and associated `Dockerfile` with the dependencies from GCS location and build/push the custom training container image to Container Registry.
- **Inputs**: The inputs to this component are GCS path to the training application code and Dockerfile.
- **Outputs**: The output from this step is the Container or Artifact registry URI of the custom training container.
**Create `Dockerfile` from PyTorch GPU image as base, install required dependencies and copy training application code**
```
%%writefile ./custom_container/Dockerfile
# Use pytorch GPU base image
# FROM gcr.io/cloud-aiplatform/training/pytorch-gpu.1-7
FROM us-docker.pkg.dev/vertex-ai/training/pytorch-gpu.1-10:latest
# set working directory
WORKDIR /app
# Install required packages
RUN pip install google-cloud-storage transformers datasets tqdm cloudml-hypertune
# Copies the trainer code to the docker image.
COPY ./trainer/__init__.py /app/trainer/__init__.py
COPY ./trainer/experiment.py /app/trainer/experiment.py
COPY ./trainer/utils.py /app/trainer/utils.py
COPY ./trainer/metadata.py /app/trainer/metadata.py
COPY ./trainer/model.py /app/trainer/model.py
COPY ./trainer/task.py /app/trainer/task.py
# Set up the entry point to invoke the trainer.
ENTRYPOINT ["python", "-m", "trainer.task"]
```
**Copy training application code and `Dockerfile` from local path to GCS location**
```
# copy training Dockerfile
!gsutil cp ./custom_container/Dockerfile {BUCKET_NAME}/{APP_NAME}/train/
# copy training application code
!gsutil cp -r ./python_package/trainer/ {BUCKET_NAME}/{APP_NAME}/train/
# list copied files from GCS location
!gsutil ls -Rl {BUCKET_NAME}/{APP_NAME}/train/
print(
f"Copied training application code and Dockerfile to {BUCKET_NAME}/{APP_NAME}/train/"
)
```
**Define custom pipeline component to build custom training container**
```
@component(
base_image="gcr.io/google.com/cloudsdktool/cloud-sdk:latest",
packages_to_install=["google-cloud-build"],
output_component_file="./pipelines/build_custom_train_image.yaml",
)
def build_custom_train_image(
project: str, gs_train_src_path: str, training_image_uri: str
) -> NamedTuple("Outputs", [("training_image_uri", str)]):
"""custom pipeline component to build custom training image using
Cloud Build and the training application code and dependencies
defined in the Dockerfile
"""
import logging
import os
from google.cloud.devtools import cloudbuild_v1 as cloudbuild
from google.protobuf.duration_pb2 import Duration
# initialize client for cloud build
logging.getLogger().setLevel(logging.INFO)
build_client = cloudbuild.services.cloud_build.CloudBuildClient()
# parse step inputs to get path to Dockerfile and training application code
gs_dockerfile_path = os.path.join(gs_train_src_path, "Dockerfile")
gs_train_src_path = os.path.join(gs_train_src_path, "trainer/")
logging.info(f"training_image_uri: {training_image_uri}")
# define build steps to pull the training code and Dockerfile
# and build/push the custom training container image
build = cloudbuild.Build()
build.steps = [
{
"name": "gcr.io/cloud-builders/gsutil",
"args": ["cp", "-r", gs_train_src_path, "."],
},
{
"name": "gcr.io/cloud-builders/gsutil",
"args": ["cp", gs_dockerfile_path, "Dockerfile"],
},
# enabling Kaniko cache in a Docker build that caches intermediate
# layers and pushes image automatically to Container Registry
# https://cloud.google.com/build/docs/kaniko-cache
{
"name": "gcr.io/kaniko-project/executor:latest",
"args": [f"--destination={training_image_uri}", "--cache=true"],
},
]
# override default timeout of 10min
timeout = Duration()
timeout.seconds = 7200
build.timeout = timeout
# create build
operation = build_client.create_build(project_id=project, build=build)
logging.info("IN PROGRESS:")
logging.info(operation.metadata)
# get build status
result = operation.result()
logging.info("RESULT:", result.status)
# return step outputs
return (training_image_uri,)
```
There are a few things to notice about the component specification:
- The standalone function defined is converted as a pipeline component using the [`@kfp.v2.dsl.component`](https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/v2/components/component_decorator.py) decorator.
- All the arguments in the standalone function must have data type annotations because KFP uses the function’s inputs and outputs to define the component’s interface.
- By default Python 3.7 is used as the base image to run the code defined. You can [configure the `@component` decorator](https://www.kubeflow.org/docs/components/pipelines/sdk-v2/python-function-components/#building-python-function-based-components) to override the default image by specifying `base_image`, install additional python packages using `packages_to_install` parameter and write the compiled component file as a YAML file using `output_component_file` to share or reuse the component.
### 2. Component: Get Custom Training Job Details from Vertex AI
This step gets details from a custom training job from Vertex AI including training elapsed time, model performance metrics that will be used in the next step before the model deployment. The step additionally creates [Model](https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/v2/components/types/artifact_types.py#L77) artifact with trained model artifacts.
**NOTE:** The pre-built [custom job component](https://google-cloud-pipeline-components.readthedocs.io/en/google-cloud-pipeline-components-0.2.1/google_cloud_pipeline_components.experimental.custom_job.html) used in the pipeline outputs CustomJob resource but not the model artifacts.
- **Inputs**:
- **`job_resource`:** Custom job resource returned by pre-built CustomJob component
- **`project`:** Project ID where the job ran
- **`region`:** Region where the job ran
- **`eval_metric_key`:** Evaluation metric key name such as eval_accuracy
- **`model_display_name`:** Model display name for saving model artifacts
- **Outputs**:
- **`model`**: Trained model artifacts created by the training job with added model metadata
- **`metrics`**: Model performance metrics captured from the training job
```
@component(
base_image="python:3.9",
packages_to_install=[
"google-cloud-pipeline-components",
"google-cloud-aiplatform",
"pandas",
"fsspec",
],
output_component_file="./pipelines/get_training_job_details.yaml",
)
def get_training_job_details(
project: str,
location: str,
job_resource: str,
eval_metric_key: str,
model_display_name: str,
metrics: Output[Metrics],
model: Output[Model],
) -> NamedTuple(
"Outputs", [("eval_metric", float), ("eval_loss", float), ("model_artifacts", str)]
):
"""custom pipeline component to get model artifacts and performance
metrics from custom training job
"""
import logging
import shutil
from collections import namedtuple
import pandas as pd
from google.cloud.aiplatform import gapic as aip
from google.protobuf.json_format import Parse
from google_cloud_pipeline_components.proto.gcp_resources_pb2 import \
GcpResources
# parse training job resource
logging.info(f"Custom job resource = {job_resource}")
training_gcp_resources = Parse(job_resource, GcpResources())
custom_job_id = training_gcp_resources.resources[0].resource_uri
custom_job_name = "/".join(custom_job_id.split("/")[-6:])
logging.info(f"Custom job name parsed = {custom_job_name}")
# get custom job information
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(location)
client_options = {"api_endpoint": API_ENDPOINT}
job_client = aip.JobServiceClient(client_options=client_options)
job_resource = job_client.get_custom_job(name=custom_job_name)
job_base_dir = job_resource.job_spec.base_output_directory.output_uri_prefix
logging.info(f"Custom job base output directory = {job_base_dir}")
# copy model artifacts
logging.info(f"Copying model artifacts to {model.path}")
destination = shutil.copytree(job_base_dir.replace("gs://", "/gcs/"), model.path)
logging.info(destination)
logging.info(f"Model artifacts located at {model.uri}/model/{model_display_name}")
logging.info(f"Model artifacts located at model.uri = {model.uri}")
# set model metadata
start, end = job_resource.start_time, job_resource.end_time
model.metadata["model_name"] = model_display_name
model.metadata["framework"] = "pytorch"
model.metadata["job_name"] = custom_job_name
model.metadata["time_to_train_in_seconds"] = (end - start).total_seconds()
# fetch metrics from the training job run
metrics_uri = f"{model.path}/model/{model_display_name}/all_results.json"
logging.info(f"Reading and logging metrics from {metrics_uri}")
metrics_df = pd.read_json(metrics_uri, typ="series")
for k, v in metrics_df.items():
logging.info(f" {k} -> {v}")
metrics.log_metric(k, v)
# capture eval metric and log to model metadata
eval_metric = (
metrics_df[eval_metric_key] if eval_metric_key in metrics_df.keys() else None
)
eval_loss = metrics_df["eval_loss"] if "eval_loss" in metrics_df.keys() else None
logging.info(f" {eval_metric_key} -> {eval_metric}")
logging.info(f' "eval_loss" -> {eval_loss}')
model.metadata[eval_metric_key] = eval_metric
model.metadata["eval_loss"] = eval_loss
# return output parameters
outputs = namedtuple("Outputs", ["eval_metric", "eval_loss", "model_artifacts"])
return outputs(eval_metric, eval_loss, job_base_dir)
```
### 3. Component: Create Model Archive (MAR) file using Torch Model Archiver
This step packages trained model artifacts and custom prediction handler (define in the earlier notebook) as a model archive (.mar) file usign [Torch Model Archiver](https://github.com/pytorch/serve/tree/master/model-archiver) tool.
- **Inputs**:
- **`model_display_name`:** Model display name for saving model archive file
- **`model_version`:** Model version for saving model archive file
- **`handler`:** Location of custom prediction handler
- **`model`:** Trained model artifacts from the previous step
- **Outputs**:
- **`model_mar`**: Packaged model archive file (artifact) on GCS
- **`mar_env`**: A list of environment variables required for creating model resource
- **`mar_export_uri`**: GCS path to the model archive file
**Copy custom prediction handler code from local path to GCS location**
**NOTE**: Custom prediction handler is defined in the [previous notebook](./pytorch-text-classification-vertex-ai-train-tune-deploy.ipynb)
```
# copy custom prediction handler
!gsutil cp ./predictor/custom_handler.py ./predictor/index_to_name.json {BUCKET_NAME}/{APP_NAME}/serve/predictor/
# list copied files from GCS location
!gsutil ls -lR {BUCKET_NAME}/{APP_NAME}/serve/
print(f"Copied custom prediction handler code to {BUCKET_NAME}/{APP_NAME}/serve/")
```
**Define custom pipeline component to create model archive file**
```
@component(
base_image="python:3.9",
packages_to_install=["torch-model-archiver"],
output_component_file="./pipelines/generate_mar_file.yaml",
)
def generate_mar_file(
model_display_name: str,
model_version: str,
handler: str,
model: Input[Model],
model_mar: Output[Model],
) -> NamedTuple("Outputs", [("mar_env_var", list), ("mar_export_uri", str)]):
"""custom pipeline component to package model artifacts and custom
handler to a model archive file using Torch Model Archiver tool
"""
import logging
import os
import subprocess
import time
from collections import namedtuple
from pathlib import Path
logging.getLogger().setLevel(logging.INFO)
# create directory to save model archive file
model_output_root = model.path
mar_output_root = model_mar.path
export_path = f"{mar_output_root}/model-store"
try:
Path(export_path).mkdir(parents=True, exist_ok=True)
except Exception as e:
logging.warning(e)
# retry after pause
time.sleep(2)
Path(export_path).mkdir(parents=True, exist_ok=True)
# parse and configure paths for model archive config
handler_path = (
handler.replace("gs://", "/gcs/") + "predictor/custom_handler.py"
if handler.startswith("gs://")
else handler
)
model_artifacts_dir = f"{model_output_root}/model/{model_display_name}"
extra_files = [
os.path.join(model_artifacts_dir, f)
for f in os.listdir(model_artifacts_dir)
if f != "pytorch_model.bin"
]
# define model archive config
mar_config = {
"MODEL_NAME": model_display_name,
"HANDLER": handler_path,
"SERIALIZED_FILE": f"{model_artifacts_dir}/pytorch_model.bin",
"VERSION": model_version,
"EXTRA_FILES": ",".join(extra_files),
"EXPORT_PATH": f"{model_mar.path}/model-store",
}
# generate model archive command
archiver_cmd = (
"torch-model-archiver --force "
f"--model-name {mar_config['MODEL_NAME']} "
f"--serialized-file {mar_config['SERIALIZED_FILE']} "
f"--handler {mar_config['HANDLER']} "
f"--version {mar_config['VERSION']}"
)
if "EXPORT_PATH" in mar_config:
archiver_cmd += f" --export-path {mar_config['EXPORT_PATH']}"
if "EXTRA_FILES" in mar_config:
archiver_cmd += f" --extra-files {mar_config['EXTRA_FILES']}"
if "REQUIREMENTS_FILE" in mar_config:
archiver_cmd += f" --requirements-file {mar_config['REQUIREMENTS_FILE']}"
# run archiver command
logging.warning("Running archiver command: %s", archiver_cmd)
with subprocess.Popen(
archiver_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as p:
_, err = p.communicate()
if err:
raise ValueError(err)
# set output variables
mar_env_var = [{"name": "MODEL_NAME", "value": model_display_name}]
mar_export_uri = f"{model_mar.uri}/model-store/"
outputs = namedtuple("Outputs", ["mar_env_var", "mar_export_uri"])
return outputs(mar_env_var, mar_export_uri)
```
### 4. Component: Create custom serving container running TorchServe
The step builds a [custom serving container](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements) running [TorchServe](https://pytorch.org/serve/) HTTP server to serve prediction requests for the models mounted. The output from this step is the Container registry URI to the custom serving container.
- **Inputs**:
- **`project`:** Project ID to run
- **`serving_image_uri`:** Custom serving container URI from Container registry
- **`gs_serving_dependencies_path`:** Location of serving dependencies - Dockerfile
- **Outputs**:
- **`serving_image_uri`**: Custom serving container URI from Container registry
**Create `Dockerfile` from TorchServe CPU image as base, install required dependencies and run TorchServe serve command**
```
%%bash -s $APP_NAME
APP_NAME=$1
cat << EOF > ./predictor/Dockerfile.serve
FROM pytorch/torchserve:latest-cpu
USER root
# run and update some basic packages software packages, including security libs
RUN apt-get update && \
apt-get install -y software-properties-common && \
add-apt-repository -y ppa:ubuntu-toolchain-r/test && \
apt-get update && \
apt-get install -y gcc-9 g++-9 apt-transport-https ca-certificates gnupg curl
# Install gcloud tools for gsutil as well as debugging
RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] http://packages.cloud.google.com/apt cloud-sdk main" | \
tee -a /etc/apt/sources.list.d/google-cloud-sdk.list && \
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | \
apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - && \
apt-get update -y && \
apt-get install google-cloud-sdk -y
USER model-server
# install dependencies
RUN python3 -m pip install --upgrade pip
RUN pip3 install transformers
ARG MODEL_NAME=$APP_NAME
ENV MODEL_NAME="\${MODEL_NAME}"
# health and prediction listener ports
ARG AIP_HTTP_PORT=7080
ENV AIP_HTTP_PORT="\${AIP_HTTP_PORT}"
ARG MODEL_MGMT_PORT=7081
# expose health and prediction listener ports from the image
EXPOSE "\${AIP_HTTP_PORT}"
EXPOSE "\${MODEL_MGMT_PORT}"
EXPOSE 8080 8081 8082 7070 7071
# create torchserve configuration file
USER root
RUN echo "service_envelope=json\n" \
"inference_address=http://0.0.0.0:\${AIP_HTTP_PORT}\n" \
"management_address=http://0.0.0.0:\${MODEL_MGMT_PORT}" >> \
/home/model-server/config.properties
USER model-server
# run Torchserve HTTP serve to respond to prediction requests
CMD ["echo", "AIP_STORAGE_URI=\${AIP_STORAGE_URI}", ";", \
"gsutil", "cp", "-r", "\${AIP_STORAGE_URI}/\${MODEL_NAME}.mar", "/home/model-server/model-store/", ";", \
"ls", "-ltr", "/home/model-server/model-store/", ";", \
"torchserve", "--start", "--ts-config=/home/model-server/config.properties", \
"--models", "\${MODEL_NAME}=\${MODEL_NAME}.mar", \
"--model-store", "/home/model-server/model-store"]
EOF
echo "Writing ./predictor/Dockerfile"
```
**Copy serving `Dockerfile` from local path to GCS location**
```
# copy serving Dockerfile
!gsutil cp ./predictor/Dockerfile.serve {BUCKET_NAME}/{APP_NAME}/serve/
# list copied files from GCS location
!gsutil ls -lR {BUCKET_NAME}/{APP_NAME}/serve/
print(f"Copied serving Dockerfile to {BUCKET_NAME}/{APP_NAME}/serve/")
```
**Define custom pipeline component to build custom serving container**
```
@component(
base_image="python:3.9",
packages_to_install=["google-cloud-build"],
output_component_file="./pipelines/build_custom_serving_image.yaml",
)
def build_custom_serving_image(
project: str, gs_serving_dependencies_path: str, serving_image_uri: str
) -> NamedTuple("Outputs", [("serving_image_uri", str)],):
"""custom pipeline component to build custom serving image using
Cloud Build and dependencies defined in the Dockerfile
"""
import logging
import os
from google.cloud.devtools import cloudbuild_v1 as cloudbuild
from google.protobuf.duration_pb2 import Duration
logging.getLogger().setLevel(logging.INFO)
build_client = cloudbuild.services.cloud_build.CloudBuildClient()
logging.info(f"gs_serving_dependencies_path: {gs_serving_dependencies_path}")
gs_dockerfile_path = os.path.join(gs_serving_dependencies_path, "Dockerfile.serve")
logging.info(f"serving_image_uri: {serving_image_uri}")
build = cloudbuild.Build()
build.steps = [
{
"name": "gcr.io/cloud-builders/gsutil",
"args": ["cp", gs_dockerfile_path, "Dockerfile"],
},
# enabling Kaniko cache in a Docker build that caches intermediate
# layers and pushes image automatically to Container Registry
# https://cloud.google.com/build/docs/kaniko-cache
{
"name": "gcr.io/kaniko-project/executor:latest",
"args": [f"--destination={serving_image_uri}", "--cache=true"],
},
]
# override default timeout of 10min
timeout = Duration()
timeout.seconds = 7200
build.timeout = timeout
# create build
operation = build_client.create_build(project_id=project, build=build)
logging.info("IN PROGRESS:")
logging.info(operation.metadata)
# get build status
result = operation.result()
logging.info("RESULT:", result.status)
# return step outputs
return (serving_image_uri,)
```
### 5. Component: Test model deployment making online prediction requests
This step sends test requests to the Vertex AI Endpoint and validates the deployment by sending test prediction requests. Deployment is considered successful when the response from model server returns text sentiment.
- **Inputs**:
- **`project`:** Project ID to run
- **`bucket`:** Staging GCS bucket path
- **`endpoint`:** Location of Vertex AI Endpoint from the Endpoint creation task
- **`instances`:** List of test prediction requests
- **Outputs**:
- None
```
@component(
base_image="python:3.9",
packages_to_install=["google-cloud-aiplatform", "google-cloud-pipeline-components"],
output_component_file="./pipelines/make_prediction_request.yaml",
)
def make_prediction_request(project: str, bucket: str, endpoint: str, instances: list):
"""custom pipeline component to pass prediction requests to Vertex AI
endpoint and get responses
"""
import base64
import logging
from google.cloud import aiplatform
from google.protobuf.json_format import Parse
from google_cloud_pipeline_components.proto.gcp_resources_pb2 import \
GcpResources
logging.getLogger().setLevel(logging.INFO)
aiplatform.init(project=project, staging_bucket=bucket)
# parse endpoint resource
logging.info(f"Endpoint = {endpoint}")
gcp_resources = Parse(endpoint, GcpResources())
endpoint_uri = gcp_resources.resources[0].resource_uri
endpoint_id = "/".join(endpoint_uri.split("/")[-8:-2])
logging.info(f"Endpoint ID = {endpoint_id}")
# define endpoint client
_endpoint = aiplatform.Endpoint(endpoint_id)
# call prediction endpoint for each instance
for instance in instances:
if not isinstance(instance, (bytes, bytearray)):
instance = instance.encode()
logging.info(f"Input text: {instance.decode('utf-8')}")
b64_encoded = base64.b64encode(instance)
test_instance = [{"data": {"b64": f"{str(b64_encoded.decode('utf-8'))}"}}]
response = _endpoint.predict(instances=test_instance)
logging.info(f"Prediction response: {response.predictions}")
```
## Define Pipeline Specification
The pipeline definition describes how input and output parameters and artifacts are passed between the steps.
**Set environment variables**
These environment variables will be used to define resource specifications such as training jobs, model resource etc.
```
os.environ["PROJECT_ID"] = PROJECT_ID
os.environ["BUCKET"] = BUCKET_NAME
os.environ["REGION"] = REGION
os.environ["APP_NAME"] = APP_NAME
```
**Create pipeline configuration file**
Pipeline configuration files helps in templatizing a pipeline enabling to run the same pipeline with different parameters.
```
%%writefile ./pipelines/pipeline_config.py
import os
from datetime import datetime
PROJECT_ID = os.getenv("PROJECT_ID", "")
BUCKET = os.getenv("BUCKET", "")
REGION = os.getenv("REGION", "us-central1")
APP_NAME = os.getenv("APP_NAME", "finetuned-bert-classifier")
VERSION = datetime.now().strftime("%Y%m%d%H%M%S")
MODEL_NAME = APP_NAME
MODEL_DISPLAY_NAME = f"{MODEL_NAME}-{VERSION}"
PIPELINE_NAME = f"pytorch-{APP_NAME}"
PIPELINE_ROOT = f"{BUCKET}/pipeline_root/{MODEL_NAME}"
GCS_STAGING = f"{BUCKET}/pipeline_root/{MODEL_NAME}"
TRAIN_IMAGE_URI = f"gcr.io/{PROJECT_ID}/pytorch_gpu_train_{MODEL_NAME}"
SERVE_IMAGE_URI = f"gcr.io/{PROJECT_ID}/pytorch_cpu_predict_{MODEL_NAME}"
MACHINE_TYPE = "n1-standard-8"
REPLICA_COUNT = "1"
ACCELERATOR_TYPE = "NVIDIA_TESLA_T4"
ACCELERATOR_COUNT = "1"
NUM_WORKERS = 1
SERVING_HEALTH_ROUTE = "/ping"
SERVING_PREDICT_ROUTE = f"/predictions/{MODEL_NAME}"
SERVING_CONTAINER_PORT= [{"containerPort": 7080}]
SERVING_MACHINE_TYPE = "n1-standard-4"
SERVING_MIN_REPLICA_COUNT = 1
SERVING_MAX_REPLICA_COUNT=1
SERVING_TRAFFIC_SPLIT='{"0": 100}'
```
**Define pipeline specification**
The pipeline is defined as a standalone Python function annotated with the [`@kfp.dsl.pipeline`](https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/v2/components/pipeline_context.py) decorator, specifying the pipeline's name and the root path where the pipeline's artifacts are stored.
The pipeline definition consists of both pre-built and custom defined components:
- Pre-built components from [Google Cloud Pipeline Components SDK](https://cloud.google.com/vertex-ai/docs/pipelines/components-introduction) are defined for tasks calling Vertex AI services such as submitting custom training job (`custom_job.CustomTrainingJobOp`), uploading a model (`ModelUploadOp`), creating an endpoint (`EndpointCreateOp`) and deploying a model to the endpoint (`ModelDeployOp`)
- Custom components are defined for tasks to build custom containers for training (`build_custom_train_image`), get training job details (`get_training_job_details`), create mar file (`generate_mar_file`) and serving (`build_custom_serving_image`) and validating the model deployment task (`ake_prediction_request`). Refer to the notebook for custom component specification for these tasks.
```
from pipelines import pipeline_config as cfg
@dsl.pipeline(
name=cfg.PIPELINE_NAME,
pipeline_root=cfg.PIPELINE_ROOT,
)
def pytorch_text_classifier_pipeline(
pipeline_job_id: str,
gs_train_script_path: str,
gs_serving_dependencies_path: str,
eval_acc_threshold: float,
is_hp_tuning_enabled: str = "n",
):
# ========================================================================
# build custom training container image
# ========================================================================
# build custom container for training job passing the
# GCS location of the training application code
build_custom_train_image_task = (
build_custom_train_image(
project=cfg.PROJECT_ID,
gs_train_src_path=gs_train_script_path,
training_image_uri=cfg.TRAIN_IMAGE_URI,
)
.set_caching_options(True)
.set_display_name("Build custom training image")
)
# ========================================================================
# model training
# ========================================================================
# train the model on Vertex AI by submitting a CustomJob
# using the custom container (no hyper-parameter tuning)
# define training code arguments
training_args = ["--num-epochs", "2", "--model-name", cfg.MODEL_NAME]
# define job name
JOB_NAME = f"{cfg.MODEL_NAME}-train-pytorch-cstm-cntr-{TIMESTAMP}"
GCS_BASE_OUTPUT_DIR = f"{cfg.GCS_STAGING}/{TIMESTAMP}"
# define worker pool specs
worker_pool_specs = [
{
"machine_spec": {
"machine_type": cfg.MACHINE_TYPE,
"accelerator_type": cfg.ACCELERATOR_TYPE,
"accelerator_count": cfg.ACCELERATOR_COUNT,
},
"replica_count": cfg.REPLICA_COUNT,
"container_spec": {"image_uri": cfg.TRAIN_IMAGE_URI, "args": training_args},
}
]
run_train_task = (
custom_job.CustomTrainingJobOp(
project=cfg.PROJECT_ID,
location=cfg.REGION,
display_name=JOB_NAME,
base_output_directory=GCS_BASE_OUTPUT_DIR,
worker_pool_specs=worker_pool_specs,
)
.set_display_name("Run custom training job")
.after(build_custom_train_image_task)
)
# ========================================================================
# get training job details
# ========================================================================
training_job_details_task = get_training_job_details(
project=cfg.PROJECT_ID,
location=cfg.REGION,
job_resource=run_train_task.output,
eval_metric_key="eval_accuracy",
model_display_name=cfg.MODEL_NAME,
).set_display_name("Get custom training job details")
# ========================================================================
# model deployment when condition is met
# ========================================================================
with dsl.Condition(
training_job_details_task.outputs["eval_metric"] > eval_acc_threshold,
name="model-deploy-decision",
):
# ===================================================================
# create model archive file
# ===================================================================
create_mar_task = generate_mar_file(
model_display_name=cfg.MODEL_NAME,
model_version=cfg.VERSION,
handler=gs_serving_dependencies_path,
model=training_job_details_task.outputs["model"],
).set_display_name("Create MAR file")
# ===================================================================
# build custom serving container running TorchServe
# ===================================================================
# build custom container for serving predictions using
# the trained model artifacts served by TorchServe
build_custom_serving_image_task = build_custom_serving_image(
project=cfg.PROJECT_ID,
gs_serving_dependencies_path=gs_serving_dependencies_path,
serving_image_uri=cfg.SERVE_IMAGE_URI,
).set_display_name("Build custom serving image")
# ===================================================================
# create model resource
# ===================================================================
# upload model to vertex ai
model_upload_task = (
aip_components.ModelUploadOp(
project=cfg.PROJECT_ID,
display_name=cfg.MODEL_DISPLAY_NAME,
serving_container_image_uri=cfg.SERVE_IMAGE_URI,
serving_container_predict_route=cfg.SERVING_PREDICT_ROUTE,
serving_container_health_route=cfg.SERVING_HEALTH_ROUTE,
serving_container_ports=cfg.SERVING_CONTAINER_PORT,
serving_container_environment_variables=create_mar_task.outputs[
"mar_env_var"
],
artifact_uri=create_mar_task.outputs["mar_export_uri"],
)
.set_display_name("Upload model")
.after(build_custom_serving_image_task)
)
# ===================================================================
# create Vertex AI Endpoint
# ===================================================================
# create endpoint to deploy one or more models
# An endpoint provides a service URL where the prediction requests are sent
endpoint_create_task = (
aip_components.EndpointCreateOp(
project=cfg.PROJECT_ID,
display_name=cfg.MODEL_NAME + "-endpoint",
)
.set_display_name("Create endpoint")
.after(create_mar_task)
)
# ===================================================================
# deploy model to Vertex AI Endpoint
# ===================================================================
# deploy models to endpoint to associates physical resources with the model
# so it can serve online predictions
model_deploy_task = aip_components.ModelDeployOp(
endpoint=endpoint_create_task.outputs["endpoint"],
model=model_upload_task.outputs["model"],
deployed_model_display_name=cfg.MODEL_NAME,
dedicated_resources_machine_type=cfg.SERVING_MACHINE_TYPE,
dedicated_resources_min_replica_count=cfg.SERVING_MIN_REPLICA_COUNT,
dedicated_resources_max_replica_count=cfg.SERVING_MAX_REPLICA_COUNT,
traffic_split=cfg.SERVING_TRAFFIC_SPLIT,
).set_display_name("Deploy model to endpoint")
# ===================================================================
# test model deployment
# ===================================================================
# test model deployment by making online prediction requests
test_instances = [
"Jaw dropping visual affects and action! One of the best I have seen to date.",
"Take away the CGI and the A-list cast and you end up with film with less punch.",
]
predict_test_instances_task = make_prediction_request(
project=cfg.PROJECT_ID,
bucket=cfg.BUCKET,
endpoint=model_deploy_task.outputs["gcp_resources"],
instances=test_instances,
).set_display_name("Test model deployment making online predictions")
predict_test_instances_task
```
Let’s unpack this code and understand a few things:
- A component’s inputs can be set from the pipeline's inputs (passed as arguments) or they can depend on the output of other components within this pipeline. For example, `ModelUploadOp` depends on custom serving container image URI from `build_custom_serving_image` task along with the pipeline’s inputs such as project id.
- `kfp.dsl.Condition` is a control structure with a group of tasks which runs only when the condition is met. In this pipeline, model deployment steps run only when the trained model performance exceeds the set threshold. If not, those steps are skipped.
- Each component in the pipeline runs within its own container image. You can specify machine type for each pipeline step such as CPU, GPU and memory limits. By default, each component runs as a Vertex AI CustomJob using an e2-standard-4 machine.
- By default, pipeline execution caching is enabled. Vertex AI Pipelines service checks to see whether an execution of each pipeline step exists in Vertex ML metadata. It uses a combination of pipeline name, step’s inputs, output and component specification. When a matching execution already exists, the step is skipped and thereby reducing costs. Execution caching can be turned off at task level or at pipeline level.
Following is the runtime graph generated for this pipeline

To learn more about building pipelines, refer to the [building Kubeflow pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/build-pipeline#build-pipeline) section, and follow the [pipelines samples and tutorials](https://cloud.google.com/vertex-ai/docs/pipelines/notebooks#general-tutorials).
## Submit Pipeline
#### Compile Pipeline Specification as JSON
After defining the pipeline, it must be compiled for [executing on Vertex AI Pipeline services](https://cloud.google.com/vertex-ai/docs/pipelines/run-pipeline). When the pipeline is compiled, the KFP SDK analyzes the data dependencies between the components to create a directed acyclic graph. The compiled pipeline is in JSON format with all information required to run the pipeline.
```
PIPELINE_JSON_SPEC_PATH = "./pipelines/pytorch_text_classifier_pipeline_spec.json"
compiler.Compiler().compile(
pipeline_func=pytorch_text_classifier_pipeline, package_path=PIPELINE_JSON_SPEC_PATH
)
```
#### Submit Pipeline for Execution on Vertex AI Pipelines
Pipeline is submitted to Vertex AI Pipelines by defining a PipelineJob using Vertex AI SDK for Python client, passing necessary pipeline inputs.
```
# initialize Vertex AI SDK
aiplatform.init(project=PROJECT_ID, location=REGION)
# define pipeline parameters
# NOTE: These parameters can be included in the pipeline config file as needed
PIPELINE_JOB_ID = f"pipeline-{APP_NAME}-{get_timestamp()}"
TRAIN_APP_CODE_PATH = f"{BUCKET_NAME}/{APP_NAME}/train/"
SERVE_DEPENDENCIES_PATH = f"{BUCKET_NAME}/{APP_NAME}/serve/"
pipeline_params = {
"pipeline_job_id": PIPELINE_JOB_ID,
"gs_train_script_path": TRAIN_APP_CODE_PATH,
"gs_serving_dependencies_path": SERVE_DEPENDENCIES_PATH,
"eval_acc_threshold": 0.87,
"is_hp_tuning_enabled": "n",
}
# define pipeline job
pipeline_job = pipeline_jobs.PipelineJob(
display_name=cfg.PIPELINE_NAME,
job_id=PIPELINE_JOB_ID,
template_path=PIPELINE_JSON_SPEC_PATH,
pipeline_root=PIPELINE_ROOT,
parameter_values=pipeline_params,
enable_caching=True,
)
```
**When the pipeline is submitted, the logs show a link to view the pipeline run on Google Cloud Console or access the run by opening [Pipelines dashboard on Vertex AI](https://console.cloud.google.com/vertex-ai/pipelines)**
```
# submit pipeline job for execution
response = pipeline_job.run(sync=True)
response
```
## Monitoring the Pipeline
You can monitor the progress of a pipeline execution by navigating to the [Vertex AI Pipelines dashboard](https://console.cloud.google.com/vertex-ai/pipelines).
```
INFO:google.cloud.aiplatform.pipeline_jobs:Creating PipelineJob
INFO:google.cloud.aiplatform.pipeline_jobs:PipelineJob created. Resource name: projects/<project-id>/locations/<region>/pipelineJobs/pipeline-finetuned-bert-classifier-20220119061941
INFO:google.cloud.aiplatform.pipeline_jobs:To use this PipelineJob in another session:
INFO:google.cloud.aiplatform.pipeline_jobs:pipeline_job = aiplatform.PipelineJob.get('projects/<project-id>/locations/<region>/pipelineJobs/pipeline-finetuned-bert-classifier-20220119061941')
INFO:google.cloud.aiplatform.pipeline_jobs:View Pipeline Job:
https://console.cloud.google.com/vertex-ai/locations/region/pipelines/runs/pipeline-finetuned-bert-classifier-20220119061941?project=<project-id>
```
#### Component Execution Logs
Since every step in the pipeline runs in its own container or as a remote job (such as Dataflow, Dataproc job), you can view the step logs by clicking on "View Logs" button on a step.

#### Artifacts and Lineage
In the pipeline graph, you can notice the small boxes after each step. Those are artifacts generated from the step. For example, "Create MAR file" step generates MAR file as an artifact. Click on the artifact to know more details about it.

You can track lineage of an artifact describing its relationship with the steps in the pipeline. Vertex AI Pipelines automatically tracks the metadata and lineage. This lineage aids in establishing model governance and reproducibility. Click on "View Lineage" button on an artifact and it shows you the lineage graph as below.

#### Comparing Pipeline runs with the Vertex AI SDK
When running pipeline executions for different experiments, you may want to compare the metrics across the pipeline runs. You can [compare pipeline runs](https://cloud.google.com/vertex-ai/docs/pipelines/visualize-pipeline#compare_pipeline_runs_using) from the Vertex AI Pipelines dashboard.
Alternatively, you can use `aiplatform.get_pipeline_df()` method from Vertex AI SDK for Python that fetches pipeline execution metadata for a pipeline and returns a Pandas dataframe.
```
# underscores are not supported in the pipeline name, so
# replace underscores with hyphen
df_pipeline = aiplatform.get_pipeline_df(pipeline=cfg.PIPELINE_NAME.replace("_", "-"))
df_pipeline
```
## Cleaning up
### Cleaning up training and deployment resources
To clean up all Google Cloud resources used in this notebook, you can [delete the Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial:
- Training Jobs
- Model
- Endpoint
- Cloud Storage Bucket
- Container Images
- Pipeline runs
Set flags for the resource type to be deleted
```
delete_custom_job = False
delete_hp_tuning_job = False
delete_endpoint = False
delete_model = False
delete_bucket = False
delete_image = False
delete_pipeline_job = False
```
Define clients for jobs, models and endpoints
```
# API Endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = f"projects/{PROJECT_ID}/locations/{REGION}"
client_options = {"api_endpoint": API_ENDPOINT}
# Initialize Vertex SDK
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME)
# functions to create client
def create_job_client():
client = aip.JobServiceClient(client_options=client_options)
return client
def create_model_client():
client = aip.ModelServiceClient(client_options=client_options)
return client
def create_endpoint_client():
client = aip.EndpointServiceClient(client_options=client_options)
return client
def create_pipeline_client():
client = aip.PipelineServiceClient(client_options=client_options)
return client
clients = {}
clients["job"] = create_job_client()
clients["model"] = create_model_client()
clients["endpoint"] = create_endpoint_client()
clients["pipeline"] = create_pipeline_client()
```
Define functions to list the jobs, models and endpoints starting with APP_NAME defined earlier in the notebook
```
def list_custom_jobs():
client = clients["job"]
jobs = []
response = client.list_custom_jobs(parent=PARENT)
for row in response:
_row = MessageToDict(row._pb)
if _row["displayName"].startswith(APP_NAME):
jobs.append((_row["name"], _row["displayName"]))
return jobs
def list_hp_tuning_jobs():
client = clients["job"]
jobs = []
response = client.list_hyperparameter_tuning_jobs(parent=PARENT)
for row in response:
_row = MessageToDict(row._pb)
if _row["displayName"].startswith(APP_NAME):
jobs.append((_row["name"], _row["displayName"]))
return jobs
def list_models():
client = clients["model"]
models = []
response = client.list_models(parent=PARENT)
for row in response:
_row = MessageToDict(row._pb)
if _row["displayName"].startswith(APP_NAME):
models.append((_row["name"], _row["displayName"]))
return models
def list_endpoints():
client = clients["endpoint"]
endpoints = []
response = client.list_endpoints(parent=PARENT)
for row in response:
_row = MessageToDict(row._pb)
if _row["displayName"].startswith(APP_NAME):
endpoints.append((_row["name"], _row["displayName"]))
return endpoints
def list_pipelines():
client = clients["pipeline"]
pipelines = []
request = aip.ListPipelineJobsRequest(
parent=PARENT, filter=f'display_name="{cfg.PIPELINE_NAME}"', order_by="end_time"
)
response = client.list_pipeline_jobs(request=request)
for row in response:
_row = MessageToDict(row._pb)
pipelines.append(_row["name"])
return pipelines
```
### Deleting custom training jobs
```
# Delete the custom training using the Vertex AI fully qualified identifier for the custom training
try:
if delete_custom_job:
custom_jobs = list_custom_jobs()
for job_id, job_name in custom_jobs:
print(f"Deleting job {job_id} [{job_name}]")
clients["job"].delete_custom_job(name=job_id)
except Exception as e:
print(e)
```
### Deleting hyperparameter tuning jobs
```
# Delete the hyperparameter tuning jobs using the Vertex AI fully qualified identifier for the hyperparameter tuning job
try:
if delete_hp_tuning_job:
hp_tuning_jobs = list_hp_tuning_jobs()
for job_id, job_name in hp_tuning_jobs:
print(f"Deleting job {job_id} [{job_name}]")
clients["job"].delete_hyperparameter_tuning_job(name=job_id)
except Exception as e:
print(e)
```
### Undeploy models and Delete endpoints
```
# Delete the endpoint using the Vertex AI fully qualified identifier for the endpoint
try:
if delete_endpoint:
endpoints = list_endpoints()
for endpoint_id, endpoint_name in endpoints:
endpoint = aiplatform.Endpoint(endpoint_id)
# undeploy models from the endpoint
print(f"Undeploying all deployed models from the endpoint {endpoint_name}")
endpoint.undeploy_all(sync=True)
# deleting endpoint
print(f"Deleting endpoint {endpoint_id} [{endpoint_name}]")
clients["endpoint"].delete_endpoint(name=endpoint_id)
except Exception as e:
print(e)
```
### Deleting models
```
# Delete the model using the Vertex AI fully qualified identifier for the model
try:
if delete_model:
models = list_models()
for model_id, model_name in models:
print(f"Deleting model {model_id} [{model_name}]")
clients["model"].delete_model(name=model_id)
except Exception as e:
print(e)
```
### Deleting pipeline runs
```
# Delete the pipeline execution using the Vertex AI fully qualified identifier for the pipeline job
try:
if delete_pipeline_job:
pipelines = list_pipelines()
for pipeline_name in pipelines[:1]:
print(f"Deleting pipeline run {pipeline_name}")
if delete_custom_job:
print("\t Deleting underlying custom jobs")
pipeline_job = clients["pipeline"].get_pipeline_job(name=pipeline_name)
pipeline_job = MessageToDict(pipeline_job._pb)
task_details = pipeline_job["jobDetail"]["taskDetails"]
for task in tasks:
if "containerDetail" in task["executorDetail"]:
custom_job_id = task["executorDetail"]["containerDetail"][
"mainJob"
]
print(
f"\t Deleting custom job {custom_job_id} for task {task['taskName']}"
)
clients["job"].delete_custom_job(name=custom_job_id)
clients["pipeline"].delete_pipeline_job(name=pipeline_name)
except Exception as e:
print(e)
```
### Delete contents from the staging bucket
---
***NOTE: Everything in this Cloud Storage bucket will be DELETED. Please run it with caution.***
---
```
if delete_bucket and "BUCKET_NAME" in globals():
print(f"Deleting all contents from the bucket {BUCKET_NAME}")
shell_output = ! gsutil du -as $BUCKET_NAME
print(
f"Size of the bucket {BUCKET_NAME} before deleting = {shell_output[0].split()[0]} bytes"
)
# uncomment below line to delete contents of the bucket
# ! gsutil rm -r $BUCKET_NAME
shell_output = ! gsutil du -as $BUCKET_NAME
if float(shell_output[0].split()[0]) > 0:
print(
"PLEASE UNCOMMENT LINE TO DELETE BUCKET. CONTENT FROM THE BUCKET NOT DELETED"
)
print(
f"Size of the bucket {BUCKET_NAME} after deleting = {shell_output[0].split()[0]} bytes"
)
```
### Delete images from Container Registry
Deletes all the container images created in this tutorial with prefix defined by variable APP_NAME from the registry. All associated tags are also deleted.
```
gcr_images = !gcloud container images list --repository=gcr.io/$PROJECT_ID --filter="name~"$APP_NAME
if delete_image:
for image in gcr_images:
if image != "NAME": # skip header line
print(f"Deleting image {image} including all tags")
!gcloud container images delete $image --force-delete-tags --quiet
```
### Cleaning up Notebook Environment
After you are done experimenting, you can either STOP or DELETE the AI Notebook instance to prevent any charges. If you want to save your work, you can choose to stop the instance instead.
```
# Stopping Notebook instance
gcloud notebooks instances stop example-instance --location=us-central1-a
# Deleting Notebook instance
gcloud notebooks instances delete example-instance --location=us-central1-a
```
| github_jupyter |
```
# ========================================
# library
# ========================================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold, KFold,GroupKFold
from sklearn.metrics import mean_squared_error
%matplotlib inline
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, Subset
import transformers
from transformers import LongformerTokenizer, LongformerModel,AutoTokenizer,RobertaModel,BartModel
from transformers import AdamW, get_linear_schedule_with_warmup
from torch.cuda.amp import autocast, GradScaler
import logging
from ast import literal_eval
import sys
from contextlib import contextmanager
import time
import random
from tqdm import tqdm
import os
# ==================
# Constant
# ==================
ex = "048"
TRAIN_PATH = "../data/train.csv"
DATA_DIR = "../data/bart-large/"
if not os.path.exists(f"../output/exp/ex{ex}"):
os.makedirs(f"../output/exp/ex{ex}")
os.makedirs(f"../output/exp/ex{ex}/ex{ex}_model")
OUTPUT_DIR = f"../output/exp/ex{ex}"
MODEL_PATH_BASE = f"../output/exp/ex{ex}/ex{ex}_model/ex{ex}"
LOGGER_PATH = f"../output/exp/ex{ex}/ex{ex}.txt"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ===============
# Configs
# ===============
SEED = 0
N_SPLITS = 5
SHUFFLE = True
BATCH_SIZE = 8
n_epochs = 6
max_len = 512
weight_decay = 0.1
beta = (0.9, 0.98)
lr = 2e-5
num_warmup_steps_rate = 0.1
MODEL_PATH = 'facebook/bart-large'
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
# ===============
# Functions
# ===============
def set_seed(seed: int = 42):
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def setup_logger(out_file=None, stderr=True, stderr_level=logging.INFO, file_level=logging.DEBUG):
LOGGER.handlers = []
LOGGER.setLevel(min(stderr_level, file_level))
if stderr:
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(FORMATTER)
handler.setLevel(stderr_level)
LOGGER.addHandler(handler)
if out_file is not None:
handler = logging.FileHandler(out_file)
handler.setFormatter(FORMATTER)
handler.setLevel(file_level)
LOGGER.addHandler(handler)
LOGGER.info("logger set up")
return LOGGER
@contextmanager
def timer(name):
t0 = time.time()
yield
LOGGER.info(f'[{name}] done in {time.time() - t0:.0f} s')
LOGGER = logging.getLogger()
FORMATTER = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
setup_logger(out_file=LOGGER_PATH)
class TrainDataset(Dataset):
def __init__(self, token,attentiona_mask,label=None):
self.len = len(token)
self.token = token
self.attention_mask = attentiona_mask
self.label = label
#self.get_wids = get_wids # for validation
def __getitem__(self, index):
# GET TEXT AND WORD LABELS
if self.label is not None:
return {
'token': torch.tensor(self.token[index], dtype=torch.long),
'mask': torch.tensor(self.attention_mask[index], dtype=torch.long),
"y":torch.tensor(self.label[index], dtype=torch.float32)
}
else:
return {
'token': torch.tensor(self.token[index], dtype=torch.long),
'mask': torch.tensor(self.attention_mask[index], dtype=torch.long),
}
def __len__(self):
return self.len
class custom_model(nn.Module):
def __init__(self):
super(custom_model, self).__init__()
self.backbone = BartModel.from_pretrained(
MODEL_PATH,
)
#self.dropout = nn.Dropout(p=0.2)
self.ln = nn.LayerNorm(1024)
self.conv1= nn.Conv1d(1024, 512, kernel_size=3, padding=1)
self.conv2= nn.Conv1d(1024, 512, kernel_size=9, padding=4)
self.conv3= nn.Conv1d(1024, 512, kernel_size=15, padding=7)
self.conv4= nn.Conv1d(1024, 512, kernel_size=31, padding=15)
self.ln1 = nn.Sequential(nn.LayerNorm(512),
nn.ReLU(),
nn.Dropout(0.2))
self.ln2 = nn.Sequential( nn.LayerNorm(512),
nn.ReLU(),
nn.Dropout(0.2))
self.ln3 = nn.Sequential( nn.LayerNorm(512),
nn.ReLU(),
nn.Dropout(0.2))
self.ln4 = nn.Sequential( nn.LayerNorm(512),
nn.ReLU(),
nn.Dropout(0.2))
self.linear1 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear2 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear3 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear4 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear5 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear6 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear7 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,2),
)
self.linear8 = nn.Sequential(
nn.Linear(2048,1024),
nn.LayerNorm(1024),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(1024,1),
)
def forward(self, ids, mask):
# pooler
emb = self.backbone(ids, attention_mask=mask)["last_hidden_state"]
output = self.ln(emb)
output = output.permute((0, 2, 1)).contiguous()
output1 = self.conv1(output)
output1 = self.ln1(output1.permute((0, 2, 1)).contiguous())
output2 = self.conv2(output)
output2 = self.ln2(output2.permute((0, 2, 1)).contiguous())
output3 = self.conv3(output)
output3 = self.ln3(output3.permute((0, 2, 1)).contiguous())
output4 = self.conv4(output)
output4 = self.ln4(output4.permute((0, 2, 1)).contiguous())
output_concat = torch.cat([output1,output2,output3,output4],axis=-1)
output2_1 = self.linear1(output_concat)
output2_2 = self.linear2(output_concat)
output2_3 = self.linear3(output_concat)
output2_4 = self.linear4(output_concat)
output2_5 = self.linear5(output_concat)
output2_6 = self.linear6(output_concat)
output2_7= self.linear7(output_concat)
output2_8 = self.linear8(output_concat)
out = torch.cat(
[output2_1,output2_2,output2_3,output2_4,
output2_5,output2_6,output2_7,output2_8], axis=2)
return out
target_map_rev = {0:'Lead', 1:'Position', 2:'Evidence', 3:'Claim', 4:'Concluding Statement',
5:'Counterclaim', 6:'Rebuttal', 7:'blank'}
def get_preds_collate(dataset, verbose,text_ids, preds, preds_len):
all_predictions = []
for id_num in tqdm(range(len(preds))):
# GET ID
#if (id_num%100==0)&(verbose):
# print(id_num,', ',end='')
n = text_ids[id_num]
max_len = int(preds_len[id_num])
# GET TOKEN POSITIONS IN CHARS
name = f'../data/{dataset}/{n}.txt'
txt = open(name, 'r').read()
tokens = tokenizer.encode_plus(txt, max_length=max_len, padding='max_length',
truncation=True, return_offsets_mapping=True)
off = tokens['offset_mapping']
# GET WORD POSITIONS IN CHARS
w = []
blank = True
for i in range(len(txt)):
if (txt[i]!=' ')&(txt[i]!='\n')&(txt[i]!='\xa0')&(txt[i]!='\x85')&(blank==True):
w.append(i)
blank=False
elif (txt[i]==' ')|(txt[i]=='\n')|(txt[i]=='\xa0')|(txt[i]=='\x85'):
blank=True
w.append(1e6)
# MAPPING FROM TOKENS TO WORDS
word_map = -1 * np.ones(max_len,dtype='int32')
w_i = 0
for i in range(len(off)):
if off[i][1]==0: continue
while off[i][0]>=w[w_i+1]: w_i += 1
word_map[i] = int(w_i)
# CONVERT TOKEN PREDICTIONS INTO WORD LABELS
### KEY: ###
# 0: LEAD_B, 1: LEAD_I
# 2: POSITION_B, 3: POSITION_I
# 4: EVIDENCE_B, 5: EVIDENCE_I
# 6: CLAIM_B, 7: CLAIM_I
# 8: CONCLUSION_B, 9: CONCLUSION_I
# 10: COUNTERCLAIM_B, 11: COUNTERCLAIM_I
# 12: REBUTTAL_B, 13: REBUTTAL_I
# 14: NOTHING i.e. O
### NOTE THESE VALUES ARE DIVIDED BY 2 IN NEXT CODE LINE
pred = preds[id_num,]/2.0
i = 0
while i<max_len:
prediction = []
start = pred[i]
if start in [0,1,2,3,4,5,6,7]:
prediction.append(word_map[i])
i += 1
if i>=max_len: break
while pred[i]==start+0.5:
if not word_map[i] in prediction:
prediction.append(word_map[i])
i += 1
if i>=max_len: break
else:
i += 1
prediction = [x for x in prediction if x!=-1]
if len(prediction)>4:
all_predictions.append( (n, target_map_rev[int(start)],
' '.join([str(x) for x in prediction]) ) )
# MAKE DATAFRAME
df = pd.DataFrame(all_predictions)
df.columns = ['id','class','predictionstring']
return df
def calc_overlap(row):
"""
Calculates the overlap between prediction and
ground truth and overlap percentages used for determining
true positives.
"""
set_pred = set(row.predictionstring_pred.split(' '))
set_gt = set(row.predictionstring_gt.split(' '))
# Length of each and intersection
len_gt = len(set_gt)
len_pred = len(set_pred)
inter = len(set_gt.intersection(set_pred))
overlap_1 = inter / len_gt
overlap_2 = inter/ len_pred
return [overlap_1, overlap_2]
def score_feedback_comp(pred_df, gt_df):
"""
A function that scores for the kaggle
Student Writing Competition
Uses the steps in the evaluation page here:
https://www.kaggle.com/c/feedback-prize-2021/overview/evaluation
"""
gt_df = gt_df[['id','discourse_type','predictionstring']] \
.reset_index(drop=True).copy()
pred_df = pred_df[['id','class','predictionstring']] \
.reset_index(drop=True).copy()
pred_df['pred_id'] = pred_df.index
gt_df['gt_id'] = gt_df.index
# Step 1. all ground truths and predictions for a given class are compared.
joined = pred_df.merge(gt_df,
left_on=['id','class'],
right_on=['id','discourse_type'],
how='outer',
suffixes=('_pred','_gt')
)
joined['predictionstring_gt'] = joined['predictionstring_gt'].fillna(' ')
joined['predictionstring_pred'] = joined['predictionstring_pred'].fillna(' ')
joined['overlaps'] = joined.apply(calc_overlap, axis=1)
# 2. If the overlap between the ground truth and prediction is >= 0.5,
# and the overlap between the prediction and the ground truth >= 0.5,
# the prediction is a match and considered a true positive.
# If multiple matches exist, the match with the highest pair of overlaps is taken.
joined['overlap1'] = joined['overlaps'].apply(lambda x: eval(str(x))[0])
joined['overlap2'] = joined['overlaps'].apply(lambda x: eval(str(x))[1])
joined['potential_TP'] = (joined['overlap1'] >= 0.5) & (joined['overlap2'] >= 0.5)
joined['max_overlap'] = joined[['overlap1','overlap2']].max(axis=1)
tp_pred_ids = joined.query('potential_TP') \
.sort_values('max_overlap', ascending=False) \
.groupby(['id','predictionstring_gt']).first()['pred_id'].values
# 3. Any unmatched ground truths are false negatives
# and any unmatched predictions are false positives.
fp_pred_ids = [p for p in joined['pred_id'].unique() if p not in tp_pred_ids]
matched_gt_ids = joined.query('potential_TP')['gt_id'].unique()
unmatched_gt_ids = [c for c in joined['gt_id'].unique() if c not in matched_gt_ids]
# Get numbers of each type
TP = len(tp_pred_ids)
FP = len(fp_pred_ids)
FN = len(unmatched_gt_ids)
#calc microf1
my_f1_score = TP / (TP + 0.5*(FP+FN))
return my_f1_score
def collate(d,train=True):
mask_len = int(d["mask"].sum(axis=1).max())
if train:
return {"token" : d['token'][:,:mask_len],
"mask" : d['mask'][:,:mask_len],
"y" : d['y'][:,:mask_len],
"max_len" : mask_len}
else:
return {"token" : d['token'][:,:mask_len],
"mask" : d['mask'][:,:mask_len],
"max_len" : mask_len}
# ================================
# Main
# ================================
train = pd.read_csv(TRAIN_PATH)
IDS = train.id.unique()
id_array = np.array(IDS)
targets = np.load(DATA_DIR + f"targets_{max_len}.npy")
train_tokens = np.load(DATA_DIR + f"tokens_{max_len}.npy")
train_attention = np.load(DATA_DIR + f"attention_{max_len}.npy")
# ================================
# train
# ================================
with timer("bart_large"):
set_seed(SEED)
oof = pd.DataFrame()
oof_pred = np.ndarray((0,max_len,15))
kf = KFold(n_splits=N_SPLITS, shuffle=SHUFFLE, random_state=SEED)
for fold, (train_idx, valid_idx) in enumerate(kf.split(id_array)):
print(f"fold{fold}:start")
x_train_token, x_train_attention, y_train = train_tokens[train_idx], train_attention[train_idx], targets[train_idx]
x_val_token, x_val_attention, y_val = train_tokens[valid_idx], train_attention[valid_idx], targets[valid_idx]
train_val = train[train.id.isin(id_array[valid_idx])].reset_index(drop=True)
# dataset
train_ = TrainDataset( x_train_token, x_train_attention, y_train)
val_ = TrainDataset( x_val_token, x_val_attention, y_val)
# loader
train_loader = DataLoader(dataset=train_, batch_size=BATCH_SIZE, shuffle = True ,pin_memory=True)
val_loader = DataLoader(dataset=val_, batch_size=BATCH_SIZE, shuffle = False , pin_memory=True)
# model
model = custom_model()
model = model.to(device)
# optimizer, scheduler
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': weight_decay},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters,
lr=lr,
betas=beta,
weight_decay=weight_decay,
)
num_train_optimization_steps = int(len(train_loader) * n_epochs)
num_warmup_steps = int(num_train_optimization_steps * num_warmup_steps_rate)
scheduler = get_linear_schedule_with_warmup(optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_train_optimization_steps)
criterion = nn.BCEWithLogitsLoss()
best_val = 0
for epoch in range(n_epochs):
print(f"============start epoch:{epoch}==============")
model.train()
val_losses_batch = []
scaler = GradScaler()
for i, d in tqdm(enumerate(train_loader),total=len(train_loader)):
d = collate(d)
ids = d['token'].to(device)
mask = d['mask'].to(device)
labels = d['y'].to(device)
#labels = labels.unsqueeze(-1)
optimizer.zero_grad()
with autocast():
output = model(ids,mask)
loss = criterion(output[mask == 1], labels[mask == 1])
scaler.scale(loss).backward()
#torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad_norm)
scaler.step(optimizer)
scaler.update()
scheduler.step()
y_pred2 = []
val_preds = np.ndarray((0,max_len,15))
val_len = np.ndarray(0)
model.eval() # switch model to the evaluation mode
with torch.no_grad():
# Predicting on validation set
for d in tqdm(val_loader,total=len(val_loader)):
# =========================
# data loader
# =========================
d = collate(d)
ids = d['token'].to(device)
mask = d['mask'].to(device)
with autocast():
outputs = model(ids, mask)
outputs = np.concatenate([outputs.sigmoid().detach().cpu().numpy(),np.zeros([len(outputs),max_len - d["max_len"],15])],axis=1)
val_preds = np.concatenate([val_preds, outputs], axis=0)
val_len = np.concatenate([val_len,np.array([d["max_len"] for i in range(len(ids))])],axis=0)
val_preds_max = np.argmax(val_preds,axis=-1)
oof_ = get_preds_collate( dataset='train', verbose=True, text_ids=id_array[valid_idx],
preds = val_preds_max,preds_len=val_len)
# COMPUTE F1 SCORE
f1s = []
CLASSES = oof_['class'].unique()
print()
for c in CLASSES:
pred_df = oof_.loc[oof_['class']==c].copy()
gt_df = train_val.loc[train_val['discourse_type']==c].copy()
f1 = score_feedback_comp(pred_df, gt_df)
print(c,f1)
f1s.append(f1)
score = np.mean(f1s)
LOGGER.info(f'{fold},{epoch}:{i},val_score:{score}')
if best_val < score:
print("save model weight")
best_val = score
best_val_preds = val_preds
oof_best = oof_.copy()
torch.save(model.state_dict(), MODEL_PATH_BASE + f"_{fold}.pth") # Saving current best model
oof_best["fold"] = fold
oof_best.to_csv(OUTPUT_DIR + f"/ex{ex}_oof_{fold}.csv",index=False)
np.save(OUTPUT_DIR + f"/ex{ex}_oof_npy_{fold}.npy",best_val_preds)
oof = pd.DataFrame()
for i in range(5):
oof__ = pd.read_csv(OUTPUT_DIR + f"/ex{ex}_oof_{i}.csv")
oof = pd.concat([oof,oof__]).reset_index(drop=True)
# COMPUTE F1 SCORE
f1s = []
CLASSES = oof['class'].unique()
for c in CLASSES:
pred_df = oof.loc[oof['class']==c].copy()
gt_df = train.loc[train['discourse_type']==c].copy()
f1 = score_feedback_comp(pred_df, gt_df)
print(c,f1)
f1s.append(f1)
score = np.mean(f1s)
LOGGER.info(f'CV:{score}')
```
| github_jupyter |
# Energy Meter Examples
## Monsoon Power Monitor
*NOTE*: the **monsoon.py** tool is required to collect data from the power monitor.
Instructions on how to install it can be found here:
https://github.com/ARM-software/lisa/wiki/Energy-Meters-Requirements#monsoon-power-monitor.
```
import logging
from conf import LisaLogging
LisaLogging.setup()
```
#### Import required modules
```
# Generate plots inline
%matplotlib inline
import os
# Support to access the remote target
import devlib
from env import TestEnv
# RTApp configurator for generation of PERIODIC tasks
from wlgen import RTA, Ramp
```
## Target Configuration
The target configuration is used to describe and configure your test environment.
You can find more details in **examples/utils/testenv_example.ipynb**.
```
# Let's assume the monsoon binary is installed in the following path
MONSOON_BIN = os.path.join(os.getenv('LISA_HOME'), 'tools', 'scripts', 'monsoon.py')
# Setup target configuration
my_conf = {
# Target platform and board
"platform" : 'android',
"board" : 'wahoo',
# Android tools
"ANDROID_HOME" : "/home/derkling/Code/lisa/tools/android-sdk-linux",
# Folder where all the results will be collected
"results_dir" : "EnergyMeter_Monsoon",
# Define devlib modules to load
"exclude_modules" : [ 'hwmon' ],
# Energy Meters Configuration for ARM Energy Probe
"emeter" : {
"instrument" : "monsoon",
"conf" : {
'monsoon_bin' : MONSOON_BIN,
},
},
# Tools required by the experiments
"tools" : [ 'trace-cmd', 'rt-app' ],
# Comment this line to calibrate RTApp in your own platform
"rtapp-calib" : {"0": 360, "1": 142, "2": 138, "3": 352, "4": 352, "5": 353},
}
# Once powered the Monsoon Power Monitor does not enable the output voltage.
# Since the devlib's API expects that the device is powered and available for
# an ADB connection, let's manually power on the device before initializing the TestEnv
# Power on the device
!$MONSOON_BIN --device /dev/ttyACM1 --voltage 4.2
# Enable USB passthrough to be able to connect the device
!$MONSOON_BIN --usbpassthrough on
# Initialize a test environment using:
te = TestEnv(my_conf, wipe=False, force_new=True)
target = te.target
# If your device support charge via USB, let's disable it in order
# to read the overall power consumption from the main output channel
# For example, this is the API for a Pixel phone:
te.target.write_value('/sys/class/power_supply/battery/charging_enabled', 0)
```
## Workload Execution and Power Consumptions Samping
Detailed information on RTApp can be found in **examples/wlgen/rtapp_example.ipynb**.
Each **EnergyMeter** derived class has two main methods: **reset** and **report**.
- The **reset** method will reset the energy meter and start sampling from channels specified in the target configuration. <br>
- The **report** method will stop capture and will retrieve the energy consumption data. This returns an EnergyReport composed of the measured channels energy and the report file. Each of the samples can also be obtained, as you can see below.
```
# Create and RTApp RAMP task
rtapp = RTA(te.target, 'ramp', calibration=te.calibration())
rtapp.conf(kind='profile',
params={
'ramp' : Ramp(
start_pct = 60,
end_pct = 20,
delta_pct = 5,
time_s = 0.5).get()
})
# EnergyMeter Start
te.emeter.reset()
rtapp.run(out_dir=te.res_dir)
# EnergyMeter Stop and samples collection
nrg_report = te.emeter.report(te.res_dir)
logging.info("Collected data:")
!tree $te.res_dir
```
## Power Measurements Data
```
logging.info("Measured channels energy:")
logging.info("%s", nrg_report.channels)
logging.info("Generated energy file:")
logging.info(" %s", nrg_report.report_file)
!cat $nrg_report.report_file
logging.info("Samples collected for the Output and Battery channels (only first 10)")
samples_file = os.path.join(te.res_dir, 'samples.csv')
!head $samples_file
logging.info("DataFrame of collected samples (only first 5)")
nrg_report.data_frame.head()
logging.info("Plot of collected power samples")
axes = nrg_report.data_frame[('output', 'power')].plot(
figsize=(16,8), drawstyle='steps-post');
axes.set_title('Power samples');
axes.set_xlabel('Time [s]');
axes.set_ylabel('Output power [W]');
logging.info("Plot of collected power samples")
nrg_report.data_frame.describe(percentiles=[0.90, 0.95, 0.99]).T
logging.info("Power distribution")
axes = nrg_report.data_frame[('output', 'power')].plot(
kind='hist', bins=32,
figsize=(16,8));
axes.set_title('Power Histogram');
axes.set_xlabel('Output power [W] buckets');
axes.set_ylabel('Samples per bucket');
```
| github_jupyter |
```
import numpy as np
import math
from numpy import linalg as la
from numpy import random as rd
import pandas as pd
from matplotlib import pyplot as plt
import os
from GaussianExp import Experiment1, DrawX, SamplerTheta, SamplerS, PSucLB, gss
path = './plots/Gaussian'
if not os.path.exists(path):
os.mkdir(path)
# Fixing parameters of the experiment.
rd.seed(9)
d = 20
sigmaX = 2
beta = rd.uniform(-sigmaX,sigmaX,d)
sigmaY = 2
range_ = [21,40,60,80,100,120,140]
precision = 1000
genErrEmpList = []
genErrBList = []
SucRateList = []
LBList = []
mseList = []
for n in range_: #Loop over size of the training set.
X = DrawX(d,n,sigmaX) # X is fixed for each n.
Q = np.transpose(X)@X
Qinv = la.inv(Q)
Normal0 = SamplerTheta(0,beta,Qinv,sigmaY,X) #Distribution of the model parameters given T=0
NormalY = SamplerS(beta,sigmaY,X)
# Generalization gap.
genErr = 2*d*(sigmaY**2)/n
# MSE
mseAuxList = []
#Generalization gap estimation.
genErrList = []
#Lower bound on probability of Success.
auxF = lambda param : PSucLB(sigmaY,n,d,param)
inter = gss(auxF, 0, 40)
value = (inter[1]+inter[0])/2
LB = PSucLB(sigmaY,n,d,value)
n_Suc = 0
for seed in range(precision): # Repeating the experiment described by algorithm 1 "precision" times.
Suc, genErrEmp, mse = Experiment1(X,beta,Qinv,Normal0,NormalY,sigmaY,seed*3)
n_Suc += Suc
genErrList.append(genErrEmp)
mseAuxList.append(mse)
# Success rate for the optimal attack.
SucRate = n_Suc/precision
genErrEmp = np.mean(genErrList)
genErrEmpList.append(genErrEmp) # Empirical Generalization gap, averaged over different models.
genErrBList.append(genErr) # Generalization gap, computed analytically.
SucRateList.append(SucRate) # Success rate of the optimal attacker.
LBList.append(LB) # Lower bound on success rate of the optimal attacker.
mseList.append(np.mean(mseAuxList)) #MSE on the training set, averaged over different models.
print('Size of the training set: %d, Generalization gap: %f, Gen gap Estimate %f, Success Rate: %f, Lower Bound: %f, MSE: %f' %
(n,genErr,genErrEmp,SucRate,LB, mse))
# Plotting and saving data.
SucRate = pd.DataFrame(genErrBList, columns=['c'])
SucRate.insert(0,'a',SucRateList)
SucRate.insert(2,'b',range_)
SucRate.to_csv(path+'/SucRateVsGenD20.csv',index=False)
genErrEmp = pd.DataFrame(genErrBList, columns=['c'])
genErrEmp.insert(0,'a',genErrEmpList)
genErrEmp.insert(2,'b',range_)
genErrEmp.to_csv(path+'/genEmpVsTheoreticalD20.csv',index=False)
plt.figure(1)
plt.plot(range_,genErrBList)
plt.plot(range_,genErrEmpList)
plt.legend(['Theoretical','Estimate'])
plt.xlabel('Number of samples in the Universe')
plt.ylabel('Generalization Error')
plt.show()
PSucLB = pd.DataFrame(genErrBList, columns=['c'])
PSucLB.insert(0,'a',LBList)
PSucLB.insert(2,'b',range_)
PSucLB.to_csv(path+'/LBVsGenD20.csv',index=False)
MSEdf = pd.DataFrame(mseList, columns=['a'])
MSEdf.insert(0,'b',range_)
MSEdf.to_csv(path+'/MSEVsND20.csv',index=False)
plt.figure(2)
plt.plot(range_,LBList)
plt.plot(range_,SucRateList)
plt.legend(['Lower Bound','Estimate'])
plt.xlabel('Number of samples in the Universe')
plt.ylabel('Prob of Success of the Optimal Attack')
plt.show()
plt.figure(3)
plt.plot(range_,mseList)
plt.xlabel('Number of samples in the Universe')
plt.ylabel('MSE on training set')
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/conquerv0/Pynaissance/blob/master/1.%20Basic%20Framework/Data_Visualization.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Data Visualization Guide
This notebook features data visualization techniques in areas such as static 2D, 3D plotting and interactive 2D plotting using packages `matplotlib, ploly`.
__I. Static 2D Plotting__
```
# Import necessary packages and configuration.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
# Optional for displaying inline
%matplotlib inline
# Sample data source for plotting
np.random.seed(1000)
y = np.random.standard_normal(20)
x = np.arange(len(y))
# Plotting
plt.plot(x, y)
plt.plot(y.cumsum())
# Some modification to plotting: Turning off the grid and create equal scalling for the two axes.
plt.plot(y.cumsum())
plt.grid(False)
plt.axis('equal')
```
Some options for `plt.axis()`
Parameter | Description
------------ | -------------
Empty | Returns current axis limit
off | Turns axis lines and labels off
equal | Leads to equal scalling
scaled | Produces equal scaling via dimension changes
tight | Makes all data visible(tighten limits)
image | Makes all data visible(with data limits)
[xmin, xmax, ymin, ymax] | Sets limits to given list of values
```
plt.plot(y.cumsum())
plt.xlim(-1, 20)
plt.ylim(np.min(y.cumsum())-1,
np.max(y.cumsum()) + 1)
# Add labelling in the plot for Readability
plt.xlabel('Index')
plt.ylabel('Value')
plt.title('Simple Plot')
plt.legend(loc=0)
```
Creating mutilple plots on one line
```
y = np.random.standard_normal((20, 2)).cumsum(axis=0)
plt.figure(figsize=(10, 6))
plt.subplot(121)
plt.plot(y[:, 0], lw=1.5, label='1st')
plt.plot(y[:, 0], 'r')
plt.xlabel('index')
plt.ylabel('value')
plt.title('1st Data Set')
# Second plot
plt.subplot(122)
plt.bar(np.arange(len(y)), y[:,1], width=0.5, color='b', label='2nd')
plt.legend(loc=0)
plt.xlabel('index')
plt.title('2nd Data Set')
```
__Other Plotting Style__
```
# Regular Scatter plot
y = np.random.standard_normal((1000, 2))
plt.figure(figsize=(10, 6))
plt.scatter(y[:, 0], y[:, 1], marker='o')
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
# Integrate Color map to Scatter plot
c = np.random.randint(0, 10, len(y))
plt.figure(figsize=(10, 6))
plt.scatter(y[:, 0], y[:, 1], c=c, cmap='coolwarm', marker='o') # Define the dot to be marked as a bigger dot
plt.colorbar()
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot with Color Map')
# Histogram
plt.figure(figsize=(10, 6))
plt.hist(y, label=['1st', '2nd'], bins=30)
plt.legend(loc=0)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histogram')
# Boxplot
fig, ax = plt.subplots(figsize=(10, 6))
plt.boxplot(y)
plt.setp(ax, xticklabels=['1st', '2nd'])
plt.xlabel('data set')
plt.ylabel('value')
plt.title('Boxplot')
# Plotting of mathematical function
def func(x):
return 0.5*np.exp(x)+1
a, b = 0.5, 1.5
x = np.linspace(0, 2)
y = func(x)
Ix = np.linspace(a, b) # Integral limits of x value
Iy = func(Ix) # Integral limits of y value
verts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]
#
from matplotlib.patches import Polygon
fig, ax = plt.subplots(figsize = (10, 6))
plt.plot(x, y, 'b', linewidth=2)
plt.ylim(bottom=0)
poly = Polygon(verts, facecolor='0.7', edgecolor='0.5')
ax.add_patch(poly)
plt.text(0.5 * (a+b), 1, r'$\int_a^b f(x)\mathrm{d}x$',
horizontalalignment='center', fontsize=20) # Labelling for plot
plt.figtext(0.9, 0.075, '$x$')
plt.figtext(0.075, 0.9, '$f(x)$')
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([func(a), func(b)])
ax.set_yticklabels(('$f(a)$', '$f(b)$'))
```
__II. Static 3D Plotting__
Using `np.meshgrid()` function to generate a two-dimensional coordinates system out of two one-dimensional ndarray.
```
# Set a call option data values with
# Strike values = [50, 150]
# Time-to-Maturity = [0.5, 2.5]
strike = np.linspace(50, 150, 24)
ttm = np.linspace(0.5, 2.5, 24)
strike, ttm = np.meshgrid(strike, ttm)
strike[:2].round(2)
# Calculate implied volatility
iv = (strike - 100) ** 2 / (100 * strike) / ttm
iv[:5, :3]
```
Plotting a 3D figure using the generated Call options data with `Axes3D`
```
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10, 6))
ax = fig.gca(projection = '3d')
surf = ax.plot_surface(strike, ttm, iv, rstride=2, cstride=2,
cmap = plt.cm.coolwarm, linewidth = 0.5, antialiased=True)
ax.set_xlabel('Strike Price')
ax.set_ylabel('Time-to-Maturity')
ax.set_zlabel('Implied Volatility')
fig.colorbar(surf, shrink = 0.5, aspect =5)
```
| github_jupyter |
# Doc2Vec to wikipedia articles
We conduct the replication to **Document Embedding with Paragraph Vectors** (http://arxiv.org/abs/1507.07998).
In this paper, they showed only DBOW results to Wikipedia data. So we replicate this experiments using not only DBOW but also DM.
## Basic Setup
Let's import Doc2Vec module.
```
from gensim.corpora.wikicorpus import WikiCorpus
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from pprint import pprint
import multiprocessing
```
## Preparing the corpus
First, download the dump of all Wikipedia articles from [here](http://download.wikimedia.org/enwiki/) (you want the file enwiki-latest-pages-articles.xml.bz2, or enwiki-YYYYMMDD-pages-articles.xml.bz2 for date-specific dumps).
Second, convert the articles to WikiCorpus. WikiCorpus construct a corpus from a Wikipedia (or other MediaWiki-based) database dump.
For more details on WikiCorpus, you should access [Corpus from a Wikipedia dump](https://radimrehurek.com/gensim/corpora/wikicorpus.html).
```
wiki = WikiCorpus("enwiki-latest-pages-articles.xml.bz2")
#wiki = WikiCorpus("enwiki-YYYYMMDD-pages-articles.xml.bz2")
```
Define **TaggedWikiDocument** class to convert WikiCorpus into suitable form for Doc2Vec.
```
class TaggedWikiDocument(object):
def __init__(self, wiki):
self.wiki = wiki
self.wiki.metadata = True
def __iter__(self):
for content, (page_id, title) in self.wiki.get_texts():
yield TaggedDocument([c.decode("utf-8") for c in content], [title])
documents = TaggedWikiDocument(wiki)
```
## Preprocessing
To set the same vocabulary size with original papar. We first calculate the optimal **min_count** parameter.
```
pre = Doc2Vec(min_count=0)
pre.scan_vocab(documents)
for num in range(0, 20):
print('min_count: {}, size of vocab: '.format(num), pre.scale_vocab(min_count=num, dry_run=True)['memory']['vocab']/700)
```
In the original paper, they set the vocabulary size 915,715. It seems similar size of vocabulary if we set min_count = 19. (size of vocab = 898,725)
## Training the Doc2Vec Model
To train Doc2Vec model by several method, DBOW and DM, we define the list of models.
```
cores = multiprocessing.cpu_count()
models = [
# PV-DBOW
Doc2Vec(dm=0, dbow_words=1, size=200, window=8, min_count=19, iter=10, workers=cores),
# PV-DM w/average
Doc2Vec(dm=1, dm_mean=1, size=200, window=8, min_count=19, iter =10, workers=cores),
]
models[0].build_vocab(documents)
print(str(models[0]))
models[1].reset_from(models[0])
print(str(models[1]))
```
Now we’re ready to train Doc2Vec of the English Wikipedia.
```
for model in models:
%%time model.train(documents)
```
## Similarity interface
After that, let's test both models! DBOW model show the simillar results with the original paper. First, calculating cosine simillarity of "Machine learning" using Paragraph Vector. Word Vector and Document Vector are separately stored. We have to add .docvecs after model name to extract Document Vector from Doc2Vec Model.
```
for model in models:
print(str(model))
pprint(model.docvecs.most_similar(positive=["Machine learning"], topn=20))
```
DBOW model interpret the word 'Machine Learning' as a part of Computer Science field, and DM model as Data Science related field.
Second, calculating cosine simillarity of "Lady Gaga" using Paragraph Vector.
```
for model in models:
print(str(model))
pprint(model.docvecs.most_similar(positive=["Lady Gaga"], topn=10))
```
DBOW model reveal the similar singer in the U.S., and DM model understand that many of Lady Gaga's songs are similar with the word "Lady Gaga".
Third, calculating cosine simillarity of "Lady Gaga" - "American" + "Japanese" using Document vector and Word Vectors. "American" and "Japanese" are Word Vectors, not Paragraph Vectors. Word Vectors are already converted to lowercases by WikiCorpus.
```
for model in models:
print(str(model))
vec = [model.docvecs["Lady Gaga"] - model["american"] + model["japanese"]]
pprint([m for m in model.docvecs.most_similar(vec, topn=11) if m[0] != "Lady Gaga"])
```
As a result, DBOW model demonstrate the similar artists with Lady Gaga in Japan such as 'Perfume', which is the Most famous Idol in Japan. On the other hand, DM model results don't include the Japanese aritsts in top 10 simillar documents. It's almost same with no vector calculated results.
This results demonstrate that DBOW employed in the original paper is outstanding for calculating the similarity between Document Vector and Word Vector.
| github_jupyter |
# Regression Week 5: LASSO (coordinate descent)
In this notebook, you will implement your very own LASSO solver via coordinate descent. You will:
* Write a function to normalize features
* Implement coordinate descent for LASSO
* Explore effects of L1 penalty
# Fire up graphlab create
Make sure you have the latest version of graphlab (>= 1.7)
```
import graphlab
```
# Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
```
sales = graphlab.SFrame('kc_house_data.gl/')
# In the dataset, 'floors' was defined with type string,
# so we'll convert them to int, before using it below
sales['floors'] = sales['floors'].astype(int)
```
If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do this directly using the SFrames as seen in the first notebook of Week 2. For this notebook, however, we will work with the existing features.
# Import useful functions from previous notebook
As in Week 2, we convert the SFrame into a 2D Numpy array. Copy and paste `get_num_data()` from the second notebook of Week 2.
```
import numpy as np # note this allows us to refer to numpy as np instead
def get_numpy_data(data_sframe, features, output):
data_sframe['constant'] = 1 # this is how you add a constant column to an SFrame
# add the column 'constant' to the front of the features list so that we can extract it along with the others:
features = ['constant'] + features # this is how you combine two lists
# select the columns of data_SFrame given by the features list into the SFrame features_sframe (now including constant):
features_sframe = data_sframe[features]
# the following line will convert the features_SFrame into a numpy matrix:
feature_matrix = features_sframe.to_numpy()
# assign the column of data_sframe associated with the output to the SArray output_sarray
output_sarray = data_sframe[output]
# the following will convert the SArray into a numpy array by first converting it to a list
output_array = output_sarray.to_numpy()
return(feature_matrix, output_array)
```
Also, copy and paste the `predict_output()` function to compute the predictions for an entire matrix of features given the matrix and the weights:
```
def predict_output(feature_matrix, weights):
# assume feature_matrix is a numpy matrix containing the features as columns and weights is a corresponding numpy array
# create the predictions vector by using np.dot()
predictions = np.dot(feature_matrix, weights)
return(predictions)
```
# Normalize features
In the house dataset, features vary wildly in their relative magnitude: `sqft_living` is very large overall compared to `bedrooms`, for instance. As a result, weight for `sqft_living` would be much smaller than weight for `bedrooms`. This is problematic because "small" weights are dropped first as `l1_penalty` goes up.
To give equal considerations for all features, we need to **normalize features** as discussed in the lectures: we divide each feature by its 2-norm so that the transformed feature has norm 1.
Let's see how we can do this normalization easily with Numpy: let us first consider a small matrix.
```
X = np.array([[3.,5.,8.],[4.,12.,15.]])
print X
```
Numpy provides a shorthand for computing 2-norms of each column:
```
norms = np.linalg.norm(X, axis=0) # gives [norm(X[:,0]), norm(X[:,1]), norm(X[:,2])]
print norms
```
To normalize, apply element-wise division:
```
print X / norms # gives [X[:,0]/norm(X[:,0]), X[:,1]/norm(X[:,1]), X[:,2]/norm(X[:,2])]
```
Using the shorthand we just covered, write a short function called `normalize_features(feature_matrix)`, which normalizes columns of a given feature matrix. The function should return a pair `(normalized_features, norms)`, where the second item contains the norms of original features. As discussed in the lectures, we will use these norms to normalize the test data in the same way as we normalized the training data.
```
def normalize_features(feature_matrix):
norms = np.linalg.norm(feature_matrix, axis = 0)
normalized_features = feature_matrix / norms
return (normalized_features, norms)
```
To test the function, run the following:
```
features, norms = normalize_features(np.array([[3.,6.,9.],[4.,8.,12.]]))
print features
# should print
# [[ 0.6 0.6 0.6]
# [ 0.8 0.8 0.8]]
print norms
# should print
# [5. 10. 15.]
```
# Implementing Coordinate Descent with normalized features
We seek to obtain a sparse set of weights by minimizing the LASSO cost function
```
SUM[ (prediction - output)^2 ] + lambda*( |w[1]| + ... + |w[k]|).
```
(By convention, we do not include `w[0]` in the L1 penalty term. We never want to push the intercept to zero.)
The absolute value sign makes the cost function non-differentiable, so simple gradient descent is not viable (you would need to implement a method called subgradient descent). Instead, we will use **coordinate descent**: at each iteration, we will fix all weights but weight `i` and find the value of weight `i` that minimizes the objective. That is, we look for
```
argmin_{w[i]} [ SUM[ (prediction - output)^2 ] + lambda*( |w[1]| + ... + |w[k]|) ]
```
where all weights other than `w[i]` are held to be constant. We will optimize one `w[i]` at a time, circling through the weights multiple times.
1. Pick a coordinate `i`
2. Compute `w[i]` that minimizes the cost function `SUM[ (prediction - output)^2 ] + lambda*( |w[1]| + ... + |w[k]|)`
3. Repeat Steps 1 and 2 for all coordinates, multiple times
For this notebook, we use **cyclical coordinate descent with normalized features**, where we cycle through coordinates 0 to (d-1) in order, and assume the features were normalized as discussed above. The formula for optimizing each coordinate is as follows:
```
┌ (ro[i] + lambda/2) if ro[i] < -lambda/2
w[i] = ├ 0 if -lambda/2 <= ro[i] <= lambda/2
└ (ro[i] - lambda/2) if ro[i] > lambda/2
```
where
```
ro[i] = SUM[ [feature_i]*(output - prediction + w[i]*[feature_i]) ].
```
Note that we do not regularize the weight of the constant feature (intercept) `w[0]`, so, for this weight, the update is simply:
```
w[0] = ro[i]
```
## Effect of L1 penalty
Let us consider a simple model with 2 features:
```
simple_features = ['sqft_living', 'bedrooms']
my_output = 'price'
(simple_feature_matrix, output) = get_numpy_data(sales, simple_features, my_output)
```
Don't forget to normalize features:
```
simple_feature_matrix, norms = normalize_features(simple_feature_matrix)
```
We assign some random set of initial weights and inspect the values of `ro[i]`:
```
weights = np.array([1., 4., 1.])
```
Use `predict_output()` to make predictions on this data.
```
prediction = predict_output(simple_feature_matrix, weights)
```
Compute the values of `ro[i]` for each feature in this simple model, using the formula given above, using the formula:
```
ro[i] = SUM[ [feature_i]*(output - prediction + w[i]*[feature_i]) ]
```
*Hint: You can get a Numpy vector for feature_i using:*
```
simple_feature_matrix[:,i]
```
```
ro = [0,0]
for i in range(2):
ro[i] = (simple_feature_matrix[:,i] * (output - prediction + weights[i] * simple_feature_matrix[:,i])).sum()
```
***QUIZ QUESTION***
Recall that, whenever `ro[i]` falls between `-l1_penalty/2` and `l1_penalty/2`, the corresponding weight `w[i]` is sent to zero. Now suppose we were to take one step of coordinate descent on either feature 1 or feature 2. What range of values of `l1_penalty` **would not** set `w[1]` zero, but **would** set `w[2]` to zero, if we were to take a step in that coordinate?
```
print ro
```
***QUIZ QUESTION***
What range of values of `l1_penalty` would set **both** `w[1]` and `w[2]` to zero, if we were to take a step in that coordinate?
So we can say that `ro[i]` quantifies the significance of the i-th feature: the larger `ro[i]` is, the more likely it is for the i-th feature to be retained.
## Single Coordinate Descent Step
Using the formula above, implement coordinate descent that minimizes the cost function over a single feature i. Note that the intercept (weight 0) is not regularized. The function should accept feature matrix, output, current weights, l1 penalty, and index of feature to optimize over. The function should return new weight for feature i.
```
def lasso_coordinate_descent_step(i, feature_matrix, output, weights, l1_penalty):
# compute prediction
prediction = predict_output(feature_matrix, weights)
# compute ro[i] = SUM[ [feature_i]*(output - prediction + weight[i]*[feature_i]) ]
ro_i = (feature_matrix[:,i] * (output - prediction + weights[i] * feature_matrix[:,i])).sum()
if i == 0: # intercept -- do not regularize
new_weight_i = ro_i
elif ro_i < -l1_penalty/2.:
new_weight_i = ro_i + l1_penalty / 2
elif ro_i > l1_penalty/2.:
new_weight_i = ro_i - l1_penalty / 2
else:
new_weight_i = 0.
return new_weight_i
```
To test the function, run the following cell:
```
# should print 0.425558846691
import math
print lasso_coordinate_descent_step(1, np.array([[3./math.sqrt(13),1./math.sqrt(10)],[2./math.sqrt(13),3./math.sqrt(10)]]),
np.array([1., 1.]), np.array([1., 4.]), 0.1)
```
## Cyclical coordinate descent
Now that we have a function that optimizes the cost function over a single coordinate, let us implement cyclical coordinate descent where we optimize coordinates 0, 1, ..., (d-1) in order and repeat.
When do we know to stop? Each time we scan all the coordinates (features) once, we measure the change in weight for each coordinate. If no coordinate changes by more than a specified threshold, we stop.
For each iteration:
1. As you loop over features in order and perform coordinate descent, measure how much each coordinate changes.
2. After the loop, if the maximum change across all coordinates is falls below the tolerance, stop. Otherwise, go back to step 1.
Return weights
**IMPORTANT: when computing a new weight for coordinate i, make sure to incorporate the new weights for coordinates 0, 1, ..., i-1. One good way is to update your weights variable in-place. See following pseudocode for illustration.**
```
for i in range(len(weights)):
old_weights_i = weights[i] # remember old value of weight[i], as it will be overwritten
# the following line uses new values for weight[0], weight[1], ..., weight[i-1]
# and old values for weight[i], ..., weight[d-1]
weights[i] = lasso_coordinate_descent_step(i, feature_matrix, output, weights, l1_penalty)
# use old_weights_i to compute change in coordinate
...
```
```
def lasso_cyclical_coordinate_descent(feature_matrix, output, initial_weights, l1_penalty, tolerance):
weights = initial_weights
max_change = 2 * tolerance
while max_change >= tolerance:
max_change = 0
for i in range(len(initial_weights)):
old_weights_i = weights[i]
weights[i] = lasso_coordinate_descent_step(i, feature_matrix, output, weights, l1_penalty)
if abs(old_weights_i - weights[i]) > max_change:
max_change = abs(old_weights_i - weights[i])
return weights
```
Using the following parameters, learn the weights on the sales dataset.
```
simple_features = ['sqft_living', 'bedrooms']
my_output = 'price'
initial_weights = np.zeros(3)
l1_penalty = 1e7
tolerance = 1.0
```
First create a normalized version of the feature matrix, `normalized_simple_feature_matrix`
```
(simple_feature_matrix, output) = get_numpy_data(sales, simple_features, my_output)
(normalized_simple_feature_matrix, simple_norms) = normalize_features(simple_feature_matrix) # normalize features
```
Then, run your implementation of LASSO coordinate descent:
```
weights = lasso_cyclical_coordinate_descent(normalized_simple_feature_matrix, output,
initial_weights, l1_penalty, tolerance)
prediction = predict_output(normalized_simple_feature_matrix, weights)
residuals = prediction - output
RSS = (residuals * residuals).sum()
print RSS
print weights
```
***QUIZ QUESTIONS***
1. What is the RSS of the learned model on the normalized dataset?
2. Which features had weight zero at convergence?
# Evaluating LASSO fit with more features
Let us split the sales dataset into training and test sets.
```
train_data,test_data = sales.random_split(.8,seed=0)
```
Let us consider the following set of features.
```
all_features = ['bedrooms',
'bathrooms',
'sqft_living',
'sqft_lot',
'floors',
'waterfront',
'view',
'condition',
'grade',
'sqft_above',
'sqft_basement',
'yr_built',
'yr_renovated']
```
First, create a normalized feature matrix from the TRAINING data with these features. (Make you store the norms for the normalization, since we'll use them later)
```
my_output = "price"
(feature_matrix, output) = get_numpy_data(train_data, all_features, my_output)
(normalized_feature_matrix, norms) = normalize_features(feature_matrix)
```
First, learn the weights with `l1_penalty=1e7`, on the training data. Initialize weights to all zeros, and set the `tolerance=1`. Call resulting weights `weights1e7`, you will need them later.
```
initial_weights = np.zeros(len(all_features) + 1)
l1_penalty = 1e7
tolerance = 1
weights1e7 = lasso_cyclical_coordinate_descent(normalized_feature_matrix, output,
initial_weights, l1_penalty, tolerance)
for i in range(len(all_features) + 1):
if i > 0 and weights1e7[i] != 0:
print all_features[i - 1]
if i == 0 and weights1e8[i] != 0:
print "constant"
```
***QUIZ QUESTION***
What features had non-zero weight in this case?
Next, learn the weights with `l1_penalty=1e8`, on the training data. Initialize weights to all zeros, and set the `tolerance=1`. Call resulting weights `weights1e8`, you will need them later.
```
initial_weights = np.zeros(len(all_features) + 1)
l1_penalty = 1e8
tolerance = 1
weights1e8 = lasso_cyclical_coordinate_descent(normalized_feature_matrix, output,
initial_weights, l1_penalty, tolerance)
for i in range(len(all_features) + 1):
if i > 0 and weights1e8[i] != 0:
print all_features[i - 1]
if i == 0 and weights1e8[i] != 0:
print "constant"
```
***QUIZ QUESTION***
What features had non-zero weight in this case?
Finally, learn the weights with `l1_penalty=1e4`, on the training data. Initialize weights to all zeros, and set the `tolerance=5e5`. Call resulting weights `weights1e4`, you will need them later. (This case will take quite a bit longer to converge than the others above.)
```
initial_weights = np.zeros(len(all_features) + 1)
l1_penalty = 1e4
tolerance = 5e5
weights1e4 = lasso_cyclical_coordinate_descent(normalized_feature_matrix, output,
initial_weights, l1_penalty, tolerance)
for i in range(len(all_features) + 1):
if i > 0 and weights1e4[i] != 0:
print all_features[i - 1]
if i == 0 and weights1e8[i] != 0:
print "constant"
```
***QUIZ QUESTION***
What features had non-zero weight in this case?
## Rescaling learned weights
Recall that we normalized our feature matrix, before learning the weights. To use these weights on a test set, we must normalize the test data in the same way.
Alternatively, we can rescale the learned weights to include the normalization, so we never have to worry about normalizing the test data:
In this case, we must scale the resulting weights so that we can make predictions with *original* features:
1. Store the norms of the original features to a vector called `norms`:
```
features, norms = normalize_features(features)
```
2. Run Lasso on the normalized features and obtain a `weights` vector
3. Compute the weights for the original features by performing element-wise division, i.e.
```
weights_normalized = weights / norms
```
Now, we can apply `weights_normalized` to the test data, without normalizing it!
Create a normalized version of each of the weights learned above. (`weights1e4`, `weights1e7`, `weights1e8`).
To check your results, if you call `normalized_weights1e7` the normalized version of `weights1e7`, then:
```
print normalized_weights1e7[3]
```
should return 161.31745624837794.
## Evaluating each of the learned models on the test data
Let's now evaluate the three models on the test data:
```
(test_feature_matrix, test_output) = get_numpy_data(test_data, all_features, 'price')
```
Compute the RSS of each of the three normalized weights on the (unnormalized) `test_feature_matrix`:
***QUIZ QUESTION***
Which model performed best on the test data?
| github_jupyter |
```
%matplotlib inline
```
Postprocessing Tutorial
=======================
Spike sorters generally output a set of units with corresponding spike trains. The :code:`toolkit.postprocessing`
submodule allows to combine the :code:`RecordingExtractor` and the sorted :code:`SortingExtractor` objects to perform
further postprocessing.
```
import matplotlib.pylab as plt
import spikeinterface.extractors as se
import spikeinterface.toolkit as st
```
First, let's create a toy example:
```
recording, sorting = se.example_datasets.toy_example(num_channels=4, duration=10, seed=0)
```
Assuming the :code:`sorting` is the output of a spike sorter, the
:code:`postprocessing` module allows to extract all relevant information
from the paired recording-sorting.
Compute spike waveforms
--------------------------
Waveforms are extracted with the :code:`get_unit_waveforms` function by
extracting snippets of the recordings when spikes are detected. When
waveforms are extracted, the can be loaded in the :code:`SortingExtractor`
object as features. The ms before and after the spike event can be
chosen. Waveforms are returned as a list of np.arrays (n\_spikes,
n\_channels, n\_points)
```
wf = st.postprocessing.get_unit_waveforms(recording, sorting, ms_before=1, ms_after=2,
save_as_features=True, verbose=True)
```
Now :code:`waveforms` is a unit spike feature!
```
print(sorting.get_shared_unit_spike_feature_names())
print(wf[0].shape)
```
plotting waveforms of units 0,1,2 on channel 0
```
fig, ax = plt.subplots()
ax.plot(wf[0][:, 0, :].T, color='k', lw=0.3)
ax.plot(wf[1][:, 0, :].T, color='r', lw=0.3)
_=ax.plot(wf[2][:, 0, :].T, color='b', lw=0.3)
```
If the a certain property (e.g. :code:`group`) is present in the
RecordingExtractor, the waveforms can be extracted only on the channels
with that property using the :code:`grouping_property` and
:code:`compute_property_from_recording` arguments. For example, if channel
[0,1] are in group 0 and channel [2,3] are in group 2, then if the peak
of the waveforms is in channel [0,1] it will be assigned to group 0 and
will have 2 channels and the same for group 1.
```
channel_groups = [[0, 1], [2, 3]]
for ch in recording.get_channel_ids():
for gr, channel_group in enumerate(channel_groups):
if ch in channel_group:
recording.set_channel_property(ch, 'group', gr)
print(recording.get_channel_property(0, 'group'), recording.get_channel_property(2, 'group'))
wf_by_group = st.postprocessing.get_unit_waveforms(recording, sorting, ms_before=1, ms_after=2,
save_as_features=False, verbose=True,
grouping_property='group',
compute_property_from_recording=True)
# now waveforms will only have 2 channels
print(wf_by_group[0].shape)
```
Compute unit templates
--------------------------
Similarly to waveforms, templates - average waveforms - can be easily
extracted using the :code:`get_unit_templates`. When spike trains have
numerous spikes, you can set the :code:`max_spikes_per_unit` to be extracted.
If waveforms have already been computed and stored as :code:`features`, those
will be used. Templates can be saved as unit properties.
```
templates = st.postprocessing.get_unit_templates(recording, sorting, max_spikes_per_unit=200,
save_as_property=True, verbose=True)
print(sorting.get_shared_unit_property_names())
```
Plotting templates of units 0,1,2 on all four channels
```
fig, ax = plt.subplots()
ax.plot(templates[0].T, color='k')
ax.plot(templates[1].T, color='r')
ax.plot(templates[2].T, color='b')
```
Compute unit maximum channel
-------------------------------
In the same way, one can get the ecording channel with the maximum
amplitude and save it as a property.
```
max_chan = st.postprocessing.get_unit_max_channels(recording, sorting, save_as_property=True, verbose=True)
print(max_chan)
print(sorting.get_shared_unit_property_names())
```
Compute pca scores
---------------------
For some applications, for example validating the spike sorting output,
PCA scores can be computed.
```
pca_scores = st.postprocessing.compute_unit_pca_scores(recording, sorting, n_comp=3, verbose=True)
for pc in pca_scores:
print(pc.shape)
fig, ax = plt.subplots()
ax.plot(pca_scores[0][:, 0], pca_scores[0][:, 1], 'r*')
ax.plot(pca_scores[2][:, 0], pca_scores[2][:, 1], 'b*')
```
PCA scores can be also computed electrode-wise. In the previous example,
PCA was applied to the concatenation of the waveforms over channels.
```
pca_scores_by_electrode = st.postprocessing.compute_unit_pca_scores(recording, sorting, n_comp=3, by_electrode=True)
for pc in pca_scores_by_electrode:
print(pc.shape)
```
In this case, as expected, 3 principal components are extracted for each
electrode.
```
fig, ax = plt.subplots()
ax.plot(pca_scores_by_electrode[0][:, 0, 0], pca_scores_by_electrode[0][:, 1, 0], 'r*')
ax.plot(pca_scores_by_electrode[2][:, 0, 0], pca_scores_by_electrode[2][:, 1, 1], 'b*')
```
Export sorted data to Phy for manual curation
-----------------------------------------------
Finally, it is common to visualize and manually curate the data after
spike sorting. In order to do so, we interface wiht the Phy
(https://phy-contrib.readthedocs.io/en/latest/template-gui/).
First, we need to export the data to the phy format:
```
st.postprocessing.export_to_phy(recording, sorting, output_folder='phy', verbose=True)
!phy template-gui /home/alexgonzalez/Documents/TreeMazeAnalyses/Notebooks/spikeinterface_examples/phy/params.py
```
To run phy you can then run (from terminal):
:code:`phy template-gui phy/params.py`
Or from a notebook: :code:`!phy template-gui phy/params.py`
After manual curation you can load back the curated data using the :code:`PhySortingExtractor`:
| github_jupyter |
<img src='images/pic1.jpg'/>
```
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import sqlite3
import csv
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from wordcloud import WordCloud
import re
import os
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score
import numpy as np
from sqlalchemy import create_engine # database connection
import datetime as dt
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem.snowball import SnowballStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import SGDClassifier
from sklearn import metrics
from sklearn.metrics import f1_score,precision_score,recall_score
from sklearn import svm
from sklearn.linear_model import LogisticRegression
from skmultilearn.adapt import mlknn
from skmultilearn.problem_transform import ClassifierChain
from skmultilearn.problem_transform import BinaryRelevance
from skmultilearn.problem_transform import LabelPowerset
from sklearn.naive_bayes import GaussianNB
from datetime import datetime
import pickle
from sklearn.externals import joblib
```
# Stack Overflow: Tag Prediction
<h1>1. Business Problem </h1>
<h2> 1.1 Description </h2>
<p style='font-size:18px'><b> Description </b></p>
<p>
Stack Overflow is the largest, most trusted online community for developers to learn, share their programming knowledge, and build their careers.<br />
<br />
Stack Overflow is something which every programmer use one way or another. Each month, over 50 million developers come to Stack Overflow to learn, share their knowledge, and build their careers. It features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. As of April 2014 Stack Overflow has over 4,000,000 registered users, and it exceeded 10,000,000 questions in late August 2015. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML.<br />
<br />
</p>
<p style='font-size:18px'><b> Problem Statemtent </b></p>
Suggest the tags based on the content that was there in the question posted on Stackoverflow.
<h2> 1.2 Real World / Business Objectives and Constraints </h2>
1. Predict as many tags as possible with high precision and recall.
2. Incorrect tags could impact customer experience on StackOverflow.
3. No strict latency constraints.
<h1>2. Machine Learning problem </h1>
<h2> 2.1 Data </h2>
<h3> 2.1.1 Data Overview </h3>
Refer: https://www.kaggle.com/c/facebook-recruiting-iii-keyword-extraction/data
<br>
All of the data is in 2 files: Train and Test.<br />
<pre>
<b>Train.csv</b> contains 4 columns: Id,Title,Body,Tags.<br />
<b>Test.csv</b> contains the same columns but without the Tags, which you are to predict.<br />
<b>Size of Train.csv</b> - 6.75GB<br />
<b>Size of Test.csv</b> - 2GB<br />
<b>Number of rows in Train.csv</b> = 6034195<br />
</pre>
The questions are randomized and contains a mix of verbose text sites as well as sites related to math and programming. The number of questions from each site may vary, and no filtering has been performed on the questions (such as closed questions).<br />
<br />
__Data Field Explaination__
Dataset contains 6,034,195 rows. The columns in the table are:<br />
<pre>
<b>Id</b> - Unique identifier for each question<br />
<b>Title</b> - The question's title<br />
<b>Body</b> - The body of the question<br />
<b>Tags</b> - The tags associated with the question in a space-seperated format (all lowercase, should not contain tabs '\t' or ampersands '&')<br />
</pre>
<br />
<h3>2.1.2 Example Data point </h3>
<pre>
<b>Title</b>: Implementing Boundary Value Analysis of Software Testing in a C++ program?
<b>Body </b>: <pre><code>
#include<
iostream>\n
#include<
stdlib.h>\n\n
using namespace std;\n\n
int main()\n
{\n
int n,a[n],x,c,u[n],m[n],e[n][4];\n
cout<<"Enter the number of variables";\n cin>>n;\n\n
cout<<"Enter the Lower, and Upper Limits of the variables";\n
for(int y=1; y<n+1; y++)\n
{\n
cin>>m[y];\n
cin>>u[y];\n
}\n
for(x=1; x<n+1; x++)\n
{\n
a[x] = (m[x] + u[x])/2;\n
}\n
c=(n*4)-4;\n
for(int a1=1; a1<n+1; a1++)\n
{\n\n
e[a1][0] = m[a1];\n
e[a1][1] = m[a1]+1;\n
e[a1][2] = u[a1]-1;\n
e[a1][3] = u[a1];\n
}\n
for(int i=1; i<n+1; i++)\n
{\n
for(int l=1; l<=i; l++)\n
{\n
if(l!=1)\n
{\n
cout<<a[l]<<"\\t";\n
}\n
}\n
for(int j=0; j<4; j++)\n
{\n
cout<<e[i][j];\n
for(int k=0; k<n-(i+1); k++)\n
{\n
cout<<a[k]<<"\\t";\n
}\n
cout<<"\\n";\n
}\n
} \n\n
system("PAUSE");\n
return 0; \n
}\n
</code></pre>\n\n
<p>The answer should come in the form of a table like</p>\n\n
<pre><code>
1 50 50\n
2 50 50\n
99 50 50\n
100 50 50\n
50 1 50\n
50 2 50\n
50 99 50\n
50 100 50\n
50 50 1\n
50 50 2\n
50 50 99\n
50 50 100\n
</code></pre>\n\n
<p>if the no of inputs is 3 and their ranges are\n
1,100\n
1,100\n
1,100\n
(could be varied too)</p>\n\n
<p>The output is not coming,can anyone correct the code or tell me what\'s wrong?</p>\n'
<b>Tags </b>: 'c++ c'
</pre>
<h1> 3. Exploratory Data Analysis </h1>
<h2> 3.1 Data Loading and Cleaning </h2>
<h3>3.1.1 Using Pandas with SQLite to Load the data</h3>
```
import zipfile
archive = zipfile.ZipFile('Train.zip', 'r')
csvfile = archive.open('Train.csv')
#Creating db file from csv
#Learn SQL: https://www.w3schools.com/sql/default.asp
if not os.path.isfile('train.db'):
start = datetime.now()
disk_engine = create_engine('sqlite:///train.db')
start = dt.datetime.now()
chunksize = 180000
j = 0
index_start = 1
for df in pd.read_csv(csvfile, names=['Id', 'Title', 'Body', 'Tags'], chunksize=chunksize, iterator=True, encoding='utf-8', ):
df.index += index_start
j+=1
print('{} rows'.format(j*chunksize))
df.to_sql('data', disk_engine, if_exists='append')
index_start = df.index[-1] + 1
print("Time taken to run this cell :", datetime.now() - start)
```
<h3> 3.1.2 Counting the number of rows </h3>
```
if os.path.isfile('train.db'):
start = datetime.now()
con = sqlite3.connect('train.db')
num_rows = pd.read_sql_query("""SELECT count(*) FROM data""", con)
#Always remember to close the database
print("Number of rows in the database :","\n",num_rows['count(*)'].values[0])
con.close()
print("Time taken to count the number of rows :", datetime.now() - start)
else:
print("Please download the train.db file from drive or run the above cell to genarate train.db file")
```
<h3>3.1.3 Checking for duplicates </h3>
```
#Learn SQl: https://www.w3schools.com/sql/default.asp
if os.path.isfile('train.db'):
start = datetime.now()
con = sqlite3.connect('train.db')
df_no_dup = pd.read_sql_query('SELECT Title, Body, Tags, COUNT(*) as cnt_dup FROM data GROUP BY Title, Body, Tags', con)
con.close()
print("Time taken to run this cell :", datetime.now() - start)
else:
print("Please download the train.db file from drive or run the first to genarate train.db file")
df_no_dup.head()
# we can observe that there are duplicates
print("number of duplicate questions :", num_rows['count(*)'].values[0]- df_no_dup.shape[0], "(",(1-((df_no_dup.shape[0])/(num_rows['count(*)'].values[0])))*100,"% )")
# number of times each question appeared in our database
df_no_dup.cnt_dup.value_counts()
print(df_no_dup.head())
start = datetime.now()
aa_count=[]
hh=[]
for j in range(len(df_no_dup)):
tex=df_no_dup['Tags'][j]
#print(tex)
if tex is not None:
#print("heyram")
#start=datetime.now()
hh.append(tex)
text=len(tex.split(" ") )
#print(text)
aa_count.append(text)
print(len(aa_count))
aaa=pd.DataFrame(aa_count,columns=['tag_count'])
hhh=pd.DataFrame(hh,columns=['Tags'])
df_no_dup=pd.concat([hhh,aaa],axis=1)
# adding a new feature number of tags per question
print("Time taken to run this cell :", datetime.now() - start)
df_no_dup.head()
np.where(pd.isnull(df_no_dup))
df_no_dup=df_no_dup.dropna()
start = datetime.now()
df_no_dup["tag_count"] = df_no_dup["Tags"].apply(lambda text: len(text.split(" ")))
# adding a new feature number of tags per question
print("Time taken to run this cell :", datetime.now() - start)
df_no_dup.head()
# distribution of number of tags per question
df_no_dup.tag_count.value_counts()
#Creating a new database with no duplicates
if not os.path.isfile('train_no_dup.db'):
disk_dup = create_engine("sqlite:///train_no_dup.db")
no_dup = pd.DataFrame(df_no_dup, columns=['Title', 'Body', 'Tags'])
no_dup.to_sql('no_dup_train',disk_dup)
#This method seems more appropriate to work with this much data.
#creating the connection with database file.
if os.path.isfile('train_no_dup.db'):
start = datetime.now()
con = sqlite3.connect('train_no_dup.db')
tag_data = pd.read_sql_query("""SELECT Tags FROM no_dup_train""", con)
#Always remember to close the database
con.close()
# Let's now drop unwanted column.
tag_data.drop(tag_data.index[0], inplace=True)
#Printing first 5 columns from our data frame
tag_data.head()
print("Time taken to run this cell :", datetime.now() - start)
else:
print("Please download the train.db file from drive or run the above cells to genarate train.db file")
```
<h2> 3.2 Analysis of Tags </h2>
<h3> 3.2.1 Total number of unique tags </h3>
```
tag_data=tag_data.dropna()
# Taking only 0.5 million data points
#tag_data=tag_data[0:10000]
print(tag_data.head())
print(len(tag_data))
# Importing & Initializing the "CountVectorizer" object, which
#is scikit-learn's bag of words tool.
#by default 'split()' will tokenize each tag using space.
vectorizer = CountVectorizer(tokenizer = lambda x: x.split())
# fit_transform() does two functions: First, it fits the model
# and learns the vocabulary; second, it transforms our training data
# into feature vectors. The input to fit_transform should be a list of strings.
tag_dtm = vectorizer.fit_transform(tag_data['Tags'])
print("Number of data points :", tag_dtm.shape[0])
print("Number of unique tags :", tag_dtm.shape[1])
#'get_feature_name()' gives us the vocabulary.
tags = vectorizer.get_feature_names()
#Lets look at the tags we have.
print("Some of the tags we have :", tags[:10])
```
<h3> 3.2.3 Number of times a tag appeared </h3>
```
# https://stackoverflow.com/questions/15115765/how-to-access-sparse-matrix-elements
#Lets now store the document term matrix in a dictionary.
freqs = tag_dtm.sum(axis=0).A1
result = dict(zip(tags, freqs))
#print(result)
#Saving this dictionary to csv files.
if not os.path.isfile('tag_counts_dict_dtm.csv'):
with open('tag_counts_dict_dtm.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in result.items():
writer.writerow([key, value])
tag_df = pd.read_csv("tag_counts_dict_dtm.csv", names=['Tags', 'Counts'])
tag_df.head()
tag_df_sorted = tag_df.sort_values(['Counts'], ascending=False)
tag_counts = tag_df_sorted['Counts'].values
plt.plot(tag_counts)
plt.title("Distribution of number of times tag appeared questions")
plt.grid()
plt.xlabel("Tag number")
plt.ylabel("Number of times tag appeared")
plt.show()
plt.plot(tag_counts[0:10000])
plt.title('first 10k tags: Distribution of number of times tag appeared questions')
plt.grid()
plt.xlabel("Tag number")
plt.ylabel("Number of times tag appeared")
plt.show()
print(len(tag_counts[0:10000:25]), tag_counts[0:10000:25])
plt.plot(tag_counts[0:1000])
plt.title('first 1k tags: Distribution of number of times tag appeared questions')
plt.grid()
plt.xlabel("Tag number")
plt.ylabel("Number of times tag appeared")
plt.show()
print(len(tag_counts[0:1000:5]), tag_counts[0:1000:5])
plt.plot(tag_counts[0:500])
plt.title('first 500 tags: Distribution of number of times tag appeared questions')
plt.grid()
plt.xlabel("Tag number")
plt.ylabel("Number of times tag appeared")
plt.show()
print(len(tag_counts[0:500:5]), tag_counts[0:500:5])
plt.plot(tag_counts[0:100], c='b')
plt.scatter(x=list(range(0,100,5)), y=tag_counts[0:100:5], c='orange', label="quantiles with 0.05 intervals")
# quantiles with 0.25 difference
plt.scatter(x=list(range(0,100,25)), y=tag_counts[0:100:25], c='m', label = "quantiles with 0.25 intervals")
for x,y in zip(list(range(0,100,25)), tag_counts[0:100:25]):
plt.annotate(s="({} , {})".format(x,y), xy=(x,y), xytext=(x-0.05, y+500))
plt.title('first 100 tags: Distribution of number of times tag appeared questions')
plt.grid()
plt.xlabel("Tag number")
plt.ylabel("Number of times tag appeared")
plt.legend()
plt.show()
print(len(tag_counts[0:100:5]), tag_counts[0:100:5])
# Store tags greater than 10K in one list
lst_tags_gt_10k = tag_df[tag_df.Counts>10000].Tags
#Print the length of the list
print ('{} Tags are used more than 10000 times'.format(len(lst_tags_gt_10k)))
# Store tags greater than 100K in one list
lst_tags_gt_100k = tag_df[tag_df.Counts>100000].Tags
#Print the length of the list.
print ('{} Tags are used more than 100000 times'.format(len(lst_tags_gt_100k)))
```
<b>Observations:</b><br />
1. There are total 153 tags which are used more than 10000 times.
2. 14 tags are used more than 100000 times.
3. Most frequent tag (i.e. c#) is used 331505 times.
4. Since some tags occur much more frequenctly than others, Micro-averaged F1-score is the appropriate metric for this probelm.
<h3> 3.2.4 Tags Per Question </h3>
```
#Storing the count of tag in each question in list 'tag_count'
tag_quest_count = tag_dtm.sum(axis=1).tolist()
#Converting each value in the 'tag_quest_count' to integer.
tag_quest_count=[int(j) for i in tag_quest_count for j in i]
print ('We have total {} datapoints.'.format(len(tag_quest_count)))
print(tag_quest_count[:5])
print( "Maximum number of tags per question: %d"%max(tag_quest_count))
print( "Minimum number of tags per question: %d"%min(tag_quest_count))
print( "Avg. number of tags per question: %f"% ((sum(tag_quest_count)*1.0)/len(tag_quest_count)))
sns.countplot(tag_quest_count, palette='gist_rainbow')
plt.title("Number of tags in the questions ")
plt.xlabel("Number of Tags")
plt.ylabel("Number of questions")
plt.show()
```
<b>Observations:</b><br />
1. Maximum number of tags per question: 5
2. Minimum number of tags per question: 1
3. Avg. number of tags per question: 2.899
4. Most of the questions are having 2 or 3 tags
<h3> 3.2.5 The top 20 tags </h3>
```
i=np.arange(30)
tag_df_sorted.head(30).plot(kind='bar')
plt.title('Frequency of top 20 tags')
plt.xticks(i, tag_df_sorted['Tags'])
plt.xlabel('Tags')
plt.ylabel('Counts')
plt.show()
```
<b>Observations:</b><br />
1. Majority of the most frequent tags are programming language.
2. C# is the top most frequent programming language.
3. Android, IOS, Linux and windows are among the top most frequent operating systems.
<h3> 3.3 Cleaning and preprocessing of Questions </h3>
<h3> 3.3.1 Preprocessing </h3>
<ol>
<li> Sample 0.5M data points </li>
<li> Separate out code-snippets from Body </li>
<li> Remove Spcial characters from Question title and description (not in code)</li>
<li> Remove stop words (Except 'C') </li>
<li> Remove HTML Tags </li>
<li> Convert all the characters into small letters </li>
<li> Use SnowballStemmer to stem the words </li>
</ol>
```
import nltk
nltk.download('stopwords')
def striphtml(data):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, ' ', str(data))
return cleantext
stop_words = set(stopwords.words('english'))
stemmer = SnowballStemmer("english")
#http://www.sqlitetutorial.net/sqlite-python/create-tables/
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def checkTableExists(dbcon):
cursr = dbcon.cursor()
str = "select name from sqlite_master where type='table'"
table_names = cursr.execute(str)
print("Tables in the databse:")
tables =table_names.fetchall()
print(tables[0][0])
return(len(tables))
def create_database_table(database, query):
conn = create_connection(database)
if conn is not None:
create_table(conn, query)
checkTableExists(conn)
else:
print("Error! cannot create the database connection.")
conn.close()
sql_create_table = """CREATE TABLE IF NOT EXISTS QuestionsProcessed (question text NOT NULL, code text, tags text, words_pre integer, words_post integer, is_code integer);"""
create_database_table("Processed.db", sql_create_table)
```
__ we create a new data base to store the sampled and preprocessed questions __
```
nltk.download('punkt')
print("\n")
```
<h1>4. Machine Learning Models </h1>
<h2> 4.1 Converting tags for multilabel problems </h2>
<table>
<tr>
<th>X</th><th>y1</th><th>y2</th><th>y3</th><th>y4</th>
</tr>
<tr>
<td>x1</td><td>0</td><td>1</td><td>1</td><td>0</td>
</tr>
<tr>
<td>x1</td><td>1</td><td>0</td><td>0</td><td>0</td>
</tr>
<tr>
<td>x1</td><td>0</td><td>1</td><td>0</td><td>0</td>
</tr>
</table>
<h2> 4.5 Modeling with less data points (0.5M data points) and more weight to title and 500 tags only. </h2>
```
sql_create_table = """CREATE TABLE IF NOT EXISTS QuestionsProcessed (question text NOT NULL, code text, tags text, words_pre integer, words_post integer, is_code integer);"""
create_database_table("Titlemoreweight.db", sql_create_table)
# http://www.sqlitetutorial.net/sqlite-delete/
# https://stackoverflow.com/questions/2279706/select-random-row-from-a-sqlite-table
read_db = 'train_no_dup.db'
write_db = 'Titlemoreweight.db'
train_datasize = 400000
if os.path.isfile(read_db):
conn_r = create_connection(read_db)
if conn_r is not None:
reader =conn_r.cursor()
# for selecting first 0.5M rows
reader.execute("SELECT Title, Body, Tags From no_dup_train LIMIT 500001;")
# for selecting random points
#reader.execute("SELECT Title, Body, Tags From no_dup_train ORDER BY RANDOM() LIMIT 500001;")
if os.path.isfile(write_db):
conn_w = create_connection(write_db)
if conn_w is not None:
tables = checkTableExists(conn_w)
writer =conn_w.cursor()
if tables != 0:
writer.execute("DELETE FROM QuestionsProcessed WHERE 1")
print("Cleared All the rows")
```
<h3> 4.5.1 Preprocessing of questions </h3>
<ol>
<li> Separate Code from Body </li>
<li> Remove Spcial characters from Question title and description (not in code)</li>
<li> <b> Give more weightage to title : Add title three times to the question </b> </li>
<li> Remove stop words (Except 'C') </li>
<li> Remove HTML Tags </li>
<li> Convert all the characters into small letters </li>
<li> Use SnowballStemmer to stem the words </li>
</ol>
```
#http://www.bernzilla.com/2008/05/13/selecting-a-random-row-from-an-sqlite-table/
start = datetime.now()
preprocessed_data_list=[]
reader.fetchone()
questions_with_code=0
len_pre=0
len_post=0
questions_proccesed = 0
for row in reader:
is_code = 0
title, question, tags = row[0], row[1], str(row[2])
if '<code>' in question:
questions_with_code+=1
is_code = 1
x = len(question)+len(title)
len_pre+=x
code = str(re.findall(r'<code>(.*?)</code>', question, flags=re.DOTALL))
question=re.sub('<code>(.*?)</code>', '', question, flags=re.MULTILINE|re.DOTALL)
question=striphtml(question.encode('utf-8'))
title=title.encode('utf-8')
# adding title three time to the data to increase its weight
# add tags string to the training data
question=str(title)+" "+str(title)+" "+str(title)+" "+question
# if questions_proccesed<=train_datasize:
# question=str(title)+" "+str(title)+" "+str(title)+" "+question+" "+str(tags)
# else:
# question=str(title)+" "+str(title)+" "+str(title)+" "+question
question=re.sub(r'[^A-Za-z0-9#+.\-]+',' ',question)
words=word_tokenize(str(question.lower()))
#Removing all single letter and and stopwords from question exceptt for the letter 'c'
question=' '.join(str(stemmer.stem(j)) for j in words if j not in stop_words and (len(j)!=1 or j=='c'))
len_post+=len(question)
tup = (question,code,tags,x,len(question),is_code)
questions_proccesed += 1
writer.execute("insert into QuestionsProcessed(question,code,tags,words_pre,words_post,is_code) values (?,?,?,?,?,?)",tup)
if (questions_proccesed%100000==0):
print("number of questions completed=",questions_proccesed)
no_dup_avg_len_pre=(len_pre*1.0)/questions_proccesed
no_dup_avg_len_post=(len_post*1.0)/questions_proccesed
print( "Avg. length of questions(Title+Body) before processing: %d"%no_dup_avg_len_pre)
print( "Avg. length of questions(Title+Body) after processing: %d"%no_dup_avg_len_post)
print ("Percent of questions containing code: %d"%((questions_with_code*100.0)/questions_proccesed))
print("Time taken to run this cell :", datetime.now() - start)
# never forget to close the conections or else we will end up with database locks
conn_r.commit()
conn_w.commit()
conn_r.close()
conn_w.close()
```
__ Sample quesitons after preprocessing of data __
```
if os.path.isfile(write_db):
conn_r = create_connection(write_db)
if conn_r is not None:
reader =conn_r.cursor()
reader.execute("SELECT question From QuestionsProcessed LIMIT 10")
print("Questions after preprocessed")
print('='*100)
reader.fetchone()
for row in reader:
print(row)
print('-'*100)
conn_r.commit()
conn_r.close()
```
__ Saving Preprocessed data to a Database __
```
#Taking 0.5 Million entries to a dataframe.
write_db = 'Titlemoreweight.db'
if os.path.isfile(write_db):
conn_r = create_connection(write_db)
if conn_r is not None:
preprocessed_data = pd.read_sql_query("""SELECT question, Tags FROM QuestionsProcessed""", conn_r)
conn_r.commit()
conn_r.close()
preprocessed_data.head()
print("number of data points in sample :", preprocessed_data.shape[0])
print("number of dimensions :", preprocessed_data.shape[1])
```
__ Converting string Tags to multilable output variables __
```
vectorizer = CountVectorizer(tokenizer = lambda x: x.split(), binary='true')
multilabel_y = vectorizer.fit_transform(preprocessed_data['tags'])
```
__ Selecting 500 Tags __
```
def tags_to_choose(n):
t = multilabel_y.sum(axis=0).tolist()[0]
sorted_tags_i = sorted(range(len(t)), key=lambda i: t[i], reverse=True)
multilabel_yn=multilabel_y[:,sorted_tags_i[:n]]
return multilabel_yn
def questions_explained_fn(n):
multilabel_yn = tags_to_choose(n)
x= multilabel_yn.sum(axis=1)
return (np.count_nonzero(x==0))
questions_explained = []
total_tags=multilabel_y.shape[1]
total_qs=preprocessed_data.shape[0]
for i in range(500, total_tags, 100):
questions_explained.append(np.round(((total_qs-questions_explained_fn(i))/total_qs)*100,3))
fig, ax = plt.subplots()
ax.plot(questions_explained)
xlabel = list(500+np.array(range(-50,450,50))*50)
ax.set_xticklabels(xlabel)
plt.xlabel("Number of tags")
plt.ylabel("Number Questions coverd partially")
plt.grid()
plt.show()
# you can choose any number of tags based on your computing power, minimun is 500(it covers 90% of the tags)
print("with ",5500,"tags we are covering ",questions_explained[50],"% of questions")
print("with ",500,"tags we are covering ",questions_explained[0],"% of questions")
# we will be taking 500 tags
multilabel_yx = tags_to_choose(500)
print("number of questions that are not covered :", questions_explained_fn(500),"out of ", total_qs)
from sklearn.externals import joblib
joblib.dump(preprocessed_data, 'preprocessed_data.pkl')
x_train=preprocessed_data.head(train_datasize)
x_test=preprocessed_data.tail(preprocessed_data.shape[0] - 400000)
y_train = multilabel_yx[0:train_datasize,:]
y_test = multilabel_yx[train_datasize:preprocessed_data.shape[0],:]
print("Number of data points in train data :", y_train.shape)
print("Number of data points in test data :", y_test.shape)
```
<h3> 4.5.2 Featurizing data with TfIdf vectorizer </h3>
```
print("a")
start = datetime.now()
vectorizer = TfidfVectorizer(min_df=0.00009, max_features=200000, smooth_idf=True, norm="l2", \
tokenizer = lambda x: x.split(), sublinear_tf=False,
ngram_range=(1,4))
x_train_multilabel = vectorizer.fit_transform(x_train['question'])
x_test_multilabel = vectorizer.transform(x_test['question'])
print("Time taken to run this cell :", datetime.now() - start)
print("Dimensions of train data X:",x_train_multilabel.shape, "Y :",y_train.shape)
print("Dimensions of test data X:",x_test_multilabel.shape,"Y:",y_test.shape)
```
<h3> 4.5.3 OneVsRest Classifier with SGDClassifier using TFIDF </h3>
```
start = datetime.now()
classifier = OneVsRestClassifier(SGDClassifier(loss='log',
alpha=0.00001,
penalty='l1'), n_jobs=-1)
classifier.fit(x_train_multilabel, y_train)
predictions = classifier.predict (x_test_multilabel)
print("Accuracy :",metrics.accuracy_score(y_test, predictions))
print("Hamming loss ",metrics.hamming_loss(y_test,predictions))
precision = precision_score(y_test, predictions, average='micro')
recall = recall_score(y_test, predictions, average='micro')
f1 = f1_score(y_test, predictions, average='micro')
print("Micro-average quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
precision = precision_score(y_test, predictions, average='macro')
recall = recall_score(y_test, predictions, average='macro')
f1 = f1_score(y_test, predictions, average='macro')
print("Macro-average quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
print (metrics.classification_report(y_test, predictions))
print("Time taken to run this cell :", datetime.now() - start)
joblib.dump(classifier, 'lr_with_more_title_weight.pkl')
```
##### ASSIGNMENT
<ol>
<li> bag of words upto 4 grams and compute the micro f1 score with Logistic regression(OvR) </li>
<li> Perform hyperparam tuning on alpha (or lambda) for Logistic regression to improve the performance using GridSearch </li>
<li> OneVsRestClassifier with Linear-SVM (SGDClassifier with loss-hinge)</li>
</ol>
## Featurizing Using Bag of Words
```
alpha=[10**-3,10**-2,10**-1]
start = datetime.now()
vectorizer = CountVectorizer(min_df=0.00009, max_features=200000, \
tokenizer = lambda x: x.split(), ngram_range=(1,4))
x_train_multilabel = vectorizer.fit_transform(x_train['question'])
x_test_multilabel = vectorizer.transform(x_test['question'])
print("Time taken to run this cell :", datetime.now() - start)
print("Dimensions of train data X:",x_train_multilabel.shape, "Y :",y_train.shape)
print("Dimensions of test data X:",x_test_multilabel.shape,"Y:",y_test.shape)
```
##### Dump and load train and test data into joblib
```
joblib.dump(x_train_multilabel, 'x_train_BOW.pkl')
joblib.dump(x_test_multilabel, 'x_test_BOW.pkl')
joblib.dump(y_train, 'y_train.pkl')
joblib.dump(y_test, 'y_test.pkl')
x_train_multilabel = joblib.load('x_train_BOW.pkl')
y_train = joblib.load('y_train.pkl')
x_test_multilabel = joblib.load('x_test_BOW.pkl')
y_test = joblib.load('y_test.pkl')
```
# OneVsRestClassifier with Logistic regression
#### (alpha tuning using Gridsearch)
## OneVsRestClassifier with SGDClassifier( penalty=l2, loss=log )==> {Logistic regression}
```
start = datetime.now()
import warnings
warnings.filterwarnings('ignore')
# hp1={'estimator__C':alpha}
cv_scores = []
for i in alpha:
print(i)
hp1={'estimator__alpha':[i],
'estimator__loss':['log'],
'estimator__penalty':['l2']}
print(hp1)
classifier = OneVsRestClassifier(SGDClassifier())
model11 =GridSearchCV(classifier,hp1,
cv=3, scoring='f1_micro',n_jobs=-1)
print("Gridsearchcv")
best_model1=model11.fit(x_train_multilabel, y_train)
print('fit model')
Train_model_score=best_model1.score(x_train_multilabel,
y_train)
#print("best_model1")
cv_scores.append(Train_model_score.mean())
fscore = [x for x in cv_scores]
# determining best alpha
optimal_alpha21 = alpha[fscore.index(max(fscore))]
print('\n The optimal value of alpha with penalty=l2 and loss= log is %d.' % optimal_alpha21)
# Plots
fig4 = plt.figure( facecolor='c', edgecolor='k')
plt.plot(alpha, fscore,color='green', marker='o', linestyle='dashed',
linewidth=2, markersize=12)
for xy in zip(alpha, np.round(fscore,3)):
plt.annotate('(%s, %s)' % xy, xy=xy, textcoords='data')
plt.xlabel('Hyper parameter Alpha')
plt.ylabel('F1_Score value ')
plt.show()
print("Time taken to run this cell :", datetime.now() - start)
print(optimal_alpha21)
start = datetime.now()
best_model1 = OneVsRestClassifier(SGDClassifier(loss='log', alpha=optimal_alpha21,
penalty='l2'), n_jobs=-1)
best_model1.fit(x_train_multilabel, y_train)
joblib.dump(best_model1, 'best_model1_LR.pkl')
best_model1=joblib.load('best_model1_LR.pkl')
predictions = best_model1.predict (x_test_multilabel)
print("Accuracy :",metrics.accuracy_score(y_test, predictions))
print("Hamming loss ",metrics.hamming_loss(y_test,predictions))
precision = precision_score(y_test, predictions, average='micro')
recall = recall_score(y_test, predictions, average='micro')
f1 = f1_score(y_test, predictions, average='micro')
print("Micro-averasge quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
precision = precision_score(y_test, predictions, average='macro')
recall = recall_score(y_test, predictions, average='macro')
f1 = f1_score(y_test, predictions, average='macro')
print("Macro-average quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
print (metrics.classification_report(y_test, predictions)) #printing classification report for all 500 labels
print("Time taken to run this cell :", datetime.now() - start)
```
## OneVsRestClassifier with Logistic regression( penalty=l1 )
```
start = datetime.now()
import warnings
warnings.filterwarnings('ignore')
# hp1={'estimator__C':alpha}
cv_scores = []
for i in alpha:
print(i)
hp1={'estimator__alpha':[i],
'estimator__loss':['log'],
'estimator__penalty':['l1']}
print(hp1)
classifier = OneVsRestClassifier(SGDClassifier())
model11 =GridSearchCV(classifier,hp1,
cv=3, scoring='f1_micro',n_jobs=-1)
print("Gridsearchcv")
best_model1=model11.fit(x_train_multilabel, y_train)
print('fit model')
Train_model_score=best_model1.score(x_train_multilabel,
y_train)
#print("best_model1")
cv_scores.append(Train_model_score.mean())
fscore = [x for x in cv_scores]
# determining best alpha
optimal_alpha22 = alpha[fscore.index(max(fscore))]
print('\n The optimal value of alpha with penalty=l1 and loss= log is %d.' % optimal_alpha22)
# Plots
fig4 = plt.figure( facecolor='c', edgecolor='k')
plt.plot(alpha, fscore,color='green', marker='o', linestyle='dashed',
linewidth=2, markersize=12)
for xy in zip(alpha, np.round(fscore,3)):
plt.annotate('(%s, %s)' % xy, xy=xy, textcoords='data')
plt.xlabel('Hyper parameter Alpha')
plt.ylabel('F1_Score value ')
plt.show()
print("Time taken to run this cell :", datetime.now() - start)
start = datetime.now()
best_model2 = OneVsRestClassifier(SGDClassifier(loss='log', alpha=optimal_alpha22,
penalty='l1'), n_jobs=-1)
best_model2.fit(x_train_multilabel, y_train)
joblib.dump(best_model2, 'best_model2_LR.pkl')
best_model2=joblib.load('best_model2_LR.pkl')
```
## Logistic regression with l1 penalty
```
start = datetime.now()
#classifier = OneVsRestClassifier(LogisticRegression(penalty='l1'), n_jobs=-1)
#classifier.fit(x_train_multilabel, y_train)
predictions = best_model2.predict(x_test_multilabel)
print("Accuracy :",metrics.accuracy_score(y_test, predictions))
print("Hamming loss ",metrics.hamming_loss(y_test,predictions))
precision = precision_score(y_test, predictions, average='micro')
recall = recall_score(y_test, predictions, average='micro')
f1 = f1_score(y_test, predictions, average='micro')
print("Micro-average quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
precision = precision_score(y_test, predictions, average='macro')
recall = recall_score(y_test, predictions, average='macro')
f1 = f1_score(y_test, predictions, average='macro')
print("Macro-average quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
print (metrics.classification_report(y_test, predictions))
print("Time taken to run this cell :", datetime.now() - start)
```
## OneVsRestClassifier with Linear-SVM (SGDClassifier with loss-hinge)
```
start = datetime.now()
import warnings
warnings.filterwarnings('ignore')
# hp1={'estimator__C':alpha}
cv_scores = []
for i in alpha:
print(i)
hp1={'estimator__alpha':[i],
'estimator__loss':['hinge'],
'estimator__penalty':['l1']}
print(hp1)
classifier = OneVsRestClassifier(SGDClassifier())
model11 =GridSearchCV(classifier,hp1,
cv=3, scoring='f1_micro',n_jobs=-1)
print("Gridsearchcv")
best_model1=model11.fit(x_train_multilabel, y_train)
print('fit model')
Train_model_score=best_model1.score(x_train_multilabel,
y_train)
#print("best_model1")
cv_scores.append(Train_model_score.mean())
fscore = [x for x in cv_scores]
# determining best alpha
optimal_alpha23 = alpha[fscore.index(max(fscore))]
print('\n The optimal value of alpha with penalty=l1 and loss= log is %d.' % optimal_alpha23)
# Plots
fig4 = plt.figure( facecolor='c', edgecolor='k')
plt.plot(alpha, fscore,color='green', marker='o', linestyle='dashed',
linewidth=2, markersize=12)
for xy in zip(alpha, np.round(fscore,3)):
plt.annotate('(%s, %s)' % xy, xy=xy, textcoords='data')
plt.xlabel('Hyper parameter Alpha')
plt.ylabel('F1_Score value ')
plt.show()
print("Time taken to run this cell :", datetime.now() - start)
```
## OneVsRestClassifier with SGDClassifier for optimal alpha with hinge loss
```
start = datetime.now()
classifier2 = OneVsRestClassifier(SGDClassifier(loss='hinge',
alpha=optimal_alpha23,
penalty='l1'))
classifier2=classifier2.fit(x_train_multilabel, y_train)
joblib.dump(classifier2, 'classifier2.pkl')
classifier2=joblib.load('classifier2.pkl')
predictions = classifier2.predict (x_test_multilabel)
print("Accuracy :",metrics.accuracy_score(y_test, predictions))
print("Hamming loss ",metrics.hamming_loss(y_test,predictions))
precision = precision_score(y_test, predictions, average='micro')
recall = recall_score(y_test, predictions, average='micro')
f1 = f1_score(y_test, predictions, average='micro')
print("Micro-averasge quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
precision = precision_score(y_test, predictions, average='macro')
recall = recall_score(y_test, predictions, average='macro')
f1 = f1_score(y_test, predictions, average='macro')
print("Macro-average quality numbers")
print("Precision: {:.4f}, Recall: {:.4f}, F1-measure: {:.4f}".format(precision, recall, f1))
print (metrics.classification_report(y_test, predictions)) #printing classification report for all 500 labels
print("Time taken to run this cell :", datetime.now() - start)
```
# Observation
```
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["Sr.No", "MODEL","FEATURIZATION","PENALTY" ,"ALPHA",'LOSS','MICRO_F1_SCORE']
x.add_row(["1", 'OneVsRest+SGD Classifier', "Tf-idf","l1",0.0001,"log",0.4488])
x.add_row(["2", 'OneVsRest+SGD(log)=LR', "Bag-of-words","l2",0.001,"log",0.4268])
x.add_row(["3", 'OneVsRest+SGD(log)=LR', "Bag-of-words","l1",0.001,"log",0.4104])
x.add_row(["4", 'OneVsRest+SGD Classifier', "Bag-of-words","l1",0.001,"Hinge",0.4028])
print(x)
```
* The objective's result is shown as above.
* Model {bag of words upto 4 grams and computed the micro f1 score with Logistic regression(OvR)} performs 42.68% on tag prediction which is not higher than the result obtained with model{ TF-IDF with alpha=00.0001 ,n_grams=(1,3)}
* The performance of model with various alpha value is shown in graph.
| github_jupyter |
# Introduction to `cf_xarray`
This notebook is a brief introduction to `cf_xarray`'s current capabilities.
```
import cf_xarray
import numpy as np
import xarray as xr
xr.set_options(display_style="text") # work around issue 57
```
Lets read two datasets.
```
ds = xr.tutorial.load_dataset("air_temperature")
ds.air.attrs["standard_name"] = "air_temperature"
ds
```
This one is inspired by POP model output and illustrates how the coordinates
attribute is interpreted
```
pop = xr.Dataset()
pop.coords["TLONG"] = (
("nlat", "nlon"),
np.ones((20, 30)),
{"units": "degrees_east"},
)
pop.coords["TLAT"] = (
("nlat", "nlon"),
2 * np.ones((20, 30)),
{"units": "degrees_north"},
)
pop.coords["ULONG"] = (
("nlat", "nlon"),
0.5 * np.ones((20, 30)),
{"units": "degrees_east"},
)
pop.coords["ULAT"] = (
("nlat", "nlon"),
2.5 * np.ones((20, 30)),
{"units": "degrees_north"},
)
pop["UVEL"] = (
("nlat", "nlon"),
np.ones((20, 30)) * 15,
{"coordinates": "ULONG ULAT", "standard_name": "sea_water_x_velocity"},
)
pop["TEMP"] = (
("nlat", "nlon"),
np.ones((20, 30)) * 15,
{
"coordinates": "TLONG TLAT",
"standard_name": "sea_water_potential_temperature",
},
)
pop
```
This synthetic dataset has multiple `X` and `Y` coords. An example would be
model output on a staggered grid.
```
multiple = xr.Dataset()
multiple.coords["x1"] = ("x1", range(30), {"axis": "X"})
multiple.coords["y1"] = ("y1", range(20), {"axis": "Y"})
multiple.coords["x2"] = ("x2", range(10), {"axis": "X"})
multiple.coords["y2"] = ("y2", range(5), {"axis": "Y"})
multiple["v1"] = (("x1", "y1"), np.ones((30, 20)) * 15)
multiple["v2"] = (("x2", "y2"), np.ones((10, 5)) * 15)
multiple
# This dataset has ancillary variables
anc = xr.Dataset()
anc["q"] = (
("x", "y"),
np.random.randn(10, 20),
dict(
standard_name="specific_humidity",
units="g/g",
ancillary_variables="q_error_limit q_detection_limit",
),
)
anc["q_error_limit"] = (
("x", "y"),
np.random.randn(10, 20),
dict(standard_name="specific_humidity standard_error", units="g/g"),
)
anc["q_detection_limit"] = xr.DataArray(
1e-3,
attrs=dict(
standard_name="specific_humidity detection_minimum", units="g/g"
),
)
anc
```
## What attributes have been discovered?
```
ds.lon
```
`ds.lon` has attributes `axis: X`. This means that `cf_xarray` can identify the
`'X'` axis as being represented by the `lon` variable.
It can also use the `standard_name` and `units` attributes to infer that `lon`
is "Longitude". To see variable names that `cf_xarray` can infer, use
`.cf.describe()`
```
ds.cf.describe()
```
For `pop`, only `latitude` and `longitude` are detected, not `X` or `Y`. Please
comment here: https://github.com/xarray-contrib/cf-xarray/issues/23 if you have
opinions about this behaviour.
```
pop.cf.describe()
```
For `multiple`, multiple `X` and `Y` coordinates are detected
```
multiple.cf.describe()
```
## Feature: Accessing coordinate variables
`.cf` implements `__getitem__` to allow easy access to coordinate and axis
variables.
```
ds.cf["X"]
```
Indexing with a scalar key raises an error if the key maps to multiple variables
names
```
multiple.cf["X"]
pop.cf["longitude"]
```
To get back all variables associated with that key, pass a single element list
instead.
```
multiple.cf[["X"]]
pop.cf[["longitude"]]
```
DataArrays return DataArrays
```
pop.UVEL.cf["longitude"]
```
`Dataset.cf[...]` returns a single `DataArray`, parsing the `coordinates`
attribute if present, so we correctly get the `TLONG` variable and not the
`ULONG` variable
```
pop.cf["TEMP"]
```
`Dataset.cf[...]` also interprets the `ancillary_variables` attribute. The
ancillary variables are returned as coordinates of a DataArray
```
anc.cf["q"]
```
## Feature: Accessing variables by standard names
```
pop.cf[["sea_water_potential_temperature", "UVEL"]]
anc.cf["specific_humidity"]
```
## Feature: Utility functions
There are some utility functions to allow use by downstream libraries
```
pop.cf.get_valid_keys()
```
You can test for presence of these keys
```
"sea_water_x_velocity" in pop.cf
```
## Feature: Rewriting property dictionaries
`cf_xarray` will rewrite the `.sizes` and `.chunks` dictionaries so that one can
index by a special CF axis or coordinate name
```
ds.cf.sizes
```
Note the duplicate entries above:
1. One for `X`, `Y`, `T`
2. and one for `longitude`, `latitude` and `time`.
An error is raised if there are multiple `'X'` variables (for example)
```
multiple.cf.sizes
multiple.v1.cf.sizes
```
## Feature: Renaming coordinate variables
`cf_xarray` lets you rewrite coordinate variables in one dataset to like
variables in another dataset. This can only be done when a one-to-one mapping is
possible
In this example, `TLONG` and `TLAT` are renamed to `lon` and `lat` i.e. their
counterparts in `ds`. Note the the `coordinates` attribute is appropriately
changed.
```
pop.cf["TEMP"].cf.rename_like(ds)
```
## Feature: Rewriting arguments
`cf_xarray` can rewrite arguments for a large number of xarray functions. By
this I mean that instead of specifing say `dim="lon"`, you can pass `dim="X"` or
`dim="longitude"` and `cf_xarray` will rewrite that to `dim="lon"` based on the
attributes present in the dataset.
Here are a few examples
### Slicing
```
ds.air.cf.isel(T=1)
```
Slicing works will expand a single key like `X` to multiple dimensions if those
dimensions are tagged with `axis: X`
```
multiple.cf.isel(X=1, Y=1)
```
### Reductions
```
ds.air.cf.mean("X")
```
Expanding to multiple dimensions is also supported
```
# takes the mean along ["x1", "x2"]
multiple.cf.mean("X")
```
### Plotting
```
ds.air.cf.isel(time=1).cf.plot(x="X", y="Y")
ds.air.cf.isel(T=1, Y=[0, 1, 2]).cf.plot(x="longitude", hue="latitude")
```
`cf_xarray` can facet
```
seasonal = (
ds.air.groupby("time.season")
.mean()
.reindex(season=["DJF", "MAM", "JJA", "SON"])
)
seasonal.cf.plot(x="longitude", y="latitude", col="season")
```
### Resample & groupby
```
ds.cf.resample(T="D").mean()
```
`cf_xarray` also understands the "datetime accessor" syntax for groupby
```
ds.cf.groupby("T.month").mean("longitude")
```
### Rolling & coarsen
```
ds.cf.rolling(X=5).mean()
```
`coarsen` works but everything later will break because of xarray bug
https://github.com/pydata/xarray/issues/4120
`ds.isel(lon=slice(50)).cf.coarsen(Y=5, X=10).mean()`
## Feature: mix "special names" and variable names
```
ds.cf.groupby("T.month").mean(["lat", "X"])
```
## Feature: Weight by Cell Measures
`cf_xarray` can weight by cell measure variables `"area"` and `"volume"` if the
appropriate attribute is set
```
# Lets make some weights (not sure if this is right)
ds.coords["cell_area"] = (
np.cos(ds.air.cf["latitude"] * np.pi / 180)
* xr.ones_like(ds.air.cf["longitude"])
* 105e3
* 110e3
)
# and set proper attributes
ds.air.attrs["cell_measures"] = "area: cell_area"
ds.air.cf.weighted("area").mean(["latitude", "time"]).cf.plot(x="longitude")
ds.air.mean(["lat", "time"]).cf.plot(x="longitude")
```
| github_jupyter |
# Interact with decay data in ENDF-6 format (MF=8, MT=457)
First import `sandy` and other packages importing for formatting and postprocessing that are used in this notebook.
```
import os
import yaml
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import sandy
%load_ext autoreload
%autoreload 2
```
## Read decay data in ENDF-6 format
As always, any nuclear data evaluation can be imported into a `Endf6` instance
```
tape = sandy.Endf6.from_file("dec-027_Co_060.endf")
```
The radioactive decay data text (in ENDF-6 format) for all sections and isotopes in `tape` can be
parsed and extracted in a hierarchical format (nested `dict`) into a `DecayData` instance, say, variable `rdd`.
```
rdd = sandy.DecayData.from_endf6(tape)
rdd.data
```
A better rendering of the `rdd` data content can be obtained with the `yaml` python package.
```
print(yaml.dump(rdd.data))
```
The description of the `rdd.data` structure is explained below, where `zam` and `zap` are
equal to `Z * 10000 + A * 10 + M` for the parent and daughter isotopes, respectively, with
`Z`, `A`, and `M` being the charge, nucleons and metastate numbers.
```yaml
zam :
half_life : value in s
decay_constant : value in 1/s
stable : True/False
decay_energy :
alpha: value in eV
beta: value in eV
gamma: value in eV
total: value in eV
decay_energy_uncertainty :
alpha: value in eV
beta: value in eV
gamma: value in eV
total: value in eV
decay_modes :
rtyp :
decay_products :
zap : yield
zap_2 : yield_2
...
branching_ratio : value
rtyp_2 : ...
zam_2 : ...
```
`rtyp` is a string storing a sequence of integers, each of which defining the
several decay events covered by a given decay mode.
The list of individual decay events is accessible via variable `sandy.decay_modes`.
```
print(yaml.dump(sandy.decay_modes))
```
## Extract structured information into dataframes
We can extract the decay chains information (decay constant, branching ratio, yield, ...) into a `pandas.DataFrame`.
```
chains = rdd.get_decay_chains()
chains
```
Or get the B-matrix, the matrix of branching ratios used to produce...
```
bm = rdd.get_bmatrix()
bm
```
...the Q-matrix, to get cumulative yields `Y` from independent yields `C`, according to `Y = Q C`.
```
qm = rdd.get_qmatrix()
qm
```
Another thing you can get is the transition matrix `T` used to solve the depletion equation
for radioactive decay `dN\N = T N `.
```
tm = rdd.get_transition_matrix()
tm
```
## Convert decay data into HDF5 format
We can write the content of `rdd` into a hdf5 file, say `"decay.hdf5"`,
under a group namespace to identify the library, e.g. `"endfb_71"`.
```
h5filename = "decay.hdf5"
libname = "endfb_71"
rdd.to_hdf5("decay.hdf5", "endfb_71")
rdd2 = sandy.DecayData.from_hdf5(h5filename, libname)
assert rdd2.get_decay_chains().equals(chains)
os.remove(h5filename)
```
| github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
import numpy as np
import sklearn as sk
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
import sklearn.model_selection as ms
import sklearn.preprocessing as p
import math
tf.version.VERSION
mnist = pd.read_csv("../input/digit-recognizer/train.csv")
mnist.shape
mnist.columns
x = mnist.drop('label', axis=1)
x.head()
y = mnist['label']
y.head()
y = tf.keras.utils.to_categorical(y, num_classes=10)
y[0]
X_train, X_val, y_train, y_val = ms.train_test_split(x, y, test_size=0.15)
scaler = p.StandardScaler()
X_train = scaler.fit_transform(X_train)
X_train = X_train.reshape(-1, 28, 28, 1)
X_val = scaler.transform(X_val)
X_val = X_val.reshape(-1, 28, 28, 1)
X_train.shape, X_val.shape
y_train.shape, y_val.shape
X_train.min()
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D, Flatten
model = Sequential()
# Convolutional Layer
model.add(Conv2D(filters=32, kernel_size=(4,4), input_shape=(28, 28, 1), activation='relu'))
# pooling layer
model.add(MaxPool2D(pool_size=(2,2)))
# transform both layers to dense layer, thus, we need to flatten
# 2d to 1 d
model.add(Flatten())
# Dense Layer
model.add(Dense(128, activation='relu'))
# output layer
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics = ['accuracy'])
model.summary()
model.fit(X_train, y_train, epochs=20)
from sklearn.metrics import classification_report, confusion_matrix
X_pred = pd.read_csv('../input/digit-recognizer/test.csv')
X_pred = scaler.transform(X_pred)
X_pred = X_pred.reshape(-1, 28, 28, 1)
y_pred = pd.DataFrame()
y_pred['ImageId'] = pd.Series(range(1,X_pred.shape[0] + 1))
predictions.shape
results = model.predict(X_pred)
# y_pred.to_csv("submission.csv", index=False)
results.shape
results = np.argmax(results,axis = 1)
results = pd.Series(results,name="Label")
submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1)
submission.to_csv("cnn_mnist_submission.csv",index=False)
submission.to_csv("cnn_submission.csv",index=False)
import pandas as pd
m_test = pd.read_csv("../input/digit-recognizer/test.csv")
m_train = pd.read_csv("../input/digit-recognizer/train.csv")
cols = m_test.columns
cols
m_test['dataset'] = 'test'
m_train['dataset'] = 'train'
m_test.shape
m_train.shape
m_test['dataset']
dataset = pd.concat([m_train.drop('label', axis=1), m_test]).reset_index()
dataset.shape
csv_test = pd.read_csv("../input/mnist-in-csv/mnist_test.csv")
csv_train = pd.read_csv("../input/mnist-in-csv/mnist_train.csv")
sample_submission = pd.read_csv("../input/digit-recognizer/sample_submission.csv")
csv_train.head()
mnist = pd.concat([csv_train, csv_test]).reset_index(drop=True)
mnist
labels = mnist['label'].values
labels
mnist.drop('label', axis=1, inplace=True)
mnist.columns = cols
id_mnist = mnist.sort_values(by=list(mnist.columns)).index
id_mnist
dataset_from = dataset.sort_values(by=list(mnist.columns))['dataset'].values
origin_id = dataset.sort_values(by=list(mnist.columns))['index'].values
for i in range(len(id_mnist)):
if dataset_from[i] == 'test':
sample_submission.loc[origin_id[i], 'Label'] = labels[id_mnist[i]]
sample_submission
sample_submission.to_csv("samp_fake_it.csv",index=False)
```
| github_jupyter |
# MonaLIA Pair-Wise Odds Ratio between categories (DL training set)
Experiment to explore whether a probability of appearance of one concept of a context-similar pair can improve the probability score of the second concept in the same image. For example, if a high classification probability score for a bateau could influence the score of the category mer. To achieve this, we used a logistic regression approach.
The idea is to build a pairwise regression predictor of appearance of the category A of a pair (A, B) based on the presence of category B in the Joconde dataset metadata. Both dependent variable (category A) and predictor (category B) are binary labels. The regression estimates the log-odds of observing category A when category B is present compared to situations when category B is not present.
$$log (odds(A)) = β_0+ β_1*B, where β_1=log (\frac{odds(A|B)}{odds(A no B)})$$
These estimates are dependent on the dataset. If a different dataset is used it might lead to a different value of β1. Binary indicator model compares situations when category B is present or not. But because machine learning models predict categories with continuous probability scores S(A) and S(B), we want to reuse the regression parameters to predict an adjustment of probability score of category A of pair (A, B) based on a difference of probability score of category B compared to a baseline P(B)base that category B is present.
$$log (odds(A)_{adj} ) = β_0+ β_1*(S(B) - P(B)_{base} ),$$
where $S(B)$ is a classification prediction score of B. $P(B)_{base}$ can be calculated as a frequency of this category in the dataset. Thus, we consider how much the prediction score for B is higher (or lower) than the one obtained purely by chance. For the Joconde dataset we estimated P(B)base by direct counting of concepts in the annotations in the training set (to be noticed, that the training set is better balanced than the entire dataset).
We assume that an unadjusted estimate of $S(A)$ corresponds to the baseline probability $P(B)_{base}$ and the adjustment could be made by using the actual prediction score $S(B)$. The adjusted odds of A thus become:
$$odds(A)_{adj}= \frac{S(A)}{1-S(A)} * e^{β_1*(S(B)-P(B)_{base} ) }$$
In case of $S(B) = P(B)_{base}$, there will be no adjustments to the score. This approach also considers that when the score of label B is lower than the average, it will reduce the probability of label A. This approach might impact recall and precision not symmetrically which can lead to subjective decisions.
For example, the presence of a boat often implies some body of water, however the sea might be present on a painting without any boat. We thus considered an additional threshold for the lower values of $P(B)_{base}$, below which we do not consider adjustments. This modification will adjust the prediction score of category A when the label B is present and will leave $S(A)$ unadjusted when $P(B)_{base}$ is low.
Method of adjusting the probability scores of category A in the context-bases pair (A, B) and evaluated the adjustments on the test set:
1. Estimate the odds ratio from a logistic regression on the metadata of the dataset
2. Estimate the baseline probability for category B on the same data
3. Calculate the adjusted prediction score for category A from the estimated odd ratio coefficient and the difference between the estimated baseline and prediction score for category B.
4. Evaluate the adjusted prediction using standard metrics
#### This notebook reqires SPARQL engine with Joconde dataset and model obtained prediction scores RDF loaded
Prediction scores obtained by SPARQL query assuming that the scores are already in the KB dataset
```
from __future__ import print_function
import os
import sys
import numpy as np
import pandas as pd
import SPARQLWrapper
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
from sklearn import metrics
from IPython.display import display, HTML
from textwrap import wrap
# Import MonaLIA library from the package in the subfolder of the notebook folder
module_path = os.path.abspath(os.path.join('../..'))
if module_path not in sys.path:
sys.path.append(module_path)
import importlib
from MonaLIA.util import metadata_helpers as metadata
from MonaLIA.util import visualization_helpers as vis_helpers
importlib.reload(metadata)
importlib.reload(vis_helpers)
print('SPARQLWrapper ver.', SPARQLWrapper.__version__)
print('Pandas ver.', pd.__version__)
wds_Joconde_Corese = 'http://localhost:8080/sparql'
```
## Query annotations
```
descr_path = 'C:/Datasets/Joconde/Forty classes'
dataset_description_file = os.path.join(descr_path, 'dataset1.csv')
annotations_df = pd.read_csv(dataset_description_file, na_filter=False)
print(annotations_df.shape)
annotations_df.head()
def my_tokenizer(s):
return list(filter(None, set(s.split('+'))))
annotations_df.label = annotations_df.label.apply(my_tokenizer)
annotations_df.shape
```
## Create indicators columns
```
train_annotations_df = annotations_df.loc[annotations_df.usage == 'train']
annotations_dummies_df = pd.get_dummies(train_annotations_df.explode('label').label).groupby(level=0).sum()
annotations_dummies_df.columns = annotations_dummies_df.columns.str.replace(' ', '_')
annotations_dummies_df.head()
train_annotations_df = train_annotations_df.merge(annotations_dummies_df,
left_index=True,
right_index=True)
print(annotations_df.shape)
corr_df = annotations_dummies_df.corr()
fig=plt.figure(figsize=(12, 12))
cmap_div = sns.diverging_palette(22, 130, s=99, n=16, as_cmap=True)
mask = corr_df >= 0.5
ax = sns.heatmap(corr_df , cmap=cmap_div,
mask = mask,
vmin=-0.5, vmax=0.5 , center =0.0,
square=True, cbar_kws={"shrink": 0.8})
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
ax.xaxis.set_ticks_position('top')
fig=plt.figure(figsize=(12, 4))
plt.scatter(x = corr_df[corr_df < 0.5].rank(),
y = corr_df[corr_df < 0.5])
top_corr_df = corr_df.stack().reset_index()
top_corr_df.columns = ['label_A', 'label_B', 'cor']
top_corr_df = top_corr_df[(top_corr_df.cor > 0.1) & (top_corr_df.cor < 0.5)]
print(top_corr_df.shape)
top_corr_df.sort_values(by='cor', ascending=False)
label_A = 'mer'#'cheval'#, 'mer'
label_B = 'bateau' #'voiture à attelage'#'bateau'
label_A_ = label_A.replace(' ', '_')
label_B_ = label_B.replace(' ', '_')
from collections import namedtuple
Label_Stats = namedtuple('Label_Stats', ['Probs', 'Joint_prob', 'Cond_probs',
'Variance', 'Odds',
'Covariance', 'Correlation',
'PWOR'])
def calculate_stats (df, label_A, label_B, prnt=False):
p_A = df[label_A].sum() / df.shape[0]
p_B = df[label_B].sum() / df.shape[0]
p_AB = (df[[label_A, label_B]].sum(axis=1) == 2).sum() / df.shape[0]
p_A_given_B = p_AB / p_B
p_B_given_A = p_AB / p_A
var_A = p_A * (1-p_A)
var_B = p_B * (1-p_B)
odds_A = p_A /(1 - p_A)
odds_B = p_B /(1 - p_B)
cov_AB = p_AB - p_A*p_B
cor_AB = cov_AB / ( np.sqrt(var_A) * np.sqrt(var_B) )
pwor_AB = odds_A * ((1 - p_B_given_A) / p_B_given_A)
pwor_BA = odds_B * ((1 - p_A_given_B) / p_A_given_B)
if (prnt):
print('count(%s) = %d' % ( label_A, df[label_A].sum()) )
print('count(%s) = %d' % ( label_B, df[label_B].sum()) )
print()
print('P(%s) = %f' % (label_A, p_A))
print('P(%s) = %f' % (label_B, p_B))
print('P(%s,%s) = %f' % (label_A, label_B, p_AB))
print()
print('P(%s|%s) = %f' % (label_A, label_B, p_A_given_B))
print('P(%s|%s) = %f' % (label_B, label_A, p_B_given_A))
print()
print('Odds(%s) = %f' % (label_A, odds_A))
print('Odds(%s) = %f' % (label_B, odds_B))
print()
print('Var(%s) = %f' % (label_A, var_A))
print('Var(%s) = %f' % (label_B, var_B))
print()
print('Cov(%s,%s) = %f' % (label_A, label_B, cov_AB))
print()
print('Cor(%s,%s) = %f' % (label_A, label_B, cor_AB))
print()
print('PWOR(%s|%s) = %f' % (label_A, label_B, pwor_AB))
print('PWOR(%s|%s) = %f' % (label_B, label_A, pwor_BA))
stats = Label_Stats( (p_A, p_B), p_AB, (p_A_given_B, p_B_given_A), (var_A, var_B), (odds_A, odds_B), cov_AB, cor_AB,
(pwor_AB, pwor_BA))
return stats
stats = calculate_stats(train_annotations_df, label_A_, label_B_, prnt=True)
formula = '%s ~ %s' % (label_A_, label_B_)
res = sm.formula.glm(formula, family=sm.families.Binomial(), data=train_annotations_df).fit()
print(res.summary())
```
### Extract test set data drom the annotations
```
test_annotations_df = annotations_df.loc[annotations_df.usage == 'test']
test_annotations_dummies_df = pd.get_dummies(test_annotations_df.explode('label').label).groupby(level=0).sum()
test_annotations_dummies_df.columns = annotations_dummies_df.columns.str.replace(' ', '_')
test_annotations_df = test_annotations_df.merge(test_annotations_dummies_df,
left_index=True,
right_index=True)
test_annotations_df.shape
```
### Read scores from the KB for the test set
```
query_image_for_test_set = '''
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix skos: <http://www.w3.org/2004/02/skos/core#>
prefix jcl: <http://jocondelab.iri-research.org/ns/jocondelab/>
#prefix dc: <http://purl.org/dc/elements/1.1/>
prefix ml: <http://ns.inria.fr/monalia/>
select ?ref
?imageURL
?title
?repr
#?target_labels
#?actual_labels
?classifier_label
?score
where
{
VALUES(?ref) {("%s")}
?notice jcl:noticeRef ?ref;
jcl:noticeImage [ jcl:noticeImageIsMain true ; jcl:noticeImageUrl ?imageURL].
optional {?notice jcl:noticeTitr ?title.}
optional {?notice jcl:noticeRepr ?repr.}
{
select *
where {
VALUES (?classifier_label) { ("%s"@fr) ("%s"@fr) }
?classifierCategory a jcl:Term;
skos:prefLabel ?classifier_label;
skos:inScheme <http://data.culture.fr/thesaurus/resource/ark:/67717/T523>.
?classifier rdfs:label "40_classes".
?notice ml:imageClassifier [a ?classifier ;
ml:detected [ a ?classifierCategory ;
ml:score ?score ]].
}
}
}
''' #% (test_annotations_df.ref[:100].str.cat(sep = ' ' ).replace(' ', '") ("'), label_A, label_B )
#%time test_ext_df = metadata.sparql_service_to_dataframe(wds_Joconde_Corese, query_image_for_test_set)
#print(test_ext_df.shape)
chunk_size = 100
ref_chunk_list = [test_annotations_df.ref[i:i+chunk_size] for i in range(0,test_annotations_df.ref.size, chunk_size)]
test_df = pd.DataFrame()
for i, ref_chunk in enumerate(ref_chunk_list):
print(ref_chunk.size * (i+1), end=', ')
chunk_query_str = query_image_for_test_set % (ref_chunk.str.cat(sep = ' ' ).replace(' ', '") ("') , label_A, label_B)
test_df = pd.concat([test_df, metadata.sparql_service_to_dataframe(wds_Joconde_Corese, chunk_query_str)], ignore_index=True)
print('Done')
def agg_scores(x):
_x = x#.sort_values(by='classifier_label' , ascending=True, inplace=False)
return pd.Series(dict(#targets = _x.iloc[0].target_labels,
pred_dict = dict(zip(_x['classifier_label'], _x['score'].astype(float)))
#predictions = list(_x['classifier_label']),
#scores = list(_x['score'])
))
def adjust_scores(logit_res, score_A, score_B, base_prob_B = 0.5 ):
score_A = score_A - 0.0000001 # to prevent division by 0 for score = 1.0
odds_pred_A = score_A / (1-score_A)
pwor_A_given_B = np.exp(logit_res.params[1] * (score_B - base_prob_B))
odds_pred_A_new = odds_pred_A * pwor_A_given_B
score_A_new = odds_pred_A_new / (1+ odds_pred_A_new)
return score_A_new
def adjust_scores_with_th(logit_res, score_A, score_B, base_prob_B = 0.5, th=0.5 ):
score_A = score_A - 0.0000001 # to prevent division by 0 for score = 1.0
odds_pred_A = score_A / (1-score_A)
if (score_B > th):
pwor_A_given_B = np.exp(logit_res.params[1] * (score_B - base_prob_B))
odds_pred_A_new = odds_pred_A * pwor_A_given_B
score_A_new = odds_pred_A_new / (1+ odds_pred_A_new)
else:
score_A_new = score_A
return score_A_new
test_df_ = test_df.groupby('ref') \
.apply(agg_scores) \
.reset_index() \
.set_index('ref')
test_df_['adjusted_score_'+label_A] = test_df_.apply(lambda x: adjust_scores_with_th(res,
x.pred_dict[label_A],
x.pred_dict[label_B],
base_prob_B=0.85,
th=0.5), axis=1 )
test_df_ = test_df_.merge(test_annotations_df.set_index('ref').loc[:, [label_A_, label_B_]] ,
left_index=True,
right_index=True)
print(test_df_.shape)
test_df_.head()
y_true = np.array(test_df_.loc[:, [label_A_, label_B_]] , dtype = np.dtype('B'))
y_scores = pd.DataFrame.from_dict({label_A: test_df_.pred_dict.apply(lambda x: x[label_A]),
label_B: test_df_.pred_dict.apply(lambda x: x[label_B])}).to_numpy()
AP = metrics.average_precision_score(y_true= y_true,
y_score=y_scores,
average= None)
print('original AP', dict(zip([label_A, label_B], AP)))
y_scores_adj = pd.DataFrame.from_dict({label_A: test_df_['adjusted_score_'+label_A],
label_B: test_df_.pred_dict.apply(lambda x: x[label_B])}).to_numpy()
AP_adj = metrics.average_precision_score(y_true= y_true,
y_score=y_scores_adj,
average= None)
print('adjusted AP', dict(zip([label_A, label_B], AP_adj)))
fig, (ax1, ax2) = plt.subplots(1,2)
fig.set_size_inches((12,6))
precision_A, recall_A, th = metrics.precision_recall_curve(y_true[:, 0],
y_scores[:, 0])
ax1.plot(recall_A, precision_A)
precision_A_adj, recall_A_adj, _ = metrics.precision_recall_curve(y_true[:, 0],
y_scores_adj[:, 0])
ax1.plot(recall_A_adj, precision_A_adj, color='red')
ax1.set_xlim(0.0, 1.05)
ax1.set_ylim(0.0, 1.05)
ax1.set_xlabel('Recall')
ax1.set_ylabel('Precision')
ax1.set_title('Precision-Recall curve: {0} AP={1:0.2f}, adjusted AP={2:0.2f}'.format(label_A, AP[0], AP_adj[0]))
precision_B, recall_B, _ = metrics.precision_recall_curve(y_true[:, 1],
y_scores[:, 1])
ax2.plot(recall_B, precision_B, color='b')
#ax2.fill_between(recall_B, precision_B, alpha=0.2, color='b', step='post')
ax2.set_xlim(0.0, 1.05)
ax2.set_ylim(0.0, 1.05)
ax2.set_xlabel('Recall')
ax2.set_ylabel('Precision')
ax2.set_title(' Precision-Recall curve: {0} AP={1:0.2f}'.format(label_B, AP[1]))
threshold_A = 0.9
threshold_B = 0.85
y_pred = (y_scores > np.array([threshold_A, threshold_B])).astype(dtype = np.dtype('B'))
report = metrics.classification_report(y_true= y_true,
y_pred= y_pred,
target_names = [label_A, label_B])
#print(report)
print()
y_pred_adj = (y_scores_adj > np.array([threshold_A, threshold_B])).astype(dtype = np.dtype('B'))
report_adj = metrics.classification_report(y_true= y_true,
y_pred= y_pred_adj,
target_names = [label_A, label_B])
#print(report_adj)
fig, (ax1, ax2) = plt.subplots(1,2)
fig.set_size_inches((12,8))
cm = metrics.multilabel_confusion_matrix(y_true, y_pred)
metrics.ConfusionMatrixDisplay(cm[0], display_labels=['~' + label_A, label_A]).plot(ax=ax1, cmap='Blues', values_format='d')
ax1.set_title('Before adjustment')
ax1.text(1.5, 3.1, report, horizontalalignment='right', verticalalignment='bottom', fontsize=12)
cm_adj = metrics.multilabel_confusion_matrix(y_true, y_pred_adj)
metrics.ConfusionMatrixDisplay(cm_adj[0], display_labels=['~' + label_A, label_A,]).plot(ax=ax2, cmap='Blues', values_format='d')
ax2.set_title('After adjustment')
ax2.text(1.5, 3.1, report_adj, horizontalalignment='right', verticalalignment='bottom', fontsize=12)
plt.delaxes(fig.axes[2])
plt.delaxes(fig.axes[2])
def gather_row_annotation(row):
return '\n'.join( wrap(row.title, 30 ) +
[''] +
wrap(row.repr, 30 ) +
['',
'<a target="_blank" href="https://www.pop.culture.gouv.fr/notice/joconde/%s">%s</a>' % (row.ref, row.ref),
#'',
# row.imagePath
])
def aggregate_group_by(x):
_x = x#.sort_values(by='classifier_label' , ascending=True, inplace=False)
return pd.Series(dict(imageURL = _x.iloc[0].imageURL,
info = gather_row_annotation(_x.iloc[0]),
actuals= _x.iloc[0]['actual_labels'].replace('+', '\n'),
targets= _x.iloc[0]['target_labels'].replace('+', '\n'),
predictions = '\n'.join(_x['classifier_label']),
scores = '\n'.join(_x['score'])
))
formatters_dict={'imageURL': vis_helpers.image_url_formatter,
'info': vis_helpers.label_formatter,
'repr': vis_helpers.repr_formatter,
'predictions': vis_helpers.label_formatter,
'classifier_label': vis_helpers.label_formatter,
'scores': vis_helpers.label_formatter,
'actuals': vis_helpers.label_formatter,
'targets': vis_helpers.label_formatter}
test_view_df = test_df.set_index('ref') \
.merge(test_annotations_df.set_index('ref').loc[:, ['label', 'terms']] ,
left_index=True,
right_index=True) \
.reset_index()
test_view_df.rename( columns={'label': 'target_labels',
'terms': 'actual_labels'}, inplace=True)
test_view_df.target_labels = test_view_df.target_labels.apply(lambda x: '+'.join(x))
pd.set_option('display.max_colwidth', None)
pd.set_option('colheader_justify', 'center')
pd.set_option('precision', 4)
test_view_df.fillna('', inplace=True)
print(test_view_df.groupby('ref').size().shape)
print('Sample of 20 images that annotated with either "%s" or "%s"' % (label_A, label_B ) )
HTML(test_view_df.groupby('ref') \
.apply(aggregate_group_by) \
.reset_index() \
.set_index('ref') \
.merge(test_df_.loc[(test_df_[label_A] + test_df_[label_B]) > 0 , ['adjusted_score_'+label_A]], left_index=True, right_index=True)[:20] \
.to_html(
formatters=formatters_dict,
escape=False,
index=False))
test_view_df_flipped = test_view_df.set_index('ref') \
.merge(test_annotations_df.set_index('ref').loc[:, [label_A]] ,
left_index=True,
right_index=True) \
.merge(test_df_.loc[: , ['pred_dict', 'adjusted_score_'+label_A]],
left_index=True,
right_index=True) \
.reset_index()
test_view_df_flipped[label_A+'_p'] = test_view_df_flipped.pred_dict.apply(lambda x: 1 if x[label_A] > threshold_A else 0)
test_view_df_flipped[label_A+'_ap'] = test_view_df_flipped['adjusted_score_'+label_A].apply(lambda x: 1 if x > threshold_A else 0)
print('Changed classification for "%s"' % (label_A) )
test_view_df_flipped = test_view_df_flipped.loc[ test_view_df_flipped[label_A+'_p'] != test_view_df_flipped[label_A+'_ap'], :]
#print('Classification False Positives for "%s"' % (label_A) )
#test_view_df_flipped = test_view_df_flipped.loc[ (test_view_df_flipped[label_A] == 0) & (test_view_df_flipped[label_A+'_p'] == 1), :]
pd.set_option('display.max_colwidth', None)
pd.set_option('colheader_justify', 'center')
pd.set_option('precision', 4)
test_view_df_flipped.fillna('', inplace=True)
print(test_view_df_flipped.groupby('ref').size().shape)
HTML(test_view_df_flipped.groupby('ref') \
.apply(aggregate_group_by) \
.reset_index() \
.set_index('ref') \
#.merge(test_df_.loc[:, ['adjusted_score_A']], left_index=True, right_index=True) \
.merge(test_view_df_flipped.loc[:, ['ref', 'adjusted_score_'+label_A, label_A, label_A+'_p', label_A+'_ap']].set_index('ref'), left_index=True, right_index=True) \
.drop_duplicates() \
.sort_values(by=[label_A, label_A+'_p', label_A+'_ap'])
.to_html(
formatters=formatters_dict,
escape=False,
index=False,
show_dimensions=True))
test_view_df_flipped.groupby('ref') \
.apply(aggregate_group_by) \
.reset_index() \
.set_index('ref') \
.merge(test_view_df_flipped.loc[:, ['ref', 'adjusted_score_'+label_A, label_A, label_A+'_p', label_A+'_ap']].set_index('ref'), left_index=True, right_index=True) \
.drop_duplicates() \
.sort_values(by=[label_A, label_A+'_p', label_A+'_ap']) \
.to_html( buf='results of adjusting scores of mer by bateau.html',
formatters=formatters_dict,
escape=False,
index=False,
show_dimensions=True)
```
# Scrapbook
| github_jupyter |
# Robust Linear Models
```
%matplotlib inline
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.sandbox.regression.predstd import wls_prediction_std
```
## Estimation
Load data:
```
data = sm.datasets.stackloss.load()
data.exog = sm.add_constant(data.exog)
```
Huber's T norm with the (default) median absolute deviation scaling
```
huber_t = sm.RLM(data.endog, data.exog, M=sm.robust.norms.HuberT())
hub_results = huber_t.fit()
print(hub_results.params)
print(hub_results.bse)
print(hub_results.summary(yname='y',
xname=['var_%d' % i for i in range(len(hub_results.params))]))
```
Huber's T norm with 'H2' covariance matrix
```
hub_results2 = huber_t.fit(cov="H2")
print(hub_results2.params)
print(hub_results2.bse)
```
Andrew's Wave norm with Huber's Proposal 2 scaling and 'H3' covariance matrix
```
andrew_mod = sm.RLM(data.endog, data.exog, M=sm.robust.norms.AndrewWave())
andrew_results = andrew_mod.fit(scale_est=sm.robust.scale.HuberScale(), cov="H3")
print('Parameters: ', andrew_results.params)
```
See ``help(sm.RLM.fit)`` for more options and ``module sm.robust.scale`` for scale options
## Comparing OLS and RLM
Artificial data with outliers:
```
nsample = 50
x1 = np.linspace(0, 20, nsample)
X = np.column_stack((x1, (x1-5)**2))
X = sm.add_constant(X)
sig = 0.3 # smaller error variance makes OLS<->RLM contrast bigger
beta = [5, 0.5, -0.0]
y_true2 = np.dot(X, beta)
y2 = y_true2 + sig*1. * np.random.normal(size=nsample)
y2[[39,41,43,45,48]] -= 5 # add some outliers (10% of nsample)
```
### Example 1: quadratic function with linear truth
Note that the quadratic term in OLS regression will capture outlier effects.
```
res = sm.OLS(y2, X).fit()
print(res.params)
print(res.bse)
print(res.predict())
```
Estimate RLM:
```
resrlm = sm.RLM(y2, X).fit()
print(resrlm.params)
print(resrlm.bse)
```
Draw a plot to compare OLS estimates to the robust estimates:
```
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
ax.plot(x1, y2, 'o',label="data")
ax.plot(x1, y_true2, 'b-', label="True")
prstd, iv_l, iv_u = wls_prediction_std(res)
ax.plot(x1, res.fittedvalues, 'r-', label="OLS")
ax.plot(x1, iv_u, 'r--')
ax.plot(x1, iv_l, 'r--')
ax.plot(x1, resrlm.fittedvalues, 'g.-', label="RLM")
ax.legend(loc="best")
```
### Example 2: linear function with linear truth
Fit a new OLS model using only the linear term and the constant:
```
X2 = X[:,[0,1]]
res2 = sm.OLS(y2, X2).fit()
print(res2.params)
print(res2.bse)
```
Estimate RLM:
```
resrlm2 = sm.RLM(y2, X2).fit()
print(resrlm2.params)
print(resrlm2.bse)
```
Draw a plot to compare OLS estimates to the robust estimates:
```
prstd, iv_l, iv_u = wls_prediction_std(res2)
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x1, y2, 'o', label="data")
ax.plot(x1, y_true2, 'b-', label="True")
ax.plot(x1, res2.fittedvalues, 'r-', label="OLS")
ax.plot(x1, iv_u, 'r--')
ax.plot(x1, iv_l, 'r--')
ax.plot(x1, resrlm2.fittedvalues, 'g.-', label="RLM")
legend = ax.legend(loc="best")
```
| github_jupyter |
<a href="https://colab.research.google.com/github/RecoHut-Projects/recohut/blob/master/tutorials/modeling/T973437_matching_models_ml1m_tf.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Candidate selection (Item matching) models in Tensorflow on ML-1m
## **Step 1 - Setup the environment**
### **1.1 Install libraries**
```
!pip install tensorflow==2.5.0
!pip install -q -U git+https://github.com/RecoHut-Projects/recohut.git -b v0.0.5
```
### **1.2 Download datasets**
```
!wget -q --show-progress https://files.grouplens.org/datasets/movielens/ml-1m.zip
!unzip ml-1m.zip
```
### **1.3 Import libraries**
```
import os
import numpy as np
import pandas as pd
from time import time
from tqdm import tqdm
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import BinaryCrossentropy
# transforms
from recohut.transforms.datasets.movielens import create_ml_1m_dataset
from recohut.transforms.datasets.movielens import create_implicit_ml_1m_dataset
# models
from recohut.models.tf.bpr import BPR
from recohut.models.tf.ncf import NCF
from recohut.models.tf.caser import Caser
from recohut.models.tf.sasrec import SASRec
from recohut.models.tf.attrec import AttRec
```
### **1.4 Set params**
```
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
class Args:
def __init__(self, model='bpr'):
self.file = '/content/ml-1m/ratings.dat'
self.epochs = 2
self.trans_score = 1
self.test_neg_num = 100
self.embed_dim = 64
self.mode = 'inner' # dist
self.embed_reg = 1e-6
self.K = 10
self.learning_rate = 0.001
self.batch_size = 512
self.hidden_units = [256, 128, 64]
self.activation = 'relu'
self.dropout = 0.2
self.mode = 'inner'
self.maxlen = 200
self.hor_n = 8
self.hor_h = 2
self.ver_n = 4
self.blocks = 2
self.num_heads = 1
self.ffn_hidden_unit = 64
self.norm_training = True
self.causality = False
self.gamma = 0.5
self.w = 0.5
if model == 'ncf':
self.embed_dim = 32
elif model == 'caser':
self.embed_dim = 50
elif model == 'sasrec':
self.embed_dim = 50
self.embed_reg = 0
elif model == 'attrec':
self.maxlen = 5
self.embed_dim = 100
self.batch_size = 1024
```
## **Step 2 - Training & Evaluation**
```
def getHit(df, ver=1):
"""
calculate hit rate
:return:
"""
if ver==1:
df = df.sort_values('pred_y', ascending=False).reset_index()
if df[df.true_y == 1].index.tolist()[0] < _K:
return 1
else:
return 0
def getNDCG(df):
"""
calculate NDCG
:return:
"""
df = df.sort_values('pred_y', ascending=False).reset_index()
i = df[df.true_y == 1].index.tolist()[0]
if i < _K:
return np.log(2) / np.log(i+2)
else:
return 0.
def evaluate_model(model, test, K, ver=1):
"""
evaluate model
:param model: model
:param test: test set
:param K: top K
:return: hit rate, ndcg
"""
if ver == 1:
if args.mode == 'inner':
pred_y = - model.predict(test)
else:
pred_y = model.predict(test)
rank = pred_y.argsort().argsort()[:, 0]
hr, ndcg = 0.0, 0.0
for r in rank:
if r < K:
hr += 1
ndcg += 1 / np.log2(r + 2)
return hr / len(rank), ndcg / len(rank)
elif ver == 2:
global _K
_K = K
test_X, test_y = test
pred_y = model.predict(test_X)
test_df = pd.DataFrame(test_y, columns=['true_y'])
test_df['user_id'] = test_X[0]
test_df['pred_y'] = pred_y
tg = test_df.groupby('user_id')
hit_rate = tg.apply(getHit).mean()
ndcg = tg.apply(getNDCG).mean()
return hit_rate, ndcg
```
### **2.1 BPR**
```
args = Args(model='bpr')
# ========================== Create dataset =======================
feature_columns, train, val, test = create_ml_1m_dataset(args.file, args.trans_score, args.embed_dim, args.test_neg_num)
# ============================Build Model==========================
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = BPR(feature_columns, args.mode, args.embed_reg)
model.summary()
# =========================Compile============================
model.compile(optimizer=Adam(learning_rate=args.learning_rate))
results = []
for epoch in range(1, args.epochs + 1):
# ===========================Fit==============================
t1 = time()
model.fit(
train,
None,
validation_data=(val, None),
epochs=1,
batch_size=args.batch_size,
)
# ===========================Test==============================
t2 = time()
if epoch % 2 == 0:
hit_rate, ndcg = evaluate_model(model, test, args.K)
print('Iteration %d Fit [%.1f s], Evaluate [%.1f s]: HR = %.4f, NDCG = %.4f'
% (epoch, t2 - t1, time() - t2, hit_rate, ndcg))
results.append([epoch, t2 - t1, time() - t2, hit_rate, ndcg])
# ========================== Write Log ===========================
pd.DataFrame(results, columns=['Iteration', 'fit_time', 'evaluate_time', 'hit_rate', 'ndcg'])\
.to_csv('BPR_log_dim_{}_mode_{}_K_{}.csv'.format(args.embed_dim, args.mode, args.K), index=False)
```
### **2.2 NCF**
```
args = Args(model='ncf')
# ========================== Create dataset =======================
feature_columns, train, val, test = create_ml_1m_dataset(args.file, args.trans_score, args.embed_dim, args.test_neg_num)
# ============================Build Model==========================
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = NCF(feature_columns, args.hidden_units, args.dropout, args.activation, args.embed_reg)
model.summary()
# =========================Compile============================
model.compile(optimizer=Adam(learning_rate=args.learning_rate))
results = []
for epoch in range(1, args.epochs + 1):
# ===========================Fit==============================
t1 = time()
model.fit(
train,
None,
validation_data=(val, None),
epochs=1,
batch_size=args.batch_size,
)
# ===========================Test==============================
t2 = time()
if epoch % 2 == 0:
hit_rate, ndcg = evaluate_model(model, test, args.K)
print('Iteration %d Fit [%.1f s], Evaluate [%.1f s]: HR = %.4f, NDCG = %.4f'
% (epoch, t2 - t1, time() - t2, hit_rate, ndcg))
results.append([epoch, t2 - t1, time() - t2, hit_rate, ndcg])
# ========================== Write Log ===========================
pd.DataFrame(results, columns=['Iteration', 'fit_time', 'evaluate_time', 'hit_rate', 'ndcg'])\
.to_csv('NCF_log_dim_{}__K_{}.csv'.format(args.embed_dim, args.K), index=False)
```
### **2.3 Caser**
```
args = Args(model='caser')
# ========================== Create dataset =======================
feature_columns, train, val, test = create_implicit_ml_1m_dataset(args.file, args.trans_score, args.embed_dim, args.maxlen)
train_X, train_y = train
val_X, val_y = val
# ============================Build Model==========================
model = Caser(feature_columns, args.maxlen, args.hor_n, args.hor_h, args.ver_n, args.dropout, args.activation, args.embed_reg)
model.summary()
# =========================Compile============================
model.compile(loss=BinaryCrossentropy(), optimizer=Adam(learning_rate=args.learning_rate))
results = []
for epoch in range(1, args.epochs + 1):
# ===========================Fit==============================
t1 = time()
model.fit(
train_X,
train_y,
validation_data=(val_X, val_y),
epochs=1,
batch_size=args.batch_size,
)
# ===========================Test==============================
t2 = time()
if epoch % 2 == 0:
hit_rate, ndcg = evaluate_model(model, test, args.K, ver=2)
print('Iteration %d Fit [%.1f s], Evaluate [%.1f s]: HR = %.4f, NDCG= %.4f'
% (epoch, t2 - t1, time() - t2, hit_rate, ndcg))
results.append([epoch + 1, t2 - t1, time() - t2, hit_rate, ndcg])
# ============================Write============================
pd.DataFrame(results, columns=['Iteration', 'fit_time', 'evaluate_time', 'hit_rate', 'ndcg']).\
to_csv('Caser_log_maxlen_{}_dim_{}_hor_n_{}_ver_n_{}_K_{}_.csv'.
format(args.maxlen, args.embed_dim, args.hor_n, args.ver_n, args.K), index=False)
```
## **Closure**
For more details, you can refer to https://github.com/RecoHut-Stanzas/S021355.
<a href="https://github.com/RecoHut-Stanzas/S021355/blob/main/reports/S021355.ipynb" alt="S021355_Report"> <img src="https://img.shields.io/static/v1?label=report&message=active&color=green" /></a> <a href="https://github.com/RecoHut-Stanzas/S021355" alt="S021355"> <img src="https://img.shields.io/static/v1?label=code&message=github&color=blue" /></a>
```
!pip install -q watermark
%reload_ext watermark
%watermark -a "Sparsh A." -m -iv -u -t -d
```
---
**END**
| github_jupyter |
# Image Captioning with LSTMs
In the previous exercise you implemented a vanilla RNN and applied it to image captioning. In this notebook you will implement the LSTM update rule and use it for image captioning.
```
# As usual, a bit of setup
from __future__ import print_function
import time, os, json
import numpy as np
import matplotlib.pyplot as plt
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.rnn_layers import *
from cs231n.captioning_solver import CaptioningSolver
from cs231n.classifiers.rnn import CaptioningRNN
from cs231n.coco_utils import load_coco_data, sample_coco_minibatch, decode_captions
from cs231n.image_utils import image_from_url
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
```
# Load MS-COCO data
As in the previous notebook, we will use the Microsoft COCO dataset for captioning.
```
# Load COCO data from disk; this returns a dictionary
# We'll work with dimensionality-reduced features for this notebook, but feel
# free to experiment with the original features by changing the flag below.
data = load_coco_data(pca_features=True)
# Print out all the keys and values from the data dictionary
for k, v in data.items():
if type(v) == np.ndarray:
print(k, type(v), v.shape, v.dtype)
else:
print(k, type(v), len(v))
```
# LSTM
If you read recent papers, you'll see that many people use a variant on the vanialla RNN called Long-Short Term Memory (LSTM) RNNs. Vanilla RNNs can be tough to train on long sequences due to vanishing and exploding gradiants caused by repeated matrix multiplication. LSTMs solve this problem by replacing the simple update rule of the vanilla RNN with a gating mechanism as follows.
Similar to the vanilla RNN, at each timestep we receive an input $x_t\in\mathbb{R}^D$ and the previous hidden state $h_{t-1}\in\mathbb{R}^H$; the LSTM also maintains an $H$-dimensional *cell state*, so we also receive the previous cell state $c_{t-1}\in\mathbb{R}^H$. The learnable parameters of the LSTM are an *input-to-hidden* matrix $W_x\in\mathbb{R}^{4H\times D}$, a *hidden-to-hidden* matrix $W_h\in\mathbb{R}^{4H\times H}$ and a *bias vector* $b\in\mathbb{R}^{4H}$.
At each timestep we first compute an *activation vector* $a\in\mathbb{R}^{4H}$ as $a=W_xx_t + W_hh_{t-1}+b$. We then divide this into four vectors $a_i,a_f,a_o,a_g\in\mathbb{R}^H$ where $a_i$ consists of the first $H$ elements of $a$, $a_f$ is the next $H$ elements of $a$, etc. We then compute the *input gate* $g\in\mathbb{R}^H$, *forget gate* $f\in\mathbb{R}^H$, *output gate* $o\in\mathbb{R}^H$ and *block input* $g\in\mathbb{R}^H$ as
$$
\begin{align*}
i = \sigma(a_i) \hspace{2pc}
f = \sigma(a_f) \hspace{2pc}
o = \sigma(a_o) \hspace{2pc}
g = \tanh(a_g)
\end{align*}
$$
where $\sigma$ is the sigmoid function and $\tanh$ is the hyperbolic tangent, both applied elementwise.
Finally we compute the next cell state $c_t$ and next hidden state $h_t$ as
$$
c_{t} = f\odot c_{t-1} + i\odot g \hspace{4pc}
h_t = o\odot\tanh(c_t)
$$
where $\odot$ is the elementwise product of vectors.
In the rest of the notebook we will implement the LSTM update rule and apply it to the image captioning task.
In the code, we assume that data is stored in batches so that $X_t \in \mathbb{R}^{N\times D}$, and will work with *transposed* versions of the parameters: $W_x \in \mathbb{R}^{D \times 4H}$, $W_h \in \mathbb{R}^{H\times 4H}$ so that activations $A \in \mathbb{R}^{N\times 4H}$ can be computed efficiently as $A = X_t W_x + H_{t-1} W_h$
# LSTM: step forward
Implement the forward pass for a single timestep of an LSTM in the `lstm_step_forward` function in the file `cs231n/rnn_layers.py`. This should be similar to the `rnn_step_forward` function that you implemented above, but using the LSTM update rule instead.
Once you are done, run the following to perform a simple test of your implementation. You should see errors around `1e-8` or less.
```
N, D, H = 3, 4, 5
x = np.linspace(-0.4, 1.2, num=N*D).reshape(N, D)
prev_h = np.linspace(-0.3, 0.7, num=N*H).reshape(N, H)
prev_c = np.linspace(-0.4, 0.9, num=N*H).reshape(N, H)
Wx = np.linspace(-2.1, 1.3, num=4*D*H).reshape(D, 4 * H)
Wh = np.linspace(-0.7, 2.2, num=4*H*H).reshape(H, 4 * H)
b = np.linspace(0.3, 0.7, num=4*H)
next_h, next_c, cache = lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)
expected_next_h = np.asarray([
[ 0.24635157, 0.28610883, 0.32240467, 0.35525807, 0.38474904],
[ 0.49223563, 0.55611431, 0.61507696, 0.66844003, 0.7159181 ],
[ 0.56735664, 0.66310127, 0.74419266, 0.80889665, 0.858299 ]])
expected_next_c = np.asarray([
[ 0.32986176, 0.39145139, 0.451556, 0.51014116, 0.56717407],
[ 0.66382255, 0.76674007, 0.87195994, 0.97902709, 1.08751345],
[ 0.74192008, 0.90592151, 1.07717006, 1.25120233, 1.42395676]])
print('next_h error: ', rel_error(expected_next_h, next_h))
print('next_c error: ', rel_error(expected_next_c, next_c))
```
# LSTM: step backward
Implement the backward pass for a single LSTM timestep in the function `lstm_step_backward` in the file `cs231n/rnn_layers.py`. Once you are done, run the following to perform numeric gradient checking on your implementation. You should see errors around `1e-6` or less.
```
np.random.seed(231)
N, D, H = 4, 5, 6
x = np.random.randn(N, D)
prev_h = np.random.randn(N, H)
prev_c = np.random.randn(N, H)
Wx = np.random.randn(D, 4 * H)
Wh = np.random.randn(H, 4 * H)
b = np.random.randn(4 * H)
next_h, next_c, cache = lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)
dnext_h = np.random.randn(*next_h.shape)
dnext_c = np.random.randn(*next_c.shape)
fx_h = lambda x: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[0]
fh_h = lambda h: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[0]
fc_h = lambda c: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[0]
fWx_h = lambda Wx: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[0]
fWh_h = lambda Wh: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[0]
fb_h = lambda b: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[0]
fx_c = lambda x: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[1]
fh_c = lambda h: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[1]
fc_c = lambda c: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[1]
fWx_c = lambda Wx: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[1]
fWh_c = lambda Wh: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[1]
fb_c = lambda b: lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b)[1]
num_grad = eval_numerical_gradient_array
dx_num = num_grad(fx_h, x, dnext_h) + num_grad(fx_c, x, dnext_c)
dh_num = num_grad(fh_h, prev_h, dnext_h) + num_grad(fh_c, prev_h, dnext_c)
dc_num = num_grad(fc_h, prev_c, dnext_h) + num_grad(fc_c, prev_c, dnext_c)
dWx_num = num_grad(fWx_h, Wx, dnext_h) + num_grad(fWx_c, Wx, dnext_c)
dWh_num = num_grad(fWh_h, Wh, dnext_h) + num_grad(fWh_c, Wh, dnext_c)
db_num = num_grad(fb_h, b, dnext_h) + num_grad(fb_c, b, dnext_c)
dx, dh, dc, dWx, dWh, db = lstm_step_backward(dnext_h, dnext_c, cache)
print('dx error: ', rel_error(dx_num, dx))
print('dh error: ', rel_error(dh_num, dh))
print('dc error: ', rel_error(dc_num, dc))
print('dWx error: ', rel_error(dWx_num, dWx))
print('dWh error: ', rel_error(dWh_num, dWh))
print('db error: ', rel_error(db_num, db))
```
# LSTM: forward
In the function `lstm_forward` in the file `cs231n/rnn_layers.py`, implement the `lstm_forward` function to run an LSTM forward on an entire timeseries of data.
When you are done, run the following to check your implementation. You should see an error around `1e-7`.
```
N, D, H, T = 2, 5, 4, 3
x = np.linspace(-0.4, 0.6, num=N*T*D).reshape(N, T, D)
h0 = np.linspace(-0.4, 0.8, num=N*H).reshape(N, H)
Wx = np.linspace(-0.2, 0.9, num=4*D*H).reshape(D, 4 * H)
Wh = np.linspace(-0.3, 0.6, num=4*H*H).reshape(H, 4 * H)
b = np.linspace(0.2, 0.7, num=4*H)
h, cache = lstm_forward(x, h0, Wx, Wh, b)
expected_h = np.asarray([
[[ 0.01764008, 0.01823233, 0.01882671, 0.0194232 ],
[ 0.11287491, 0.12146228, 0.13018446, 0.13902939],
[ 0.31358768, 0.33338627, 0.35304453, 0.37250975]],
[[ 0.45767879, 0.4761092, 0.4936887, 0.51041945],
[ 0.6704845, 0.69350089, 0.71486014, 0.7346449 ],
[ 0.81733511, 0.83677871, 0.85403753, 0.86935314]]])
print('h error: ', rel_error(expected_h, h))
```
# LSTM: backward
Implement the backward pass for an LSTM over an entire timeseries of data in the function `lstm_backward` in the file `cs231n/rnn_layers.py`. When you are done, run the following to perform numeric gradient checking on your implementation. You should see errors around `1e-7` or less.
```
from cs231n.rnn_layers import lstm_forward, lstm_backward
np.random.seed(231)
N, D, T, H = 2, 3, 10, 6
x = np.random.randn(N, T, D)
h0 = np.random.randn(N, H)
Wx = np.random.randn(D, 4 * H)
Wh = np.random.randn(H, 4 * H)
b = np.random.randn(4 * H)
out, cache = lstm_forward(x, h0, Wx, Wh, b)
dout = np.random.randn(*out.shape)
dx, dh0, dWx, dWh, db = lstm_backward(dout, cache)
fx = lambda x: lstm_forward(x, h0, Wx, Wh, b)[0]
fh0 = lambda h0: lstm_forward(x, h0, Wx, Wh, b)[0]
fWx = lambda Wx: lstm_forward(x, h0, Wx, Wh, b)[0]
fWh = lambda Wh: lstm_forward(x, h0, Wx, Wh, b)[0]
fb = lambda b: lstm_forward(x, h0, Wx, Wh, b)[0]
dx_num = eval_numerical_gradient_array(fx, x, dout)
dh0_num = eval_numerical_gradient_array(fh0, h0, dout)
dWx_num = eval_numerical_gradient_array(fWx, Wx, dout)
dWh_num = eval_numerical_gradient_array(fWh, Wh, dout)
db_num = eval_numerical_gradient_array(fb, b, dout)
print('dx error: ', rel_error(dx_num, dx))
print('dh0 error: ', rel_error(dh0_num, dh0))
print('dWx error: ', rel_error(dWx_num, dWx))
print('dWh error: ', rel_error(dWh_num, dWh))
print('db error: ', rel_error(db_num, db))
```
# LSTM captioning model
Now that you have implemented an LSTM, update the implementation of the `loss` method of the `CaptioningRNN` class in the file `cs231n/classifiers/rnn.py` to handle the case where `self.cell_type` is `lstm`. This should require adding less than 10 lines of code.
Once you have done so, run the following to check your implementation. You should see a difference of less than `1e-10`.
```
N, D, W, H = 10, 20, 30, 40
word_to_idx = {'<NULL>': 0, 'cat': 2, 'dog': 3}
V = len(word_to_idx)
T = 13
model = CaptioningRNN(word_to_idx,
input_dim=D,
wordvec_dim=W,
hidden_dim=H,
cell_type='lstm',
dtype=np.float64)
# Set all model parameters to fixed values
for k, v in model.params.items():
model.params[k] = np.linspace(-1.4, 1.3, num=v.size).reshape(*v.shape)
features = np.linspace(-0.5, 1.7, num=N*D).reshape(N, D)
captions = (np.arange(N * T) % V).reshape(N, T)
loss, grads = model.loss(features, captions)
expected_loss = 9.82445935443
print('loss: ', loss)
print('expected loss: ', expected_loss)
print('difference: ', abs(loss - expected_loss))
```
# Overfit LSTM captioning model
Run the following to overfit an LSTM captioning model on the same small dataset as we used for the RNN previously. You should see losses less than 0.5.
```
np.random.seed(231)
small_data = load_coco_data(max_train=50)
small_lstm_model = CaptioningRNN(
cell_type='lstm',
word_to_idx=data['word_to_idx'],
input_dim=data['train_features'].shape[1],
hidden_dim=512,
wordvec_dim=256,
dtype=np.float32,
)
small_lstm_solver = CaptioningSolver(small_lstm_model, small_data,
update_rule='adam',
num_epochs=50,
batch_size=25,
optim_config={
'learning_rate': 5e-3,
},
lr_decay=0.995,
verbose=True, print_every=10,
)
small_lstm_solver.train()
# Plot the training losses
plt.plot(small_lstm_solver.loss_history)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.title('Training loss history')
plt.show()
```
# LSTM test-time sampling
Modify the `sample` method of the `CaptioningRNN` class to handle the case where `self.cell_type` is `lstm`. This should take fewer than 10 lines of code.
When you are done run the following to sample from your overfit LSTM model on some training and validation set samples.
```
for split in ['train', 'val']:
minibatch = sample_coco_minibatch(small_data, split=split, batch_size=2)
gt_captions, features, urls = minibatch
gt_captions = decode_captions(gt_captions, data['idx_to_word'])
sample_captions = small_lstm_model.sample(features)
sample_captions = decode_captions(sample_captions, data['idx_to_word'])
for gt_caption, sample_caption, url in zip(gt_captions, sample_captions, urls):
plt.imshow(image_from_url(url))
plt.title('%s\n%s\nGT:%s' % (split, sample_caption, gt_caption))
plt.axis('off')
plt.show()
```
# Extra Credit: Train a good captioning model!
Using the pieces you have implemented in this and the previous notebook, try to train a captioning model that gives decent qualitative results (better than the random garbage you saw with the overfit models) when sampling on the validation set. You can subsample the training set if you want; we just want to see samples on the validation set that are better than random.
In addition to qualitatively evaluating your model by inspecting its results, you can also quantitatively evaluate your model using the BLEU unigram precision metric. We'll give you a small amount of extra credit if you can train a model that achieves a BLEU unigram score of >0.3. BLEU scores range from 0 to 1; the closer to 1, the better. Here's a reference to the [paper](http://www.aclweb.org/anthology/P02-1040.pdf) that introduces BLEU if you're interested in learning more about how it works.
Feel free to use PyTorch or TensorFlow for this section if you'd like to train faster on a GPU... though you can definitely get above 0.3 using your Numpy code. We're providing you the evaluation code that is compatible with the Numpy model as defined above... you should be able to adapt it for TensorFlow/PyTorch if you go that route.
```
def BLEU_score(gt_caption, sample_caption):
"""
gt_caption: string, ground-truth caption
sample_caption: string, your model's predicted caption
Returns unigram BLEU score.
"""
reference = [x for x in gt_caption.split(' ')
if ('<END>' not in x and '<START>' not in x and '<UNK>' not in x)]
hypothesis = [x for x in sample_caption.split(' ')
if ('<END>' not in x and '<START>' not in x and '<UNK>' not in x)]
BLEUscore = nltk.translate.bleu_score.sentence_bleu([reference], hypothesis, weights = [1])
return BLEUscore
def evaluate_model(model):
"""
model: CaptioningRNN model
Prints unigram BLEU score averaged over 1000 training and val examples.
"""
for split in ['train', 'val']:
minibatch = sample_coco_minibatch(med_data, split=split, batch_size=1000)
gt_captions, features, urls = minibatch
gt_captions = decode_captions(gt_captions, data['idx_to_word'])
sample_captions = model.sample(features)
sample_captions = decode_captions(sample_captions, data['idx_to_word'])
total_score = 0.0
for gt_caption, sample_caption, url in zip(gt_captions, sample_captions, urls):
total_score += BLEU_score(gt_caption, sample_caption)
BLEUscores[split] = total_score / len(sample_captions)
for split in BLEUscores:
print('Average BLEU score for %s: %f' % (split, BLEUscores[split]))
```
| 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.
```
# Hello, many worlds
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/quantum/tutorials/hello_many_worlds"><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/quantum/blob/master/docs/tutorials/hello_many_worlds.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/quantum/blob/master/docs/tutorials/hello_many_worlds.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/quantum/docs/tutorials/hello_many_worlds.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
This tutorial shows how a classical neural network can learn to correct qubit calibration errors. It introduces <a target="_blank" href="https://github.com/quantumlib/Cirq" class="external">Cirq</a>, a Python framework to create, edit, and invoke Noisy Intermediate Scale Quantum (NISQ) circuits, and demonstrates how Cirq interfaces with TensorFlow Quantum.
## Setup
```
!pip install tensorflow==2.3.1
```
Install TensorFlow Quantum:
```
!pip install tensorflow-quantum
```
Now import TensorFlow and the module dependencies:
```
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit
```
## 1. The Basics
### 1.1 Cirq and parameterized quantum circuits
Before exploring TensorFlow Quantum (TFQ), let's look at some <a target="_blank" href="https://github.com/quantumlib/Cirq" class="external">Cirq</a> basics. Cirq is a Python library for quantum computing from Google. You use it to define circuits, including static and parameterized gates.
Cirq uses <a target="_blank" href="https://www.sympy.org" class="external">SymPy</a> symbols to represent free parameters.
```
a, b = sympy.symbols('a b')
```
The following code creates a two-qubit circuit using your parameters:
```
# Create two qubits
q0, q1 = cirq.GridQubit.rect(1, 2)
# Create a circuit on these qubits using the parameters you created above.
circuit = cirq.Circuit(
cirq.rx(a).on(q0),
cirq.ry(b).on(q1), cirq.CNOT(control=q0, target=q1))
SVGCircuit(circuit)
```
To evaluate circuits, you can use the `cirq.Simulator` interface. You replace free parameters in a circuit with specific numbers by passing in a `cirq.ParamResolver` object. The following code calculates the raw state vector output of your parameterized circuit:
```
# Calculate a state vector with a=0.5 and b=-0.5.
resolver = cirq.ParamResolver({a: 0.5, b: -0.5})
output_state_vector = cirq.Simulator().simulate(circuit, resolver).final_state_vector
output_state_vector
```
State vectors are not directly accessible outside of simulation (notice the complex numbers in the output above). To be physically realistic, you must specify a measurement, which converts a state vector into a real number that classical computers can understand. Cirq specifies measurements using combinations of the <a target="_blank" href="https://en.wikipedia.org/wiki/Pauli_matrices" class="external">Pauli operators</a> $\hat{X}$, $\hat{Y}$, and $\hat{Z}$. As illustration, the following code measures $\hat{Z}_0$ and $\frac{1}{2}\hat{Z}_0 + \hat{X}_1$ on the state vector you just simulated:
```
z0 = cirq.Z(q0)
qubit_map={q0: 0, q1: 1}
z0.expectation_from_state_vector(output_state_vector, qubit_map).real
z0x1 = 0.5 * z0 + cirq.X(q1)
z0x1.expectation_from_state_vector(output_state_vector, qubit_map).real
```
### 1.2 Quantum circuits as tensors
TensorFlow Quantum (TFQ) provides `tfq.convert_to_tensor`, a function that converts Cirq objects into tensors. This allows you to send Cirq objects to our <a target="_blank" href="https://www.tensorflow.org/quantum/api_docs/python/tfq/layers">quantum layers</a> and <a target="_blank" href="https://www.tensorflow.org/quantum/api_docs/python/tfq/get_expectation_op">quantum ops</a>. The function can be called on lists or arrays of Cirq Circuits and Cirq Paulis:
```
# Rank 1 tensor containing 1 circuit.
circuit_tensor = tfq.convert_to_tensor([circuit])
print(circuit_tensor.shape)
print(circuit_tensor.dtype)
```
This encodes the Cirq objects as `tf.string` tensors that `tfq` operations decode as needed.
```
# Rank 1 tensor containing 2 Pauli operators.
pauli_tensor = tfq.convert_to_tensor([z0, z0x1])
pauli_tensor.shape
```
### 1.3 Batching circuit simulation
TFQ provides methods for computing expectation values, samples, and state vectors. For now, let's focus on *expectation values*.
The highest-level interface for calculating expectation values is the `tfq.layers.Expectation` layer, which is a `tf.keras.Layer`. In its simplest form, this layer is equivalent to simulating a parameterized circuit over many `cirq.ParamResolvers`; however, TFQ allows batching following TensorFlow semantics, and circuits are simulated using efficient C++ code.
Create a batch of values to substitute for our `a` and `b` parameters:
```
batch_vals = np.array(np.random.uniform(0, 2 * np.pi, (5, 2)), dtype=np.float32)
```
Batching circuit execution over parameter values in Cirq requires a loop:
```
cirq_results = []
cirq_simulator = cirq.Simulator()
for vals in batch_vals:
resolver = cirq.ParamResolver({a: vals[0], b: vals[1]})
final_state_vector = cirq_simulator.simulate(circuit, resolver).final_state_vector
cirq_results.append(
[z0.expectation_from_state_vector(final_state_vector, {
q0: 0,
q1: 1
}).real])
print('cirq batch results: \n {}'.format(np.array(cirq_results)))
```
The same operation is simplified in TFQ:
```
tfq.layers.Expectation()(circuit,
symbol_names=[a, b],
symbol_values=batch_vals,
operators=z0)
```
## 2. Hybrid quantum-classical optimization
Now that you've seen the basics, let's use TensorFlow Quantum to construct a *hybrid quantum-classical neural net*. You will train a classical neural net to control a single qubit. The control will be optimized to correctly prepare the qubit in the `0` or `1` state, overcoming a simulated systematic calibration error. This figure shows the architecture:
<img src="./images/nn_control1.png" width="1000">
Even without a neural network this is a straightforward problem to solve, but the theme is similar to the real quantum control problems you might solve using TFQ. It demonstrates an end-to-end example of a quantum-classical computation using the `tfq.layers.ControlledPQC` (Parametrized Quantum Circuit) layer inside of a `tf.keras.Model`.
For the implementation of this tutorial, this is architecture is split into 3 parts:
- The *input circuit* or *datapoint circuit*: The first three $R$ gates.
- The *controlled circuit*: The other three $R$ gates.
- The *controller*: The classical neural-network setting the parameters of the controlled circuit.
### 2.1 The controlled circuit definition
Define a learnable single bit rotation, as indicated in the figure above. This will correspond to our controlled circuit.
```
# Parameters that the classical NN will feed values into.
control_params = sympy.symbols('theta_1 theta_2 theta_3')
# Create the parameterized circuit.
qubit = cirq.GridQubit(0, 0)
model_circuit = cirq.Circuit(
cirq.rz(control_params[0])(qubit),
cirq.ry(control_params[1])(qubit),
cirq.rx(control_params[2])(qubit))
SVGCircuit(model_circuit)
```
### 2.2 The controller
Now define controller network:
```
# The classical neural network layers.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='elu'),
tf.keras.layers.Dense(3)
])
```
Given a batch of commands, the controller outputs a batch of control signals for the controlled circuit.
The controller is randomly initialized so these outputs are not useful, yet.
```
controller(tf.constant([[0.0],[1.0]])).numpy()
```
### 2.3 Connect the controller to the circuit
Use `tfq` to connect the controller to the controlled circuit, as a single `keras.Model`.
See the [Keras Functional API guide](https://www.tensorflow.org/guide/keras/functional) for more about this style of model definition.
First define the inputs to the model:
```
# This input is the simulated miscalibration that the model will learn to correct.
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.string,
name='circuits_input')
# Commands will be either `0` or `1`, specifying the state to set the qubit to.
commands_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.float32,
name='commands_input')
```
Next apply operations to those inputs, to define the computation.
```
dense_2 = controller(commands_input)
# TFQ layer for classically controlled circuits.
expectation_layer = tfq.layers.ControlledPQC(model_circuit,
# Observe Z
operators = cirq.Z(qubit))
expectation = expectation_layer([circuits_input, dense_2])
```
Now package this computation as a `tf.keras.Model`:
```
# The full Keras model is built from our layers.
model = tf.keras.Model(inputs=[circuits_input, commands_input],
outputs=expectation)
```
The network architecture is indicated by the plot of the model below.
Compare this model plot to the architecture diagram to verify correctness.
Note: May require a system install of the `graphviz` package.
```
tf.keras.utils.plot_model(model, show_shapes=True, dpi=70)
```
This model takes two inputs: The commands for the controller, and the input-circuit whose output the controller is attempting to correct.
### 2.4 The dataset
The model attempts to output the correct correct measurement value of $\hat{Z}$ for each command. The commands and correct values are defined below.
```
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired Z expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
```
This is not the entire training dataset for this task.
Each datapoint in the dataset also needs an input circuit.
### 2.4 Input circuit definition
The input-circuit below defines the random miscalibration the model will learn to correct.
```
random_rotations = np.random.uniform(0, 2 * np.pi, 3)
noisy_preparation = cirq.Circuit(
cirq.rx(random_rotations[0])(qubit),
cirq.ry(random_rotations[1])(qubit),
cirq.rz(random_rotations[2])(qubit)
)
datapoint_circuits = tfq.convert_to_tensor([
noisy_preparation
] * 2) # Make two copied of this circuit
```
There are two copies of the circuit, one for each datapoint.
```
datapoint_circuits.shape
```
### 2.5 Training
With the inputs defined you can test-run the `tfq` model.
```
model([datapoint_circuits, commands]).numpy()
```
Now run a standard training process to adjust these values towards the `expected_outputs`.
```
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
model.compile(optimizer=optimizer, loss=loss)
history = model.fit(x=[datapoint_circuits, commands],
y=expected_outputs,
epochs=30,
verbose=0)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
```
From this plot you can see that the neural network has learned to overcome the systematic miscalibration.
### 2.6 Verify outputs
Now use the trained model, to correct the qubit calibration errors. With Cirq:
```
def check_error(command_values, desired_values):
"""Based on the value in `command_value` see how well you could prepare
the full circuit to have `desired_value` when taking expectation w.r.t. Z."""
params_to_prepare_output = controller(command_values).numpy()
full_circuit = noisy_preparation + model_circuit
# Test how well you can prepare a state to get expectation the expectation
# value in `desired_values`
for index in [0, 1]:
state = cirq_simulator.simulate(
full_circuit,
{s:v for (s,v) in zip(control_params, params_to_prepare_output[index])}
).final_state_vector
expectation = z0.expectation_from_state_vector(state, {qubit: 0}).real
print(f'For a desired output (expectation) of {desired_values[index]} with'
f' noisy preparation, the controller\nnetwork found the following '
f'values for theta: {params_to_prepare_output[index]}\nWhich gives an'
f' actual expectation of: {expectation}\n')
check_error(commands, expected_outputs)
```
The value of the loss function during training provides a rough idea of how well the model is learning. The lower the loss, the closer the expectation values in the above cell is to `desired_values`. If you aren't as concerned with the parameter values, you can always check the outputs from above using `tfq`:
```
model([datapoint_circuits, commands])
```
## 3 Learning to prepare eigenstates of different operators
The choice of the $\pm \hat{Z}$ eigenstates corresponding to 1 and 0 was arbitrary. You could have just as easily wanted 1 to correspond to the $+ \hat{Z}$ eigenstate and 0 to correspond to the $-\hat{X}$ eigenstate. One way to accomplish this is by specifying a different measurement operator for each command, as indicated in the figure below:
<img src="./images/nn_control2.png" width="1000">
This requires use of <code>tfq.layers.Expectation</code>. Now your input has grown to include three objects: circuit, command, and operator. The output is still the expectation value.
### 3.1 New model definition
Lets take a look at the model to accomplish this task:
```
# Define inputs.
commands_input = tf.keras.layers.Input(shape=(1),
dtype=tf.dtypes.float32,
name='commands_input')
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.dtypes.string,
name='circuits_input')
operators_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.string,
name='operators_input')
```
Here is the controller network:
```
# Define classical NN.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='elu'),
tf.keras.layers.Dense(3)
])
```
Combine the circuit and the controller into a single `keras.Model` using `tfq`:
```
dense_2 = controller(commands_input)
# Since you aren't using a PQC or ControlledPQC you must append
# your model circuit onto the datapoint circuit tensor manually.
full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit)
expectation_output = tfq.layers.Expectation()(full_circuit,
symbol_names=control_params,
symbol_values=dense_2,
operators=operators_input)
# Contruct your Keras model.
two_axis_control_model = tf.keras.Model(
inputs=[circuits_input, commands_input, operators_input],
outputs=[expectation_output])
```
### 3.2 The dataset
Now you will also include the operators you wish to measure for each datapoint you supply for `model_circuit`:
```
# The operators to measure, for each command.
operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]])
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
```
### 3.3 Training
Now that you have your new inputs and outputs you can train once again using keras.
```
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
two_axis_control_model.compile(optimizer=optimizer, loss=loss)
history = two_axis_control_model.fit(
x=[datapoint_circuits, commands, operator_data],
y=expected_outputs,
epochs=30,
verbose=1)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
```
The loss function has dropped to zero.
The `controller` is available as a stand-alone model. Call the controller, and check its response to each command signal. It would take some work to correctly compare these outputs to the contents of `random_rotations`.
```
controller.predict(np.array([0,1]))
```
Success: See if you can adapt the `check_error` function from your first model to work with this new model architecture.
| github_jupyter |
```
%matplotlib inline
import sys
sys.path.append('..')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
rect1 = pd.DataFrame(np.random.rand(1000, 2)*np.asarray([0.2, 1]), columns=['a', 'b'])
rect2 = pd.DataFrame(np.random.rand(100, 2)*np.asarray([0.2, 0.1]) + 0.5, columns=['a', 'b'])
rect = pd.concat([rect1, rect2])
plt.figure()
ax = plt.subplot(111)
rect.plot.scatter(x='a', y='b', ax=ax)
plt.axis('off')
plt.savefig('original_problem.png')
kmeans = KMeans(n_clusters=2)
kmeans.fit(rect)
labels = kmeans.predict(rect)
labels
rect.head()
plt.figure()
ax = plt.subplot(111)
rect.loc[labels== 0].plot.scatter(x='a', y='b', ax=ax)
rect.loc[labels== 1].plot.scatter(x='a', y='b', color='r', ax=ax)
plt.axis('off')
plt.savefig('bad_kmeans.png')
from clusteror import Clusteror
clusteror = Clusteror(rect)
clusteror.cleaned_data = np.tanh(rect - rect.median())
clusteror.train_sda_dim_reducer(hidden_layers_sizes=[5], corruption_levels=[0.1])
clusteror.reduce_to_one_dim()
clusteror.train_kmeans(n_clusters=2)
clusteror.add_cluster()
clusteror.raw_data.head()
plt.figure()
ax = plt.subplot(111)
clusteror.raw_data.loc[(clusteror.raw_data.cluster == 1).values].plot.scatter(x='a', y='b', ax=ax)
clusteror.raw_data.loc[(clusteror.raw_data.cluster == 0).values].plot.scatter(x='a', y='b', ax=ax, color='r')
plt.axis('off')
plt.savefig('leveraged_kmeans.png')
clusteror.raw_data.cluster.value_counts()
from clusteror.plot import *
hist_plot_one_dim_group_data(clusteror.one_dim_data, clusteror.raw_data.cluster, show=False, filepath='hist.png')
valley_clusteror = Clusteror(rect)
valley_clusteror.cleaned_data = np.tanh(rect.iloc[:, :2] - rect.iloc[:, :2].median())
valley_clusteror.train_sda_dim_reducer()
valley_clusteror.cleaned_data.head()
valley_clusteror.reduce_to_one_dim()
valley_clusteror.train_valley(bins=200, contrast=0.1)
valley_clusteror.add_cluster()
valley_clusteror.raw_data.cluster.value_counts()
hist_plot_one_dim_group_data(valley_clusteror.one_dim_data, valley_clusteror.raw_data.cluster, bins=100)
ax = valley_clusteror.raw_data.loc[(valley_clusteror.raw_data.cluster == 1).values].plot.scatter(x='a', y='b')
valley_clusteror.raw_data.loc[(valley_clusteror.raw_data.cluster == 2).values].plot.scatter(x='a', y='b', ax=ax, color='r')
#valley_clusteror.raw_data.loc[(valley_clusteror.raw_data.cluster == 3).values].plot.scatter(x='a', y='b', ax=ax, color='k')
ax = valley_clusteror.raw_data.loc[(valley_clusteror.raw_data.cluster == 1).values].plot.scatter(x='a', y='b')
```
| github_jupyter |
# NLP (Natural Language Processing) with Python
This is the notebook that goes along with the NLP video lecture!
In this lecture we will discuss a higher level overview of the basics of Natural Language Processing, which basically consists of combining machine learning techniques with text, and using math and statistics to get that text in a format that the machine learning algorithms can understand!
Once you've completed this lecture you'll have a project using some Yelp Text Data!
**Requirements: You will need to have NLTK installed, along with downloading the corpus for stopwords. To download everything with a conda installation, run the cell below. Or reference the full video lecture**
```
import nltk
nltk.download_shell()
```
## Part 1: Get the Data
We'll be using a dataset from the [UCI datasets](https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection)! This dataset is already located in the folder for this section.
The file we are using contains a collection of more than 5 thousand SMS phone messages. You can check out the **readme** file for more info.
*Recall that __rstrip()__ is used to return a copy of the string with the trailing characters removed.*
<br>
<br>
Let's go ahead and use __rstrip()__ plus a list comprehension to get a list of all the lines of text messages:
```
messages = [line.rstrip() for line in open('smsspamcollection/SMSSpamCollection')]
print(len(messages))
messages[10]
```
<font color=#2948ff>A collection of texts is also sometimes called __"corpus"__. Let's print the first ten messages and number them using **enumerate**:</font>
```
for message_number, message in enumerate(messages[:11]):
print(message_number, message)
print('\n')
```
Due to the spacing we can tell that this is a **[TSV](http://en.wikipedia.org/wiki/Tab-separated_values) ("tab separated values") file**, where the first column is a label saying whether the given message is a normal message (commonly known as <font color=#a80077>"ham"</font>) or <font color=#a80077>"spam"</font>. The second column is the message itself. (Note our numbers aren't part of the file, they are just from the **enumerate** call).
Using these labeled ham and spam examples, we'll **train a machine learning model to learn to discriminate between ham/spam automatically**. Then, with a trained model, we'll be able to **classify arbitrary unlabeled messages** as ham or spam.
From the official SciKit Learn documentation, we can visualize our process:
Instead of parsing TSV manually using Python, we can just take advantage of pandas! Let's go ahead and import it!
```
import pandas as pd
```
We'll use **read_csv** and make note of the **sep** argument, we can also specify the desired column names by passing in a list of *names*.
```
messages = pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\t', names=['label', 'message'])
messages.head()
```
## Part 2: Exploratory Data Analysis
Let's check out some of the stats with some plots and the built-in methods in pandas!
```
messages.describe()
```
<font color=#a80077>Let's use **groupby** to use describe by label, this way we can begin to think about the features that separate ham and spam!</font>
```
messages.groupby('label').describe()
```
As we continue our analysis we want to start thinking about the features we are going to be using. This goes along with the general idea of [feature engineering](https://en.wikipedia.org/wiki/Feature_engineering). The better your domain knowledge on the data, the better your ability to engineer more features from it. Feature engineering is a very large part of spam detection in general. I encourage you to read up on the topic!
Let's make a new column to detect how long the text messages are:
```
messages['length'] = messages['message'].apply(len)
messages.head()
```
### Data Visualization
Let's visualize this! Let's do the imports:
```
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set_style('whitegrid')
plt.figure(figsize=(12,6))
messages['length'].plot(kind='hist', bins=150, colormap='magma')
```
Play around with the bin size! Looks like text length may be a good feature to think about! Let's try to explain why the x-axis goes all the way to 1000ish, this must mean that there is some really long message!
```
messages['length'].describe()
# messages.length.describe() can also be used here
```
Woah! 910 characters, let's use masking to find this message:
```
messages[messages['length'] == 910]
messages[messages['length'] == 910]['message'].iloc[0]
```
Looks like we have some sort of Romeo sending texts! But let's focus back on the idea of trying to see if message length is a distinguishing feature between ham and spam:
```
messages.hist(column='length', by='label', bins=60, figsize=(12,6))
```
Very interesting! Through just basic EDA we've been able to discover a trend that spam messages tend to have more characters. (Sorry Romeo!)
Now let's begin to process the data so we can eventually use it with SciKit Learn!
## Part 3: Text Pre-processing
Our main issue with our data is that it is all in text format (strings). The classification algorithms that we've learned about so far will need some sort of numerical feature vector in order to perform the classification task. __<font color=#a80077>There are actually many methods to convert a corpus to a vector format. The simplest is the the [bag-of-words](http://en.wikipedia.org/wiki/Bag-of-words_model) approach, where each unique word in a text will be represented by one number.</font>__
In this section we'll convert the raw messages (sequence of characters) into vectors (sequences of numbers).
1. __As a first step, let's write a function that will split a message into its individual words and return a list.__
<br>
2. __We'll also remove very common words, ('the', 'a', etc..).__ To do this we will take advantage of the NLTK library. It's pretty much the standard library in Python for processing text and has a lot of useful features. We'll only use some of the basic ones here.
Let's create a function that will process the string in the message column, then we can just use **apply()** in pandas do process all the text in the DataFrame.
First removing punctuation. We can just take advantage of Python's built-in **string** library to get a quick list of all the possible punctuation:
```
import string
example = 'Sample message! Notice: it has punctuation.'
# Check characters to see if they are in punctuation
nopunc = [char for char in example if char not in string.punctuation]
# Join the characters again to form the string.
nopunc = ''.join(nopunc)
nopunc = ''.join(nopunc)
nopunc
```
Now let's see how to remove stopwords. We can import a list of english stopwords from NLTK (check the documentation for more languages and info).
```
from nltk.corpus import stopwords
# Some English stop words
stopwords.words('english')[:10]
# back to the example, we are going to remove the stopwords in nopunc
nopunc.split()
# remove stopwords
nopunc_clean = [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]
nopunc_clean
```
Now let's put both of these together in a function to apply it to our DataFrame later on:
```
def text_process(mess):
"""
Takes in a string of text, then performs the following:
1. Remove all punctuation
2. Remove all stopwords
3. Returns a list of the cleaned text
"""
# check characters to see if they contain punctuation
nopunc = [char for char in mess if char not in string.punctuation]
# join the characters again to form the string.
nopunc = ''.join(nopunc)
# remove any stopwords
return[word for word in nopunc.split() if word.lower() not in stopwords.words('english')]
```
Here is the original DataFrame again:
```
messages.head()
```
Now let's "tokenize" these messages. <font color=#a80077>__Tokenization__ is just the term used to describe the process of converting the normal text strings in to a list of tokens (words that we actually want).</font>
Let's see an example output on on column:
**Note:**
We may get some warnings or errors for symbols we didn't account for or that weren't in Unicode (like a British pound symbol)
```
# Check to make sure its working
messages['message'].head().apply(text_process)
# Original dataframe
messages.head()
```
### Continuing Normalization
__There are a lot of ways to continue normalizing this text. Such as [Stemming](https://en.wikipedia.org/wiki/Stemming) or distinguishing by [part of speech](http://www.nltk.org/book/ch05.html).__
NLTK has lots of built-in tools and great documentation on a lot of these methods. __*Sometimes they don't work well for text-messages due to the way a lot of people tend to use abbreviations or shorthand*__, For example:
'Nah dawg, IDK! Wut time u headin to da club?'
versus
'No dog, I don't know! What time are you heading to the club?'
Some text normalization methods will have trouble with this type of shorthand and so I'll leave you to explore those more advanced methods through the __[NLTK book online](http://www.nltk.org/book/).__
For now we will just focus on using what we have to convert our list of words to an actual vector that SciKit-Learn can use.
## Part 4: Vectorization
Currently, we have the messages as lists of tokens (also known as [lemmas](http://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html)) and now we need to convert each of those messages into a vector the SciKit Learn's algorithm models can work with.
Now we'll convert each message, represented as a list of tokens (lemmas) above, into a vector that machine learning models can understand.
__We'll do that in three steps using the bag-of-words model:__
1. __Count how many times a word occurs in each message <font color=#a80077>(Term frequency)</font>__
2. __Weigh the counts, so that frequent tokens get lower weight <font color=#a80077>(Inverse document frequency)</font>__
3. __Normalize the vectors to unit length, to abstract from the original text length <font color=#a80077>(L2 norm)</font>__
Let's begin the first step:
Each vector will have as many dimensions as there are unique words in the SMS corpus. We will first use SciKit Learn's **CountVectorizer**. This model will convert a collection of text documents to a matrix of token counts.
We can imagine this as a 2-Dimensional matrix. Where the 1-dimension is the entire vocabulary (1 row per word) and the other dimension are the actual documents, in this case a column per text message.
For example:
<table border = “1“>
<tr>
<th></th> <th>Message 1</th> <th>Message 2</th> <th>...</th> <th>Message N</th>
</tr>
<tr>
<td><b>Word 1 Count</b></td><td>0</td><td>1</td><td>...</td><td>0</td>
</tr>
<tr>
<td><b>Word 2 Count</b></td><td>0</td><td>0</td><td>...</td><td>0</td>
</tr>
<tr>
<td><b>...</b></td> <td>1</td><td>2</td><td>...</td><td>0</td>
</tr>
<tr>
<td><b>Word N Count</b></td> <td>0</td><td>1</td><td>...</td><td>1</td>
</tr>
</table>
Since there are so many messages, we can expect a lot of zero counts for the presence of that word in that document. Because of this, SciKit Learn will output a [Sparse Matrix](https://en.wikipedia.org/wiki/Sparse_matrix).
__<font color=#a80077>Shape Matrix or sparse array is a matrix where most of the elements are zero. If most of the elements are nonzero, then the matrix is considered dense</font>__
```
from sklearn.feature_extraction.text import CountVectorizer
```
There are a lot of arguments and parameters that can be passed to the CountVectorizer. In this case we will just specify the **analyzer** to be our own previously defined function:
```
bow_transformer = CountVectorizer(analyzer=text_process).fit(messages['message'])
# print total number of vocab words
print(len(bow_transformer.vocabulary_))
```
Let's take one text message and get its bag-of-words counts as a vector, putting to use our new `bow_transformer`:
```
message4 = messages['message'][3]
print(message4)
```
Now let's see its vector representation:
```
bow4 = bow_transformer.transform([message4])
print(bow4)
print('\n')
print(bow4.shape)
```
__This means that there are seven unique words in message number 4 (after removing common stop words). Two of them appear twice, the rest only once.__ Let's go ahead and check and confirm which ones appear twice:
```
print(bow_transformer.get_feature_names()[4068])
print(bow_transformer.get_feature_names()[9554])
```
Now we can use **.transform** on our Bag-of-Words (bow) transformed object and transform the entire DataFrame of messages. Let's go ahead and check out how the bag-of-words counts for the entire SMS corpus is a large, sparse matrix:
```
messages_bow = bow_transformer.transform(messages['message'])
print('Shape of Sparse Matrix: ', messages_bow.shape)
# Shape Matrix or sparse array is a matrix where most of the elements are zero.
print('Amount of Non-Zero occurences: ', messages_bow.nnz)
# .nnz == non zero occurences
sparsity = (100.0 * messages_bow.nnz / (messages_bow.shape[0] * messages_bow.shape[1]))
# print('sparsity: {}'.format(sparsity))
print('sparsity: {}'.format(round(sparsity)))
```
After the counting, the term weighting and normalization can be done with [TF-IDF](http://en.wikipedia.org/wiki/Tf%E2%80%93idf), using scikit-learn's `TfidfTransformer`.
____
### So what is TF-IDF?
__<font color=#a80077>TF-IDF stands for *term frequency-inverse document frequency.* The tf-idf weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is *offset* by the frequency of the word in the corpus. Variations of the tf-idf weighting scheme are often used by search engines as a central tool in scoring and ranking a document's relevance given a user query.</font>__
__One of the simplest ranking functions is computed by summing the tf-idf for each query term;__ many more sophisticated ranking functions are variants of this simple model.
__Typically, the tf-idf weight is composed by two terms:__
__<font color=#a80077>The first computes the normalized Term Frequency (TF),</font> aka the number of times a word appears in a document, divided by the total number of words in that document;__
__<font color=#a80077>The second term is the Inverse Document Frequency (IDF),</font> computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears.__
<font color=#a80077>**TF: Term Frequency**</font>, which measures how frequently a term occurs in a document. Since every document is different in length, it is possible that a term would appear much more times in long documents than shorter ones. Thus, the term frequency is often divided by the document length (aka the total number of terms in the document) as a way of normalization:
<font color=#2C7744>*TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document)*</font>
<font color=#a80077>**IDF: Inverse Document Frequency**</font>, which measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as "is", "of", and "that", may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following:
<font color=#2C7744>*IDF(t) = log_e(Total number of documents / Number of documents with term t in it)*</font>
See below for a simple example.
**Example:**
Consider a document containing 100 words wherein the word cat appears 3 times.
The term frequency (i.e., tf) for cat is then (3 / 100) = 0.03. Now, assume we have 10 million documents and the word cat appears in one thousand of these. Then, the inverse document frequency (i.e., idf) is calculated as log(10,000,000 / 1,000) = 4. Thus, the Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12.
____
Let's go ahead and see how we can do this in SciKit Learn:
```
from sklearn.feature_extraction.text import TfidfTransformer
tfidf_transformer = TfidfTransformer().fit(messages_bow)
tfidf4 = tfidf_transformer.transform(bow4)
print(tfidf4)
```
We'll go ahead and check what is the IDF (inverse document frequency) of the word `"u"` and of word `"university"`?
```
print(tfidf_transformer.idf_[bow_transformer.vocabulary_['u']])
print(tfidf_transformer.idf_[bow_transformer.vocabulary_['university']])
```
To transform the entire bag-of-words corpus into TF-IDF corpus at once:
```
messages_tfidf = tfidf_transformer.transform(messages_bow)
print(messages_tfidf.shape)
```
__There are many ways the data can be preprocessed and vectorized. These steps involve feature engineering and building a "pipeline".__ I encourage you to check out SciKit Learn's documentation on dealing with text data as well as the expansive collection of available papers and books on the general topic of NLP.
## Part 5: Training a model
With messages represented as vectors, we can finally train our spam/ham classifier. Now we can actually use almost any sort of classification algorithms. For a [variety of reasons](http://www.inf.ed.ac.uk/teaching/courses/inf2b/learnnotes/inf2b-learn-note07-2up.pdf), the __Naive Bayes classifier algorithm__ is a good choice.
We'll be using scikit-learn here, choosing the [Naive Bayes](http://en.wikipedia.org/wiki/Naive_Bayes_classifier) classifier to start with:
```
from sklearn.naive_bayes import MultinomialNB
spam_detect_model = MultinomialNB().fit(messages_tfidf, messages['label'])
```
Let's try classifying our single random message and checking how we do:
```
print('predicted: ', spam_detect_model.predict(tfidf4)[0])
print('expected: ', messages.label[3])
```
Fantastic! We've developed a model that can attempt to predict spam vs ham classification!
## Part 6: Model Evaluation
Now we want to determine how well our model will do overall on the entire dataset. Let's begin by getting all the predictions:
```
all_predictions = spam_detect_model.predict(messages_tfidf)
print(all_predictions)
```
__We can use SciKit Learn's built-in classification report, which returns [precision, recall,](https://en.wikipedia.org/wiki/Precision_and_recall) [f1-score](https://en.wikipedia.org/wiki/F1_score), and a column for support (meaning how many cases supported that classification).__ Check out the links for more detailed info on each of these metrics and the figure below:
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Precisionrecall.svg/700px-Precisionrecall.svg.png' width=400 />
```
from sklearn.metrics import classification_report
print(classification_report(messages['label'], all_predictions))
```
There are quite a few possible metrics for evaluating model performance. Which one is the most important depends on the task and the business effects of decisions based off of the model. For example, the cost of mis-predicting "spam" as "ham" is probably much lower than mis-predicting "ham" as "spam".
In the above "evaluation", we evaluated accuracy on the same data we used for training. <font color=#DC281E>**You should never actually evaluate on the same dataset you train on!**</font>
Such evaluation tells us nothing about the true predictive power of our model. If we simply remembered each example during training, the accuracy on training data would trivially be 100%, even though we wouldn't be able to classify any new messages.
A proper way is to split the data into a training/test set, where the model only ever sees the **training data** during its model fitting and parameter tuning. The **test data** is never used in any way. This is then our final evaluation on test data is representative of true predictive performance.
## Train Test Split
```
from sklearn.model_selection import train_test_split
msg_train, msg_test, label_train, label_test = train_test_split(messages['message'], messages['label'], test_size=0.3)
print(len(msg_train), len(msg_test), len(msg_train) + len(msg_test))
```
The test size is 30% of the entire dataset (1672 messages out of total 5572), and the training is the rest (3900 out of 5572). Note: this is the default split(30/70).
## Creating a Data Pipeline
Let's run our model again and then predict off the test set. __We will use SciKit Learn's [pipeline](http://scikit-learn.org/stable/modules/pipeline.html) capabilities to store a pipeline of workflow.__ This will allow us to set up all the transformations that we will do to the data for future use. Let's see an example of how it works:
```
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
# strings to token integer counts
('bow', CountVectorizer(analyzer=text_process)),
# integer counts to weighted TF-IDF scores
('tfidf', TfidfTransformer()),
# train on TF-IDF vectors w/ Naive Bayes classifier
('classifier', MultinomialNB()),
])
```
Now we can directly pass message text data and the pipeline will do our pre-processing for us! We can treat it as a model/estimator API:
```
pipeline.fit(msg_train, label_train)
predictions = pipeline.predict(msg_test)
print(classification_report(label_test, predictions))
```
Now we have a classification report for our model on a true testing set! You can try out different classification models. There is a lot more to Natural Language Processing than what we've covered here, and its vast expanse of topic could fill up several college courses! I encourage you to check out the resources below for more information on NLP!
## More Resources
Check out the links below for more info on Natural Language Processing:
[NLTK Book Online](http://www.nltk.org/book/)
[Kaggle Walkthrough](https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-1-for-beginners-bag-of-words)
[SciKit Learn's Tutorial](http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html)
# Good Job!
| github_jupyter |
```
import numpy as np
import pandas as pd
from numpy.testing import assert_array_equal, assert_array_almost_equal, assert_equal
from pandas.testing import assert_frame_equal
import warnings
warnings.filterwarnings("ignore")
```
# Ближайший элемент
Реализуйте функцию, принимающую на вход непустой тензор (может быть многомерным) $X$ и некоторое число $a$ и возвращающую ближайший к числу элемент тензора. Если ближайших несколько - выведите минимальный из ближайших. (Вернуть нужно само число, а не индекс числа!)
### Sample
#### Input:
```python
X = np.array([[ 1, 2, 13],
[15, 6, 8],
[ 7, 18, 9]])
a = 7.2
```
#### Output:
```python
7
```
```
import numpy as np
def nearest_value(X: np.ndarray, a: float) -> float:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
######################################################
assert_equal(
nearest_value(np.array([ 1, 2, 13]), 10),
13)
######################################################
assert_equal(
nearest_value(np.array([ -1, 0]), -0.5),
-1)
######################################################
assert_equal(
nearest_value(np.array([[[ 1], [2],[3]],[[4],[5],[6]]]), 4.5),
4)
######################################################
assert_equal(
nearest_value(np.array([[ 1, 2, 13],
[15, 6, 8],
[ 7, 18, 9]]), 7.2),
7)
######################################################
assert_equal(
nearest_value(np.array([[ -1, -2],
[-15, -6]]), -100),
-15)
######################################################
assert_equal(
nearest_value(np.array([[ 2, 2],
[12, 12]]), 7),
2)
######################################################
assert_equal(
nearest_value(np.array([[ -2, -2],
[-12, -12]]), -7),
-12)
######################################################
```
# Сортировка чисел
Дан одномерный массив целых чисел. Необходимо отсортировать в нем только числа, которые делятся на $2$. При этом начальный массив изменять нельзя.
### Sample
#### Input:
```python
A = np.array([43, 66, 34, 55, 78, 105, 2])
```
#### Output:
```python
array([ 43, 2, 34, 55, 66, 105, 78])
```
```
import numpy as np
def sort_evens(A: np.ndarray) -> np.ndarray:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
######################################################
assert_array_equal(sort_evens(np.array([])), np.array([]))
######################################################
A1 = np.array([2, 0])
A2 = np.array([2, 0])
Ans = np.array([0, 2])
assert_array_equal(sort_evens(A1), Ans)
assert_array_equal(A1, A2)
######################################################
assert_array_equal(sort_evens(np.array([2, 0])), np.array([0, 2]))
######################################################
assert_array_equal(sort_evens(np.array([9, 3, 1, 5, 7])), np.array([9, 3, 1, 5, 7]))
######################################################
assert_array_equal(sort_evens(np.array([8, 12, 4, 10, 6, 2])), np.array([2, 4, 6, 8, 10, 12]))
######################################################
assert_array_equal(sort_evens(np.array([8, 5, -4, -1, -10, 9])), np.array([-10, 5, -4, -1, 8, 9]))
######################################################
assert_array_equal(sort_evens(np.array([43, 66, 34, 55, 78, 105, 2])), np.array([43, 2, 34, 55, 66, 105, 78]))
######################################################
```
# Страшные маски
Даны трехмерный тензор размерности $X(n, k, k)$, состоящий из $0$ или $1$, или $n$ картинок $k \times k$. Нужно применить к нему указанную маску размерности $(k, k)$: В случае, если биты в маске и картинке совпадают, то результирующий бит должен быть равен $0$, иначе $1$.
### Sample
#### Input:
```python
X = np.array([
[[ 1, 0, 1],
[ 1, 1, 1],
[ 0, 0, 1]],
[[ 1, 1, 1],
[ 1, 1, 1],
[ 1, 1, 1]]
])
mask = np.array([[1, 1, 0],
[1, 1, 0],
[1, 1, 0]])
```
#### Output:
```python
array([[[0, 1, 1],
[0, 0, 1],
[1, 1, 1]],
[[0, 0, 1],
[0, 0, 1],
[0, 0, 1]]])
```
```
import numpy as np
def tensor_mask(X: np.ndarray, mask: np.ndarray) -> np.ndarray:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
######################################################
X = np.zeros(9, dtype=int).reshape((1,3,3))
mask = np.zeros(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.zeros(9, dtype=int).reshape((1,3,3)))
######################################################
X = np.ones(9, dtype=int).reshape((1,3,3))
mask = np.ones(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.zeros(9, dtype=int).reshape((1,3,3)))
######################################################
X = np.ones(9, dtype=int).reshape((1,3,3))
mask = np.zeros(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.ones(9, dtype=int).reshape((1,3,3)))
######################################################
X = np.zeros(9, dtype=int).reshape((1,3,3))
mask = np.ones(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.ones(9, dtype=int).reshape((1,3,3)))
######################################################
X = np.zeros(9*3, dtype=int).reshape((3,3,3))
mask = np.zeros(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.zeros(9*3, dtype=int).reshape((3,3,3)))
######################################################
X = np.ones(9*3, dtype=int).reshape((3,3,3))
mask = np.ones(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.zeros(9*3, dtype=int).reshape((3,3,3)))
######################################################
X = np.ones(9*3, dtype=int).reshape((3,3,3))
mask = np.zeros(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.ones(9*3, dtype=int).reshape((3,3,3)))
######################################################
X = np.zeros(9*3, dtype=int).reshape((3,3,3))
mask = np.ones(9, dtype=int).reshape((3,3))
assert_array_equal(tensor_mask(X, mask), np.ones(9*3, dtype=int).reshape((3,3,3)))
######################################################
```
# Сумма цифр в массиве
На вход подается `np.ndarray` c натуральными числами. Надо получить массив сумм цифр в этих числах.
### Sample
#### Input:
```python
a = np.array([1241, 354, 121])
```
#### Output:
```python
array([ 8, 12, 4])
```
```
import numpy as np
def num_sum(a: np.ndarray) -> np.ndarray:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
######################################################
assert_array_equal(num_sum(np.array([82])), np.array([10]))
######################################################
assert_array_equal(num_sum(np.array([1241, 354, 121])), np.array([ 8, 12, 4]))
######################################################
assert_array_equal(num_sum(np.array([1, 22, 333, 4444, 55555])), np.array([1, 4, 9, 16, 25]))
######################################################
```
# Чистка NaN-ов
Одна из важных проблем данных - пустые значения. В *numpy* и *pandas* они обычно объявляются специальным типом ```np.nan```. В реальных задачах нам часто нужно что-то сделать с этими значениями. Например заменить на 0, среднее или медиану.
Реализуйте функцию, которая во входной вещественной матрице ```X``` находит все значения ```nan``` и заменяет их на **медиану** остальных элементов столбца. Если все элементы столбца матрицы ```nan```, то заполняем столбец нулями.
### Sample
#### Input:
```python
X = np.array([[np.nan, 4, np.nan],
[np.nan, np.nan, 8],
[np.nan, 5, np.nan]])
```
#### Output:
```python
array([[0. , 4. , 8. ],
[0. , 4.5, 8. ],
[0. , 5. , 8. ]])
```
```
import numpy as np
def replace_nans(X: np.ndarray) -> np.ndarray:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
from numpy.testing import assert_array_equal, assert_array_almost_equal
######################################################
assert_array_equal(replace_nans(
np.array([[np.nan], [np.nan], [np.nan]])),
np.array([[0. ],[ 0. ],[ 0. ]])
)
######################################################
assert_array_equal(replace_nans(
np.array([[0, 42, 42]])),
np.array([[0, 42 , 42]])
)
######################################################
assert_array_equal(replace_nans(
np.array([[np.nan], [1], [np.nan]])),
np.array([[1.] ,[ 1.] ,[ 1. ]])
)
######################################################
assert_array_equal(replace_nans(
np.array([[4], [1], [np.nan]])),
np.array([[4 ], [1] ,[ 2.5]])
)
######################################################
assert_array_equal(replace_nans(
np.array([[-8], [1], [np.nan]])),
np.array([[-8] , [1] , [-3.5]])
)
######################################################
assert_array_almost_equal(replace_nans(
np.array([[-1.515], [2.252], [np.nan]])),
np.array([[-1.515], [2.252], [0.3685]])
)
######################################################
assert_array_equal(replace_nans(
np.array([[np.nan, np.nan, np.nan],
[ 4, np.nan, 5],
[np.nan, 8, np.nan]]).T),
np.array([[0. , 0. , 0. ],
[4. , 4.5, 5. ],
[8. , 8. , 8. ]]).T
)
######################################################
```
# Бухгалтерия зоопарка
Вам на вход подается словарь, где ключ - это тип животного, а значение - словарь с признаками этого животного, где ключ - тип признака, а значение - значение признака (Типичный json проще говоря). Наименования признаков животного - всегда строки. Значения признаков - любой из типов pandas.
Вам следует создать табличку, где по строчкам будут идти животные, а по колонкам - их признаки, которая удовлетворяет следующим условиям:
* Тип животного нужно выделить в отдельную колонку `Type`
* Строки отсортированы по типу животного в алфавитном порядке
* Колонки отсортированы в алфавитном порядке, кроме колонки `Type` - она первая
* Индексы строк - ряд натуральных чисел начиная с 0 без пропусков
Имейте в виду, что признаки у двух животных могут не совпадать, значит незаполненные данные нужно заполнить `Nan` значением.
Верните на выходе табличку(`DataFrame`), в которой отсутствуют Nan значения. При этом могут отсутствовать некоторые признаки, но животные должны присутствовать **все**. Изначальные типы значений из словаря: `int64`, `float64`, `bool` и.т.д. должны сохраниться и в конечной табличке, а не превратиться в `object`-ы. (От удаляемых признаков этого, очевидно, не требуется).
### Sample 1
#### Input:
```python
ZOO = {
'cat':{'color':'black', 'tail_len': 50, 'injured': False},
'dog':{'age': 6, 'tail_len': 30.5, 'injured': True}
}
```
#### Output:
| | Type | injured |tail_len |
|--|----|--------|-------|
|0 | cat | False | 50.0 |
|1 | dog | True | 30.5 |
```
import numpy as np
import pandas as pd
def ZOOtable(zoo: dict) -> pd.DataFrame:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
######################################################
ZOO = {
'cat': {'color':'black', 'tail_len': 50.0, 'injured': False},
'dog': {'age': 6, 'tail_len': 30.5, 'injured': True}
}
df = ZOOtable(ZOO)
assert_frame_equal(
df.reset_index(drop=True),
pd.DataFrame(
{
'Type':['cat', 'dog'],
'injured':[False, True],
'tail_len':[50.0, 30.5]
}
)
)
######################################################
ZOO = {
'cat': {'color':'black'},
'dog': {'age': 6}
}
df = ZOOtable(ZOO)
assert_frame_equal(
df.reset_index(drop=True),
pd.DataFrame(
{
'Type':['cat', 'dog']
}
)
)
######################################################
```
# Простые преобразования
На вход подается `DataFrame` из 3-х колонок дата рождения и смерти человека на **русском** языке в формате представленом ниже:
| | Имя | Дата рождения | Дата смерти
|--|-----------------|----------------|------------------
|0 |Никола Тесла |10 июля 1856 г. |7 января 1943 г.
|1 |Альберт Эйнштейн |14 марта 1879 г.|18 апреля 1955 г.
Необходимо вернуть исходную таблицу с добавленным в конце столбцом полных лет жизни.
| | Имя | Дата рождения | Дата смерти | Полных лет
|--|-----------------|----------------|-----------------|-----------
|0 |Никола Тесла |10 июля 1856 г. |7 января 1943 г. | 86
|1 |Альберт Эйнштейн |14 марта 1879 г.|18 апреля 1955 г.| 76
Формат даты единый, исключений нет, пробелы между элементами дат присутствуют, исключений (`Nan`) нет.
P.S. Для обработки високосных годов используйте модуль `dateutil.relativedelta`.
```
import numpy as np
import pandas as pd
def rus_feature(df: pd.DataFrame) -> pd.DataFrame:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
######################################################
names = pd.DataFrame({'Имя':['Никола Тесла', 'Альберт Эйнштейн'],
'Дата рождения':['10 июля 1856 г.','14 марта 1879 г.'],
'Дата смерти': ['7 января 1943 г.', '18 апреля 1955 г.']})
assert_frame_equal(
rus_feature(names),
pd.DataFrame({'Имя':['Никола Тесла', 'Альберт Эйнштейн'],
'Дата рождения':['10 июля 1856 г.','14 марта 1879 г.'],
'Дата смерти': ['7 января 1943 г.', '18 апреля 1955 г.'],
'Полных лет':[86, 76]})
)
######################################################
names = pd.DataFrame({'Имя':['Никола Тесла'],
'Дата рождения':['10 июля 1856 г.'],
'Дата смерти': ['7 января 1857 г.']})
assert_frame_equal(
rus_feature(names),
pd.DataFrame({'Имя':['Никола Тесла'],
'Дата рождения':['10 июля 1856 г.'],
'Дата смерти': ['7 января 1857 г.'],
'Полных лет':[0]})
)
######################################################
names = pd.DataFrame({'Имя':['Никола Тесла'],
'Дата рождения':['1 января 2000 г.'],
'Дата смерти': ['31 декабря 2000 г.']})
assert_frame_equal(
rus_feature(names),
pd.DataFrame({'Имя':['Никола Тесла'],
'Дата рождения':['1 января 2000 г.'],
'Дата смерти': ['31 декабря 2000 г.'],
'Полных лет':[0]})
)
######################################################
names = pd.DataFrame({'Имя':['Никола Тесла'],
'Дата рождения':['1 января 2000 г.'],
'Дата смерти': ['1 января 2001 г.']})
assert_frame_equal(
rus_feature(names),
pd.DataFrame({'Имя':['Никола Тесла'],
'Дата рождения':['1 января 2000 г.'],
'Дата смерти': ['1 января 2001 г.'],
'Полных лет':[1]})
)
######################################################
```
# Характеристики
В этой задаче на вход подаются всем известные данные о погибших/выживших пассажирах на титанике. (Файл `titanik_train.csv` в [папке data](https://github.com/samstikhin/ml2021/tree/master/01-Analysis/data)).
Верните максимальное значение, минимальное значение, медиану, среднее, дисперсию возраста **погибших** мужчин. Именно в данном порядке.
### Sample 1
#### Input:
```python
df = pd.read_csv('data/titanic_train.csv', index_col='PassengerId')
```
```
def men_stat(df: pd.DataFrame) -> (float, float, float, float, float):
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
# В этой задаче нет открытых тестов ;)
```
# Сводная таблица
В этой задаче на вход подаются всем известные данные о погибших/выживших пассажирах на титанике. (Файл `titanik_train.csv` в [папке data](https://github.com/samstikhin/ml2021/tree/master/01-Analysis/data)).
Сделать сводную таблицу по **максимальному возрасту** для пола и класса. Для примера посмотрите сводную таблицу по сумме выживших, для пола и класса.
| Sex | Pclass | Survived |
|------------|---------|----------|
| **female** | **1** | 91 |
| | **2** | 70 |
| | **3** | 72 |
| **male** | **1** | 45 |
| | **2** | 17 |
| | **3** | 47 |
Обратите внимание, что первые 2 столбца - это не колонки, а `MultiIndex`.
### Sample 1
#### Input:
```python
df = pd.read_csv('data/titanic_train.csv', index_col='PassengerId')
```
```
def age_stat(df: pd.DataFrame) -> pd.DataFrame:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
# В этой задаче нет открытых тестов ;)
```
# Популярные девушки
В этой задаче на вход подаются всем известные данные о погибших/выживших пассажирах на титанике. (Файл `titanik_train.csv` в [папке data](https://github.com/samstikhin/ml2021/tree/master/01-Analysis/data)).
Выведите список имен незамужних женщин(`Miss`) отсортированный по популярности.
* В полном имени девушек **имя** - это **первое слово без скобок** после `Miss`.
* Остальные строки не рассматриваем.
* Девушки с одинаковой популярностью сортируются по имени в алфавитном порядке.
**Слово/имя** - подстрока без пробелов.
**Популярность** - количество таких имен в таблице.
### Sample 1
#### Input:
```python
data = pd.read_csv('data/titanic_train.csv', index_col='PassengerId')
```
#### Output:
Вот начало данного списка. Заметьте, **названия колонок должны совпадать**
| | Name | Popularity |
|--|----|--------|
|0 |Anna |9|
|1 |Mary |9
|2 |Margaret|6
|3 |Elizabeth|5
|4 |Alice |4
|5 |Bertha |4
|6 |Ellen |4
|7 |Helen |4
```
def fename_stat(df: pd.DataFrame) -> pd.DataFrame:
### ╰( ͡° ͜ʖ ͡° )つ──☆*:・゚
pass
# В этой задаче нет открытых тестов ;)
```
| github_jupyter |
```
import pandas as pd
import re
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 100)
technoeconomic_data = pd.read_csv("/Users/alexanderkell/Documents/SGI/Projects/11-starter-kits/data/raw/starter-kits/kenya/Table2_KEN.csv")
technoeconomic_data
pd.unique(technoeconomic_data.Parameter)
muse_technodata = pd.read_csv("/Users/alexanderkell/Documents/SGI/Projects/11-starter-kits/data/external/muse_data/default/technodata/power/Technodata.csv")
muse_technodata
technoeconomic_data_wide = technoeconomic_data.pivot(index='Technology', columns='Parameter', values='Value')
technoeconomic_data_wide.insert(0,"RegionName", "R1")
technoeconomic_data_wide.insert(1,"Time", "2020")
technoeconomic_data_wide.insert(2,"Level", "fixed")
technoeconomic_data_wide.insert(3,"cap_exp", 1)
technoeconomic_data_wide.insert(4,"fix_exp", 1)
technoeconomic_data_wide.insert(5,"var_par", 0)
technoeconomic_data_wide.insert(6,"var_exp", 1)
technoeconomic_data_wide.insert(7,"Type", "energy")
technoeconomic_data_wide.insert(8,"EndUse", "Electricity")
technoeconomic_data_wide.insert(9,"Agent2", 1)
technoeconomic_data_wide.insert(9,"InterestRate", 0.1)
technoeconomic_data_wide
technoeconomic_data_wide = technoeconomic_data_wide.reset_index()
technoeconomic_data_wide_named = technoeconomic_data_wide.rename(columns={"Average Capacity Factor": "UtilizationFactor", "Capital Cost ($/kW in 2020)": "cap_par", "Fixed Cost ($/kW/yr in 2020)": "fix_par", "Operational Life (years)":"TechnicalLife", "Technology":"ProcessName", "Efficiency ": "efficiency"})
technoeconomic_data_wide_named
plants = list(pd.unique(technoeconomic_data_wide_named.ProcessName))
plants
fuels = ["biomass", "solar", "solar", "coal", "gas", "gas", "geothermal", "hydro", "oil", "oil", "hydro", "uranium", "wind", "oil", "wind", "hydro", "solar", "solar"]
plants_fuels = dict(zip(plants, fuels))
plants_fuels
technoeconomic_data_wide_named['Fuel']= technoeconomic_data_wide_named['ProcessName'].map(plants_fuels)
technoeconomic_data_wide_named
plants = list(pd.unique(technoeconomic_data_wide_named.ProcessName))
plant_sizes = {}
for plant in plants:
size = 1
kw = False
if "kW" in plant:
kw = True
if re.search(r'\d+', plant) is not None:
size = float(re.search(r'\d+', plant).group())
if kw:
size /= 1000
plant_sizes[plant] = size
technoeconomic_data_wide_named['ScalingSize'] = technoeconomic_data_wide_named['ProcessName'].map(plant_sizes)
technoeconomic_data_wide_named
technoeconomic_data_wide_named['MaxCapacityAddition'] = 20
technoeconomic_data_wide_named['MaxCapacityGrowth'] = 20
technoeconomic_data_wide_named['TotalCapacityLimit'] = 20
technoeconomic_data_wide_named
# technoeconomic_data_wide_named
technoeconomic_data_wide_named = technoeconomic_data_wide_named.apply(pd.to_numeric, errors='ignore')
technoeconomic_data_wide_named.dtypes
projected_capex = pd.read_csv("/Users/alexanderkell/Documents/SGI/Projects/11-starter-kits/data/raw/starter-kits/kenya/Table3_KEN.csv")
projected_capex.head()
projected_capex.dtypes
projected_capex = projected_capex.rename(columns={"Technology": "ProcessName", "Year": "Time", "Value": "cap_par"})
projected_capex = projected_capex.drop(columns="Parameter")
projected_capex
projected_capex
projected_capex_with_unknowns = pd.merge(projected_capex[['ProcessName', "Time"]], technoeconomic_data_wide_named[["ProcessName"]], how="cross")
with_years = projected_capex_with_unknowns.drop(columns="ProcessName_x").drop_duplicates().rename(columns={"ProcessName_y":"ProcessName"})
filled_years = pd.merge(with_years, projected_capex, how="outer")
combined_years = pd.merge(filled_years, technoeconomic_data_wide_named[['ProcessName', "cap_par"]], on="ProcessName")
combined_years['cap_par_x'] = combined_years['cap_par_x'].fillna(combined_years['cap_par_y'])
projected_capex_all_technologies = combined_years.drop(columns="cap_par_y").rename(columns={"cap_par_x": "cap_par"})
projected_capex_all_technologies
projected_technoeconomic = pd.merge(technoeconomic_data_wide_named, projected_capex_all_technologies, on=['ProcessName', "Time"], how='outer')
projected_technoeconomic
backfilled_projected_technoeconomic = projected_technoeconomic.groupby(['ProcessName']).apply(lambda group: group.fillna(method="bfill"))
backfilled_projected_technoeconomic
forwardfilled_projected_technoeconomic = backfilled_projected_technoeconomic.groupby(['ProcessName']).apply(lambda group: group.fillna(method="ffill"))
forwardfilled_projected_technoeconomic
forwardfilled_projected_technoeconomic['cap_par_y'] = forwardfilled_projected_technoeconomic.cap_par_y.fillna(forwardfilled_projected_technoeconomic.cap_par_x)
forwardfilled_projected_technoeconomic
forwardfilled_projected_technoeconomic = forwardfilled_projected_technoeconomic.drop(columns="cap_par_x")
forwardfilled_projected_technoeconomic = forwardfilled_projected_technoeconomic.rename(columns={"cap_par_y":"cap_par"})
forwardfilled_projected_technoeconomic
# 'Capital Cost ($/kW in 2020)', 'Fixed Cost ($/kW/yr in 2020)'
kw_columns = ["cap_par", "fix_par"]
forwardfilled_projected_technoeconomic[kw_columns] *= 1000
forwardfilled_projected_technoeconomic
forwardfilled_projected_technoeconomic = forwardfilled_projected_technoeconomic.reindex(muse_technodata.columns, axis=1)
forwardfilled_projected_technoeconomic
muse_technodata = muse_technodata[muse_technodata.ProcessName == "Unit"].append(forwardfilled_projected_technoeconomic)
muse_technodata
muse_technodata.to_csv("/Users/alexanderkell/Documents/SGI/Projects/11-starter-kits/data/interim/technodata/power_technodata.csv")
fixed_costs = pd.read_csv("/Users/alexanderkell/Documents/SGI/Projects/11-starter-kits/data/interim/fixed_costs/Kenya-fixed-costs.csv")
fixed_costs
fixed_costs_long = fixed_costs.melt(id_vars="ProcessName", var_name="Time", value_name="fix_par")
fixed_costs_long
fixed_costs_long["Time"] = pd.to_numeric(fixed_costs_long.Time)
fixed_costs_long
fixed_costs_long['fix_par'] = fixed_costs_long['fix_par'] * 1 / (8600 * 0.0036)
fixed_costs_long.head()
units = pd.DataFrame({"ProcessName":["Unit"], "Time":["Year"], "fix_par":["MUS$2010/PJ"]})
units
fixed_costs_long = pd.concat([units,fixed_costs_long])
fixed_costs_long[fixed_costs_long.Time==2020]
muse_technodata[(muse_technodata.ProcessName=="Onshore Wind") & (muse_technodata.Time==2020)]
technodata_edited = pd.merge(muse_technodata, fixed_costs_long, on=["ProcessName", "Time"], how="left")
technodata_edited
technodata_edited["fix_par_y"] = technodata_edited.fix_par_y.fillna(technodata_edited.fix_par_x)
technodata_edited = technodata_edited.drop(columns="fix_par_x")
technodata_edited = technodata_edited.rename(columns={"fix_par_y": "fix_par"})
technodata_edited
technodata_edited = technodata_edited.reindex(muse_technodata.columns, axis=1)
technodata_edited[technodata_edited.ProcessName=="Onshore Wind"]
```
| github_jupyter |
```
import panel as pn
pn.extension()
```
The ``FloatSlider`` widget allows selecting selecting a numeric floating-point value within a set bounds using a slider.
For more information about listening to widget events and laying out widgets refer to the [widgets user guide](../../user_guide/Widgets.ipynb). Alternatively you can learn how to build GUIs by declaring parameters independently of any specific widgets in the [param user guide](../../user_guide/Param.ipynb). To express interactivity entirely using Javascript without the need for a Python server take a look at the [links user guide](../../user_guide/Param.ipynb).
#### Parameters:
For layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb).
##### Core
* **``start``** (float): The range's lower bound
* **``end``** (float): The range's upper bound
* **``step``** (float): The interval between values
* **``value``** (float): The selected value as a float type
* **``value_throttled``** (float): The selected value as a float type throttled until mouseup
##### Display
* **``bar_color``** (color): Color of the slider bar as a hexadecimal RGB value
* **``direction``** (str): Whether the slider should go from left to right ('ltr') or right to left ('rtl')
* **``disabled``** (boolean): Whether the widget is editable
* **``format``** (str, bokeh.models.TickFormatter): Formatter to apply to the slider value
* **``name``** (str): The title of the widget
* **``orientation``** (str): Whether the slider should be displayed in a 'horizontal' or 'vertical' orientation.
* **``tooltips``** (boolean): Whether to display tooltips on the slider handle
___
```
float_slider = pn.widgets.FloatSlider(name='Float Slider', start=0, end=3.141, step=0.01, value=1.57)
float_slider
```
The ``FloatSlider`` value is returned as a float and can be accessed and set like any other widget:
```
float_slider.value
```
A custom format string or bokeh TickFormatter may be used to format the slider values:
```
from bokeh.models.formatters import PrintfTickFormatter
str_format = pn.widgets.FloatSlider(name='Distance', format='1[.]00')
tick_format = pn.widgets.FloatSlider(name='Distance', format=PrintfTickFormatter(format='%.3f m'))
pn.Column(str_format, tick_format)
```
### Controls
The `FloatSlider` widget exposes a number of options which can be changed from both Python and Javascript. Try out the effect of these parameters interactively:
```
pn.Row(float_slider.controls(jslink=True), float_slider)
```
| github_jupyter |
In this note book, I
* replicate some of the simulations in the paers, and
* add some variations of my own.
<table align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/facebookresearch/mc/blob/master/notebooks/simulations_py.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
</table>
```
# install the mc package
!pip install -q git+https://github.com/facebookresearch/mc
#@title imports {form-width: "20%"}
import pandas as pd
import numpy as np
import mc
#@title function mc {form-width: "20%"}
def one_run(
N=400, # sample size for main data
n=100, # sample size for calibration data
pi=[0.2, 0.8], # true membership proportions
p=[[[0.9, 0.2], [0.1, 0.8]], [[0.9, 0.2], [0.1, 0.8]]], # miscalssification matrix
mu=[0.8, 0.4], # true mean of y
seed=123, # seed for random data generation
verbose=False, # if true, print details
):
# N = 400; n = 100; pi = [0.2, 0.8];
# p =[[[0.9, 0.2], [0.1, 0.8]], [[0.9, 0.2], [0.1, 0.8]]]
# mu = [0.8, 0.4]; seed=123
np.random.seed(seed)
pi = np.array(pi)
p = np.array(p)
mu = np.array(mu)
i = np.random.binomial(n=1, p=pi[1], size=N + n) # true group
y = np.random.binomial(n=1, p=mu[i]) # y_value depends on true group info i
j = np.random.binomial(n=1, p=p[y, 1, i]) # observed group
df = pd.DataFrame({
"sample": ["P"] * N + ["V"] * n,
"i": i, "j": j, "y": y, "y_squared": y ** 2,
})
# start calculation
df_P = df.query("sample == 'P'")
df_V = df.query("sample == 'V'")
n_jd_P = df_P.groupby("j").size().to_numpy()
y_sum_jd_P = df_P.groupby("j")["y"].sum().to_numpy()
n_ji_V = pd.crosstab(df_V["j"], df_V["i"]).to_numpy()
y_sum_ji_V = df_V.pivot_table(
index="j", columns="i", values="y", aggfunc=np.sum, fill_value=0).to_numpy()
y2_sum_ji_V = df_V.pivot_table(
index="j", columns="i", values="y_squared",
aggfunc=np.sum, fill_value=0).to_numpy()
# get estimates
mom = mc.mc_mom(n_jd_P, y_sum_jd_P, n_ji_V, y_sum_ji_V)
rmle = mc.mc_rmle(n_jd_P, y_sum_jd_P, n_ji_V, y_sum_ji_V, y2_sum_ji_V)
out = pd.concat(
(pd.DataFrame({"mu": mu}), mom, rmle),
axis=1
)
for col in out.columns:
if col not in ("mu", "mak_li_var"):
if any(~out[col].between(0., 1.)):
out[col] = np.nan
return out
#@title function simulation {form-width: "20%"}
def simulation(n_reps=1000, verbose=True, *args, **kwargs):
# n_reps=100; verbose=True; args=[]; kwargs={}
res = pd.concat([
one_run(seed=seed + 8101352, *args, **kwargs) for seed in range(n_reps)
])
pct_bad = res.isna().mean()
est_cols = [col for col in res.columns if col not in ("mu", "mak_li_var")]
err = res[est_cols].sub(res["mu"], axis=0)
bias = err.groupby(level=0).mean()
mse = err.groupby(level=0).apply(lambda df: (df ** 2).mean())
estimated_var = res.groupby(level=0)['mak_li_var'].mean().to_numpy()
empirical_var = res.groupby(level=0)["mak_li"].var().to_numpy()
right_direction = (
res[est_cols]
.diff().loc[1].apply(lambda x: (x[~np.isnan(x)] < 0).mean())
)
if verbose:
print(res.head(2))
print(f"\nbias: \n {bias}")
print(f"MSE: \n {mse}")
print(f"\n\n % with bad estimates:\n {pct_bad}")
print(f"\n\nestimated mak_li_var: {estimated_var}")
print(f"\n\nempirical mak_li_var: {empirical_var}")
print(f"\n\nright_direction:\n {right_direction}")
return {
"res":res, "err": err, "bias": bias, "mse": mse,
"pct_bad": pct_bad, "empirical_var": empirical_var,
"right_direction": right_direction
}
# simulation()
```
## simulations in paper
```
#@title p's that define simulation setup {form-width: "20%"}
p_a = [[[0.9, 0.2], [0.1, 0.8]], [[0.9, 0.2], [0.1, 0.8]]]
p_b = [[[0.8, 0.3], [0.2, 0.7]], [[0.8, 0.3], [0.2, 0.7]]]
p_c = [[[0.93, 0.23], [0.07, 0.77]], [[0.87, 0.17], [0.13, 0.83]]]
p_d = [[[0.95, 0.25], [0.05, 0.75]], [[0.85, 0.15], [0.15, 0.85]]]
#@title a {form-width: "20%"}
a = simulation(p=p_a)
#@title b {form-width: "20%"}
b = simulation(p=p_b)
#@title c {form-width: "20%"}
c = simulation(p=p_c)
#@title d {form-width: "20%"}
d = simulation(p=p_d)
```
## simulations with larger primary data
```
#@title a2 {form-width: "20%"}
big_N = 40_000
a2 = simulation(
N=big_N,
p=p_a
)
#@title b2 {form-width: "20%"}
b2 = simulation(
N=big_N,
p=p_a
)
#@title c2 {form-width: "20%"}
c2 = simulation(
N=big_N,
p=p_c
)
#@title d2 {form-width: "20%"}
d2 = simulation(
N=big_N,
p=p_d
)
```
## Collected results
```
#@title 1000 X bias and mse {form-width: "20%"}
setups = np.repeat(("a", "b", "c", "d", "a2", "b2", "c2", "d2"), 2)
setups = np.tile(setups, 2)
multipler = 1000
metrics = np.repeat((f"bia X {multipler}", f"mse X {multipler}"), len(setups)/2)
biases = pd.concat([
r["bias"] * multipler
for r in (a,b,c,d,a2,b2,c2,d2)
])
mses = pd.concat([
r["mse"] * multipler
for r in (a,b,c,d,a2,b2,c2,d2)
])
all = pd.concat([biases, mses])
all["setup"] = setups
all["metric"] = metrics
all["parameter"] = all.index.map({0: "mu1", 1: "mu2"})
all = (
all.sort_values(["parameter", "metric", "setup",])
[["parameter", "metric", "setup", "naive", "validation", "no_y_V", "with_y_V", "mak_li"]]
.round(2)
)
all
```
## smaller effect size
```
s1 = simulation(mu=[0.5, 0.4])
s2 = simulation(mu=[0.5, 0.45])
s3 = simulation(mu=[0.5, 0.48])
```
| github_jupyter |
### Problem Statement
Classify the _notMNIST_ dataset using logistic regression with gradient descent on tensorflow.
This notebook uses the [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) dataset to be used with python experiments. This dataset is designed to look like the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset, while looking a little more like real data: it's a harder task, and the data is a lot less 'clean' than MNIST.
```
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlretrieve
from six.moves import cPickle as pickle
# Config the matplotlib backend as plotting inline in IPython
%matplotlib inline
```
First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labeled examples. Given these sizes, it should be possible to train models quickly on any machine.
```
url = 'https://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None
data_root = '.' # Change me to store data elsewhere
def download_progress_hook(count, blockSize, totalSize):
"""A hook to report the progress of a download. This is mostly intended for users with
slow internet connections. Reports every 5% change in download progress.
"""
global last_percent_reported
percent = int(count * blockSize * 100 / totalSize)
if last_percent_reported != percent:
if percent % 5 == 0:
sys.stdout.write("%s%%" % percent)
sys.stdout.flush()
else:
sys.stdout.write(".")
sys.stdout.flush()
last_percent_reported = percent
def maybe_download(filename, expected_bytes, force=False):
"""Download a file if not present, and make sure it's the right size."""
dest_filename = os.path.join(data_root, filename)
if force or not os.path.exists(dest_filename):
print('Attempting to download:', filename)
filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)
print('\nDownload Complete!')
statinfo = os.stat(dest_filename)
if statinfo.st_size == expected_bytes:
print('Found and verified', dest_filename)
else:
raise Exception(
'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')
return dest_filename
train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)
test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)
```
Extract the dataset from the compressed .tar.gz file.
This should give you a set of directories, labeled A through J.
```
num_classes = 10
np.random.seed(133)
def maybe_extract(filename, force=False):
root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz
if os.path.isdir(root) and not force:
# You may override by setting force=True.
print('%s already present - Skipping extraction of %s.' % (root, filename))
else:
print('Extracting data for %s. This may take a while. Please wait.' % root)
tar = tarfile.open(filename)
sys.stdout.flush()
tar.extractall(data_root)
tar.close()
data_folders = [
os.path.join(root, d) for d in sorted(os.listdir(root))
if os.path.isdir(os.path.join(root, d))]
if len(data_folders) != num_classes:
raise Exception(
'Expected %d folders, one per class. Found %d instead.' % (
num_classes, len(data_folders)))
print(data_folders)
return data_folders
train_folders = maybe_extract(train_filename)
test_folders = maybe_extract(test_filename)
```
---
Problem 1
---------
Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint: you can use the package IPython.display.
---
Now let's load the data in a more manageable format. Since, depending on your computer setup you might not be able to fit it all in memory, we'll load each class into a separate dataset, store them on disk and curate them independently. Later we'll merge them into a single dataset of manageable size.
We'll convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road.
A few images might not be readable, we'll just skip them.
```
image_size = 28 # Pixel width and height.
pixel_depth = 255.0 # Number of levels per pixel.
def load_letter(folder, min_num_images):
"""Load the data for a single letter label."""
image_files = os.listdir(folder)
dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
dtype=np.float32)
print(folder)
num_images = 0
for image in image_files:
image_file = os.path.join(folder, image)
try:
image_data = (imageio.imread(image_file).astype(float) -
pixel_depth / 2) / pixel_depth
if image_data.shape != (image_size, image_size):
raise Exception('Unexpected image shape: %s' % str(image_data.shape))
dataset[num_images, :, :] = image_data
num_images = num_images + 1
except (IOError, ValueError) as e:
print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.')
dataset = dataset[0:num_images, :, :]
if num_images < min_num_images:
raise Exception('Many fewer images than expected: %d < %d' %
(num_images, min_num_images))
print('Full dataset tensor:', dataset.shape)
print('Mean:', np.mean(dataset))
print('Standard deviation:', np.std(dataset))
return dataset
def maybe_pickle(data_folders, min_num_images_per_class, force=False):
dataset_names = []
for folder in data_folders:
set_filename = folder + '.pickle'
dataset_names.append(set_filename)
if os.path.exists(set_filename) and not force:
# You may override by setting force=True.
print('%s already present - Skipping pickling.' % set_filename)
else:
print('Pickling %s.' % set_filename)
dataset = load_letter(folder, min_num_images_per_class)
try:
with open(set_filename, 'wb') as f:
pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)
except Exception as e:
print('Unable to save data to', set_filename, ':', e)
return dataset_names
train_datasets = maybe_pickle(train_folders, 45000)
test_datasets = maybe_pickle(test_folders, 1800)
```
---
Problem 2
---------
Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint: you can use matplotlib.pyplot.
---
---
Problem 3
---------
Another check: we expect the data to be balanced across classes. Verify that.
---
Merge and prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune `train_size` as needed. The labels will be stored into a separate array of integers 0 through 9.
Also create a validation dataset for hyperparameter tuning.
```
def make_arrays(nb_rows, img_size):
if nb_rows:
dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)
labels = np.ndarray(nb_rows, dtype=np.int32)
else:
dataset, labels = None, None
return dataset, labels
def merge_datasets(pickle_files, train_size, valid_size=0):
num_classes = len(pickle_files)
valid_dataset, valid_labels = make_arrays(valid_size, image_size)
train_dataset, train_labels = make_arrays(train_size, image_size)
vsize_per_class = valid_size // num_classes
tsize_per_class = train_size // num_classes
start_v, start_t = 0, 0
end_v, end_t = vsize_per_class, tsize_per_class
end_l = vsize_per_class+tsize_per_class
for label, pickle_file in enumerate(pickle_files):
try:
with open(pickle_file, 'rb') as f:
letter_set = pickle.load(f)
# let's shuffle the letters to have random validation and training set
np.random.shuffle(letter_set)
if valid_dataset is not None:
valid_letter = letter_set[:vsize_per_class, :, :]
valid_dataset[start_v:end_v, :, :] = valid_letter
valid_labels[start_v:end_v] = label
start_v += vsize_per_class
end_v += vsize_per_class
train_letter = letter_set[vsize_per_class:end_l, :, :]
train_dataset[start_t:end_t, :, :] = train_letter
train_labels[start_t:end_t] = label
start_t += tsize_per_class
end_t += tsize_per_class
except Exception as e:
print('Unable to process data from', pickle_file, ':', e)
raise
return valid_dataset, valid_labels, train_dataset, train_labels
train_size = 200000
valid_size = 10000
test_size = 10000
valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(
train_datasets, train_size, valid_size)
_, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)
print('Training:', train_dataset.shape, train_labels.shape)
print('Validation:', valid_dataset.shape, valid_labels.shape)
print('Testing:', test_dataset.shape, test_labels.shape)
```
Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match.
```
def randomize(dataset, labels):
permutation = np.random.permutation(labels.shape[0])
shuffled_dataset = dataset[permutation,:,:]
shuffled_labels = labels[permutation]
return shuffled_dataset, shuffled_labels
train_dataset, train_labels = randomize(train_dataset, train_labels)
test_dataset, test_labels = randomize(test_dataset, test_labels)
valid_dataset, valid_labels = randomize(valid_dataset, valid_labels)
```
---
Problem 4
---------
Convince yourself that the data is still good after shuffling!
---
```
final = []
for i in range(5):
v1 = train_dataset[random.randint(3,200000),:,:]
for i in range(10):
v1 = np.column_stack([v1,train_dataset[random.randint(3,200000),:,:]])
final.append(v1)
final = np.concatenate((final))
plt.imshow(final)
```
Finally, let's save the data for later reuse:
```
pickle_file = os.path.join(data_root, 'notMNIST.pickle')
try:
f = open(pickle_file, 'wb')
save = {
'train_dataset': train_dataset,
'train_labels': train_labels,
'valid_dataset': valid_dataset,
'valid_labels': valid_labels,
'test_dataset': test_dataset,
'test_labels': test_labels,
}
pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)
f.close()
except Exception as e:
print('Unable to save data to', pickle_file, ':', e)
raise
statinfo = os.stat(pickle_file)
print('Compressed pickle size:', statinfo.st_size)
```
---
Problem 5
---------
By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it.
Measure how much overlap there is between training, validation and test samples.
---
```
def check_overlap(image_set1,image_set2):
image_set1.flags.writeable=False
image_set2.flags.writeable=False
set1 = set([hash(image_.tobytes()) for image_ in image_set1])
set2 = set([hash(image_.tobytes()) for image_ in image_set2])
all_overlaps = set.intersection(set1, set2)
return all_overlaps
overlap1 = check_overlap(train_dataset,test_dataset)
overlap2 = check_overlap(train_dataset,valid_dataset)
overlap3 = check_overlap(test_dataset,valid_dataset)
print(f"Number of overlapping images between the Training and Test dataset: {len(overlap1)}")
print(f"Number of overlapping images between the Training and Validation dataset: {len(overlap2)}")
print(f"Number of overlapping images between the Test and Validation dataset: {len(overlap3)}")
```
---
Problem 6
---------
Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it.
Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint: you can use the LogisticRegression model from sklearn.linear_model.
Optional question: train an off-the-shelf model on all the data!
---
```
from sklearn.linear_model import LogisticRegression
for i in [50,100,1000,5000,200000]:
LR = LogisticRegression()
train_pixels = train_dataset.flatten().reshape(train_dataset.shape[0],28*28)
valid_pixels = valid_dataset.flatten().reshape(valid_dataset.shape[0],28*28)
test_pixels = test_dataset.flatten().reshape(test_dataset.shape[0],28*28)
#TODO: Fit the logistic regression model to our training data and labels
?
#TODO: Calculate the training, validation, and test scores
training_score = ?
validation_score = ?
test_score = ?
print(f"Score for {i} training samples: \n\
Training score: {training_score}, \n\
Validation score: {validation_score}, \n\
Test score: {test_score} \n\n")
filename = 'LogisticRegression_notMNIST.sav'
pickle.dump(LR, open(filename, 'wb'))
```
| github_jupyter |
## ADM1F_SRT: Ph control method
The `ph control` method was developed by Wenjuan Zhang and uses Data Consistent Inversion Method.
Authors: Wenjuan Zhang and Elchin Jafarov
```
import os
import adm1f_utils as adm1fu
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
%matplotlib inline
```
### 1. Relation between cation and PH
Here we explore the cation/ph relationships using diffrerent configurations. Note, based in the results will be different based on the ADM1F code version (i.e. original or SRT).
```
# navigate to simulations folder
os.chdir('../simulations')
# Configuration of the one-phase reactor
config_default = {'Vliq':3400, 't_resx':0, 'Q':134}
config1 = {'Vliq':340, 't_resx':1.5, 'Q':618}
config2 = {'Vliq':3400, 't_resx':700, 'Q':618}
```
**Configurations**
| Configuration | Vliq (m$^3$) | t\_resx (d) | Q (m$^3$/d)|
| ------ | ------ | ------ | ------|
Default | 3400 | 0 | 134 |
Phase 1 | 340 | 1.5 | 618 |
Phase 2 | 3400 | 700 | 618/--- |
where t\_resx = SRT - HRT
```
# check if file exsits read from file
# otherwise run the simulations with different cations `cat_test`
cat_test = [i*0.001 for i in range(200)]
filename='data/no-configuration.dat'
if adm1fu.check_filename(filename):
ph_test = np.loadtxt(filename)
else:
ph_test = [adm1fu.ph(i,verbose='off',**config_default)[0] for i in cat_test]
np.savetxt(filename, ph_test, fmt='%5.6f')
```
**Relation b/t cation and Ph under Default config**
```
# Relation b/t cation and Ph under Default config
plt.figure(figsize=(12,5))
plt.scatter(cat_test, ph_test)
plt.ylabel('PH',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.xlabel('Cation (kmole/m3)',fontsize=15)
plt.title("Default configuration",fontsize=20);
```
**Relation b/t cation and Ph under Phase 1 config**
```
filename='data/configuration1.dat'
if adm1fu.check_filename(filename):
ph_test_config1 = np.loadtxt(filename)
else:
ph_test_config1 = [adm1fu.ph(i, verbose='off', **config1)[0] for i in cat_test]
np.savetxt(filename, ph_test_config1, fmt='%5.6f')
plt.figure(figsize=(12,5))
plt.scatter(cat_test, ph_test_config1)
plt.ylabel('PH',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.xlabel('Cation (kmole/m3)',fontsize=15)
plt.title("Phase 1 Configuration with only cation being changed",fontsize=20);
```
**Relation b/t cation and Ph under Phase 2 config**
```
filename='data/configuration2.dat'
if adm1fu.check_filename(filename):
ph_test_config2 = np.loadtxt(filename)
else:
ph_test_config2 = [adm1fu.ph(i, verbose='off', **config2)[0] for i in cat_test]
np.savetxt(filename, ph_test_config2, fmt='%5.6f')
plt.figure(figsize=(12,5))
plt.scatter(cat_test, ph_test_config2)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.ylabel('PH',fontsize=15)
plt.xlabel('Cation (kmole/m3)',fontsize=15)
plt.title("Phase 2 Configuration 2 with only cation being changed",fontsize=20);
```
### 2. PH: one-phase reactor
```
old_ph0 = adm1fu.ph(0)
print('Predicted PH is {} if using the original cation value {}'.format(old_ph0[0], old_ph0[1]))
old_ph1 = adm1fu.ph(0, **config1)
print('Predicted PH is {} if using the original cation value {}'.format(old_ph1[0], old_ph1[1]))
old_ph2 = adm1fu.ph(0, **config2)
print('Predicted PH is {} if using the original cation value {}'.format(old_ph2[0], old_ph2[1]))
```
**Set Target:** Let's calculate the amount of cation needed by the one-phase reactor to match required `ph` targets using Data Consistent Inversion method.
```
class target:
def __init__(self,ph,sig):
self.ph = ph
self.sig = sig
def pdf(self,x):
return norm.pdf(x,self.ph,self.sig)
# Give the necessary information
# target_ph = 6.5 # target_ph: target PH value, target_sig: allow some variations around target PH
target_sig = 0.01 # The smaller this value is, the more accurate we will get in the end
sample_size = 100
infl_path = 'influent.dat'
params_path = 'params.dat'
ic_path = 'ic.dat'
## Use data consistent inversion method to return the needed cation to get the target PH
init_sample = np.random.uniform(0,0.2,sample_size) #the more samples we generate, the more accurate we will get in the end
target72 = target(7.2,target_sig)
target73 = target(7.3,target_sig)
target75 = target(7.5,target_sig)
```
**Target 1: target_ph=7.2 with Default configuration**
```
## ph_control accepts target, initial sample, number of cation values and file path of each input file
## ph_control return the needed cation to get the target PH
cat_tar72_dc = adm1fu.ph_control(target72,init_sample,1,infl_path,params_path,ic_path,verbose='off', **config_default)
# Print out the Needed Cation value!!
print('The amount of cation in the reactor should be:', cat_tar72_dc[0], 'kmole/m3')
[adm1fu.ph(i, **config_default) for i in cat_tar72_dc]
```
**Target 2: target_ph=7.2 with configuration 1**
```
## ph_control accepts target, initial sample, number of cation values and file path of each input file
## pph_control return the needed cation to get the target PH
cat_tar72_c1 = adm1fu.ph_control(target72,init_sample,1,infl_path,params_path,ic_path,verbose='off', **config1)
# Print out the Needed Cation value!!
print('The amount of cation in the reactor should be:', cat_tar72_c1[0], 'kmole/m3')
[adm1fu.ph(i, **config1) for i in cat_tar72_c1]
```
**Target 3: target_ph=7.2 with configuration 2**
```
## ph_control accepts target, initial sample, number of cation values and file path of each input file
## ph_control return the needed cation to get the target PH
cat_tar72_c2 = adm1fu.ph_control(target72,init_sample,1,infl_path,params_path,ic_path,verbose='off', **config2)
# Print out the Needed Cation value!!
print('The amount of cation in the reactor should be:', cat_tar72_c2[0], 'kmole/m3')
[adm1fu.ph(i, **config2) for i in cat_tar72_c2]
```
### 3. PH: two-phase reactor
**PH control for both phase 1 and phase 2**
reactor_cat(target_1=target1, target_2=target2, Q1=1, Vliq1=1, t_resx1=1, Q2=1, Vliq2=1, t_res2=1)
**PH control for just phase 1 in two-phase reactor**
reactor_cat(target_1=target1, Q1=1, Vliq1=1, t_resx1=1, Q2=1, Vliq2=1, t_res2=1)
```
## Configuration of two-phase reacotr
# config12 = {"Vliq1":340, "Vliq2":3400, "t_resx1":1.5, "t_resx2":700, "Q1":618, "Q2":618}
config12 = {"Vliq1":340, "Vliq2":3400, "t_resx1":1.5, "t_resx2":700, "Q1":618}
```
**target_ph1=7.5, target_ph2=7.2 with default configuration12**
```
config12 = {"Vliq1":340, "Vliq2":3400, "t_resx1":1.5, "t_resx2":700, "Q1":618}
adm1fu.reactor2_cat(init_sample,target_1=target75,target_2=target72,verbose='off',**config12)
```
**target_ph1=7.5, target_ph2=None with default configuration12**
```
adm1fu.reactor2_cat(init_sample,target_1=target75,verbose='off',**config12)
```
| github_jupyter |
```
import pymongo
import os
import pandas as pd
import yaml
from collections import Counter
from datetime import datetime
import sys
SRC = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "src")
sys.path.append(SRC)
from content_api.details_utils import extract_from_details, cs_extract_text, cs_extract_links
### Get dirs
DATA_DIR = os.getenv("DATA_DIR")
config = os.path.join(SRC, "config")
black_list_path = os.path.join(config, "document_types_excluded_from_the_topic_taxonomy.yml")
### Get database running locally
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
print(myclient.list_database_names())
mydb = myclient["content_store"]
mycol = mydb["content_items"]
with open(black_list_path, 'r') as stream:
blacklisted_content_page = sorted(yaml.load(stream)['document_types'])
blacklisted_content_page[0:5]
keep_columns = \
['_id',
# 'access_limited',
# 'analytics_identifier',
'content_id',
'content_purpose_document_supertype',
'content_purpose_subgroup',
'content_purpose_supergroup',
# 'created_at',
'description',
'details',
'document_type',
'email_document_supertype',
# 'expanded_links',
'first_published_at',
# 'format',
'government_document_supertype',
# 'links',
'locale',
'navigation_document_supertype',
# 'need_ids',
# 'payload_version',
'phase',
'public_updated_at',
'publishing_app',
# 'publishing_request_id',
'publishing_scheduled_at',
# 'redirects',
'rendering_app',
# 'routes',
# 'scheduled_publishing_delay_seconds',
# 'schema_name',
'search_user_need_document_supertype',
'title',
'updated_at',
'user_journey_document_supertype'
# 'withdrawn_notice'
]
links_keep = \
[
'organisations',
'primary_publishing_organisation',
'taxons',
# 'finder',
# 'available_translations',
'mainstream_browse_pages',
# 'parent',
'part_of_step_navs',
'ordered_related_items',
# 'meets_user_needs',
'topics',
'ordered_related_items_overrides',
'pages_part_of_step_nav',
'pages_related_to_step_nav',
'related_to_step_navs',
# 'children',
'document_collections',
# 'lead_organisations',
# 'world_locations',
# 'worldwide_organisations',
# 'supporting_organisations',
# 'worldwide_priorities',
# 'original_primary_publishing_organisation',
'documents',
'policy_areas',
# 'topical_events',
# 'suggested_ordered_related_items',
'related_policies',
# 'ministers',
# 'people',
# 'roles',
# 'field_of_operation'
]
keep_keys = \
[
# 'analytics_identifier',
# 'api_path',
'base_path',
'content_id',
# 'description',
# 'document_type',
# 'locale',
# 'schema_name',
# 'title',
# 'withdrawn',
# 'details',
# 'links'
]
def handle_expanded_links(content_links, row_dict):
for key,value in content_links.items():
if key in links_keep:
row_dict[key] = []
for item in value:
row = {}
for k in keep_keys:
if k in item.keys():
row[k] = item[k]
row_dict[key].append(row)
mydoc = mycol.find({ "$and": [
{ "document_type": {"$not" : { "$in": blacklisted_content_page}}},
{ "phase": "live"}]})
print("Started:",datetime.now().strftime("%H:%M:%S"))
rowlist = []
for i,item in enumerate(mydoc):
if i < 50000:
row = {key:value for key,value in item.items() if key in keep_columns}
# row['body'] = extract_from_details(item['details'], "text")
# row['embedded_links'] = extract_from_details(item['details'], "links")
if "expanded_links" in item.keys():
handle_expanded_links(item["expanded_links"], row)
rowlist.append(row)
else:
break
if i % 10000==0:
print(i,datetime.now().strftime("%H:%M:%S"))
print("Ended:",datetime.now().strftime("%H:%M:%S"))
df = pd.DataFrame(rowlist)
df.shape
df.iloc[0].details
df.details.iloc[0]['body'][0].keys()
target = "parts"
for det in df.details.values:
if target in det.keys():
for item in det[target]:
print(item.keys())
if "body" in item.keys():
print(item['body'],"\n")
# print(det[target])
# print([item['body'] for item in det[target]])
# print("".join([d['content'] for d in det[target]\
# if d['content_type'] == "text/html" ]))
break
Counter([d for det in df.details.values for d in det.keys()])
for item in df.details.iloc[0]['headers']:
print(item)
df.details.iloc[0]['metadata']
cs_extract_text(df.details.iloc[1000])
cs_extract_links(df.details.iloc[1010])
target = "transaction_start_link"
for i,det in enumerate(df.details.values):
if target in det.keys():
print(i)
# for item in det[target]:
# print(item)
# if "body" in item.keys():
# print(item['body'],"\n")
# print(det[target])
# print([item['body'] for item in det[target]])
# print("".join([d['content'] for d in det[target]\
# if d['content_type'] == "text/html" ]))
break
dets = df.iloc[10554].details
dets['transaction_start_link']
cs_extract_links(dets)
cs_extract_text(dets)
df['body'] = df.details.map(cs_extract_text)
df['body'].iloc[0]
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import sqlite3
import json
import matplotlib.pyplot as plt
import seaborn as sns
from cmcrameri import cm
from os.path import expanduser
%matplotlib inline
EXPERIMENT_NAME = 'P3830'
```
#### prepare the TFD/E results
```
# load the results
# EXPERIMENT_DIR = '/media/data-4t-a/results-P3830_YUPS1/2021-10-10-01-59-26'
EXPERIMENT_DIR = '{}/Downloads/experiments/results-P3830_YUPS1/2021-10-10-01-59-26'.format(expanduser('~'))
RESULTS_DB_NAME = '{}/summarised-results/results.sqlite'.format(EXPERIMENT_DIR)
db_conn = sqlite3.connect(RESULTS_DB_NAME)
results_yups1_df = pd.read_sql_query("select * from sequences", db_conn)
db_conn.close()
# load the results
# EXPERIMENT_DIR = '/media/data-4t-a/results-P3830_YUPS2/2021-10-11-12-21-21'
EXPERIMENT_DIR = '{}/Downloads/experiments/results-P3830_YUPS2/2021-10-11-12-21-21'.format(expanduser('~'))
RESULTS_DB_NAME = '{}/summarised-results/results.sqlite'.format(EXPERIMENT_DIR)
db_conn = sqlite3.connect(RESULTS_DB_NAME)
results_yups2_df = pd.read_sql_query("select * from sequences", db_conn)
db_conn.close()
results_df = pd.concat([results_yups1_df,results_yups2_df], axis=0, sort=False, ignore_index=True)
len(results_df)
# convert the identifications from JSON to Python objects
results_df['identifications_d'] = results_df.apply(lambda row: json.loads(row.identifications), axis=1)
def classify_protein(protein):
result = 'UNKNOWN'
if 'HUMAN' in protein.upper():
result = 'Human'
elif 'YEAST' in protein.upper():
result = 'Yeast'
return result
# separate some key metrics into separate columns
results_df['id_perc_q_value'] = results_df.apply(lambda row: row.identifications_d['perc_q_value'], axis=1)
results_df['id_count_all_runs'] = results_df.apply(lambda row: len(row.identifications_d['run_names']), axis=1)
results_df['id_count_human_only_runs'] = results_df.apply(lambda row: sum('YHE010' in s for s in row.identifications_d['run_names']), axis=1)
results_df['id_number_of_proteins'] = results_df.apply(lambda row: row.identifications_d['number_of_proteins'], axis=1)
results_df['id_protein'] = results_df.apply(lambda row: row.identifications_d['proteins'][0], axis=1)
results_df['id_species'] = results_df.apply(lambda row: classify_protein(row.id_protein), axis=1)
results_df.id_species.unique()
# remove the results that couldn't be extracted or were not classified as a target
results_df = results_df[results_df.extractions.notnull()].copy()
# convert from JSON to Python objects
results_df['extractions_l'] = results_df.apply(lambda row: json.loads(row.extractions), axis=1)
# separate some key metrics into separate columns
results_df['ext_count_all_runs'] = results_df.apply(lambda row: len(row.extractions_l), axis=1)
results_df.sample(n=3)
results_df.iloc[0].identifications
# count the number of unique peptide identifications in each run
counts_d = {}
for row in results_df.itertuples():
for run_name in row.identifications_d['run_names']:
if run_name not in counts_d:
counts_d[run_name] = 0
counts_d[run_name] += 1
# sort the run names by group then run number within the group
sorted_counts_l = []
for k in sorted(list(counts_d.keys()), key=lambda x: ( x.split('_')[1], int(x.split('_')[2]) )):
short_run_name = '_'.join(k.split('_Slot')[0].split('_')[1:])
sorted_counts_l.append((short_run_name, counts_d[k]))
sorted_counts_df = pd.DataFrame(sorted_counts_l, columns=['run_name','count'])
```
#### prepare the MaxQuant results
```
# MQ_RESULTS_DIR = '{}'.format(expanduser('~'))
MQ_RESULTS_DIR = '{}/Downloads/experiments'.format(expanduser('~'))
mq_results_df = pd.read_csv('{}/MQ-analysis-of-P3830/combined/txt/evidence.txt'.format(MQ_RESULTS_DIR), sep='\\t', engine='python')
# remove decoys, which are indicated by a '+' in the Reverse column
mq_results_df = mq_results_df[pd.isna(mq_results_df.Reverse)]
# remove identifications with no intensity
mq_results_df = mq_results_df[(mq_results_df.Intensity > 0)]
# remove potential contaminants
mq_results_df = mq_results_df[pd.isna(mq_results_df['Potential contaminant'])]
# remove identifications with mass error more than +/- 5 ppm
mq_results_df = mq_results_df[np.abs(mq_results_df['Mass error [ppm]']) <= 5.0]
# definition of uniqueness in MaxQuant output with MBR on
unique_peptide_key = ['Sequence','Modifications','Charge']
# count the number of unique peptide identifications in each run
mq_counts_d = {}
for group_name,group_df in mq_results_df.groupby(unique_peptide_key, as_index=False):
df = group_df[(group_df.Type == 'TIMS-MULTI-MSMS')]
for run_name in df['Raw file'].unique():
if run_name not in mq_counts_d:
mq_counts_d[run_name] = 0
mq_counts_d[run_name] += 1
mq_sorted_counts_l = []
for k in sorted(mq_counts_d.keys()):
short_run_name = '_'.join(k.split('_Slot')[0].split('_')[1:3])
mq_sorted_counts_l.append((short_run_name, mq_counts_d[k]))
mq_sorted_counts_df = pd.DataFrame(mq_sorted_counts_l, columns=['run_name','count'])
```
#### prepare the MSFragger results
```
# use the Fragger analysis without MBR because there doesn't seem to be a way of distinguishing between identification and matching
# FRAGGER_RESULTS_DIR = '{}'.format(expanduser('~'))
FRAGGER_RESULTS_DIR = '{}/Downloads/experiments'.format(expanduser('~'))
fragger_results_df = pd.read_csv('{}/MSFragger-analysis-P3830/P3830-results/MSstats.csv'.format(FRAGGER_RESULTS_DIR), sep=',')
fragger_results_df = fragger_results_df[fragger_results_df.Intensity.notnull()]
fragger_results_df.sample(n=5)
# count the number of unique peptide identifications in each run
fragger_counts_d = {}
for group_name,group_df in fragger_results_df.groupby(['PeptideSequence', 'PrecursorCharge'], as_index=False):
for run_name in group_df['Run'].unique():
if run_name not in fragger_counts_d:
fragger_counts_d[run_name] = 0
fragger_counts_d[run_name] += 1
# sort the run names by group then run number within the group
sorted_counts_l = []
for k in sorted(list(fragger_counts_d.keys()), key=lambda x: ( x.split('_')[1], int(x.split('_')[2]) )):
short_run_name = '_'.join(k.split('_Slot')[0].split('_')[1:])
sorted_counts_l.append((short_run_name, fragger_counts_d[k]))
fragger_sorted_counts_df = pd.DataFrame(sorted_counts_l, columns=['run_name','count'])
```
#### plot the unique peptide level
```
merged_df = sorted_counts_df.merge(mq_sorted_counts_df,on='run_name').merge(fragger_sorted_counts_df,on='run_name')
merged_df.rename({'count_x':'TFD/E', 'count_y':'MaxQuant', 'count':'MSFragger'}, axis=1, inplace=True)
merged_df.index = merged_df.run_name
```
```
merged_df.sample(n=3)
merged_df.plot(kind='bar', figsize=(15,8))
_ = plt.title("Unique peptides identified in each run")
_ = plt.xlabel("run")
_ = plt.ylabel("number of unique peptides identified")
```
## missing-ness heatmaps
```
# return True if we can include an extraction from the specified group, given the groups in which it was identified
# need to implement these rules differently for each experiment, probably best with a simple rules parameter file
def extract_from_group(extract_group, identification_run_names_l):
return True
```
#### prepare the TFD/E data
```
# gather the lower intensity decile
results_df.columns
sequences_l = []
for row in results_df.itertuples():
for group_name in ['YeastUPS1','YeastUPS2']:
if extract_from_group(extract_group=group_name, identification_run_names_l=row.identifications_d['run_names']):
for extraction in row.extractions_l:
if group_name in extraction['run_name']:
short_run_name = '_'.join(extraction['run_name'].split('_Slot')[0].split('_')[1:3])
identified_in_run = extraction['run_name'] in row.identifications_d['run_names']
sequences_l.append((row.sequence, row.charge, row.id_perc_q_value, row.id_protein, row.id_species, short_run_name, group_name, extraction['intensity'], identified_in_run))
sequences_df = pd.DataFrame(sequences_l, columns=['sequence', 'charge', 'id_perc_q_value', 'protein', 'species', 'short_run_name', 'group','intensity','identified_in_run'])
# find the mean intensity for each peptide in each group
intensities_l = []
for group_name,group_df in sequences_df.groupby(['sequence','charge','group'], as_index=False):
mean_intensity = group_df.intensity.mean()
intensities_l.append((group_name[0], group_name[1], group_name[2], mean_intensity))
intensities_df = pd.DataFrame(intensities_l, columns=['sequence', 'charge', 'group', 'group_mean_intensity'])
# sort each group by descending intensity
intensities_df.sort_values(by=['group_mean_intensity'], ascending=False, inplace=True)
intensities_df.tail()
# make a separate DF for each group
YeastUPS1_df = intensities_df[(intensities_df.group == 'YeastUPS1')].copy()
YeastUPS2_df = intensities_df[(intensities_df.group == 'YeastUPS2')].copy()
# find the lowest-intensity peptides in each group
lower_number = 500
YeastUPS1_lowest_df = YeastUPS1_df.tail(lower_number)
YeastUPS2_lowest_df = YeastUPS2_df.tail(lower_number)
```
## TFD/E heatmaps
#### plot YeastUPS1
```
YeastUPS1_df.tail(n=5)
run_names_l = sorted(list(sequences_df[sequences_df.group == 'YeastUPS1'].short_run_name.unique()), key=lambda x: int(x.split('_')[1]))
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
# as a heatmap, plot the missing-ness across this group of runs
occurences_l = []
index_l = []
for row in YeastUPS1_lowest_df.itertuples():
run_occurences_df = sequences_df[(sequences_df.sequence == row.sequence) & (sequences_df.charge == row.charge) & (sequences_df.group == row.group)]
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
index_l.append('{},{}'.format(row.sequence, row.charge))
for r in run_occurences_df.itertuples():
occurences_d[r.short_run_name] = np.log2(r.intensity)
occurences_l.append(occurences_d)
occurences_df = pd.DataFrame(occurences_l, columns=occurences_d.keys(), index=index_l)
occurences_df.tail(n=10)
plt.figure(figsize=(15,30))
a = occurences_df.to_numpy()
hm = sns.heatmap(occurences_df, cmap=cm.batlow_r, vmin=a[a > 0].min(), vmax=a.max(), mask=(occurences_df==0), linewidths=0)
hm.set(yticklabels=[])
hm.set(ylabel=None)
hm.tick_params(left=False)
# plt.title('Lowest {} peptides by mean intensity for YeastUPS1 by TFD/E'.format(lower_number))
```
#### plot YeastUPS2
```
run_names_l = sorted(list(sequences_df[sequences_df.group == 'YeastUPS2'].short_run_name.unique()), key=lambda x: int(x.split('_')[1]))
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
# as a heatmap, plot the missing-ness across this group of runs
occurences_l = []
index_l = []
for row in YeastUPS2_lowest_df.itertuples():
run_occurences_df = sequences_df[(sequences_df.sequence == row.sequence) & (sequences_df.charge == row.charge) & (sequences_df.group == row.group)]
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
index_l.append('{},{}'.format(row.sequence, row.charge))
for r in run_occurences_df.itertuples():
occurences_d[r.short_run_name] = np.log2(r.intensity)
occurences_l.append(occurences_d)
occurences_df = pd.DataFrame(occurences_l, columns=occurences_d.keys(), index=index_l)
plt.figure(figsize=(15,30))
a = occurences_df.to_numpy()
hm = sns.heatmap(occurences_df, cmap=cm.batlow_r, vmin=a[a > 0].min(), vmax=a.max(), mask=(occurences_df==0), linewidths=0)
hm.set(yticklabels=[])
hm.set(ylabel=None)
hm.tick_params(left=False)
# plt.title('Lowest {} peptides by mean intensity for YeastUPS2 by TFD/E'.format(lower_number))
```
## MaxQuant heatmaps
```
mq_results_df.columns
mq_results_df.iloc[1466].Proteins
# get one reading for each unique peptide in each run, and count how many identifications and extractions (i.e.
# matches) across each group. Note that a sequence can be counted as an identification and a match in the same file
# (i.e. it's given a different score).
mq_sequences_l = []
unique_peptide_key_file = unique_peptide_key + ['Raw file']
for group_name,group_df in mq_results_df.groupby(unique_peptide_key_file, as_index=False):
identified_in_file = (len(group_df[group_df.Type == 'TIMS-MULTI-MSMS']) > 0)
short_run_name = '_'.join(group_name[3].split('_Slot')[0].split('_')[1:3])
grp_name = short_run_name.split('_')[0]
sorted_df = group_df.sort_values(by=['Intensity'], ascending=False, inplace=False)
if identified_in_file:
score = sorted_df.iloc[0]['Score']
else:
score = sorted_df.iloc[0]['Match score']
intensity = sorted_df.iloc[0].Intensity
protein = sorted_df.iloc[0].Proteins
species = classify_protein(protein)
mq_sequences_l.append((group_name[0], group_name[1], group_name[2], species, short_run_name, grp_name, identified_in_file, score, intensity))
mq_sequences_df = pd.DataFrame(mq_sequences_l, columns=['sequence','modifications','charge','species','short_run_name','group','identified_in_file','score','intensity'])
mq_sequences_df.sample(n=5)
# find the mean intensity for each peptide in each group
mq_intensities_l = []
for group_name,group_df in mq_sequences_df.groupby(['sequence','modifications','charge','group'], as_index=False):
mean_intensity = group_df.intensity.mean()
mq_intensities_l.append((group_name[0], group_name[1], group_name[2], group_name[3], mean_intensity))
mq_intensities_df = pd.DataFrame(mq_intensities_l, columns=['sequence', 'modifications', 'charge', 'group', 'group_mean_intensity'])
# sort each group by descending intensity
mq_intensities_df.sort_values(by=['group_mean_intensity'], ascending=False, inplace=True)
mq_intensities_df.tail()
# make a separate DF for each group
YeastUPS1_df = mq_intensities_df[(mq_intensities_df.group == 'YeastUPS1')].copy()
YeastUPS2_df = mq_intensities_df[(mq_intensities_df.group == 'YeastUPS2')].copy()
# find the lowest-intensity peptides in each group
lower_number = 500
YeastUPS1_lowest_df = YeastUPS1_df.tail(lower_number)
YeastUPS2_lowest_df = YeastUPS2_df.tail(lower_number)
```
#### plot YeastUPS1
```
run_names_l = sorted(list(mq_sequences_df[mq_sequences_df.group == 'YeastUPS1'].short_run_name.unique()), key=lambda x: int(x.split('_')[1]))
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
# as a heatmap, plot the missing-ness across this group of runs
occurences_l = []
index_l = []
for row in YeastUPS1_lowest_df.itertuples():
run_occurences_df = mq_sequences_df[(mq_sequences_df.sequence == row.sequence) & (mq_sequences_df.modifications == row.modifications) & (mq_sequences_df.charge == row.charge) & (mq_sequences_df.group == row.group)]
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
index_l.append('{},{}'.format(row.sequence, row.charge))
for r in run_occurences_df.itertuples():
occurences_d[r.short_run_name] = np.log2(r.intensity)
occurences_l.append(occurences_d)
occurences_df = pd.DataFrame(occurences_l, columns=occurences_d.keys(), index=index_l)
plt.figure(figsize=(15,30))
a = occurences_df.to_numpy()
hm = sns.heatmap(occurences_df, cmap=cm.batlow_r, vmin=a[a > 0].min(), vmax=a.max(), mask=(occurences_df==0), linewidths=0)
hm.set(yticklabels=[])
hm.set(ylabel=None)
hm.tick_params(left=False)
# plt.title('Lowest {} peptides by mean intensity for YeastUPS1 by MaxQuant'.format(lower_number))
```
#### plot YeastUPS2
```
run_names_l = sorted(list(mq_sequences_df[mq_sequences_df.group == 'YeastUPS2'].short_run_name.unique()), key=lambda x: int(x.split('_')[1]))
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
# as a heatmap, plot the missing-ness across this group of runs
occurences_l = []
index_l = []
for row in YeastUPS2_lowest_df.itertuples():
run_occurences_df = mq_sequences_df[(mq_sequences_df.sequence == row.sequence) & (mq_sequences_df.modifications == row.modifications) & (mq_sequences_df.charge == row.charge) & (mq_sequences_df.group == row.group)]
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
index_l.append('{},{}'.format(row.sequence, row.charge))
for r in run_occurences_df.itertuples():
occurences_d[r.short_run_name] = np.log2(r.intensity)
occurences_l.append(occurences_d)
occurences_df = pd.DataFrame(occurences_l, columns=occurences_d.keys(), index=index_l)
plt.figure(figsize=(15,30))
a = occurences_df.to_numpy()
hm = sns.heatmap(occurences_df, cmap=cm.batlow_r, vmin=a[a > 0].min(), vmax=a.max(), mask=(occurences_df==0), linewidths=0)
hm.set(yticklabels=[])
hm.set(ylabel=None)
hm.tick_params(left=False)
# plt.title('Lowest {} peptides by mean intensity for YeastUPS2 by MaxQuant'.format(lower_number))
```
## Fragger heatmaps
```
# use the analysis with MBR
# FRAGGER_RESULTS_DIR = '{}'.format(expanduser('~'))
FRAGGER_RESULTS_DIR = '{}/Downloads/experiments'.format(expanduser('~'))
fragger_results_df = pd.read_csv('{}/MSFragger-analysis-P3830/P3830-results/MSstats.csv'.format(FRAGGER_RESULTS_DIR), sep=',')
fragger_sequences_df = fragger_results_df.copy()
fragger_sequences_df.columns
condition_mapping_d = {'YUPS1':'YeastUPS1', 'YUPS2':'YeastUPS2'}
fragger_sequences_df['short_run_name'] = fragger_sequences_df.apply(lambda row: '_'.join(row.Run.split('_Slot')[0].split('_')[1:3]), axis=1)
fragger_sequences_df['group'] = fragger_sequences_df.apply(lambda row: condition_mapping_d[row.Condition], axis=1)
fragger_sequences_df['species'] = fragger_sequences_df.apply(lambda row: classify_protein(row.ProteinName), axis=1)
fragger_sequences_df = fragger_sequences_df[fragger_sequences_df.Intensity.notnull()]
fragger_sequences_df = fragger_sequences_df[fragger_sequences_df.Intensity > 0]
fragger_sequences_df.sample(n=3)
# find the mean intensity for each peptide in each group
fragger_intensities_l = []
for group_name,group_df in fragger_sequences_df.groupby(['PeptideSequence','PrecursorCharge','group'], as_index=False):
mean_intensity = group_df.Intensity.mean()
fragger_intensities_l.append((group_name[0], group_name[1], group_name[2], mean_intensity))
fragger_intensities_df = pd.DataFrame(fragger_intensities_l, columns=['sequence', 'charge', 'group', 'group_mean_intensity'])
# sort each group by descending intensity
fragger_intensities_df.sort_values(by=['group_mean_intensity'], ascending=False, inplace=True)
fragger_intensities_df.tail()
# make a separate DF for each group
YeastUPS1_df = fragger_intensities_df[(fragger_intensities_df.group == 'YeastUPS1')].copy()
YeastUPS2_df = fragger_intensities_df[(fragger_intensities_df.group == 'YeastUPS2')].copy()
# find the lowest-intensity peptides in each group
lower_number = 500
YeastUPS1_lowest_df = YeastUPS1_df.tail(lower_number)
YeastUPS2_lowest_df = YeastUPS2_df.tail(lower_number)
```
#### plot YeastUPS1
```
run_names_l = sorted(list(fragger_sequences_df[fragger_sequences_df.group == 'YeastUPS1'].short_run_name.unique()), key=lambda x: int(x.split('_')[1]))
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
# as a heatmap, plot the missing-ness across this group of runs
occurences_l = []
index_l = []
for row in YeastUPS1_lowest_df.itertuples():
run_occurences_df = fragger_sequences_df[(fragger_sequences_df.PeptideSequence == row.sequence) & (fragger_sequences_df.PrecursorCharge == row.charge) & (fragger_sequences_df.group == row.group)]
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
index_l.append('{},{}'.format(row.sequence, row.charge))
for r in run_occurences_df.itertuples():
occurences_d[r.short_run_name] = np.log2(r.Intensity)
occurences_l.append(occurences_d)
occurences_df = pd.DataFrame(occurences_l, columns=occurences_d.keys(), index=index_l)
plt.figure(figsize=(15,30))
a = occurences_df.to_numpy()
hm = sns.heatmap(occurences_df, cmap=cm.batlow_r, vmin=a[a > 0].min(), vmax=a.max(), mask=(occurences_df==0), linewidths=0)
hm.set(yticklabels=[])
hm.set(ylabel=None)
hm.tick_params(left=False)
# plt.title('Lowest {} peptides by mean intensity for YeastUPS1 by MSFragger'.format(lower_number))
```
#### plot YeastUPS2
```
run_names_l = sorted(list(fragger_sequences_df[fragger_sequences_df.group == 'YeastUPS2'].short_run_name.unique()), key=lambda x: int(x.split('_')[1]))
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
# as a heatmap, plot the missing-ness across this group of runs
occurences_l = []
index_l = []
for row in YeastUPS2_lowest_df.itertuples():
run_occurences_df = fragger_sequences_df[(fragger_sequences_df.PeptideSequence == row.sequence) & (fragger_sequences_df.PrecursorCharge == row.charge) & (fragger_sequences_df.group == row.group)]
occurences_d = dict(zip(run_names_l, [0] * len(run_names_l)))
index_l.append('{},{}'.format(row.sequence, row.charge))
for r in run_occurences_df.itertuples():
occurences_d[r.short_run_name] = np.log2(r.Intensity)
occurences_l.append(occurences_d)
occurences_df = pd.DataFrame(occurences_l, columns=occurences_d.keys(), index=index_l)
plt.figure(figsize=(15,30))
a = occurences_df.to_numpy()
hm = sns.heatmap(occurences_df, cmap=cm.batlow_r, vmin=a[a > 0].min(), vmax=a.max(), mask=(occurences_df==0), linewidths=0)
hm.set(yticklabels=[])
hm.set(ylabel=None)
hm.tick_params(left=False)
# plt.title('Lowest {} peptides by intensity for YeastUPS2 by MSFragger'.format(lower_number))
```
## visualise the percentage of missing values across runs
#### prepare TFD/E results
```
subset_groups = ['YeastUPS1']
tfde_subset_df = sequences_df[(sequences_df.group.isin(subset_groups))]
number_of_runs_in_subset = len(tfde_subset_df.short_run_name.unique())
print('there are {} {} runs in the experiment'.format(number_of_runs_in_subset, subset_groups))
number_of_unique_sequences_tfde = len(tfde_subset_df.drop_duplicates(subset=['sequence', 'charge'], keep='first', inplace=False))
number_of_unique_sequences_tfde
# count how many runs each sequence/charge was extracted from and classified as a target
sequence_occurences_l = []
for group_name,group_df in tfde_subset_df.groupby(['sequence','charge'], as_index=False):
sequence_occurences_l.append((group_name, len(group_df.short_run_name.unique()), group_name[0], group_name[1]))
tfde_sequence_occurences_df = pd.DataFrame(sequence_occurences_l, columns=['sequence_charge','number_of_runs_extracted','sequence','charge'])
tfde_sequence_occurences_df['missing_files'] = number_of_runs_in_subset - tfde_sequence_occurences_df.number_of_runs_extracted
# display the number of missing values across the subset
tfde_missing_values = tfde_sequence_occurences_df.missing_files.sum() / (len(tfde_sequence_occurences_df) * number_of_runs_in_subset)
tfde_sequence_occurences_df.sample(n=3)
run_count_l = []
for number_of_runs in range(1,number_of_runs_in_subset+1):
run_count_l.append((number_of_runs, len(tfde_sequence_occurences_df[tfde_sequence_occurences_df.number_of_runs_extracted >= number_of_runs])))
tfde_run_count_df = pd.DataFrame(run_count_l, columns=['run_count','number_of_sequences'])
tfde_run_count_df['percent_quantified'] = tfde_run_count_df.number_of_sequences / number_of_unique_sequences_tfde * 100
```
#### prepare MQ results
```
mq_sequences_df.columns
mq_subset_df = mq_sequences_df[(mq_sequences_df.group.isin(subset_groups))]
number_of_unique_sequences_mq = len(mq_subset_df.drop_duplicates(subset=['sequence','modifications','charge'], keep='first', inplace=False))
number_of_unique_sequences_mq
# count how many runs each sequence/charge was extracted from
sequence_occurences_l = []
for group_name,group_df in mq_subset_df.groupby(['sequence', 'modifications', 'charge'], as_index=False):
sequence_occurences_l.append((group_name[0], group_name[1], group_name[2], len(group_df.short_run_name.unique())))
mq_sequence_occurences_df = pd.DataFrame(sequence_occurences_l, columns=['sequence','modifications','charge','number_of_runs_extracted'])
run_count_l = []
for number_of_runs in range(1,number_of_runs_in_subset+1):
run_count_l.append((number_of_runs, len(mq_sequence_occurences_df[mq_sequence_occurences_df.number_of_runs_extracted >= number_of_runs])))
mq_run_count_df = pd.DataFrame(run_count_l, columns=['run_count','number_of_sequences'])
mq_sequence_occurences_df['missing_files'] = number_of_runs_in_subset - mq_sequence_occurences_df.number_of_runs_extracted
mq_run_count_df['percent_quantified'] = mq_run_count_df.number_of_sequences / number_of_unique_sequences_mq * 100
# display the number of missing values across the subset
mq_missing_values = mq_sequence_occurences_df.missing_files.sum() / (len(mq_sequence_occurences_df) * number_of_runs_in_subset)
```
#### prepare Fragger results
```
fragger_subset_df = fragger_sequences_df[(fragger_sequences_df.group.isin(subset_groups))]
number_of_unique_sequences_fragger = len(fragger_subset_df.drop_duplicates(subset=['PeptideSequence', 'PrecursorCharge'], keep='first', inplace=False))
number_of_unique_sequences_fragger
# count how many runs each sequence/charge was found in
sequence_occurences_l = []
for group_name,group_df in fragger_subset_df.groupby(['PeptideSequence','PrecursorCharge'], as_index=False):
sequence_occurences_l.append((group_name[0], group_name[1], len(group_df.short_run_name.unique())))
fragger_sequence_occurences_df = pd.DataFrame(sequence_occurences_l, columns=['sequence','charge','number_of_runs_extracted'])
run_count_l = []
for number_of_runs in range(1,number_of_runs_in_subset+1):
run_count_l.append((number_of_runs, len(fragger_sequence_occurences_df[fragger_sequence_occurences_df.number_of_runs_extracted >= number_of_runs])))
fragger_run_count_df = pd.DataFrame(run_count_l, columns=['run_count','number_of_sequences'])
fragger_sequence_occurences_df['missing_files'] = number_of_runs_in_subset - fragger_sequence_occurences_df.number_of_runs_extracted
fragger_run_count_df['percent_quantified'] = fragger_run_count_df.number_of_sequences / number_of_unique_sequences_fragger * 100
# display the number of missing values across the subset
fragger_missing_values = fragger_sequence_occurences_df.missing_files.sum() / (len(fragger_sequence_occurences_df) * number_of_runs_in_subset)
```
#### now plot the results
```
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
# plt.title('percentage of peptides without missing values as a function of run numbers for conditions {}'.format(subset_groups))
ax1.plot(tfde_run_count_df.run_count, tfde_run_count_df.percent_quantified, label='TFD/E')
ax1.plot(mq_run_count_df.run_count, mq_run_count_df.percent_quantified, label='MaxQuant')
ax1.plot(fragger_run_count_df.run_count, fragger_run_count_df.percent_quantified, label='MSFragger')
plt.xlabel('peptides quantified in >= number of runs')
plt.ylabel('% of total peptides quantified')
plt.ylim((15,105))
ax1.set(xticks=range(1,number_of_runs_in_subset+1), xlim=[0, number_of_runs_in_subset+1])
plt.legend(loc="best")
plt.show()
```
## missing-ness distributions
#### plot TFD/E results
```
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
# plt.suptitle('TFD/E distribution of sequence identifications for conditions {}'.format(subset_groups))
# plt.title('total of {} modified peptide sequences, {}% of values missing'.format(number_of_unique_sequences_tfde, int(round(tfde_missing_values*100))))
counts = np.bincount(tfde_sequence_occurences_df.number_of_runs_extracted)
ax1.bar(range(number_of_runs_in_subset+1), counts, width=0.8, align='center')
plt.xlabel('number of files in which a modified sequence-charge was quantified')
plt.ylabel('frequency')
ax1.set(xticks=range(1,number_of_runs_in_subset+1), xlim=[0, number_of_runs_in_subset+1])
plt.ylim((0,9000))
plt.show()
```
#### plot MQ results
```
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
# plt.suptitle('MaxQuant distribution of sequence identifications for conditions {}'.format(subset_groups))
# plt.title('total of {} modified peptide sequences, {}% of values missing'.format(number_of_unique_sequences_mq, int(round(mq_missing_values*100))))
counts = np.bincount(mq_sequence_occurences_df.number_of_runs_extracted)
ax1.bar(range(number_of_runs_in_subset+1), counts, width=0.8, align='center')
plt.xlabel('number of files in which a modified sequence-charge was quantified')
plt.ylabel('frequency')
ax1.set(xticks=range(1,number_of_runs_in_subset+1), xlim=[0, number_of_runs_in_subset+1])
plt.ylim((0,9000))
plt.show()
```
#### plot Fragger results
```
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
# plt.suptitle('MSFragger distribution of sequence identifications for conditions {}'.format(subset_groups))
# plt.title('total of {} modified peptide sequences, {}% of values missing'.format(number_of_unique_sequences_fragger, int(round(fragger_missing_values*100))))
counts = np.bincount(fragger_sequence_occurences_df.number_of_runs_extracted)
ax1.bar(range(number_of_runs_in_subset+1), counts, width=0.8, align='center')
plt.xlabel('number of files in which a modified sequence-charge was quantified')
plt.ylabel('frequency')
ax1.set(xticks=range(1,number_of_runs_in_subset+1), xlim=[0, number_of_runs_in_subset+1])
plt.ylim((0,9000))
plt.show()
```
## distribution of quantitative intensities
#### prepare TFD/E results
```
tfde_subset_df.sample(n=3)
# calculate the intensity mean for peptides without missing values
tfde_intensities_l = []
for group_name,group_df in tfde_subset_df.groupby(['sequence','charge'], as_index=False):
if len(group_df.short_run_name.unique()) == number_of_runs_in_subset:
intensity_mean = group_df.intensity.mean()
tfde_intensities_l.append((','.join([group_name[0],group_name[1].astype('str')]),intensity_mean,'TFD/E'))
tfde_intensities_df = pd.DataFrame(tfde_intensities_l, columns=['sequence','intensity','method'])
tfde_intensities_df['intensity_adjusted'] = tfde_intensities_df.intensity - np.min(tfde_intensities_df.intensity)
tfde_intensities_df.intensity_adjusted.replace(to_replace=[0.0], value=1.0, inplace=True)
```
#### prepare MQ results
```
mq_subset_df.sample(n=3)
# calculate the intensity mean for peptides without missing values
mq_intensities_l = []
for group_name,group_df in mq_subset_df.groupby(['sequence','modifications','charge'], as_index=False):
if len(group_df.short_run_name.unique()) == number_of_runs_in_subset:
intensity_mean = group_df.intensity.mean()
mq_intensities_l.append((','.join([group_name[0],group_name[1],group_name[2].astype('str')]),intensity_mean,'MaxQuant'))
mq_intensities_df = pd.DataFrame(mq_intensities_l, columns=['sequence','intensity','method'])
mq_intensities_df['intensity_adjusted'] = mq_intensities_df.intensity - np.min(mq_intensities_df.intensity)
mq_intensities_df.intensity_adjusted.replace(to_replace=[0.0], value=1.0, inplace=True)
```
#### prepare Fragger results
```
fragger_subset_df.sample(n=3)
# calculate the intensity mean for peptides without missing values
fragger_intensities_l = []
for group_name,group_df in fragger_subset_df.groupby(['PeptideSequence', 'PrecursorCharge'], as_index=False):
if len(group_df['Run'].unique()) == number_of_runs_in_subset:
intensity_mean = group_df.Intensity.mean()
fragger_intensities_l.append((','.join([group_name[0],group_name[1].astype('str')]),intensity_mean,'MSFragger'))
fragger_intensities_df = pd.DataFrame(fragger_intensities_l, columns=['sequence','intensity','method'])
fragger_intensities_df['intensity_adjusted'] = fragger_intensities_df.intensity - np.min(fragger_intensities_df.intensity)
fragger_intensities_df.intensity_adjusted.replace(to_replace=[0.0], value=1.0, inplace=True)
tfde_intensities_df['intensity_log'] = np.log10(tfde_intensities_df.intensity)
mq_intensities_df['intensity_log'] = np.log10(mq_intensities_df.intensity)
fragger_intensities_df['intensity_log'] = np.log10(fragger_intensities_df.intensity)
tfde_intensities_df['intensity_adjusted_log'] = tfde_intensities_df.intensity_log - np.min(tfde_intensities_df.intensity_log)
mq_intensities_df['intensity_adjusted_log'] = mq_intensities_df.intensity_log - np.min(mq_intensities_df.intensity_log)
fragger_intensities_df['intensity_adjusted_log'] = fragger_intensities_df.intensity_log - np.min(fragger_intensities_df.intensity_log)
```
#### consolidate the data
```
intensities_l = [tfde_intensities_df,mq_intensities_df,fragger_intensities_df]
intensities_df = pd.concat(intensities_l, sort=False)
intensities_df.sample(n=3)
```
#### produce the plot
```
plt.figure(figsize=(15,10))
ax = sns.violinplot(x=intensities_df.method, y=intensities_df.intensity_adjusted_log)
_ = plt.ylabel("log10 intensity")
_ = plt.title('distribution of quantitative intensities (in log10 scale) for peptides without missing values for conditions {}'.format(subset_groups))
# orders of magnitude
intensities_df.groupby('method')['intensity_adjusted_log'].agg(np.ptp)
# number of peptides that have no missing values
intensities_df.groupby('method')['intensity_adjusted_log'].count()
```
## distribution of CV
#### TFD/E analysis
```
tfde_subset_df.sample(n=3)
# for each sequence, find the CV
sequence_cv_l = []
for group_name,group_df in tfde_subset_df.groupby(['sequence','charge']):
if len(group_df) >= 2:
intensity_cv = np.std(group_df.intensity) / np.mean(group_df.intensity)
sequence_cv_l.append((group_name[0], group_name[1], intensity_cv))
sequence_cv_df = pd.DataFrame(sequence_cv_l, columns=['sequence','charge','intensity_cv'])
sequence_cv_df.sample(n=3)
sequence_cv_df[sequence_cv_df.intensity_cv > 0.25].sample(n=5)
results_df[(results_df.sequence == 'SYSNDDESNEILSYEGK') & (results_df.charge == 2)]
tfde_subset_df[(tfde_subset_df.sequence == 'SYSNDDESNEILSYEGK') & (tfde_subset_df.charge == 2)]
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
plt.title('')
bins = 300
values = sequence_cv_df.intensity_cv
y, x, _ = ax1.hist(values, bins=bins)
mean = np.mean(values)
ax1.axvline(mean, color='darkorange', lw=1.0, ls='-.', label='mean')
text_style = dict(size=10, color='brown', verticalalignment='center', horizontalalignment='left')
ax1.text(mean*0.85, y.max()*0.98, "mean {}".format(round(mean,2)), **text_style, rotation='vertical')
plt.xlabel('sequence intensity CV')
plt.ylabel('count')
# plt.title('TFD/E sequence intensity coefficient of variance for conditions {} ({} unique peptides)'.format(subset_groups,len(sequence_cv_df)))
plt.xlim((0,1))
plt.ylim((0,1000))
plt.show()
```
#### MQ analysis
```
# for each sequence, find the CV
sequence_cv_l = []
for group_name,group_df in mq_subset_df.groupby(['sequence','modifications','charge']):
if len(group_df) >= 2:
intensity_cv = np.std(group_df.intensity) / np.mean(group_df.intensity)
sequence = ','.join([group_name[0],group_name[1],group_name[2].astype('str')])
sequence_cv_l.append((sequence, intensity_cv))
mq_sequence_cv_df = pd.DataFrame(sequence_cv_l, columns=['sequence','intensity_cv'])
mq_sequence_cv_df.sample(n=3)
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
plt.title('')
bins = 300
values = mq_sequence_cv_df.intensity_cv
y, x, _ = ax1.hist(values, bins=bins)
mean = np.mean(values)
ax1.axvline(mean, color='darkorange', lw=1.0, ls='-.', label='mean')
text_style = dict(size=10, color='brown', verticalalignment='center', horizontalalignment='left')
ax1.text(mean*0.85, y.max()*0.98, "mean {}".format(round(mean,2)), **text_style, rotation='vertical')
plt.xlabel('sequence intensity CV')
plt.ylabel('count')
# plt.title('MaxQuant sequence intensity coefficient of variance for conditions {} ({} unique peptides)'.format(subset_groups, len(mq_sequence_cv_df)))
plt.xlim((0,1))
plt.ylim((0,1000))
plt.show()
```
#### Fragger analysis
```
# for each sequence, find the CV
sequence_cv_l = []
for group_name,group_df in fragger_subset_df.groupby(['PeptideSequence', 'PrecursorCharge']):
if len(group_df) >= 2:
intensity_cv = np.std(group_df.Intensity) / np.mean(group_df.Intensity)
sequence = ','.join([group_name[0],group_name[1].astype('str')])
sequence_cv_l.append((sequence, intensity_cv))
fragger_sequence_cv_df = pd.DataFrame(sequence_cv_l, columns=['sequence','intensity_cv'])
fragger_sequence_cv_df.sample(n=3)
f, ax1 = plt.subplots()
f.set_figheight(8)
f.set_figwidth(8)
plt.margins(0.06)
plt.title('')
bins = 300
values = fragger_sequence_cv_df.intensity_cv
y, x, _ = ax1.hist(values, bins=bins)
mean = np.mean(values)
ax1.axvline(mean, color='darkorange', lw=1.0, ls='-.', label='mean')
text_style = dict(size=10, color='brown', verticalalignment='center', horizontalalignment='left')
ax1.text(mean*0.85, y.max()*0.98, "mean {}".format(round(mean,2)), **text_style, rotation='vertical')
plt.xlabel('sequence intensity CV')
plt.ylabel('count')
# plt.title('MSFragger sequence intensity coefficient of variance for conditions {} ({} unique peptides)'.format(subset_groups,len(fragger_sequence_cv_df)))
plt.xlim((0,1))
plt.ylim((0,1000))
plt.show()
```
## comparison of peptide intensity in different experiment conditions
```
# the experiment conditions to compare
groupA = 'YeastUPS1'
groupA_number_of_runs = 10
groupB = 'YeastUPS2'
groupB_number_of_runs = 10
```
#### TFD/E analysis
```
sequences_df.columns
sequences_df.identified_in_run.sum()
len(sequences_df[sequences_df.identified_in_run == True])
# for each sequence and charge, if it was found in more than half the runs,
# find the mean intensity in each group, then find the intensity ratio between groups
sequence_occurences_in_group = []
for group_name,group_df in sequences_df.groupby(['sequence','charge'], as_index=False):
sequence_in_A_df = group_df[group_df.group == groupA]
sequence_in_B_df = group_df[group_df.group == groupB]
if (
(sequence_in_A_df.identified_in_run.sum() > 0) and # must have at least one ID in the group
(sequence_in_B_df.identified_in_run.sum() > 0) and
(len(sequence_in_A_df) >= int(groupA_number_of_runs / 2)) and # must have been extracted from more than half the runs in the group
(len(sequence_in_B_df) >= int(groupB_number_of_runs / 2))
):
intensity_A = sequence_in_A_df.intensity.mean()
intensity_B = sequence_in_B_df.intensity.mean()
species = group_df.iloc[0].species
sequence = group_name[0]
charge = group_name[1]
sequence_occurences_in_group.append((sequence, charge, species, intensity_A, intensity_B))
sequence_occurences_in_group_df = pd.DataFrame(sequence_occurences_in_group, columns=['sequence','charge','species','intensity_A','intensity_B'])
sequence_occurences_in_group_df['intensity_ratio'] = sequence_occurences_in_group_df.intensity_B / sequence_occurences_in_group_df.intensity_A
sequence_occurences_in_group_df['intensity_ratio_log'] = np.log2(sequence_occurences_in_group_df['intensity_ratio'])
```
#### plot the intensity ratios of the two proteomes
```
human_df = sequence_occurences_in_group_df[sequence_occurences_in_group_df.species.str.upper() == 'HUMAN']
yeast_df = sequence_occurences_in_group_df[sequence_occurences_in_group_df.species.str.upper() == 'YEAST']
kde_df = sequence_occurences_in_group_df[(sequence_occurences_in_group_df.intensity_ratio <= 3)]
import seaborn as sns
fp = sns.displot(data=kde_df, x=kde_df['intensity_ratio'], hue='species', hue_order=['Human','Yeast'], palette=['tab:green','tab:cyan'], kind='kde', height=6, aspect=1.2, common_norm=False)
x = fp.ax.lines[0].get_xdata()
y = fp.ax.lines[0].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
x = fp.ax.lines[1].get_xdata()
y = fp.ax.lines[1].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
_ = fp.ax.set(xlabel='intensity {} / intensity {}'.format(groupB, groupA), ylabel='density')
```
#### MQ analysis
```
mq_sequences_df.columns
# for each sequence and charge, if it was found in more than half the runs,
# find the mean intensity in each group, then find the intensity ratio between groups
sequence_occurences_in_group = []
for group_name,group_df in mq_sequences_df.groupby(['sequence','modifications','charge'], as_index=False):
sequence_in_A_df = group_df[group_df.group == groupA]
sequence_in_B_df = group_df[group_df.group == groupB]
if (len(sequence_in_A_df) >= int(groupA_number_of_runs / 2)) and (len(sequence_in_B_df) >= int(groupB_number_of_runs / 2)):
average_intensity_in_A = sequence_in_A_df.intensity.mean()
average_intensity_in_B = sequence_in_B_df.intensity.mean()
species = group_df.iloc[0].species
sequence = group_name[0]
charge = group_name[1]
sequence_occurences_in_group.append((sequence, charge, species, average_intensity_in_A, average_intensity_in_B))
mq_sequence_occurences_in_group_df = pd.DataFrame(sequence_occurences_in_group, columns=['sequence','charge','species','intensity_A','intensity_B'])
mq_sequence_occurences_in_group_df['intensity_ratio'] = mq_sequence_occurences_in_group_df.intensity_B / mq_sequence_occurences_in_group_df.intensity_A
human_df = mq_sequence_occurences_in_group_df[mq_sequence_occurences_in_group_df.species.str.upper() == 'HUMAN']
yeast_df = mq_sequence_occurences_in_group_df[mq_sequence_occurences_in_group_df.species.str.upper() == 'YEAST']
mq_kde_df = mq_sequence_occurences_in_group_df[(mq_sequence_occurences_in_group_df.intensity_ratio <= 3)]
import seaborn as sns
fp = sns.displot(data=mq_kde_df, x=mq_kde_df['intensity_ratio'], hue='species', hue_order=['Human','Yeast'], palette=['tab:green','tab:cyan'], kind='kde', height=6, aspect=1.2, common_norm=False)
x = fp.ax.lines[0].get_xdata()
y = fp.ax.lines[0].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
x = fp.ax.lines[1].get_xdata()
y = fp.ax.lines[1].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
_ = fp.ax.set(xlabel='intensity {} / intensity {}'.format(groupB, groupA), ylabel='density')
```
#### Fragger analysis
```
fragger_sequences_df.columns
# for each sequence and charge, if it was found in more than half the runs,
# find the mean intensity in each group, then find the intensity ratio between groups
sequence_occurences_in_group = []
for group_name,group_df in fragger_sequences_df.groupby(['PeptideSequence','PrecursorCharge'], as_index=False):
sequence_in_A_df = group_df[group_df.group == groupA]
sequence_in_B_df = group_df[group_df.group == groupB]
if (len(sequence_in_A_df) >= int(groupA_number_of_runs / 2)) and (len(sequence_in_B_df) >= int(groupB_number_of_runs / 2)):
average_intensity_in_A = sequence_in_A_df.Intensity.mean()
average_intensity_in_B = sequence_in_B_df.Intensity.mean()
species = group_df.iloc[0].species
sequence = group_name[0]
charge = group_name[1]
sequence_occurences_in_group.append((sequence, charge, species, average_intensity_in_A, average_intensity_in_B))
fragger_sequence_occurences_in_group_df = pd.DataFrame(sequence_occurences_in_group, columns=['sequence','charge','species','intensity_A','intensity_B'])
fragger_sequence_occurences_in_group_df['intensity_ratio'] = fragger_sequence_occurences_in_group_df.intensity_B / fragger_sequence_occurences_in_group_df.intensity_A
human_df = fragger_sequence_occurences_in_group_df[fragger_sequence_occurences_in_group_df.species == 'HUMAN']
yeast_df = fragger_sequence_occurences_in_group_df[fragger_sequence_occurences_in_group_df.species == 'YEAST']
fragger_kde_df = fragger_sequence_occurences_in_group_df[(fragger_sequence_occurences_in_group_df.intensity_ratio <= 3)]
import seaborn as sns
fp = sns.displot(data=fragger_kde_df, x=fragger_kde_df['intensity_ratio'], hue='species', hue_order=['Human','Yeast','E. coli'], palette=['tab:green','tab:cyan','tab:red'], kind='kde', height=6, aspect=1.2, common_norm=False)
x = fp.ax.lines[0].get_xdata()
y = fp.ax.lines[0].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
x = fp.ax.lines[1].get_xdata()
y = fp.ax.lines[1].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
x = fp.ax.lines[2].get_xdata()
y = fp.ax.lines[2].get_ydata()
_ = plt.axvline(x[np.argmax(y)], color='silver', lw=1.5, ls=':')
_ = fp.ax.set(xlabel='intensity {} / intensity {}'.format(groupB, groupA), ylabel='density')
```
| github_jupyter |
# Accessing Data in Python (part 2)
```
# %load ./imports.py
# %load /Users/bartev/dev/github-bv/sporty/notebooks/imports.py
## Where am I
!echo $VIRTUAL_ENV
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
# magics
%load_ext blackcellmagic
# start cell with `%%black` to format using `black`
%load_ext autoreload
# start cell with `%autoreload` to reload module
# https://ipython.org/ipython-doc/stable/config/extensions/autoreload.html
# reload all modules when running
%autoreload 2
# imports
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
import seaborn as sns
from importlib import reload
from pathlib import Path
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
# https://plotnine.readthedocs.io/en/stable/
import plotnine as p9
from plotnine import ggplot, aes, facet_wrap
from src.utils import lower_case_col_names
import src.data.load_data as ld
from src.data.load_data import get_nba_game_team_points
nba_games = ld.load_nba('games')
nba_games.head()
games_18 = nba_games.query("season == 2018")
games_18.info()
```
## Use `info()` to check for missing variables
```
nba_games.info()
```
Note: some variables have missing data
## Use `isnull()`, `notnull()` to look for missing values
this doesn't work - why?
```
nba_games[nba_games.isnull()]
```
This doesn't seem to do anything either
```
nba_games[nba_games.notnull()]
```
# Handling Missing Values
## Drop observations with missing values in the variable `fg_pct_home`
Using `notnull` on a single column works, though.
```
nba_games[pd.notnull(nba_games['fg_pct_home'])]
```
Call `notnull` either as a method on the column, or as a function from pandas
```
nba_games[nba_games['fg_pct_home'].notnull()]
nba_games[pd.isnull(nba_games['fg_pct_home'])].shape
```
## Data imputation
### `fillna`
```
nba_games.mean()
mean_filled = nba_games.fillna(nba_games.mean())
print(f'shape: {mean_filled.shape}')
mean_filled.head()
```
## Create variables
```
nba_games[['pts_home', 'pts_away']].head()
(nba_games['pts_home'] + nba_games['pts_away']).head()
```
### Based on a condition
Could use `home_team_wins`, but I'm doing it this way to make sure it's all consistent.m
```
(nba_games
.head()
.fillna(lambda x: x.mean())
[['pts_home', 'pts_away', 'home_team_wins']]
.assign(result=lambda x: np.where(x['pts_home'] > x['pts_away'], 'W', 'L'))
)
```
Drop the newly created variable
```
(nba_games
.head()
.fillna(lambda x: x.mean())
[['pts_home', 'pts_away', 'home_team_wins']]
.assign(result=lambda x: np.where(x['pts_home'] > x['pts_away'], 'W', 'L'))
.drop('result', axis=1)
)
nba_games.head()
```
### Create a variable based on a group
Download
```
nba_gtp = get_nba_game_team_points()
nba_gtp
```
* 2 observations: 1 each for home and away teams
* Create a variable `point_diff`.
1. sort by `game_id` and `wl`. (puts the same game rows together, with winning team first)
2. the `groupby` and `diff` will give the diff between the rows in the same match
```
(nba_gtp.sort_values(["game_id", "wl"])[["game_id", "hv", "points"]]
.assign(point_diff=lambda x: x.groupby(["game_id"])["points"].diff()))
```
`point_diff` will only have the point difference for the winning team (not the losing team)
Fill in the missing values for the losing team with the mean of the observation.
Use the `transform` function to map the values to the same index of the original data frame.
```
tmp = (
nba_gtp.sort_values(["game_id", "wl"])[["game_id", "hv", "points"]]
.assign(point_diff=lambda x: x.groupby(["game_id"])["points"].diff())
.assign(
point_diff=lambda x: x["point_diff"].fillna(
x.groupby("game_id")["point_diff"].transform("mean")
)
)
.dropna()
)
print(f"tmp.shape: {tmp.shape}")
tmp
# `transform` works on a grouped
tmp.groupby('game_id')['point_diff'].transform('mean')
display(tmp)
```
# Create a new dataframe
## Number of games per season by team
Create a variable that equals the total number of observations in a group using `size`
```
games_dataset = (
get_nba_game_team_points()
.groupby(["team_id", "season"])
.size()
.reset_index(name="game_count")
)
games_dataset
```
| github_jupyter |
Blankenbach Benchmark Case 2a
======
Temperature dependent convection
----
This is a benchmark case of two-dimensional, incompressible, bottom heated, temperature dependent convection. This example is based on case 2a in Blankenbach *et al.* 1989 for a single Rayleigh number ($Ra = 10^7$).
Here a temperature field that is already in equilibrium is loaded and a single Stokes solve is used to get the velocity and pressure fields. A few advection time steps are carried out as a demonstration of the new viscosity function.
**This lesson introduces the concepts of:**
1. material rheologies with functional dependencies
**Keywords:** Stokes system, advective diffusive systems, analysis tools, tools for post analysis, rheologies
**References**
1. B. Blankenbach, F. Busse, U. Christensen, L. Cserepes, D. Gunkel, U. Hansen, H. Harder, G. Jarvis, M. Koch, G. Marquart, D. Moore, P. Olson, H. Schmeling and T. Schnaubelt. A benchmark comparison for mantle convection codes. Geophysical Journal International, 98, 1, 23–38, 1989
http://onlinelibrary.wiley.com/doi/10.1111/j.1365-246X.1989.tb05511.x/abstract
```
import numpy as np
import underworld as uw
import math
from underworld import function as fn
import glucifer
```
Setup parameters
-----
Set simulation parameters for test.
```
Temp_Min = 0.0
Temp_Max = 1.0
res = 128
```
**Set physical values in SI units**
```
alpha = 2.5e-5
rho = 4e3
g = 10
dT = 1e3
h = 1e6
kappa = 1e-6
eta = 2.5e19
```
**Set viscosity function constants as per Case 2a**
```
Ra = 1e7
eta0 = 1.0e3
```
**Input file path**
Set input directory path
```
inputPath = 'input/1_04_BlankenbachBenchmark_Case2a/'
outputPath = 'output/'
# Make output directory if necessary.
if uw.rank()==0:
import os
if not os.path.exists(outputPath):
os.makedirs(outputPath)
```
Create mesh and finite element variables
------
```
mesh = uw.mesh.FeMesh_Cartesian( elementType = ("Q1/dQ0"),
elementRes = (res, res),
minCoord = (0., 0.),
maxCoord = (1., 1.))
velocityField = mesh.add_variable( nodeDofCount=2 )
pressureField = mesh.subMesh.add_variable( nodeDofCount=1 )
temperatureField = mesh.add_variable( nodeDofCount=1 )
temperatureDotField = mesh.add_variable( nodeDofCount=1 )
```
Initial conditions
-------
Load an equilibrium case with 128$\times$128 resolution and $Ra = 10^7$. This can be changed as per **1_03_BlankenbachBenchmark** if required.
```
meshOld = uw.mesh.FeMesh_Cartesian( elementType = ("Q1/dQ0"),
elementRes = (128, 128),
minCoord = (0., 0.),
maxCoord = (1., 1.),
partitioned = False )
temperatureFieldOld = meshOld.add_variable( nodeDofCount=1 )
temperatureFieldOld.load( inputPath + 'tempfield_case2_128_Ra1e7_10000.h5' )
temperatureField.data[:] = temperatureFieldOld.evaluate( mesh )
temperatureDotField.data[:] = 0.
velocityField.data[:] = [0.,0.]
pressureField.data[:] = 0.
```
**Plot initial temperature**
```
figtemp = glucifer.Figure()
figtemp.append( glucifer.objects.Surface(mesh, temperatureField) )
figtemp.show()
```
**Boundary conditions**
```
for index in mesh.specialSets["MinJ_VertexSet"]:
temperatureField.data[index] = Temp_Max
for index in mesh.specialSets["MaxJ_VertexSet"]:
temperatureField.data[index] = Temp_Min
iWalls = mesh.specialSets["MinI_VertexSet"] + mesh.specialSets["MaxI_VertexSet"]
jWalls = mesh.specialSets["MinJ_VertexSet"] + mesh.specialSets["MaxJ_VertexSet"]
freeslipBC = uw.conditions.DirichletCondition( variable = velocityField,
indexSetsPerDof = ( iWalls, jWalls) )
tempBC = uw.conditions.DirichletCondition( variable = temperatureField,
indexSetsPerDof = ( jWalls, ) )
```
Set up material parameters and functions
-----
Setup the viscosity to be a function of the temperature. Recall that these functions and values are preserved for the entire simulation time.
```
b = math.log(eta0)
T = temperatureField
fn_viscosity = eta0 * fn.math.exp( -1.0 * b * T )
densityFn = Ra*temperatureField
gravity = ( 0.0, 1.0 )
buoyancyFn = gravity*densityFn
```
**Plot the initial viscosity**
Plot the viscosity, which is a function of temperature, using the initial temperature conditions set above.
```
figEta = glucifer.Figure()
figEta.append( glucifer.objects.Surface(mesh, fn_viscosity) )
figEta.show()
```
System setup
-----
Since we are using a previously constructed temperature field, we will use a single Stokes solve to get consistent velocity and pressure fields.
**Setup a Stokes system**
```
stokes = uw.systems.Stokes( velocityField = velocityField,
pressureField = pressureField,
conditions = [freeslipBC,],
fn_viscosity = fn_viscosity,
fn_bodyforce = buoyancyFn )
```
**Set up and solve the Stokes system**
```
solver = uw.systems.Solver(stokes)
solver.solve()
```
**Create an advective diffusive system**
```
advDiff = uw.systems.AdvectionDiffusion( temperatureField, temperatureDotField, velocityField, fn_diffusivity = 1.,
conditions = [tempBC,], )
```
Analysis tools
-----
**Nusselt number**
```
nuTop = uw.utils.Integral( fn=temperatureField.fn_gradient[1], mesh=mesh, integrationType='Surface',
surfaceIndexSet=mesh.specialSets["MaxJ_VertexSet"])
Nu = -nuTop.evaluate()[0]
if(uw.rank()==0):
print('Initial Nusselt number = {0:.3f}'.format(Nu))
```
**RMS velocity**
```
v2sum_integral = uw.utils.Integral( mesh=mesh, fn=fn.math.dot( velocityField, velocityField ) )
volume_integral = uw.utils.Integral( mesh=mesh, fn=1. )
Vrms = math.sqrt( v2sum_integral.evaluate()[0] )/volume_integral.evaluate()[0]
if(uw.rank()==0):
print('Initial Vrms = {0:.3f}'.format(Vrms))
```
**Temperature gradients at corners**
Uses global evaluate function which can evaluate across multiple processors, but may slow the model down for very large runs.
```
def calcQs():
q1 = temperatureField.fn_gradient[1].evaluate_global( (0., 1.) )
q2 = temperatureField.fn_gradient[1].evaluate_global( (1., 1.) )
q3 = temperatureField.fn_gradient[1].evaluate_global( (1., 0.) )
q4 = temperatureField.fn_gradient[1].evaluate_global( (0., 0.) )
return q1, q2, q3, q4
q1, q2, q3, q4 = calcQs()
if(uw.rank()==0):
print('Initial T gradients = {0:.3f}, {1:.3f}, {2:.3f}, {3:.3f}'.format(q1[0][0], q2[0][0], q3[0][0], q4[0][0]))
```
Main simulation loop
-----
Run a few advection and Stokes solver steps to make sure we are in, or close to, equilibrium.
```
time = 0.
step = 0
step_end = 4
# define an update function
def update():
# Determining the maximum timestep for advancing the a-d system.
dt = advDiff.get_max_dt()
# Advect using this timestep size.
advDiff.integrate(dt)
return time+dt, step+1
while step < step_end:
# solve Stokes and advection systems
solver.solve()
# Calculate the RMS velocity and Nusselt number.
Vrms = math.sqrt( v2sum_integral.evaluate()[0] )/volume_integral.evaluate()[0]
Nu = -nuTop.evaluate()[0]
q1, q2, q3, q4 = calcQs()
if(uw.rank()==0):
print('Step {0:2d}: Vrms = {1:.3f}; Nu = {2:.3f}; q1 = {3:.3f}; q2 = {4:.3f}; q3 = {5:.3f}; q4 = {6:.3f}'
.format(step, Vrms, Nu, q1[0][0], q2[0][0], q3[0][0], q4[0][0]))
# update
time, step = update()
```
Comparison of benchmark values
-----
Compare values from Underworld against those from Blankenbach *et al.* 1989 for case 2a in the table below.
```
if(uw.rank()==0):
print('Nu = {0:.3f}'.format(Nu))
print('Vrms = {0:.3f}'.format(Vrms))
print('q1 = {0:.3f}'.format(q1[0][0]))
print('q2 = {0:.3f}'.format(q2[0][0]))
print('q3 = {0:.3f}'.format(q3[0][0]))
print('q4 = {0:.3f}'.format(q4[0][0]))
np.savetxt(outputPath+'summary.txt', [Nu, Vrms, q1, q2, q3, q4])
```
| $Ra$ | $Nu$ | $v_{rms}$| $q_1$ | $q_2$ | $q_3$ | $q_4$ |
|:------:|:--------:|:-------:|:--------:|:-------:|:-------:|:--------:|
| 10$^7$ | 10.0660 | 480.4 | 17.53136 | 1.00851 | 26.8085 | 0.497380 |
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
uber=pd.read_csv(r"D:\PYTHON\COURSE-3-EDA&STASTISTICS\ASSIGNMENT\Uber Request Data.csv")
uber.head()
uber.info()
#checking for any duplicate values in'Request id'
sum(uber.duplicated(subset='Request id'))==0
#checking for null values column wise
uber.isnull().sum()
uber['Request timestamp']=uber['Request timestamp'].astype(str)
uber['Request timestamp']=uber['Request timestamp'].str.replace('/','-')
uber['Request timestamp']=pd.to_datetime(uber['Request timestamp'],dayfirst=True)
uber['Request timestamp'].head()
uber['Drop timestamp']=pd.to_datetime(uber['Drop timestamp'],dayfirst=True)
uber['Drop timestamp'].head()
```
### converted 'Request timestamp' and 'Drop timestamp' into the required format using pd.to_datetime
```
plt.figure(figsize=(4,6))
sns.countplot(x="Status",data=uber)
plt.show()
uber['Status'].value_counts()
```
# count of requests is plotted against 'Status'.It is apparent that combined total of 'no cars available' and 'cancelled' is more than 'trips completed'
```
plt.figure(figsize=(2,4))
sns.countplot(x="Pickup point",data=uber)
plt.show()
uber['Pickup point'].value_counts()
```
# count of requests is plotted against Pickup points,number of request differ by less amount.
```
uber.head()
uber['pickup hour']=uber['Request timestamp'].dt.hour
```
# created different column hour of day to facilitate analysis
```
uber.info()
```
# now analyzing problems for uber
```
plt.figure(num=None, figsize=(8,8), dpi=100 )
sns.barplot(x='pickup hour',y='Request id',data=uber,estimator=len)
plt.title("Number of request per hour")
plt.ylabel("count of Request id")
plt.show()
```
## from the graph it is evident that max requests are made between 0500 hours-1000 hours in the morning and 1700 hours -2200 hours in the evening
```
plt.figure(figsize=(5,8))
fig1=sns.countplot(x='Status',hue='Pickup point',data=uber)
fig1.set_title("Frequency of trips according to pickup points")
ncount=len(uber)
for p in fig1.patches:
x=p.get_bbox().get_points()[:,0]
y=p.get_bbox().get_points()[1,1]
fig1.annotate((y),(x.mean(),y),ha='center',va='bottom')
plt.show()
```
### we can see the relative proportion of trips ie when the trip is completed,when
### it is cancelled and when there was no car available for both city and airport
### while 'trips completed' status is greater in city and 'no cars available' status is higher in
### airport location.
```
uber['Timeslot']=pd.cut(uber['pickup hour'],bins=[0,3,10,15,20,22,24],labels=["Early Morning","Morning","Afternoon","Evening","Night","Late Night"])
```
## using pd.cut function to create a new column 'Timeslot' from 'pickup hour'
## and created bins for different timeslots of morning etc according to time.
```
uber.head()
plt.figure(figsize=(8,9),dpi=100)
fig2=sns.countplot(x='Timeslot',hue='Status',data=uber)
fig2.set_title("Frequency of trips according to diff timeslots")
ncount=len(uber)
for p in fig2.patches:
x=p.get_bbox().get_points()[:,0]
y=p.get_bbox().get_points()[1,1]
fig2.annotate((y),(x.mean(),y),ha='center',va='bottom')
plt.show()
```
## graph showing relative proportion of trips according to timeslots
## no cars available is high during evening (from 1500 hours -2000 hours) and
## cancellation and trips completed is high during morning(from 0300 hours -1000 hours)
```
hour_pivot_df=uber.pivot_table(values=['Request id'],index=['pickup hour','Pickup point','Status'],aggfunc='count')
hour_pivot_df
```
## hourwise breakup of 'status' ie trips completed,cancellations and no cars available for both c'pickup points' ie city and airport
```
#now plotting for requests per hour according to status
plt.figure(figsize=(12,10),dpi=100,facecolor='w',edgecolor='k')
sns.barplot(x='pickup hour',y='Request id',hue='Status',data=uber,estimator=len)
plt.title("no of requests per hour according to status")
plt.ylabel("count of Request id")
plt.show()
```
## from the graph it is evident that max no of requests that are made between 5-10 am are cancelled and max no of requests between 5-10 pm in night show 'no cars available'
```
#plot of no. of requests from city to airport/airport to city
plt.figure(figsize=(12,10),dpi=80,facecolor='y',edgecolor='k')
sns.barplot(x='pickup hour', y='Request id', hue='Pickup point',data=uber, estimator=len)
plt.title("frequency of request from city-airport/airport-city")
plt.ylabel("count of Request id")
plt.show()
```
## no of request from city to airport is max between 5-10 am in the morning and no of requests from airport to city is max between 1700 hours-2200 hours
```
#plots of frquency of request
plt.figure(figsize=(14,10),dpi=80,facecolor='y',edgecolor='k')
plt.subplot(1,2,1)
sns.barplot(x='Timeslot',y='Request id',hue='Status',data=uber[(uber['Pickup point']=='Airport')&
(uber['Status']!='Trip Completed')],estimator=len)
plt.title("AIRPORT")
plt.ylabel("Count of Request id")
plt.subplot(1,2,2)
sns.barplot(x='Timeslot',y='Request id',hue='Status',data=uber[(uber['Pickup point']=='City')&
(uber['Status']!='Trip Completed')],estimator=len)
plt.title("CITY")
plt.ylabel("Count of Request id")
plt.show()
```
## creating demand and supply and gap between them.Demand= Trips completed+cancellation+no cars available and supply is the trips which were completed . So supply=Trips completed
```
# creating demand ,supply and gap between them according to timeslots
df=pd.DataFrame(uber.groupby(by='Timeslot',as_index=False)['Request id'].count())
df.columns.values[1]='Demand'
df_1=uber[uber.Status=='Trip Completed'].groupby(by='Timeslot',as_index=False)['Request id'].count()
df_1.columns.values[1]='Supply'
df['Supply']=df_1['Supply']
df['Gap']=df['Demand']-df['Supply']
df
# plot showing demand ,supply and gap between them according to timeslot
df.plot(x='Timeslot', y=['Demand','Supply','Gap'], kind='bar',figsize=(14,12), color=['blue','red','green'],
title="Demand Supply and Gap according to timeslots")
plt.show()
```
## from the graph it is clear that a huge gap exists between demand and supply in the 'morning and 'evening timeslots
```
#creating columns for demand,suply and gap according to timeslots for airport
df_Airport=uber[uber['Pickup point']=='Airport']
df_A=pd.DataFrame(df_Airport.groupby(by='Timeslot', as_index=False)['Request id'].count())
df_A.columns.values[1]='Demand'
df_2=df_Airport[df_Airport.Status=='Trip Completed'].groupby(by='Timeslot',as_index=False)['Request id'].count()
df_2.columns.values[1]='Supply'
df_A['Supply']=df_2['Supply']
df_A['Gap']=df_A['Demand']-df_A['Supply']
df_A
#plot showing demand ,supply and gap between them for airport
df_A.plot(x='Timeslot',y=['Demand','Supply','Gap'],kind='bar',figsize=(12,10),color=['green','blue','magenta'],
title="Demand, Supply and gap between requests for Airport to city")
plt.show()
```
## it is evident from the graph that the gap is highest for evening and night timeslots
```
# now creating demand ,suopply and gap between them for city
df_City=uber[uber['Pickup point']=='City']
df_C=pd.DataFrame(df_City.groupby(by='Timeslot', as_index=False)['Request id'].count())
df_C.columns.values[1]='Demand'
df_3=df_City[df_City.Status=='Trip Completed'].groupby(by='Timeslot',as_index=False)['Request id'].count()
df_3.columns.values[1]='Supply'
df_C['Supply']=df_3['Supply']
df_C['Gap']=df_C['Demand']-df_C['Supply']
df_C
#plot showing demand ,supply and gap between them for city
df_C.plot(x='Timeslot',y=['Demand','Supply','Gap'],kind='bar',figsize=(12,10),color=['yellow','blue','red'],
title="Demand, Supply and gap between requests from city to airport")
plt.show()
```
## it is evident from the graph that maximum of requests in the morning timeslot go unmet and hence a huge gap can be seen there
```
uber.to_csv(r'Desktop\UBER_NEW.csv')
uber
```
| github_jupyter |
#Demo: Interpolator
*This script provides a few examples on using the Interpolator class.
Last updated: April 14, 2015.
Copyright (C) 2014 Randall Romero-Aguilar
Licensed under the MIT license, see LICENSE.txt*
*Interpolator* is a subclass of *Basis*.
* A *Basis* object contains data to compute the interpolation matrix $\Phi(x)$ at arbitrary values of $x$ (within the interpolation box).
* An *Interpolator* is used to interpolate a given function $f(x)$, when the value of $f$ is known at the basis nodes. It adds methods to the *Basis* class to compute interpolation coefficients $c$ and to interpolate $f$ at arbitrary $x$.
Evaluation of this objects is straighforward:
* If B is a Basis, then B(x, k) computes the interpolating matrix $D^{(k)}\Phi(x)$, the k-derivative of $\Phi$
* If V is an Interpolator, then V(x, k) interpolates $D^{(k)}f(x)$, the k-derivative of $f$.
```
%matplotlib notebook
import numpy as np
from compecon import Basis, Interpolator
import matplotlib.pyplot as plt
import seaborn as sns
import time
np.set_printoptions(precision=3, suppress=True)
#sns.set(style='whitegrid')
```
##EXAMPLE 1:
Using BasisChebyshev to interpolate a 1-D function with a Chebyshev basis
**PROBLEM:** Interpolate the function $y = f(x) = 1 + sin(2x)^2$ on the domain $[0,\pi]$, using 5 Gaussian nodes.
There are two ways to create an *Interpolator* object.
* Defining the basis first, then the interpolator with known function values at nodes
```
f = lambda x: (1 + np.sin(2*x)**2)
B = Basis(5,0,np.pi)
V = Interpolator(B, y=f(B.nodes))
```
We are goint to make the same plot several times, so define it with a function
```
xx = np.linspace(0,np.pi,120)
def plot(P):
plt.figure()
plt.plot(xx,f(xx))
plt.plot(xx,P(xx))
plt.scatter(P.nodes,P(),color='red') #add nodes
```
Plot the interpolation at a refined grid. Notice how the interpolation is exact at the nodes.
```
plot(V)
```
* The second option is to create the *Interpolator* just as a regular *Basis*, adding the known function values at the next step. The difference is that we end up with only one object.
```
S = Interpolator(5,0,np.pi)
S.y = f(S.nodes)
plot(S)
```
* When we have a callable object (like the lambda f) we can pass it directly to the constructor, which will evaluate it at the nodes:
```
U = Interpolator(5,0,np.pi, y = f)
plot(U)
```
### Let's time it
Interpolate the first derivative of $S$ at the $xx$ values, repeat $10^4$ times.
```
t0 = time.time()
for k in range(10000):
S(xx, 1)
time.time() - t0
```
In MATLAB, it takes around 6 seconds!!
| github_jupyter |
## Our Mission ##
You recently used Naive Bayes to classify spam in this [dataset](https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection). In this notebook, we will expand on the previous analysis by using a few of the new techniques you saw throughout this lesson.
> In order to get caught back up to speed with what was done in the previous notebook, run the cell below
```
# Import our libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# Read in our dataset
df = pd.read_table('smsspamcollection/SMSSpamCollection',
sep='\t',
header=None,
names=['label', 'sms_message'])
# Fix our response value
df['label'] = df.label.map({'ham':0, 'spam':1})
# Split our dataset into training and testing data
X_train, X_test, y_train, y_test = train_test_split(df['sms_message'],
df['label'],
random_state=1)
# Instantiate the CountVectorizer method
count_vector = CountVectorizer()
# Fit the training data and then return the matrix
training_data = count_vector.fit_transform(X_train)
# Transform testing data and return the matrix. Note we are not fitting the testing data into the CountVectorizer()
testing_data = count_vector.transform(X_test)
# Instantiate our model
naive_bayes = MultinomialNB()
# Fit our model to the training data
naive_bayes.fit(training_data, y_train)
# Predict on the test data
predictions = naive_bayes.predict(testing_data)
# Score our model
print('Accuracy score: ', format(accuracy_score(y_test, predictions)))
print('Precision score: ', format(precision_score(y_test, predictions)))
print('Recall score: ', format(recall_score(y_test, predictions)))
print('F1 score: ', format(f1_score(y_test, predictions)))
```
### Turns Out...
It turns out that our naive bayes model actually does a pretty good job. However, let's take a look at a few additional models to see if we can't improve anyway.
Specifically in this notebook, we will take a look at the following techniques:
* [BaggingClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingClassifier.html#sklearn.ensemble.BaggingClassifier)
* [RandomForestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier)
* [AdaBoostClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html#sklearn.ensemble.AdaBoostClassifier)
Another really useful guide for ensemble methods can be found [in the documentation here](http://scikit-learn.org/stable/modules/ensemble.html).
These ensemble methods use a combination of techniques you have seen throughout this lesson:
* **Bootstrap the data** passed through a learner (bagging).
* **Subset the features** used for a learner (combined with bagging signifies the two random components of random forests).
* **Ensemble learners** together in a way that allows those that perform best in certain areas to create the largest impact (boosting).
In this notebook, let's get some practice with these methods, which will also help you get comfortable with the process used for performing supervised machine learning in python in general.
Since you cleaned and vectorized the text in the previous notebook, this notebook can be focused on the fun part - the machine learning part.
### This Process Looks Familiar...
In general, there is a five step process that can be used each type you want to use a supervised learning method (which you actually used above):
1. **Import** the model.
2. **Instantiate** the model with the hyperparameters of interest.
3. **Fit** the model to the training data.
4. **Predict** on the test data.
5. **Score** the model by comparing the predictions to the actual values.
Follow the steps through this notebook to perform these steps using each of the ensemble methods: **BaggingClassifier**, **RandomForestClassifier**, and **AdaBoostClassifier**.
> **Step 1**: First use the documentation to `import` all three of the models.
```
# Import the Bagging, RandomForest, and AdaBoost Classifier
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier, AdaBoostClassifier
```
> **Step 2:** Now that you have imported each of the classifiers, `instantiate` each with the hyperparameters specified in each comment. In the upcoming lessons, you will see how we can automate the process to finding the best hyperparameters. For now, let's get comfortable with the process and our new algorithms.
```
# Instantiate a BaggingClassifier with:
# 200 weak learners (n_estimators) and everything else as default values
bag_mod = BaggingClassifier(n_estimators=200)
# Instantiate a RandomForestClassifier with:
# 200 weak learners (n_estimators) and everything else as default values
rf_mod = RandomForestClassifier(n_estimators=200)
# Instantiate an a AdaBoostClassifier with:
# With 300 weak learners (n_estimators) and a learning_rate of 0.2
ada_mod = AdaBoostClassifier(n_estimators=300, learning_rate=0.2)
```
> **Step 3:** Now that you have instantiated each of your models, `fit` them using the **training_data** and **y_train**. This may take a bit of time, you are fitting 700 weak learners after all!
```
# Fit your BaggingClassifier to the training data
bag_mod.fit(training_data, y_train)
# Fit your RandomForestClassifier to the training data
rf_mod.fit(training_data, y_train)
# Fit your AdaBoostClassifier to the training data
ada_mod.fit(training_data, y_train)
```
> **Step 4:** Now that you have fit each of your models, you will use each to `predict` on the **testing_data**.
```
# Predict using BaggingClassifier on the test data
bag_preds = bag_mod.predict(testing_data)
# Predict using RandomForestClassifier on the test data
rf_preds = rf_mod.predict(testing_data)
# Predict using AdaBoostClassifier on the test data
ada_preds = ada_mod.predict(testing_data)
```
> **Step 5:** Now that you have made your predictions, compare your predictions to the actual values using the function below for each of your models - this will give you the `score` for how well each of your models is performing. It might also be useful to show the naive bayes model again here.
```
def print_metrics(y_true, preds, model_name=None):
'''
INPUT:
y_true - the y values that are actually true in the dataset (numpy array or pandas series)
preds - the predictions for those values from some model (numpy array or pandas series)
model_name - (str - optional) a name associated with the model if you would like to add it to the print statements
OUTPUT:
None - prints the accuracy, precision, recall, and F1 score
'''
if model_name == None:
print('Accuracy score: ', format(accuracy_score(y_true, preds)))
print('Precision score: ', format(precision_score(y_true, preds)))
print('Recall score: ', format(recall_score(y_true, preds)))
print('F1 score: ', format(f1_score(y_true, preds)))
print('\n\n')
else:
print('Accuracy score for ' + model_name + ' :' , format(accuracy_score(y_true, preds)))
print('Precision score ' + model_name + ' :', format(precision_score(y_true, preds)))
print('Recall score ' + model_name + ' :', format(recall_score(y_true, preds)))
print('F1 score ' + model_name + ' :', format(f1_score(y_true, preds)))
print('\n\n')
# Print Bagging scores
print_metrics(y_test, bag_preds, 'bagging')
# Print Random Forest scores
print_metrics(y_test, rf_preds, 'random forest')
# Print AdaBoost scores
print_metrics(y_test, ada_preds, 'adaboost')
# Naive Bayes Classifier scores
print_metrics(y_test, predictions, 'naive bayes')
```
### Recap
Now you have seen the whole process for a few ensemble models!
1. **Import** the model.
2. **Instantiate** the model with the hyperparameters of interest.
3. **Fit** the model to the training data.
4. **Predict** on the test data.
5. **Score** the model by comparing the predictions to the actual values.
This is a very common process for performing machine learning.
### But, Wait...
You might be asking -
* What do these metrics mean?
* How do I optimize to get the best model?
* There are so many hyperparameters to each of these models, how do I figure out what the best values are for each?
**This is exactly what the last two lessons of this course on supervised learning are all about.**
| github_jupyter |
```
import numpy as np
import pandas as pd
import tensorflow as tf
import os
import warnings
warnings.filterwarnings('ignore')
from tensorflow import keras
from sklearn.preprocessing import RobustScaler, Normalizer, StandardScaler
from sklearn.model_selection import train_test_split
from datasets import load_data, random_benchmark, list_datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import f1_score, accuracy_score
from Imputation import remove_and_impute
from Models import SAE, CNN_AE, LSTM_AE, GRU_AE, Bi_LSTM_AE, CNN_Bi_LSTM_AE, Causal_CNN_AE, Wavenet, Attention_Bi_LSTM_AE, Attention_CNN_Bi_LSTM_AE, Attention_Wavenet
np.random.seed(7)
tf.random.set_seed(7)
rf_clf = RandomForestClassifier(n_jobs=-1, n_estimators=100, random_state=7)
svm_clf = SVC(random_state=7, gamma='scale')
knn_clf = KNeighborsClassifier(n_neighbors=1, weights='distance', n_jobs=-1)
mlp_clf = MLPClassifier(random_state=7)
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID";
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
from tensorflow.keras.preprocessing.sequence import pad_sequences
def flatten_ts(train, test):
new_train, new_test = [], []
train_lens = []
for _, row in train.iterrows():
for i in row.index:
train_lens.append(len(row[i]))
maxlen = np.ceil(np.average(train_lens)).astype(int)
for _, row in train.iterrows():
new_list = []
for i in row.index:
ts = []
for j in range(len(row[i])):
ts.append(row[i][j])
new_list.append(ts)
new_train.append(pad_sequences(new_list, maxlen=maxlen, dtype='float32'))
for _, row in test.iterrows():
new_list = []
for i in row.index:
ts = []
for j in range(len(row[i])):
ts.append(row[i][j])
new_list.append(ts)
new_test.append(pad_sequences(new_list, maxlen=maxlen, dtype='float32'))
train_df = pd.DataFrame(np.array(new_train).reshape(train.shape[0], maxlen * train.columns.shape[0]))
test_df = pd.DataFrame(np.array(new_test).reshape(test.shape[0], maxlen * train.columns.shape[0]))
scaler = RobustScaler()
scaler.fit(train_df)
return scaler.transform(train_df), scaler.transform(test_df), maxlen * train.columns.shape[0]
# return np.array(train_df), np.array(test_df), maxlen * train.columns.shape[0]
def rnn_reshape(train, test, n_steps, n_features):
# train, test = flatten_ts(train, test)
return train.reshape(train.shape[0], n_steps, n_features), test.reshape(test.shape[0], n_steps, n_features)
def evaluate(data_name, univariate):
print('Data: ', data_name)
train_x, train_y, test_x, test_y = load_data(data_name, univariate=univariate)
n_features = train_x.iloc[0].shape[0]
X_train, X_test, n_steps = flatten_ts(train_x, test_x)
# RF
rf_clf.fit(X_train, train_y)
pred = rf_clf.predict(X_test)
rf_scores = {'accuracy': accuracy_score(test_y, pred), 'f1': f1_score(test_y, pred, average='macro')}
print('RF >>', rf_scores)
# SVM
svm_clf.fit(X_train, train_y)
pred = svm_clf.predict(X_test)
svm_scores = {'accuracy': accuracy_score(test_y, pred), 'f1': f1_score(test_y, pred, average='macro')}
print('SVM >>', svm_scores)
# 1-NN
knn_clf.fit(X_train, train_y)
pred = knn_clf.predict(X_test)
knn_scores = {'accuracy': accuracy_score(test_y, pred), 'f1': f1_score(test_y, pred, average='macro')}
print('1-NN >>', knn_scores)
# MLP
mlp_clf.fit(X_train, train_y)
pred = mlp_clf.predict(X_test)
mlp_scores = {'accuracy': accuracy_score(test_y, pred), 'f1': f1_score(test_y, pred, average='macro')}
print('MLP >>', mlp_scores)
results.append({'dataset': data_name, 'dim': str(n_steps)+', '+str(n_features),
'RF-ACC': rf_scores['accuracy'],
'SVM-ACC': svm_scores['accuracy'],
'1NN-ACC': knn_scores['accuracy'],
'MLP-ACC': mlp_scores['accuracy'],
'RF-F1': rf_scores['f1'],
'SVM-F1': svm_scores['f1'],
'1NN-F1': knn_scores['f1'],
'MLP-F1': mlp_scores['f1']
})
results = []
selected_uni_datasets = ['Earthquakes', 'ArrowHead', 'BeetleFly', 'ChlorineConcentration', 'Chinatown', 'DiatomSizeReduction', 'ECG200', 'ECG5000', 'ECGFiveDays',
'FreezerSmallTrain', 'Fungi', 'GunPoint', 'GunPointAgeSpan','GunPointMaleVersusFemale', 'GunPointOldVersusYoung', 'Herring',
'InsectEPGRegularTrain', 'InsectEPGSmallTrain', 'InsectWingbeatSound', 'Lightning2', 'MedicalImages', 'MiddlePhalanxTW',
'NonInvasiveFetalECGThorax2', 'OliveOil', 'PhalangesOutlinesCorrect', 'PickupGestureWiimoteZ','PigAirwayPressure', 'PowerCons',
'ProximalPhalanxOutlineAgeGroup', 'SemgHandGenderCh2', 'SemgHandMovementCh2', 'SemgHandSubjectCh2', 'SmoothSubspace', 'StarLightCurves',
'SyntheticControl', 'Trace', 'UMD', 'UWaveGestureLibraryAll', 'Wafer', 'Yoga']
for dataset in selected_uni_datasets:
evaluate(dataset, univariate=True)
pd.DataFrame(results).to_csv('./results/uni-baseline-results.csv', index=False)
results = []
selected_mul_datasets = ['ArticularyWordRecognition', 'AtrialFibrillation', 'BasicMotions', 'Cricket',
'ERing', 'HandMovementDirection', 'Handwriting', 'JapaneseVowels', 'PenDigits', 'RacketSports', 'SelfRegulationSCP1',
'SelfRegulationSCP2', 'SpokenArabicDigits', 'StandWalkJump', 'EthanolConcentration']
for dataset in selected_mul_datasets:
evaluate(dataset, univariate=False)
pd.DataFrame(results).to_csv('./results/mul-baseline-results.csv', index=False)
```
| github_jupyter |
# <font color='#002726'> Data Science em Produção </font>
=-=- ROSSMANN - STORE SALES PREDICTION -=-=
# <font color='#3F0094'> 0. Imports </font>
```
# general use
import numpy as np
import pandas as pd
# helper function
import inflection
# feature engineering and data analysis
import seaborn as sns
from matplotlib import gridspec, pyplot as plt
from IPython.display import Image
from scipy.stats import ranksums, chi2_contingency
from datetime import datetime, timedelta
from statsmodels.stats.weightstats import DescrStatsW, CompareMeans
# data preparation
from sklearn.preprocessing import RobustScaler, MinMaxScaler, LabelEncoder
# feature selection
from boruta import BorutaPy
# machine learning
import pickle
import xgboost as xgb
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error, mean_squared_error
```
## <font color='#200CF'> 0.1. Helper Functions </font>
```
# Notebook Setups
sns.set_style('darkgrid')
sns.set_context('talk')
sns.set_palette('Set2')
# Functions
def bootstrap(attribute, estimate='mean', n_repeat=100, n_sample=100, ci=95):
"""Bootstrap"""
results = []
if estimate == 'mean':
for n in range(n_repeat):
sample = np.random.choice(a=attribute, size=n_sample)
results.append(np.mean(sample))
elif estimate == 'median':
for n in range(n_repeat):
sample = np.random.choice(a=attribute, size=n_sample)
results.append(np.median(sample))
else:
results = [0]
ci_bottom = (100 - ci) / 2
ci_top = ci + (100 - ci) / 2
statistic_mean = np.mean(results)
statistic_std_error = np.std(results)
lower_percentile = np.percentile(results, q=ci_bottom)
upper_percentile = np.percentile(results, q=ci_top)
return [statistic_mean, statistic_std_error, lower_percentile, upper_percentile]
def cramer_v(x, y):
"""Cramér's V formula to measure the association between two nominal variables"""
# confusion matrix - getting the values only (as matrix)
cm = pd.crosstab(x, y).values
# chi2_contingency from scipy returns a list, the first value is the statistic test result
chi2 = chi2_contingency(cm)[0]
# n is the grand total of observations
n = cm.sum()
# number of rows and columns
r, k = cm.shape
# bias correction
phi_cor = max(0, chi2/n - (k-1)*(r-1)/(n-1))
k_cor = k - (k-1)**2/(n-1)
r_cor = r - (r-1)**2/(n-1)
return np.sqrt((phi_cor) / (min(k_cor-1, r_cor-1)))
def ml_error(model_name, y, yhat):
"""Tests machine learning model prediction error."""
# mean absolute error (MAE)
mae = mean_absolute_error(y , yhat)
# mean absolute percentage error (MAPE)
mape = mean_absolute_percentage_error(y, yhat)
# root-mean-square error (RMSE)
rmse = np.sqrt(mean_squared_error(y, yhat))
return pd.DataFrame({'Model Name': model_name,
'MAE': mae,
'MAPE': mape,
'RMSE': rmse}, index=[0])
def cross_validation(X_train, kfold, model_name, ml_model, verbose=False):
# lists to keep the error results
mae_list, mape_list, rmse_list = [], [], []
# cross validation folds
for k in range(kfold, 0, -1):
# checking if verbose is true
if verbose:
print(f'\nKFold Number: {k}')
# start date and end date of validation
validation_start_date = X_train['date'].max() - timedelta(days=k*6*7)
validation_end_date = X_train['date'].max() - timedelta(days=(k-1)*6*7)
# splitting into traning and validation
training = X_train[X_train['date'] < validation_start_date]
validation = X_train[(X_train['date'] >= validation_start_date) & (X_train['date'] <= validation_end_date)]
# preparing training and validation datasets - removing response subsets
# training
y_training = training['sales']
x_training_ml = training.drop(['date', 'sales'], axis=1)
# validation
y_validation = validation['sales']
x_validation_ml = validation.drop(['date', 'sales'], axis=1)
# model
model_fit = ml_model.fit(x_training_ml, y_training)
# predicition
yhat = model_fit.predict(x_validation_ml)
# performance
result = ml_error(model_name, np.expm1(y_validation), np.expm1(yhat))
# appending error values to the lists in each iteration of KFold
mae_list.append(result['MAE'][0])
mape_list.append(result['MAPE'][0])
rmse_list.append(result['RMSE'][0])
# returning a dataframe with mean and std of each error measure
return pd.DataFrame({
'Model Name': model_name,
'MAE CV': np.round(np.mean(mae_list), 2).astype(str) + ' +/- ' + np.round((np.std(mae_list)), 2).astype(str),
'MAPE CV': np.round(np.mean(mape_list), 2).astype(str) + ' +/- ' + np.round((np.std(mape_list)), 2).astype(str),
'RMSE CV': np.round(np.mean(rmse_list), 2).astype(str) + ' +/- ' + np.round((np.std(rmse_list)), 2).astype(str),
}, index=[0])
```
## <font color='#200CF'> 0.2. Loading Data </font>
```
# loading historical data - including Sales
df_sales_raw = pd.read_csv('../raw_data/train.csv', low_memory=False)
# loading information about the stores
df_store_raw = pd.read_csv('../raw_data/store.csv', low_memory=False)
# merging dataframes
df_raw = pd.merge(df_sales_raw, df_store_raw, how='left', on='Store')
```
### <font color='#F37126'> Data Fields </font>
**Most of the fields are self-explanatory. The following are descriptions for those that aren't.**
- **Id** - an Id that represents a (Store, Date) duple within the test set;
- **Store** - a unique Id for each store;
- **Sales** - the turnover for any given day (this is what you are predicting);
- **Customers** - the number of customers on a given day;
- **Open** - an indicator for whether the store was open: 0 = closed, 1 = open;
- **StateHoliday** - indicates a state holiday. Normally all stores, with few exceptions, are closed on state holidays. Note that all schools are closed on public holidays and weekends. a = public holiday, b = Easter holiday, c = Christmas, 0 = None;
- **SchoolHoliday** - indicates if the (Store, Date) was affected by the closure of public schools;
- **StoreType** - differentiates between 4 different store models: a, b, c, d;
- **Assortment** - describes an assortment level: a = basic, b = extra, c = extended;
- **CompetitionDistance** - distance in meters to the nearest competitor store;
- **CompetitionOpenSince[Month/Year]** - gives the approximate year and month of the time the nearest competitor was opened;
- **Promo** - indicates whether a store is running a promo on that day;
- **Promo2** - Promo2 is a continuing and consecutive promotion for some stores: 0 = store is not participating, 1 = store is participating;
- **Promo2Since[Year/Week]** - describes the year and calendar week when the store started participating in Promo2;
- **PromoInterval** - describes the consecutive intervals Promo2 is started, naming the months the promotion is started anew. E.g. "Feb,May,Aug,Nov" means each round starts in February, May, August, November of any given year for that store.
# <font color='#3F0094'> 1. Descriptive Data Analysis </font>
## <font color='#200CF'> 1.0. Dataframe in Progress Backup </font>
```
df1 = df_raw.copy()
```
## <font color='#200CF'> 1.1. Column Renaming </font>
```
df1.columns
# renaming df1 column names
snake_case = lambda x: inflection.underscore(x)
df1.columns = list(map(snake_case, df1.columns))
```
## <font color='#200CF'> 1.2. Data Dimension </font>
```
print(f'Store Dataframe - Number of Rows: {df1.shape[0]}. \nStore Dataframe - Number of Columns: {df1.shape[1]}.')
```
## <font color='#200CF'> 1.3. Data Types </font>
```
# dataframe data types
df1.dtypes
# setting date column as datetime type
df1['date'] = pd.to_datetime(df1['date'])
```
## <font color='#200CF'> 1.4. NA Check </font>
```
# checking NA - All NA values came from store.csv
df1.isna().sum()
# checking NA using info()
df1.info()
```
## <font color='#200CF'> 1.5. Filling in Missing/Null Values </font>
**Number of NA Values**
competition_distance 2642
competition_open_since_month 323348
competition_open_since_year 323348
promo2_since_week 508031
promo2_since_year 508031
promo_interval 508031
```
# competition_distance
# maximun distance x 2
max_dist_x_2 = df1['competition_distance'].max() * 2
# assuming competitors are twice as far away as the greatest distance found
df1['competition_distance'] = df1['competition_distance'].apply(lambda x: max_dist_x_2 if np.isnan(x) else x)
# competition_open_since_year
# frequency per year of existing competition_open_since_year data
frequency = df1['competition_open_since_year'].value_counts(
normalize=True).reset_index().rename(
columns={'index': 'year',
'competition_open_since_year': 'percent'})
# True/False missing/Null Series
missing = df1['competition_open_since_year'].isna()
# Using Numpy's random.choice to fill out missing data based on the frequency of existing info
df1.loc[missing,'competition_open_since_year'] = np.random.choice(frequency.year,
size=len(df1[missing]),
p=frequency.percent)
# competition_open_since_month
# frequency per month of existing competition_open_since_month data
frequency = df1['competition_open_since_month'].value_counts(
normalize=True).reset_index().rename(
columns={'index': 'month',
'competition_open_since_month': 'percent'})
# True/False missing/Null Series
missing = df1['competition_open_since_month'].isna()
# Using Numpy's random.choice to fill out missing data based on the frequency of existing info
df1.loc[missing,'competition_open_since_month'] = np.random.choice(frequency.month,
size=len(df1[missing]),
p=frequency.percent)
# promo2_since_week AND promo2_since_year
# the same date of sale will be used as a reference to fill in the NA values
# then a new timedelta column will be created (promo2_duration)
#promo2_since_week
df1['promo2_since_week'] = df1[['date', 'promo2_since_week']].apply(lambda x: x['date'].week if np.isnan(x['promo2_since_week']) else x['promo2_since_week'], axis=1)
# promo2_since_year
df1['promo2_since_year'] = df1[['date', 'promo2_since_year']].apply(lambda x: x['date'].year if np.isnan(x['promo2_since_year']) else x['promo2_since_year'], axis=1)
# promo_interval
# filling in NA with 'none'
df1['promo_interval'].fillna(value='none', inplace=True)
# creating a column with current month
df1['curr_month'] = df1['date'].dt.strftime('%b')
# creating a column to indicate whether promo2 is active
df1['promo2_active'] = df1.apply(lambda x: 1 if ((
x['curr_month'] in x['promo_interval'].split(',')) and (
x['date'] >= datetime.fromisocalendar(int(x['promo2_since_year']), int(x['promo2_since_week']), 1)) and (
x['promo'] == 1)) else 0, axis=1)
```
## <font color='#200CF'> 1.6. Changing Data Types </font>
```
df1.dtypes
# Changing DTypes from float to integer
df1['competition_distance'] = df1['competition_distance'].astype(int)
df1['competition_open_since_month'] = df1['competition_open_since_month'].astype(int)
df1['competition_open_since_year'] = df1['competition_open_since_year'].astype(int)
df1['promo2_since_week'] = df1['promo2_since_week'].astype(int)
df1['promo2_since_year'] = df1['promo2_since_year'].astype(int)
```
## <font color='#200CF'> 1.7. Descriptive Statistics </font>
### <font color='#2365FF'> 1.7.0. Numeric vs Categorical - Attributes Split </font>
```
# dataframe - numeric attributes
df_numeric = df1.select_dtypes(include=['int64', 'float64'])
# dataframe - categorical attributes
df_categorical = df1.select_dtypes(exclude=['int64', 'float64', 'datetime64[ns]'])
```
### <font color='#2365FF'> 1.7.1. Numeric Attributes </font>
```
# using DF describe() method
df1.describe().T
# central tendency metrics - mean, median
ct_mean = df_numeric.apply(np.mean)
ct_median = df_numeric.apply(np.median)
# dispersion metrics - std, min, max, range, skew, kurtosis
d_std = df_numeric.apply(np.std)
d_min = df_numeric.apply(min)
d_max = df_numeric.apply(max)
d_range = df_numeric.apply(lambda x: x.max() - x.min())
d_skew = df_numeric.apply(lambda x: x.skew())
d_kurtosis = df_numeric.apply(lambda x: x.kurtosis())
metrics = pd.DataFrame({
'min': d_min, 'max': d_max, 'range': d_range, 'mean': ct_mean,
'median': ct_median, 'std': d_std, 'skew': d_skew, 'kurtosis': d_kurtosis
})
metrics
```
**competition_distance**
- Skew: highly skewed data, high positive value means that the right-hand tail is much longer than the left-hand tail.
- Kurtosis: increases as the tails become heavier, the high positive value indicates a very peaked curve.
**competition_open_since_year**
- Skew: highly skewed data, high negative value means that the left-hand tail is longer than the right-hand tail.
- Kurtosis: increases as the tails become heavier, the high positive value indicates a very peaked curve.
**sales**
- Skewness is close to zero, indicating that the data is not too skewed
### <font color='#2365FF'> 1.7.2. Categorical Attributes </font>
```
# verifying unique valuesfor each categorical attribute
df_categorical.apply(lambda x: len(x.unique()))
```
**BOXPLOT OF CATEGORICAL ATTRIBUTES**
```
# Boxplot - Categorical Attributes
# not considering when: sales = 0
aux = df1[df1['sales'] > 0]
plt.figure(figsize=(24,10))
plt.subplot(1, 3, 1)
ax1 = sns.boxplot(x='state_holiday', y='sales', data=aux)
ax1.set_title('Boxplot - state_holiday', fontsize=18, pad=10)
ax1.set_xticklabels(labels=['None', 'Public', 'Easter', 'Christmas'])
plt.subplot(1, 3, 2)
ax2 = sns.boxplot(x='store_type', y='sales', data=aux)
ax2.set_title('Boxplot - store_type', fontsize=18, pad=10)
plt.subplot(1, 3, 3)
ax3 = sns.boxplot(x='assortment', y='sales', data=aux)
ax3.set_title('Boxplot - assortment', fontsize=18, pad=10)
plt.show()
```
**BOXPLOT OF BINARY CATEGORICAL ATTRIBUTES**
```
# Boxplot - Binary ategorical Attributes
plt.figure(figsize=(24,10))
plt.subplot(1, 3, 1)
ax1 = sns.boxplot(x='promo', y='sales', data=df1)
ax1.set_title('Boxplot - promo', fontsize=18, pad=10)
plt.subplot(1, 3, 2)
ax2 = sns.boxplot(x='promo2_active', y='sales', data=df1)
ax2.set_title('Boxplot - promo2_active', fontsize=18, pad=10)
plt.subplot(1, 3, 3)
ax3 = sns.boxplot(x='school_holiday', y='sales', data=df1)
ax3.set_title('Boxplot - school_holiday', fontsize=18, pad=10)
plt.show()
```
# <font color='#3F0094'> 2. Feature Egineering </font>
## <font color='#200CF'> 2.0. Dataframe in Progress Backup </font>
```
df2 = df1.copy()
```
## <font color='#200CF'> 2.1. Mind Map </font>
```
# made on coggle.it
Image('../img/mind_map01.png')
```
## <font color='#200CF'> 2.2. Hypothesis </font>
**Based on Descriptive Statistics and on Mind Map**
### <font color='#2365FF'> 2.2.1. Store-related Hypothesis </font>
**H1.** The larger the assortment the greater the global sales of the stores should be.
**H2.** The median sales of stores with the largest assortment should be the highest.
**H3.** The volume of sales varies according to the type of the store.
**H4.** The average value of sales for a specific type of store is higher than the average value for other types (store types: a, b, c, d).
**H5.** The sales revenue of stores are lower the closer the competitors are located.
**H6.** The average sales value of stores with competitors whose distance is less than 1000 meters is lower than or equal to the average value of other stores.
**H7.** The total sales revenue of stores with competitors for a longer time should be higher.
**H8.** The average sales values of stores whose competitors opened less than 18 months ago is lower than the average values of other stores.
### <font color='#2365FF'> 2.2.2. Product-related Hypothesis </font>
**H9.** The sales revenue should be greater when running a promotion (promo) than when not running a promo.
**H10.** The average sales value of stores should be greater when running a promotion (promo) than when not running a promo.
**H11.** The average sales value of stores with continuing and consecutive promotion (promo2) should be greater than those that do not have extended promotion.
**H12.** The sales revenue of stores running promo2 should grow over time.
**H13.** The median sales value of stores running promo2 for a longer period of time (more than 12 months) should be higher than stores running promo2 for a shorter period of time.
### <font color='#2365FF'> 2.2.3. Time-related Hypothesis </font>
**H14.** The average ticket per customer should be lower during holiday periods.
**H15.** Sales during the Christmas holiday are expected to be the biggest of the year. .
**H16.** Stores affected by the closure of public schools on school holidays should sell less, on average.
**H17.** The revenue in the last quarter of the year should be higher than in the other quarters.
**H18.** Sales behavior is not constant throughout the month, it should be higher in the first 7 days and decreases in the following weeks.
**H19.** Average sales during the weekend should be lower than during the rest of the week.
## <font color='#200CF'> 2.3. Feature Engineering </font>
```
# year
df2['year'] = df2['date'].dt.year
# month
df2['month'] = df2['date'].dt.month
# day
df2['day'] = df2['date'].dt.day
# week_of_year
df2['week_of_year'] = df2['date'].dt.isocalendar().week.astype('int64')
# year_week
df2['year_week'] = df2['date'].dt.strftime('%Y-%V')
# competition_months_old
# calculating the competition period, extracting the days and dividing by 30 to get the period in months
df2['competition_months_old'] = df2.apply(lambda x: (
x['date'] - datetime(year=x['competition_open_since_year'],
month=x['competition_open_since_month'],
day=1)).days / 30, axis=1).astype(int)
# assigning zero to negative values of competition_months_old
# in this case it makes no sense to work with the time that is left for the competitor to open
df2.loc[df2['competition_months_old'] < 0, 'competition_months_old'] = 0
# promo2_months_old
# calculation method: zero(0) if promo2 is zero(0) else (actual_date - promo2_starting_date) >> timedelta format
# >> then use .days and divide by 30 to extract the number of months >> as integer
df2['promo2_months_old'] = df2.apply(lambda x: 0 if x['promo2'] == 0 else (
x['date'] - datetime.fromisocalendar(x['promo2_since_year'],
x['promo2_since_week'],
1)).days / 30, axis=1).astype(int)
# assigning zero to negative values of promo2_months_old
# since the store is not yet participating (but will in the future)
df2.loc[df2['promo2_months_old'] < 0, 'promo2_months_old'] = 0
# assortment
df2['assortment'] = df2['assortment'].map({'a': 'basic', 'b': 'extra', 'c': 'extended'})
# state_holiday
df2['state_holiday'] = df2['state_holiday'].map({'0': 'none', 'a': 'public', 'b': 'easter', 'c': 'christmas'})
# =-=-=-=- WARNING: EDA USE ONLY -=-=-=-=
# customer_avg_ticket
df2['customers_avg_ticket'] = (df2['sales'] / df2['customers'])
df2['customers_avg_ticket'].fillna(value=0, inplace=True)
```
# <font color='#3F0094'> 3. Feature Filtering </font>
## <font color='#200CF'> 3.0. Dataframe in Progress Backup </font>
```
df3 = df2.copy()
```
## <font color='#200CF'> 3.1. Filtering Rows </font>
```
# eliminating all records where stores are closed and sales are zero
df3 = df3[(df3['open'] != 0) & (df3['sales'] > 0)]
```
## <font color='#200CF'> 3.2. Filtering Columns </font>
**customers:** the number of customers will not be available to be used in the model prediction, as it is an unknown and variable value in the future.
**open:** column has record 1 only.
**promo_interval, curr_month:** auxiliary columns already used in the feature engineering step.
**Important Warning:** column **customers_avg_ticket** will only be used during EDA and will be discarded later.
```
# list of columns to be droped
cols_drop = ['customers', 'open', 'promo_interval', 'curr_month']
df3.drop(cols_drop, axis=1, inplace=True)
df3.shape
```
# <font color='#3F0094'> 4. Exploratory Data Analysis </font>
## <font color='#200CF'> 4.0. Dataframe in Progress Backup </font>
```
# dataframe copy
df4 = df3.copy()
# dataframe - numeric attributes - binary attributes droped
df_numeric = df4.select_dtypes(include=['int64', 'float64'])
# dataframe - categorical attributes
df_categorical = df4.select_dtypes(exclude=['int64', 'float64', 'datetime64[ns]']).drop('year_week', axis=1)
# dataframe - categorical attributes + binary variables
df_cat_n_bin = df_categorical.join(df4[['promo', 'promo2', 'school_holiday']], how='left')
```
## <font color='#200CF'> 4.1. Univariate Analysis </font>
### <font color='#2365FF'> 4.1.1. Response Variable </font>
```
# sales histogram
plt.figure()
ax = sns.histplot(data=df4, x='sales', stat='proportion', bins=100, kde=True)
y_min, y_max = ax.get_ylim()
ax.figure.set_size_inches(17, 7)
ax.set_title('Sales Histogram', fontsize=20, pad=10)
median = np.median(df_numeric['sales'])
ax.vlines(x=median, ymin=0, ymax=y_max*0.9, linestyles='dashed', label='median', colors='firebrick')
ax.annotate(f'median = {median}', xy=(median*1.15, y_max*0.8), fontsize=14, color='firebrick')
plt.savefig('../img/univar_analysis/sales_histogram.png')
plt.show()
```
### <font color='#2365FF'> 4.1.2. Numeric Variable </font>
```
df_numeric.shape
```
**NUMERIC VARIABLES HISTOGRAMS**
```
# ploting numeric attributes histograms
axes = list()
n_bins = 50
n=0
fig, axes = plt.subplots(nrows=4, ncols=4)
fig.set_size_inches(25, 25)
for i in range(4):
for j in range(4):
if n < 15:
axes[i][j].hist(df_numeric.iloc[:, n], bins=n_bins)
axes[i][j].set_title(df_numeric.iloc[:, n].name)
n += 1
# plt.savefig('../img/univar_analysis/numeric_attr_histograms.png')
fig;
# competition_distance
plt.figure(figsize=(20,10))
plt.suptitle('Competitor Distance Analysis', fontsize=22)
plt.subplot(1, 2, 1)
ax1 = sns.histplot(data=df4, x='competition_distance', bins=100)
ax1.set_title("Histogram", fontsize=18, pad=10)
# cumulative counts as bins increase.
plt.subplot(1, 2, 2)
ax2 = sns.histplot(data=df4, x='competition_distance', bins=100, cumulative=True)
ax2.set_title("Cumulative Histogram", fontsize=18, pad=10)
# plt.savefig('../img/univar_analysis/competitor_distance.png')
plt.show()
# competition_open_since_year -- competition_months_old
plt.figure(figsize=(20,20))
plt.suptitle('Competition Over Time', fontsize=22)
# analysing values between 1985 and present day (30 years)
plt.subplot(2, 2, 1)
ax1 = sns.histplot(data=df4.query("competition_open_since_year > 1985"), x='competition_open_since_year', bins=30)
ax1.set_title("Histogram of years when competitors opened", fontsize=18, pad=10)
ax1.set_xlabel("")
plt.subplot(2, 2, 2)
ax1 = sns.histplot(data=df4.query("competition_open_since_year > 1985"), x='competition_open_since_year', bins=30, cumulative=True)
ax1.set_title("Histogram of years when competitors opened\nCumulative", fontsize=18, pad=10)
ax1.set_xlabel("")
# analysing values greater than 0 and lower than 360 (30 years)
plt.subplot(2, 2, 3)
ax2 = sns.histplot(data=df4.query("competition_months_old > 0 and competition_months_old < 360"), x='competition_months_old', bins=30)
ax2.set_title("Histogram of time elapsed since \ncompetitors' inauguration (in months)", fontsize=18, pad=10)
ax2.set_xlabel("")
plt.subplot(2, 2, 4)
ax2 = sns.histplot(data=df4.query("competition_months_old > 0 and competition_months_old < 360"), x='competition_months_old', bins=30, cumulative=True)
ax2.set_title("Histogram of time elapsed since competitors' \ninauguration (in months) - Cumulative", fontsize=18, pad=10)
ax2.set_xlabel("")
# plt.savefig('../img/univar_analysis/competition_time.png')
plt.show()
# promo2_since_year -- promo2_months_old
plt.figure(figsize=(20,20))
plt.suptitle('Extended Promotion Analysis', fontsize=22)
#
plt.subplot(2, 2, 1)
ax1 = sns.histplot(data=df4, x='promo2_since_year', bins = 7)
ax1.set_title("Histogram of years when extended promo started", fontsize=18, pad=10)
ax1.set_xlabel("")
plt.subplot(2, 2, 2)
ax1 = sns.histplot(data=df4, x='promo2_since_year', bins=50, cumulative=True)
ax1.set_title("Histogram of years when extended promo started \nCumulative", fontsize=18, pad=10)
ax1.set_xlabel("")
# analysing values greater than zero
plt.subplot(2, 2, 3)
ax2 = sns.histplot(data=df4.query("promo2_months_old > 0"), x='promo2_months_old', bins=14)
ax2.set_title("Histogram of time elapsed since \nextended promo started (in months)", fontsize=18, pad=10)
ax2.set_xlabel("")
ax2.set_xticks(ticks=np.arange(0, 72, 6))
plt.subplot(2, 2, 4)
ax2 = sns.histplot(data=df4.query("promo2_months_old > 0"), x='promo2_months_old', bins=14, cumulative=True)
ax2.set_title("Histogram of time elapsed since extended \npromo started (in months) - Cumulative", fontsize=18, pad=10)
ax2.set_xlabel("")
ax2.set_xticks(ticks=np.arange(0, 72, 6))
# plt.savefig('../img/univar_analysis/promo2_time.png')
plt.show()
# histograms - customers_avg_ticket AND sales
plt.figure(figsize=(20, 16))
plt.subplot(2, 1, 1)
ax1 = sns.histplot(data=df4, x='customers_avg_ticket', stat='proportion', bins=100, kde=True)
ax1.set_title('Customer Average Ticket Histogram', fontsize=20, pad=15)
ax1.set_xlabel('')
ax1.set_xlim(left=0)
median1 = np.median(df4['customers_avg_ticket'])
_, y1_max = ax1.get_ylim()
ax1.vlines(x=median1, ymin=0, ymax=y1_max*0.9, linestyles='dashed', label='median', colors='firebrick')
ax1.annotate(f'median = $ {median1} / customer', xy=(median1*1.15, y1_max*0.8), fontsize=14, color='firebrick')
plt.subplot(2, 1, 2)
ax2 = sns.histplot(data=df4, x='sales', stat='proportion', bins=100, kde=True)
ax2.set_title('Sales Histogram', fontsize=20, pad=10)
ax2.set_xlim(left=0)
median2 = np.median(df4['sales'])
_, y2_max = ax2.get_ylim()
ax2.vlines(x=median2, ymin=0, ymax=y2_max*0.9, linestyles='dashed', label='median', colors='firebrick')
ax2.annotate(f'median = {median2}', xy=(median2*1.15, y2_max*0.8), fontsize=14, color='firebrick')
# plt.savefig('../img/univar_analysis/customer_ticket_histogram.png')
plt.show()
```
### <font color='#2365FF'> 4.1.3. Categorical Variable </font>
**STATE HOLIDAY**
```
df4.query("state_holiday != 'none'").value_counts(subset='state_holiday')
# state_holiday
# not considering regular day -> state_holiday == 'none'
plt.figure(figsize=(20,10))
plt.subplot(1, 2, 1)
ax1 = sns.countplot(x='state_holiday', data=df4.query("state_holiday != 'none'"))
# ax.figure.set_size_inches(10, 10)
ax1.set_title('Countplot: State Holiday', fontsize=20, pad=10)
ax1.set_xlabel('')
plt.subplot(1, 2, 2)
ax2 = sns.histplot(x='sales', data=df4.query("state_holiday != 'none'"), hue='state_holiday', kde=True)
ax2.set_title('Sales Histogram \nAccording to State Holiday', fontsize=20, pad=10)
ax2.set_xlabel('')
plt.show()
```
**STORE TYPES**
```
df4.value_counts(subset='store_type')
# store_type
plt.figure(figsize=(20,10))
plt.subplot(1, 2, 1)
ax1 = sns.countplot(x='store_type', data=df4, order=['a','b','c','d'])
# ax.figure.set_size_inches(10, 10)
ax1.set_title('Countplot: Store Types', fontsize=20, pad=10)
ax1.set_xlabel('')
plt.subplot(1, 2, 2)
ax2 = sns.histplot(x='sales', data=df4, hue='store_type', stat='percent', bins=50, hue_order=['a','b','c','d'], kde=True)
ax2.set_title('Sales Histogram \nAccording to Store Types', fontsize=20, pad=10)
ax2.set_xlabel('')
plt.show()
```
**ASSORTMENT**
```
df4['assortment'].value_counts()
# assortment
plt.figure(figsize=(20,10))
plt.subplot(1, 2, 1)
ax1 = sns.countplot(x='assortment', data=df4, order=['basic','extended','extra'])
# ax.figure.set_size_inches(10, 10)
ax1.set_title('Countplot: Assortment Level', fontsize=20, pad=10)
ax1.set_xlabel('')
plt.subplot(1, 2, 2)
ax2 = sns.histplot(x='sales', data=df4, hue='assortment', stat='percent', bins=50, hue_order=['basic','extended','extra'], kde=True)
ax2.set_title('Sales Histogram \nAccording to Assortment Level', fontsize=20, pad=10)
ax2.set_xlabel('')
plt.show()
```
## <font color='#200CF'> 4.2. Bivariate Analysis </font>
### <font color='#2365FF'> Hypothesis H1. </font>
**The larger the assortment the greater the global sales of the stores should be.**
```
# group by assortment then sum the sales
aux1 = df4[['assortment', 'sales']].groupby('assortment').sum().reset_index()
# group by year-weak an by assortment then sum the sales
aux2 = df4[['year_week', 'assortment', 'sales']].groupby(['year_week', 'assortment']).sum().reset_index()
# pivoting - each year-week in a row and differents assortments in the columns
aux2 = aux2.pivot(index='year_week', columns='assortment', values='sales')
plt.figure(figsize=(22, 18))
plt.suptitle('Global Sales Analysis by Assortment')
plt.subplot(2, 2, 1)
sns.barplot(x='assortment', y='sales', data=aux1)
plt.xlabel('')
plt.ylabel('Sales Revenue')
plt.subplot(2, 2, 2)
sns.lineplot(data=aux2)
plt.xticks(ticks=[10,34,58,82,106,130], fontsize=12)
plt.xlabel('Year-Week', fontsize=15)
plt.subplot(2, 2, 3)
sns.lineplot(data=aux2[['basic', 'extended']])
plt.xticks(ticks=[10,34,58,82,106,130], fontsize=12)
plt.xlabel('Year-Week', fontsize=15)
plt.ylabel('Sales Revenue')
plt.subplot(2, 2, 4)
sns.lineplot(data=aux2[['extra']])
plt.xticks(ticks=[10,34,58,82,106,130], fontsize=12)
plt.xlabel('Year-Week', fontsize=15)
# plt.savefig('../img/bivar_analysis/assortment_global_sales.png')
plt.show()
```
<font color='firebrick'>**The number of stores with 'basic' and 'extended' assortment level is much higher (roughly fifty times greater) than the number of stores with 'extra' assortment level, so the sales volume of 'extra' assortment level stores is much smaller when compared to the other types of stores.**</font>
### <font color='#2365FF'> Hypothesis H2. </font>
**The median sales of stores with the largest assortment should be the highest.**
```
aux1 = df4[['assortment', 'sales']].groupby('assortment').aggregate(func=['count', 'sum', 'median']).droplevel(level=0, axis='columns')
aux1
# median sales by assortment - bar plot
aux1 = df4[['assortment', 'sales']].groupby('assortment').aggregate(func=['count', 'sum', 'median']).droplevel(level=0, axis='columns')
plt.figure(figsize=(18, 9))
plt.title('Medain Value of Sales by Assortment', fontsize=22)
sns.barplot(x=aux1.index, y='median', data=aux1)
plt.xlabel('')
plt.ylabel('Median Sales Value', fontsize=16)
# plt.savefig('../img/bivar_analysis/assortment_median_sales.png')
plt.show()
```
**Although the total number of sales of stores with the 'extra' assortment is much smaller, the median sales value of these stores is higher than the median sales value of the other stores.**
```
# The bootstrap (sampling with replacement from a data set) is a powerful
# tool for assessing the variability of a sample statistic.
# using to calculate the confidence interval for the median sales value,
# according to the store assortment level, with a confidence level of 95%.
# selecting all sales revenue according to the assortment level
sales_basic_assort = df4.loc[df4['assortment'] == 'basic', 'sales']
sales_extended_assort = df4.loc[df4['assortment'] == 'extended', 'sales']
sales_extra_assort = df4.loc[df4['assortment'] == 'extra', 'sales']
# bootstrapp each series of values, take a sample of 500 values,
# caluculate its median and repeat the process 500 times
boot_basic = bootstrap(sales_basic_assort, estimate = 'median', n_repeat=500, n_sample=500, ci=99)
boot_extended = bootstrap(sales_extended_assort, estimate = 'median', n_repeat=500, n_sample=500, ci=99)
boot_extra = bootstrap(sales_extra_assort, estimate = 'median', n_repeat=500, n_sample=500, ci=99)
assortment_bootstrap_statistics = pd.DataFrame([boot_basic, boot_extended, boot_extra],
columns = ['statistic_mean', 'standard_error', 'lower_ci', 'upper_ci'],
index = ['basic', 'extended', 'extra'])
assortment_bootstrap_statistics
```
### <font color='#2365FF'> Hypothesis H3. </font>
**The volume of sales varies according to the type of the store.**
```
# group by assortment then sum the sales
aux1 = df4[['store_type', 'sales']].groupby('store_type').sum().reset_index()
aux1['sales_share'] = aux1['sales'] / aux1['sales'].sum()
aux1
# group by assortment then sum the sales
aux1 = df4[['store_type', 'sales']].groupby('store_type').sum().reset_index()
# group by year-weak an by assortment then sum the sales
aux2 = df4[['year_week', 'store_type', 'sales']].groupby(['year_week', 'store_type']).sum().reset_index()
# pivoting - each year-week in a row and differents assortments in the columns
aux2 = aux2.pivot(index='year_week', columns='store_type', values='sales')
plt.figure(figsize=(22, 18))
plt.suptitle('Global Sales Analysis by Store Type')
plt.subplot(2, 2, 1)
sns.barplot(x='store_type', y='sales', data=aux1)
plt.xlabel('')
plt.ylabel('Sales Revenue')
plt.subplot(2, 2, 2)
sns.lineplot(data=aux2)
plt.xticks(ticks=[10,34,58,82,106,130], fontsize=12)
plt.xlabel('Year-Week', fontsize=15)
plt.subplot(2, 2, 3)
sns.lineplot(data=aux2[['a', 'd']])
plt.xticks(ticks=[10,34,58,82,106,130], fontsize=12)
plt.xlabel('Year-Week', fontsize=15)
plt.ylabel('Sales Revenue')
plt.subplot(2, 2, 4)
sns.lineplot(data=aux2[['b', 'c']])
plt.xticks(ticks=[10,34,58,82,106,130], fontsize=12)
plt.xlabel('Year-Week', fontsize=15)
# plt.savefig('../img/bivar_analysis/store_type_global_sales.png')
plt.show()
```
<font color='firebrick'>**Approximately 54% of sales come from type A stores, followed by type 3 stores with 30%, 13% come from type C stores and less than 3% from type B stores.**</font>
### <font color='#2365FF'> Hypothesis H4. </font>
**The average value of sales for a specific type of store is higher than the average value for other types (store types: a, b, c, d).**
```
df4[['store_type', 'sales']].groupby('store_type').aggregate(func=['count', 'sum', 'mean']).reset_index()
# store-types / assortment - bar plot
# A bar plot represents an estimate of Central Tendency (MEAN) for a numeric variable with the height of
# each rectangle and provides some indication of the uncertainty around that estimate using error bars.
plt.figure(figsize=(18, 9))
plt.title('Average Sales by Store Types', fontsize=22)
# ci -> confidence interval of 95%
sns.barplot(x='store_type', y='sales', order=['a', 'b', 'c', 'd'], data=df4, ci=95)
plt.xlabel('')
plt.ylabel('Average Sales Value')
# plt.savefig('../img/bivar_analysis/store_type_avg_sales.png')
plt.show()
```
<font color='red'> **The average sales value of type B stores seems to be considerably greater than the average sales value of the other types of stores.** </font>
<b> Performing a Statistic Test </b>
**Hipothesis**: $H_0$ e $H_1$
The null hypothesis always contains an equality claim: equal to; less than or equal to; greater than or equal to. So:
$\mu_1 \Rightarrow$ Average Sales Value of Type B Stores.
$\mu_2 \Rightarrow$ Average Sales Value of Typea A, C or D Stores.
$
\begin{cases}
H_0: \mu_1 \leq \mu_2\\
H_1: \mu_1 > \mu_2
\end{cases}
$
```
# using DescrStatsW and CompareMeans from statsmodels
# getting 2000 random sample of sales values for each type of store type
sales_store_type_a = df4.loc[df4['store_type'] == 'a', 'sales'].sample(n=2000)
sales_store_type_b = df4.loc[df4['store_type'] == 'b', 'sales'].sample(n=2000)
sales_store_type_c = df4.loc[df4['store_type'] == 'c', 'sales'].sample(n=2000)
sales_store_type_d = df4.loc[df4['store_type'] == 'd', 'sales'].sample(n=2000)
# calculating statistics with DescrStatsW
stats_a = DescrStatsW(sales_store_type_a)
stats_b = DescrStatsW(sales_store_type_b)
stats_c = DescrStatsW(sales_store_type_c)
stats_d = DescrStatsW(sales_store_type_d)
# using CompareMeans
test_b_a = CompareMeans(stats_b, stats_a)
test_b_c = CompareMeans(stats_b, stats_c)
test_b_d = CompareMeans(stats_b, stats_d)
# performing ztest_ind
# H_null: Average Sales Value of Type B Stores is less than or equal to Types (A, C, D) Stores
z_b_a, pvalue_b_a = test_b_a.ztest_ind(alternative='larger', value=0)
z_b_c, pvalue_b_c = test_b_c.ztest_ind(alternative='larger', value=0)
z_b_d, pvalue_b_d = test_b_d.ztest_ind(alternative='larger', value=0)
pd.DataFrame({
'z': [z_b_a, z_b_c, z_b_d],
'p_value': [round(pvalue_b_a, 6), round(pvalue_b_c, 6), round(pvalue_b_d, 6)],
'H_null_rejected': [pvalue_b_a < 0.05, pvalue_b_c < 0.05, pvalue_b_d < 0.05]},
index=['b_a', 'b_c', 'b_d'])
```
<font color='black'><b> Store_Type per Assortment -vs- Sales </b></font>
```
df4[['store_type', 'assortment', 'sales']].groupby(['store_type', 'assortment']).aggregate(func=['count', 'sum', 'mean']).reset_index()
# store-types / assortment - bar plot
# A bar plot represents an estimate of Central Tendency (MEAN) for a numeric variable with the height of
# each rectangle and provides some indication of the uncertainty around that estimate using error bars.
# ci -> confidence interval of 95%
ax = sns.barplot(x='store_type', y='sales', hue='assortment', order=['a', 'b', 'c', 'd'],
hue_order=['basic','extended','extra'], data=df4, ci=95)
ax.figure.set_size_inches(18, 9)
ax.set_title('Average Sales by Store Types and Assortment Level', fontsize=20, pad=10)
ax.set_xlabel('')
ax.set_ylabel('Average Sales Value')
# ax.get_figure().savefig('../img/bivar_analysis/storetype_hue_assortment_avg_sales.png')
ax;
```
**IMPORTANT:** The average sales value of Type B stores stands out even more when the types of stores are separated by assortment types, as can be seen with the average sales of Type B stores with extended assortment levels, it is still more expressive.
### <font color='#2365FF'> Hypothesis H5. </font>
**The sales revenue of stores are lower the closer the competitors are located.**
```
aux1 = df4[['competition_distance', 'sales']].groupby('competition_distance').sum().reset_index()
bins = list(np.arange(0, 25000, 1000)) + [30000, 40000, 50000, 160000]
aux1['competition_distance_binned'] = pd.cut(x=aux1['competition_distance'], bins=bins)
aux2 = aux1[['competition_distance_binned', 'sales']].groupby('competition_distance_binned').sum().reset_index()
grid = gridspec.GridSpec(2, 2)
plt.figure(figsize=(20,18))
plt.suptitle('Sales Revenue by Competition Distance', fontsize=22)
plt.subplot(grid[0,:])
sns.barplot(x='competition_distance_binned', y='sales', data=aux2)
plt.xlabel('')
plt.ylabel('Sales Revenue')
plt.xticks(fontsize=9, rotation=30)
plt.subplot(grid[1,0])
sns.scatterplot(x='competition_distance', y='sales', data=aux1)
plt.ylabel('Sales Revenue')
plt.xlabel('Distance in Meters')
plt.xticks(fontsize=12)
plt.xlim(-2000, 160000)
plt.subplot(grid[1,1])
sns.heatmap(aux1.corr(method='pearson'), annot=True)
# plt.savefig('../img/bivar_analysis/competition_distance_global_sales.png')
plt.show()
```
<font color='firebrick'>**In fact, the sum of sales of stores with closer competitors is considerably higher than the sum of sales of stores with more distant competitors, especially for distances above 3000 meters.** </font>
### <font color='#2365FF'> Hypothesis H6. </font>
**Regarding the stores with competitors whose distance is less than 1000 meters their average sales value is lower than the average sales value of the other stores.**
```
print(f"The average sales value of stores whose distance is less than 1000 meters: ${(df4.loc[df4['competition_distance'] < 1000, 'sales'].mean()):.2f}.", end='\n\n')
print(f"The average sales value of stores whose distance is greater than 1000 meters: ${(df4.loc[df4['competition_distance'] >= 1000, 'sales'].mean()):.2f}.")
```
<font color='firebrick'><b>In fact, the data shows that the average sales value of stores with competitors that are located less than 1000 meters away is higher than the average sales value of other stores. </b></font>
```
# competition distance avg sales
aux1 = df4[['competition_distance', 'sales']]
aux2 = pd.cut(x=aux1['competition_distance'], bins=[0, 1000, 160000])
aux2.name = 'competition_distance_binned'
aux1 = aux1.join(aux2, how='left')
plt.figure(figsize=(19,8))
plt.title('Average Store Sales by Competition Distance', fontsize=22)
sns.barplot(x='competition_distance_binned', y='sales', data=aux1)
plt.xlabel('Distance in Meters')
plt.ylabel('Average Sales Value')
# plt.savefig('../img/bivar_analysis/competition_distance_avg_sales.png')
plt.show()
```
**STATISTICAL TESTS TO VERIFY IF THE SETS ARE FROM THE SAME DISTRIBUTUION**
**The Wilcoxon rank-sum test tests the null hypothesis that two sets of measurements are drawn from the same distribution.**
**The alternative hypothesis is that values in one sample are more likely to be larger than the values in the other sample.**
If p_value greater than significance level (usually 5%) then the null hypothesis cannot be rejected.
**Hipothesis**: $H_0$ e $H_1$
$\mu_1 \Rightarrow$ Average Sales Value of Stores whose competitors distance is less than 1000 meters.
$\mu_2 \Rightarrow$ Average Sales Value of Stores whose competitors distance is grater than 1000 meters.
The null hypothesis always contains an equality claim. So:
$
\begin{cases}
H_0: \mu_1 \leq \mu_2\\
H_1: \mu_1 > \mu_2
\end{cases}
$
```
# unsing ranksums from scipy.stats
# getting 10000 random sample of sales values for each distance
sales_less_1k = df4.loc[df4['competition_distance'] < 1000, 'sales'].sample(10000)
sales_greater_1k = df4.loc[df4['competition_distance'] >= 1000, 'sales'].sample(10000)
statistic, p_value = ranksums(sales_less_1k, sales_greater_1k, alternative='greater')
print(f'p_value: {p_value:.6f}')
```
<font color='firebrick'><b>Once p_value is less than 5% (significance level) it can be said that the sales values of stores with competitors whose distance is less than 1000 meters is, in fact, higher than the sales values of the other stores, just the opposite of the initial assumption set out in Hypotheses f.</b></font>
### <font color='#2365FF'> Hypothesis H7. </font>
**The total sales revenue of stores with competitors for a longer time should be higher.**
```
aux1 = df4[(df4['competition_months_old'] > 0) & (df4['competition_months_old'] < 120)][['competition_months_old', 'sales']].groupby('competition_months_old').sum().reset_index()
plt.figure(figsize=(20, 18))
plt.suptitle('Global Sales Analisys by Long Time Competition', fontsize=22)
plt.subplot(2, 1, 1)
sns.barplot(x='competition_months_old', y='sales', data=aux1)
plt.xlabel('Months', fontsize=13)
plt.ylabel('Sales Revenue')
plt.xticks(fontsize=10, rotation=90)
plt.subplot(2, 1, 2)
sns.heatmap(aux1.corr(method='pearson'), annot=True)
# plt.savefig('../img/bivar_analysis/competition_months_global_sales.png')
plt.show()
```
<font color='firebrick'>**Stores with more recent competitors haver higher total sales values than stores with older competitors.**
**However, it is important to emphasize that there has been a great increase in the opening of competitors in recent years, so more stores have started to have competitors nearby.**
### <font color='#2365FF'> Hypothesis H8. </font>
***The average sales values of stores whose competitors opened less than 18 months ago are lower than the average values of other stores.***
```
# competition_months_old
sales_competition_18_less = df4[(df4['competition_months_old'] < 18) & (df4['competition_months_old'] > 0)]['sales']
print(f"The average sales value of stores whose competitors opened less than 18 months ago: ${sales_competition_18_less.mean():.2f}.", end='\n\n')
sales_competition_18_more = df4[df4['competition_months_old'] > 18]['sales']
print(f"The average sales value of stores whose competitors opened more than 18 months ago: ${sales_competition_18_more.mean():.2f}.")
# competition_months_old average sales bar plot
aux1 = df4.loc[df4['competition_months_old'] > 0, ['competition_months_old', 'sales']]
aux2 = pd.cut(x=aux1['competition_months_old'], bins=[0, 18, 1410])
aux2.name = 'competition_months_binned'
aux1 = aux1.join(aux2, how='left')
plt.figure(figsize=(19,8))
plt.title('Average Store Sales by Long Time Competition', fontsize=22)
sns.barplot(x='competition_months_binned', y='sales', data=aux1)
plt.xlabel('Time in Months')
plt.ylabel('Average Sales Value')
# plt.savefig('../img/bivar_analysis/competition_months_avg_sales.png')
plt.show()
```
<font color='firebrick'>**The difference between the averages is less than 3% and the statistical test results state that there is no statistically significant difference between sales of stores with more or less than 18 months of competition.**</font>
**Performing a Boostrap and calculating the confidence interval.**
```
# selecting all sales revenue according to the competition time - greater or less than 18 months
# less than 18 months but greater than zero
sales_competition_18_less = df4[(df4['competition_months_old'] < 18) & (df4['competition_months_old'] > 0)]['sales']
sales_competition_18_more = df4[df4['competition_months_old'] > 18]['sales']
boot_less_18 = bootstrap(sales_competition_18_less, estimate='mean', n_repeat=500, n_sample=1000, ci=95)
boot_more_18 = bootstrap(sales_competition_18_more, estimate='mean', n_repeat=500, n_sample=1000, ci=95)
competition_months_bootstrap_statistics = pd.DataFrame([boot_less_18, boot_more_18],
columns=['statistic_mean', 'standard_error', 'lower_ci', 'upper_ci'],
index=['less_than_18', 'more_than_18'])
competition_months_bootstrap_statistics
```
### <font color='#2365FF'> Hypothesis H9. </font>
**The sales revenue should be greater when running a promotion (promo) than when not running a promo.**
```
# total sales by promo
aux1 = df4[['promo', 'sales']].groupby('promo').sum().reset_index()
plt.figure(figsize=(20,10))
plt.title('Global Revenue by Sales Period')
sns.barplot(x='promo', y='sales', data=aux1)
plt.xlabel('')
plt.ylabel('Sales Revenue')
plt.xticks(ticks=[0, 1], labels=['Off Promo', 'On Promo'])
# plt.savefig('../img/bivar_analysis/promo_global_sales.png')
plt.show()
```
### <font color='#2365FF'> Hypothesis H10. </font>
**The average sales value of stores should be greater when running a promotion (promo) than when not running a promo.**
```
df4[['promo', 'sales']].groupby('promo').aggregate(func=['count', 'sum', 'mean']).reset_index()
```
<font color='firebrick'>**The average sales value of stores during the period they are on promotion (promo) is considerably higher than the average sales value outside the promotion period.** </font>
```
# promo - bar plot
# A bar plot represents an estimate of Central Tendency (MEAN) for a numeric variable with the height of
# each rectangle and provides some indication of the uncertainty around that estimate using error bars.
# ci -> confidence interval of 95%
ax = sns.barplot(x='promo', y='sales', data=df4, ci=95)
ax.figure.set_size_inches(16, 8)
ax.set_title('Average Sales Value by Sales Period \nPromo', fontsize=20, pad=10)
ax.set_xlabel('')
ax.set_ylabel('Average Sales Value')
ax.set_xticklabels(['Off Promo', 'On Promo'])
# ax.get_figure().savefig('../img/bivar_analysis/promo_avg_sales.png')
ax;
```
### <font color='#2365FF'> Hypothesis H11. </font>
**The average sales value of stores with continuing and consecutive promotion (promo2) should be greater than those that do not have extended promotion.**
```
df4[['promo2', 'promo', 'sales']].groupby(['promo2', 'promo']).aggregate(func=['count', 'sum', 'mean']).reset_index()
```
<b>The average sales value of stores that are participating in the extended promotion period is lower than the average sales value of stores that are not participating, whether they have active promotion or not.
It is necessary to identify possible causes for poor sales performance or reassess the marketing strategy for those stores specifically.
However, it should be noted that the average sales value of stores with extended promotion is higher during the promotion period than outside this period.</b>
```
# promo2 - bar plot
# A bar plot represents an estimate of Central Tendency (MEAN) for a numeric variable with the height of
# each rectangle and provides some indication of the uncertainty around that estimate using error bars.
# ci -> confidence interval of 95%
ax = sns.barplot(x='promo2', y='sales', hue='promo', data=df4, ci=95)
ax.figure.set_size_inches(16, 8)
ax.set_title('Comparison of sales of stores that are participating \n vs. not participating in the extended promotion', fontsize=20, pad=10)
ax.set_xlabel('')
ax.set_ylabel('average sales')
ax.set_xticklabels(['store is not participating', 'store is participating'])
# ax.get_figure().savefig('../img/bivar_analysis/promo2_comparison_avg_sales.png')
ax;
# analysing the average sales of promo2 stores only
# comparing the results: promo2-on vs promo2-off
df4.query("promo2 == 1")[['promo2_active', 'sales']].groupby('promo2_active').aggregate(func=['count', 'sum', 'mean']).reset_index()
# promo2_active - bar plot
# Analysing stores that participate in Promo2
# comparing the results: promo2-off vs promo2-on
ax = sns.barplot(x='promo2_active', y='sales', data=df4.query("promo2 == 1"), ci=95)
ax.figure.set_size_inches(16, 8)
ax.set_title('Bar Plot: Promo2 \nOff vs On', fontsize=20, pad=10)
ax.set_xlabel('')
ax.set_xticklabels(['not_active', 'active'])
```
### <font color='#2365FF'> Hypothesis H12. </font>
**The sales revenue of stores running promo2 should grow over time.**
```
# sales revenue over promo2 time
aux1 = df4.loc[(df4['promo2'] == 1) & (df4['promo2_months_old'] > 12), ['promo2_months_old', 'sales']].groupby('promo2_months_old').sum().reset_index()
plt.figure(figsize=(22,10))
plt.suptitle('Sales Revenue over Promo2 Time', fontsize=22)
plt.subplot(1, 2, 1)
sns.barplot(x='promo2_months_old', y='sales', data=aux1)
plt.xlabel('')
plt.ylabel('Sales Revenue')
plt.xticks(fontsize=9)
plt.subplot(1, 2, 2)
sns.heatmap(data=aux1.corr(method='pearson'), annot=True)
# plt.savefig('../img/bivar_analysis/promo2_global_sales.png')
plt.show()
```
### <font color='#2365FF'> Hypothesis H13. </font>
**The median sales value of stores running promo2 for a longer period of time (more than 12 months) should be higher than stores running promo2 for a shorter period of time.**
```
# stores participating in promo 2 for over 12 months
median_sales_promo2_over_12 = df4.loc[(df4['promo2'] == 1) & (df4['promo2_months_old'] > 12), 'sales'].median()
# stores participating in promo 2 for less than 12 months
median_sales_promo2_less_12 = df4.loc[(df4['promo2'] == 1) & (df4['promo2_months_old'] <= 12) & (df4['promo2_months_old'] > 0), 'sales'].median()
print(f'Median sales of stores participating in promo 2 for over 12 months: $ {median_sales_promo2_over_12:.2f}.', end='\n\n')
print(f'Median sales of stores participating in promo 2 for less than 12 months: $ {median_sales_promo2_less_12:.2f}.')
aux1 = df4.loc[(df4['promo2'] == 1) & (df4['promo2_months_old'] > 0), ['promo2_months_old', 'sales']]
aux2 = pd.cut(x=aux1['promo2_months_old'], bins=[0, 12, 75])
aux2.name = 'promo2_months_binned'
aux1 = aux1.join(aux2, how='left')
plt.figure(figsize=(20,9))
plt.title('Average Sales Value over Promo2 Long Time', fontsize=20)
sns.barplot(x='promo2_months_binned', y='sales', data=aux1)
plt.xlabel('')
plt.ylabel('Average Sales Value')
plt.xticks(ticks=[0, 1], labels=['Less than 12 months', "Over 12 months"])
# plt.savefig('../img/bivar_analysis/promo2_avg_sales.png')
plt.show()
```
<font color='firebrick'>**Despite being similar values, the median sales value of stores that have been participating in the promo2 for over 12 months is higher.**</font>
**Performing a Boostrap and calculating the confidence interval.**
```
# selecting all sales of stores participating in promo 2 and splitting into greater than or less than 12 months old
sales_promo2_over_12 = df4.loc[(df4['promo2'] == 1) & (df4['promo2_months_old'] > 12), 'sales']
# less than 12 months but greater than zero
sales_promo2_less_12 = df4.loc[(df4['promo2'] == 1) & (df4['promo2_months_old'] <= 12) & (df4['promo2_months_old'] > 0), 'sales']
boot_over_12 = bootstrap(sales_promo2_over_12, estimate='median', n_repeat=500, n_sample=1000, ci=95)
boot_less_12 = bootstrap(sales_promo2_less_12, estimate='median', n_repeat=500, n_sample=1000, ci=95)
promo2_months_bootstrap_statistics = pd.DataFrame([boot_over_12, boot_less_12],
columns=['statistic_mean', 'standard_error', 'lower_ci', 'upper_ci'],
index=['over_12', 'less_than_12'])
promo2_months_bootstrap_statistics
```
### <font color='#2365FF'> Hypothesis H14. </font>
**The average ticket per customer should be lower during holiday periods.**
```
# customer average ticket by state holiday
plt.figure(figsize=(19,10))
plt.title('Customer Average Ticket by Holiday/Regular Day', fontsize=20)
sns.barplot(x='state_holiday', y='customers_avg_ticket', data=df4)
plt.xlabel('')
plt.ylabel('Customer Average Ticket')
# plt.savefig('../img/bivar_analysis/customer_avg_ticket_holiday.png')
plt.show()
```
<font color='firebrick'>**The customer average ticket price is considerably higher in a regular day than during any state holiday.** </font>
```
aux1 = df4[['state_holiday', 'customers_avg_ticket']].groupby('state_holiday').mean().reset_index()
aux1
```
### <font color='#2365FF'> Hypothesis H15. </font>
**Sales during the Christmas holiday are expected to be the biggest of the year. .**
```
# sales during holidays
aux1 = df4.loc[df4['state_holiday'] != 'none', ['year', 'state_holiday', 'sales']].groupby(['year', 'state_holiday']).sum().reset_index()
plt.figure(figsize=(20,10))
plt.title('Sales Revenue during State Holidays per Year', fontsize=20)
sns.barplot(x='year', y='sales', hue='state_holiday', data=aux1)
plt.xlabel('')
plt.ylabel('Sales Revenue')
# plt.savefig('../img/bivar_analysis/state_holiday_global_sales.png')
plt.show()
```
<font color='firebrick'>**Sales during Christmas are lower than during the other State Holidays.**</font>
### <font color='#2365FF'> Hypothesis H16. </font>
**Stores affected by the closure of public schools on school holidays should sell less.**
```
# sales vs school holidays
aux1 = df4[['month', 'school_holiday', 'sales']].groupby(['month', 'school_holiday']).sum().reset_index()
plt.figure(figsize=(20,8))
plt.suptitle('How Stores Sales Are \nAfected By School Holiday', fontsize=20)
plt.subplot(1, 2, 1)
ax1 = sns.barplot(x='month', y='sales', hue='school_holiday', data=aux1)
ax1.set_title('Total Sales vs Month', fontsize=16)
ax1.set_xlabel('Month')
ax1.set_ylabel('Sales Revenue')
plt.subplot(1, 2, 2)
ax2 = sns.barplot(x='school_holiday', y='sales', data=df4)
ax2.set_title('Influence of the school holiday on average sales', fontsize=15)
ax2.set_xlabel('')
ax2.set_ylabel('Average Sales')
ax2.set_xticklabels(['regular day', 'school holiday'])
# plt.savefig('../img/bivar_analysis/school_holiday_sales.png')
plt.show()
df4[['school_holiday', 'sales']].groupby('school_holiday').mean()
```
<font color='firebrick'>**The difference between the average sales values of the stores is less than 5%.**</font>
**Performing a Boostrap and calculating the confidence interval.**
```
# splitting sales into during school holiday and off school holidays
on_school_holiday = df4.loc[df4['school_holiday'] == 1, 'sales']
# less than 12 months but greater than zero
off_school_holiday = df4.loc[df4['school_holiday'] == 0, 'sales']
boot_on = bootstrap(on_school_holiday, estimate='mean', n_repeat=500, n_sample=1000, ci=95)
boot_off = bootstrap(off_school_holiday, estimate='mean', n_repeat=500, n_sample=1000, ci=95)
school_holiday_bootstrap_statistics = pd.DataFrame([boot_on, boot_off],
columns=['statistic_mean', 'standard_error', 'lower_ci', 'upper_ci'],
index=['school_holiday', 'not_school_holiday'])
school_holiday_bootstrap_statistics
```
### <font color='#2365FF'> Hypothesis H17. </font>
**The revenue in the last quarter of the year should be higher than in the other quarters.**
```
# sales revenue over the quarters of the years
# mapping the quarters
quarter_map = {1:1, 2:1, 3:1,
4:2, 5:2, 6:2,
7:3, 8:3, 9:3,
10:4, 11:4, 12:4}
# the sales data of 2015 stops in july - considering 2013 and 2014 only
aux1 = df4.query("year != 2015")[['month', 'sales']].groupby('month').sum().reset_index()
aux1['quarter'] = aux1['month'].map(quarter_map)
aux2 = aux1[['quarter', 'sales']].groupby('quarter').sum().reset_index()
plt.figure(figsize=(20,10))
plt.suptitle('Sales Revenue vs Quarters')
plt.subplot(2, 2, 1)
ax1 = sns.barplot(x='quarter', y='sales', data=aux2)
ax1.set_xlabel('')
#ax3.set_xticklabels(ticks=[0,1,2,3], labels=['1st', '2nd', '3rd', '4th'])
plt.subplot(2, 2, 2)
ax2 = sns.regplot(x='quarter', y='sales', data=aux2)
ax2.set_xlabel('')
plt.subplot(2, 2, 3)
ax3 = sns.barplot(x='month', y='sales', data=aux1)
ax3.set_xlabel('')
plt.subplot(2, 2, 4)
ax4 = sns.heatmap(aux2.corr(method='pearson'), annot=True)
ax4.set_xlabel('')
# plt.savefig('../img/bivar_analysis/quarters_global_sales.png')
plt.show()
```
<font color='firebrick'>**There is an increase in sales in the last quarter of the year, but the difference is not significant in relation to the other quarters**</font>
### <font color='#2365FF'> Hypothesis H18. </font>
**Sales behavior is not constant throughout the month, it should be higher in the first 7 days and decreases in the following weeks.**
```
# Sales Revenue vs Days of Month
aux1 = df4[['day', 'sales']].groupby('day').sum().reset_index()
grids = gridspec.GridSpec(nrows=2, ncols=2)
plt.figure(figsize=(20,16))
plt.suptitle('Sales Revenue vs Days of Month')
plt.subplot(grid[0, 0:])
sns.barplot(x='day', y='sales', data=aux1)
plt.xlabel('')
plt.subplot(grid[1, 0])
sns.regplot(x='day', y='sales', data=aux1)
plt.xlabel('')
plt.subplot(grid[1, 1])
sns.heatmap(aux1.corr(method='pearson'), annot=True)
# plt.savefig('../img/bivar_analysis/day_global_sales.png')
plt.show()
```
<font color='firebrick'>**There is a drop in sales throughout the month.**</font>
### <font color='#2365FF'> Hypothesis H19. </font>
**Average sales in the weekend days should be lower than in the other days of the week.**
```
df4[['day_of_week', 'sales']].groupby('day_of_week').aggregate(func=['count', 'sum', 'mean'])
aux1 = df4[['day_of_week', 'sales']].groupby('day_of_week').mean().reset_index()
plt.figure(figsize=(22,9))
plt.suptitle('Average Sales by Weekday/Weekend', fontsize=20)
plt.subplot(1, 3, 1)
sns.barplot(x='day_of_week', y='sales', data=aux1)
plt.xlabel('')
plt.xticks(ticks=[0,1,2,3,4,5,6],
labels=['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])
plt.subplot(1, 3, 2)
sns.regplot(x='day_of_week', y='sales', data=aux1)
plt.xlabel('')
plt.subplot(1, 3, 3)
sns.heatmap(aux1.corr(method='pearson'), annot=True)
# plt.savefig('../img/bivar_analysis/weekend_avg_sales.png')
plt.show()
```
## <font color='#200CF'> 4.3. Multivariate Analysis </font>
### <font color='#2365FF'> 4.3.1. Numeric Attributes </font>
```
correlation = df_numeric.corr(method='pearson')
plt.figure(figsize=(26,18))
plt.title('Numeric Attributes Multivariate Analysis', fontsize=22, pad=10)
sns.heatmap(correlation, annot=True)
# plt.savefig('../img/multivar_analysis/numeric_attributes_multivar_analysis.png')
plt.show()
```
### <font color='#2365FF'> 4.3.2. Categorical Attributes </font>
https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V
```
# calculating Cramér's V
a1 = cramer_v(df_cat_n_bin['state_holiday'], df_cat_n_bin['state_holiday'])
a2 = cramer_v(df_cat_n_bin['state_holiday'], df_cat_n_bin['store_type'])
a3 = cramer_v(df_cat_n_bin['state_holiday'], df_cat_n_bin['assortment'])
a4 = cramer_v(df_cat_n_bin['state_holiday'], df_cat_n_bin['promo'])
a5 = cramer_v(df_cat_n_bin['state_holiday'], df_cat_n_bin['promo2'])
a6 = cramer_v(df_cat_n_bin['state_holiday'], df_cat_n_bin['school_holiday'])
b1 = cramer_v(df_cat_n_bin['store_type'], df_cat_n_bin['state_holiday'])
b2 = cramer_v(df_cat_n_bin['store_type'], df_cat_n_bin['store_type'])
b3 = cramer_v(df_cat_n_bin['store_type'], df_cat_n_bin['assortment'])
b4 = cramer_v(df_cat_n_bin['store_type'], df_cat_n_bin['promo'])
b5 = cramer_v(df_cat_n_bin['store_type'], df_cat_n_bin['promo2'])
b6 = cramer_v(df_cat_n_bin['store_type'], df_cat_n_bin['school_holiday'])
c1 = cramer_v(df_cat_n_bin['assortment'], df_cat_n_bin['state_holiday'])
c2 = cramer_v(df_cat_n_bin['assortment'], df_cat_n_bin['store_type'])
c3 = cramer_v(df_cat_n_bin['assortment'], df_cat_n_bin['assortment'])
c4 = cramer_v(df_cat_n_bin['assortment'], df_cat_n_bin['promo'])
c5 = cramer_v(df_cat_n_bin['assortment'], df_cat_n_bin['promo2'])
c6 = cramer_v(df_cat_n_bin['assortment'], df_cat_n_bin['school_holiday'])
d1 = cramer_v(df_cat_n_bin['promo'], df_cat_n_bin['state_holiday'])
d2 = cramer_v(df_cat_n_bin['promo'], df_cat_n_bin['store_type'])
d3 = cramer_v(df_cat_n_bin['promo'], df_cat_n_bin['assortment'])
d4 = cramer_v(df_cat_n_bin['promo'], df_cat_n_bin['promo'])
d5 = cramer_v(df_cat_n_bin['promo'], df_cat_n_bin['promo2'])
d6 = cramer_v(df_cat_n_bin['promo'], df_cat_n_bin['school_holiday'])
e1 = cramer_v(df_cat_n_bin['promo2'], df_cat_n_bin['state_holiday'])
e2 = cramer_v(df_cat_n_bin['promo2'], df_cat_n_bin['store_type'])
e3 = cramer_v(df_cat_n_bin['promo2'], df_cat_n_bin['assortment'])
e4 = cramer_v(df_cat_n_bin['promo2'], df_cat_n_bin['promo'])
e5 = cramer_v(df_cat_n_bin['promo2'], df_cat_n_bin['promo2'])
e6 = cramer_v(df_cat_n_bin['promo2'], df_cat_n_bin['school_holiday'])
f1 = cramer_v(df_cat_n_bin['school_holiday'], df_cat_n_bin['state_holiday'])
f2 = cramer_v(df_cat_n_bin['school_holiday'], df_cat_n_bin['store_type'])
f3 = cramer_v(df_cat_n_bin['school_holiday'], df_cat_n_bin['assortment'])
f4 = cramer_v(df_cat_n_bin['school_holiday'], df_cat_n_bin['promo'])
f5 = cramer_v(df_cat_n_bin['school_holiday'], df_cat_n_bin['promo2'])
f6 = cramer_v(df_cat_n_bin['school_holiday'], df_cat_n_bin['school_holiday'])
# creating dataframe with Cramer's V results
df_cramer_v = pd.DataFrame({'state_holiday': [a1, a2, a3, a4, a5, a6],
'store_type': [b1, b2, b3, b4, b5, b6],
'assortment': [c1, c2, c3, c4, c5, c6],
'promo': [d1, d2, d3, d4, d5, d6],
'promo2': [e1, e2, e3, e4, e5, e6],
'school_holiday': [f1, f2, f3, f4, f5, f6]})
# using columns names to set the indexes names
df_cramer_v.set_index(keys=df_cramer_v.columns, drop=False, inplace=True)
# heatmap
plt.figure(figsize=(19, 8))
plt.title('Categorical Attributes Heatmap', fontsize=21, pad=10)
sns.heatmap(df_cramer_v, annot=True)
# plt.savefig('../img/multivar_analysis/categorical_attributes_multivar_analysis.png')
plt.show()
```
# <font color='#3F0094'> 5. Data Preparation </font>
## <font color='#200CF'> 5.0. Dataframe Copy for Data Preparation </font>
```
# copying dataframe before filling in null values
# and before feature engineering
df5 = df_raw.copy()
```
## <font color='#200CF'> 5.1. Feature Engineering for ML Models </font>
<font color='firebrick'><b>Some features will receive different treatments from those used for Exploratory Data Analysis (EDA) and some feature engineering are not necessary for machine learning models.</b></font>
**Features with different treatment:** competition_open_since_year, competition_open_since_month
**Features not created / engineered:** customers_avg_ticket, year_week / assortment
### <font color='#2365FF'> 5.1.1. Data Cleaning </font>
```
# renaming df5 column names
snake_case = lambda x: inflection.underscore(x)
df5.columns = list(map(snake_case, df5.columns))
# setting date column as datetime type
df5['date'] = pd.to_datetime(df5['date'])
## =-= Filling in Missing/Null Values =-= ##
## competition_distance - using maximum distance x 2
# maximun distance x 2
max_dist_x_2 = df5['competition_distance'].max() * 2
# assuming competitors are twice as far away as the greatest distance found
df5['competition_distance'] = df5['competition_distance'].apply(lambda x: max_dist_x_2 if np.isnan(x) else x)
## competition_open_since_year
# assign the year of the latest date if NA
df5.loc[df5['competition_open_since_year'].isna(), 'competition_open_since_year'] = df5['date'].max().year
## competition_open_since_month
# assign the month of the latest date if NA
df5.loc[df5['competition_open_since_month'].isna(), 'competition_open_since_month'] = df5['date'].max().month
# promo2_since_week AND promo2_since_year
# in case of NA values the date of sale will be used -- the difference between these dates will be used later
## promo2_since_week
df5['promo2_since_week'] = df5[['date', 'promo2_since_week']].apply(lambda x: x['date'].week if np.isnan(x['promo2_since_week']) else x['promo2_since_week'], axis=1)
## promo2_since_year
df5['promo2_since_year'] = df5[['date', 'promo2_since_year']].apply(lambda x: x['date'].year if np.isnan(x['promo2_since_year']) else x['promo2_since_year'], axis=1)
## promo_interval: used to create a new column -> promo2_active
# filling in NA with 'none'
df5['promo_interval'].fillna(value='none', inplace=True)
# creating a column with current month
df5['curr_month'] = df5['date'].dt.strftime('%b')
## creating a column to indicate whether promo2 is active
df5['promo2_active'] = df5.apply(lambda x: 1 if ((
x['curr_month'] in x['promo_interval'].split(',')) and (
x['date'] >= datetime.fromisocalendar(int(x['promo2_since_year']), int(x['promo2_since_week']), 1)) and (
x['promo'] == 1)) else 0, axis=1)
## =-= Changing Data Types =-= ##
# Changing DTypes from float to integer
df5['competition_distance'] = df5['competition_distance'].astype(int)
df5['competition_open_since_month'] = df5['competition_open_since_month'].astype(int)
df5['competition_open_since_year'] = df5['competition_open_since_year'].astype(int)
df5['promo2_since_week'] = df5['promo2_since_week'].astype(int)
df5['promo2_since_year'] = df5['promo2_since_year'].astype(int)
```
### <font color='#2365FF'> 5.1.2. Feature Engineering </font>
```
## =-= Dates =-= ##
# year
df5['year'] = df5['date'].dt.year
# month
df5['month'] = df5['date'].dt.month
# day
df5['day'] = df5['date'].dt.day
# week_of_year
df5['week_of_year'] = df5['date'].dt.isocalendar().week.astype('int64')
# competition_months_old
# calculating the competition period, extracting the days and dividing by 30 to get the period in months
df5['competition_months_old'] = df5.apply(lambda x: (
x['date'] - datetime(year=x['competition_open_since_year'],
month=x['competition_open_since_month'],
day=1)).days / 30, axis=1).astype(int)
# assigning zero to negative values of competition_months_old
# in this case it makes no sense to work with the time that is left for the competitor to open
df5.loc[df5['competition_months_old'] < 0, 'competition_months_old'] = 0
# promo2_months_old
# calculation method: zero(0) if promo2 is zero(0) else (actual_date - promo2_starting_date) >> timedelta format
# >> then use .days and divide by 30 to extract the number of months >> as integer
df5['promo2_months_old'] = df5.apply(lambda x: 0 if x['promo2'] == 0 else (
x['date'] - datetime.fromisocalendar(x['promo2_since_year'],
x['promo2_since_week'],
1)).days / 30, axis=1).astype(int)
# assigning zero to negative values of promo2_months_old
# since the store is not yet participating (but will in the future)
df5.loc[df5['promo2_months_old'] < 0, 'promo2_months_old'] = 0
## =-= Filtering Features =-= ##
# eliminating all records where stores are closed
df5 = df5[(df5['open'] != 0) & (df5['sales'] > 0)]
# list of columns to be droped
cols_drop = ['customers', 'open', 'promo_interval', 'curr_month']
df5.drop(cols_drop, axis=1, inplace=True)
```
## <font color='#200CF'> 5.2. Feature Scaling - Standardization </font>
**Also called Z-score normalization. Standardization typically means rescales data to have a mean of 0 and a standard deviation of 1 (unit variance).**
<font color='firebrick'>**None of the features behavior is close to a Gaussian (normal) distribution, so standardization is not recommended.**</font>
## <font color='#200CF'> 5.3. Feature Scaling - Normalization </font>
**Normalization typically means rescales the values into a range of [0, 1] .**
**ROBUST SCALER**
Its use is indicated for cases where data have outliers. To overcome this, the median and interquartile range can be used to rescale numeric variables.
```
# rescaling with Robust Scaler
rs = RobustScaler()
# competition_distance
df5['competition_distance'] = rs.fit_transform(df5[['competition_distance']].values)
# pickle.dump(rs, open('../parameters/competition_distance_scaler.pkl', 'wb'))
# competition_months_old
df5['competition_months_old'] = rs.fit_transform(df5[['competition_months_old']].values)
# pickle.dump(rs, open('../parameters/competition_months_old_scaler.pkl', 'wb'))
```
**MIN-MAX SCALER**
```
# rescaling with Min-Max Scaler
mms = MinMaxScaler()
# promo2_months_old
df5['promo2_months_old'] = mms.fit_transform(df5[['promo2_months_old']].values)
# pickle.dump(mms, open('../parameters/promo2_months_old_scaler.pkl', 'wb'))
# year
df5['year'] = mms.fit_transform(df5[['year']].values)
# pickle.dump(mms, open('../parameters/year_scaler.pkl', 'wb'))
```
## <font color='#200CF'> 5.4. Feature Transformation </font>
### <font color='#2365FF'> 5.3.1. Encoding </font>
**Enconding: Transforming Categorical Features Into Numeric Features**
**ONE HOT ENCODING -- ORDINAL ENCODING -- LABEL ENCODING**
```
# state_holiday - One Hot Encoding
df5 = pd.get_dummies(df5, prefix=['st_hol'], columns=['state_holiday'])
# assortment - Ordinal Encoding
assortment_dict = {'a': 1, 'b': 2, 'c': 3}
df5['assortment'] = df5['assortment'].map(assortment_dict)
# store_type - Label Encoding
le = LabelEncoder()
df5['store_type'] = le.fit_transform(df5['store_type'])
# pickle.dump(le, open('../parameters/store_type_scaler.pkl', 'wb'))
```
### <font color='#2365FF'> 5.3.2. Nature Transformation </font>
```
# month
df5['month_sin'] = df5['month'].apply(lambda x: np.sin(x * (2. * np.pi / 12)))
df5['month_cos'] = df5['month'].apply(lambda x: np.cos(x * (2. * np.pi / 12)))
# day
df5['day_sin'] = df5['day'].apply(lambda x: np.sin(x * (2. * np.pi / 30)))
df5['day_cos'] = df5['day'].apply(lambda x: np.cos(x * (2. * np.pi / 30)))
# day_of_week
df5['day_of_week_sin'] = df5['day_of_week'].apply(lambda x: np.sin(x * (2. * np.pi / 7)))
df5['day_of_week_cos'] = df5['day_of_week'].apply(lambda x: np.cos(x * (2. * np.pi / 7)))
# week_of_year
df5['week_of_year_sin'] = df5['week_of_year'].apply(lambda x: np.sin(x * (2. * np.pi / 52)))
df5['week_of_year_cos'] = df5['week_of_year'].apply(lambda x: np.cos(x * (2. * np.pi / 52)))
```
### <font color='#2365FF'> 5.3.3. Response Variable Tranformation - Log Transform </font>
```
df5['sales'] = np.log1p(df5['sales'])
```
# <font color='#3F0094'> 6. Feature Selection </font>
## <font color='#200CF'> 6.0. Dataframe in Progress Backup </font>
```
df6 = df5.copy()
```
## <font color='#200CF'> 6.1. Dataframe Split into Training and Test Dataset </font>
```
# droping irrelevant and variables that were derived
cols_drop = ['month', 'day', 'day_of_week', 'week_of_year']
df6.drop(labels=cols_drop, axis=1, inplace=True)
# selecting the last 7 months as test dataset and all previous dates as train dataset
X_train = df6[df6['date'] < '2015-01-01']
y_train = X_train['sales']
X_test = df6[df6['date'] >= '2015-01-01']
y_test = X_test['sales']
```
## <font color='#200CF'> 6.2. Boruta as Feature Selector </font>
```
# train and test dataset for boruta
X_train_n = X_train.drop(labels=['date', 'sales'], axis=1).values
y_train_n = y_train.values.ravel()
# defining RandomForestRegressor
rf = RandomForestRegressor(n_jobs=-1)
# defining BorutaPy
boruta = BorutaPy(rf, n_estimators='auto', verbose=2, random_state=42).fit(X_train_n, y_train_n)
```
### <font color='#2365FF'> 6.2.1. Best Features from Boruta </font>
```
# all features except date and sales
X_train_fs = X_train.head(1).drop(['date', 'sales'], axis=1)
# features selected by boruta
cols_selected = boruta.support_.tolist()
cols_selected_names = X_train_fs.iloc[:, cols_selected].columns.tolist()
print(f"List of columns selected by Boruta:\n{', '.join(cols_selected_names)}.")
# features not selected by boruta
cols_rejected_boruta = list(np.setdiff1d(X_train_fs.columns, cols_selected_names))
print(f"\nList of columns rejected by Boruta:\n{', '.join(cols_rejected_boruta)}.")
```
## <font color='#200CF'> 6.3. Feature Selection - Final Decision </font>
```
# using boruta feature selection + adding month_sin
selected_features = [
'store', 'promo', 'store_type', 'assortment', 'competition_distance', 'competition_open_since_month',
'competition_open_since_year', 'promo2', 'promo2_since_week', 'promo2_since_year', 'competition_months_old',
'promo2_months_old', 'month_sin', 'month_cos', 'day_sin', 'day_cos', 'day_of_week_sin', 'day_of_week_cos',
'week_of_year_sin', 'week_of_year_cos']
# inserting 'date' and 'sales' back to the features list
selected_features.extend(['date', 'sales'])
```
# <font color='#3F0094'> 7. Machine Learning </font>
## <font color='#200CF'> 7.0. Dataframe Backup and Train/Test Split</font>
```
# selected features in the previous stage
selected_features = [
'store', 'promo', 'store_type', 'assortment', 'competition_distance', 'competition_open_since_month',
'competition_open_since_year', 'promo2', 'promo2_since_week', 'promo2_since_year', 'competition_months_old',
'promo2_months_old', 'month_sin', 'month_cos', 'day_sin', 'day_cos', 'day_of_week_sin', 'day_of_week_cos',
'week_of_year_sin', 'week_of_year_cos', 'date', 'sales']
# dataframe backup using selected features
df7 = df6[selected_features].copy()
# train/test split
# selecting the last 7 months as test dataset and all previous dates as train dataset
X_train = df7[df7['date'] < '2015-01-01']
y_train = X_train['sales']
X_test = df7[df7['date'] >= '2015-01-01']
y_test = X_test['sales']
# WARNING: Remember to drop 'date' and 'sales' columns from X_train and X_test before running models
X_train_ml = X_train.drop(labels=['date', 'sales'], axis=1)
X_test_ml = X_test.drop(labels=['date', 'sales'], axis=1)
```
## <font color='#200CF'> 7.1. Average Model </font>
```
# for this model it is fine to use date and sales from X_train and X_test
# using store and sales columns to compare actual values and predicted (average) values
aux1 = X_test[['store', 'sales']]
# using X_train dataset to calculate the average sales for each store
aux2 = X_train[['store', 'sales']].groupby('store').mean().reset_index().rename(columns={'sales': 'predictions'})
# aux1 = aux1.reset_index().merge(aux2, how='left', on='store', validate='many_to_one').set_index('index')
aux1 = aux1.merge(aux2, how='left', on='store', validate='many_to_one')
yhat_baseline = aux1['predictions']
# performance test
baseline_result = ml_error('Average Model', np.expm1(y_test), np.expm1(yhat_baseline))
baseline_result
```
## <font color='#200CF'> 7.2. Linear Regression Model </font>
```
# model
lr = LinearRegression().fit(X_train_ml, y_train)
# prediction
yhat_lr = lr.predict(X_test_ml)
# performance test
lr_result = ml_error('Linear Regression', np.expm1(y_test), np.expm1(yhat_lr))
lr_result
```
## <font color='#200CF'> 7.3. Linear Regression Regularized (Lasso) Model </font>
```
# model
lrr = Lasso(alpha=0.001).fit(X_train_ml, y_train)
# prediction
yhat_lrr = lrr.predict(X_test_ml)
# performance test
lrr_result = ml_error('Linear Regression - Lasso', np.expm1(y_test), np.expm1(yhat_lrr))
lrr_result
```
## <font color='#200CF'> 7.4. Random Forest Regressor </font>
```
# model
rf = RandomForestRegressor(n_estimators=200, n_jobs=-1, random_state=42).fit(X_train_ml, y_train)
# prediction
yhat_rf = rf.predict(X_test_ml)
# performance test
rf_result = ml_error('Random Forest Regressor', np.expm1(y_test), np.expm1(yhat_rf))
rf_result
```
## <font color='#200CF'> 7.5. XGBoost Regressor </font>
```
# model
xgb_model = xgb.XGBRegressor(objective='reg:squarederror',
n_estimators=500,
eta=0.1,
max_depth=7,
subsample=0.7,
colsample_bytree=0.7,
tree_method='gpu_hist').fit(X_train_ml, y_train)
# prediction
yhat_xgb = xgb_model.predict(X_test_ml)
# performance test
xgb_result = ml_error('XGBoost Regressor', np.expm1(y_test), np.expm1(yhat_xgb))
xgb_result
```
## <font color='#200CF'> 7.6. Comparison of Models Performance </font>
```
single_performance = pd.concat([baseline_result, lr_result, lrr_result, rf_result, xgb_result])
single_performance.sort_values(by='RMSE', inplace=True)
# single_performance.to_csv('../ml_models_performances/single_performance.csv', index=False)
single_performance.reset_index(drop=True)
```
## <font color='#200CF'> 7.7. Cross-Validation </font>
### <font color='#2365FF'> 7.7.1. Linear Regression - Cross Validation </font>
```
model = LinearRegression()
lr_result_cv = cross_validation(X_train, kfold=8, model_name='Linear Regression', ml_model=model, verbose=False)
```
### <font color='#2365FF'> 7.7.2. Linear Regression Regularized (Lasso) - Cross Validation </font>
```
model = Lasso(alpha=0.001)
lasso_result_cv = cross_validation(X_train, kfold=8, model_name='Lasso', ml_model=model, verbose=False)
```
### <font color='#2365FF'> 7.7.3. Random Forest Regressor - Cross Validation </font>
```
model = RandomForestRegressor(n_estimators=200,
n_jobs=-1,
random_state=42).fit(X_train_ml, y_train)
rf_result_cv = cross_validation(X_train, kfold=8, model_name='Random Forest Regressor', ml_model=model, verbose=True)
```
### <font color='#2365FF'> 7.7.4. XGBoost Regressor - Cross Validation </font>
```
model = xgb.XGBRegressor(objective='reg:squarederror',
n_estimators=500,
eta=0.1,
max_depth=7,
subsample=0.7,
colsample_bytree=0.7,
tree_method='gpu_hist').fit(X_train_ml, y_train)
xgb_result_cv = cross_validation(X_train, kfold=8, model_name='XGBoost Regressor', ml_model=model, verbose=True)
```
## <font color='#200CF'> 7.8. Comparison of Models Performance w/ Cross Validation </font>
```
cv_performance = pd.concat([lr_result_cv, lasso_result_cv, rf_result_cv, xgb_result_cv])
cv_performance.sort_values(by='RMSE CV', inplace=True)
# cv_performance.to_csv('../ml_models_performances/cross_validation_performance.csv', index=False)
cv_performance.reset_index(drop=True)
```
# <font color='#3F0094'> 8. Hyperparameter Fine Tuning </font>
## <font color='#200CF'> 8.0. Dataframe Backup and Train/Test Split </font>
```
# copy of dataframe -- using selected features only
df8 = df7.copy()
# train/test split
# selecting the last 7 weeks as test dataset and all previous dates as train dataset
X_train = df8[df8['date'] < '2015-06-12']
y_train = X_train['sales']
X_test = df8[df8['date'] >= '2015-06-12']
y_test = X_test['sales']
# WARNING: Remember to drop 'date' and 'sales' columns from X_train and X_test before running models
X_train_ml = X_train.drop(labels=['date', 'sales'], axis=1)
X_test_ml = X_test.drop(labels=['date', 'sales'], axis=1)
```
## <font color='#200CF'> 8.1. Random Search </font>
```
# implementing hyperparameter random search
# xgb model hyperparameters to be evaluated
params = {
'n_estimators': [1500, 2000, 2500, 2700, 3000],
'eta': [0.07, 0.1, 0.12, 0.15],
'max_depth': [5, 8, 10],
'subsample': [0.3, 0.5, 0.7],
'colsample_bytree': [0.3, 0.5, 0.7],
'min_child_weight': [3, 5, 10]
}
# max number of iterations
MAX_EVAL = 6
# to keep the error measures of each set of hyperparamenters
random_search_results = pd.DataFrame()
for i in range(MAX_EVAL):
# randomly choose among all possible hyperparameters
hp = {k: np.random.choice(v, size=1)[0] for k, v in params.items()}
print(hp)
# setting up model with random hyperparameters
xgb_model = xgb.XGBRegressor(objective='reg:squarederror',
n_estimators=hp['n_estimators'],
eta=hp['eta'],
max_depth=hp['max_depth'],
min_child_weight=hp['min_child_weight'],
subsample=hp['subsample'],
colsample_bytree=hp['colsample_bytree'],
tree_method='gpu_hist')
# performance test
result = cross_validation(X_train, kfold=8, model_name='XGBoost Regressor', ml_model=xgb_model, verbose=True)
# storing performance result in dataframe
random_search_results = pd.concat([random_search_results, result])
# random_search_results for hp fine tuning performances
random_search_results.reset_index(drop=True)
```
## <font color='#200CF'> 8.2. Final Model </font>
```
# best performance params for the lowest model size -> 12MB
param_tuned = {'n_estimators': 3000, 'eta': 0.07, 'max_depth': 5,
'subsample': 0.5, 'colsample_bytree': 0.7, 'min_child_weight': 3}
# model with tuned hyperparameters
xgb_model_tuned = xgb.XGBRegressor(objective='reg:squarederror',
n_estimators=param_tuned['n_estimators'],
eta=param_tuned['eta'],
max_depth=param_tuned['max_depth'],
min_child_weight=param_tuned['min_child_weight'],
subsample=param_tuned['subsample'],
colsample_bytree=param_tuned['colsample_bytree'],
tree_method='gpu_hist').fit(X_train_ml, y_train)
# prediction
yhat_xgb_tuned = xgb_model_tuned.predict(X_test_ml)
# performance
result_xgb_tuned = ml_error('XGBoost Regressor', np.expm1(y_test), np.expm1(yhat_xgb_tuned))
# saving model to be loaded in case of future use
# # saving model as json file
# xgb_model_tuned.save_model('../ml_model_tuned/xgb_model_tuned.json')
# # saving model as pickle file
# pickle.dump(xgb_model_tuned, open('../ml_model_tuned/xgb_model_tuned.pkl', 'wb'))
# ml model with alternative hyperparameters
# result_xgb_tuned.to_csv('../ml_models_performances/xgb_tuned_performance_on_test.csv', index=False)
result_xgb_tuned
```
# <font color='#3F0094'> 9. Error Interpretation </font>
## <font color='#200CF'> 9.0. Dataframe Backup and Rescale </font>
```
df9 = X_test.copy()
# rescaling sales and predictions
df9['sales'] = np.expm1(df9['sales'])
df9['predictions'] = np.expm1(yhat_xgb_tuned).astype('float')
```
## <font color='#200CF'> 9.1. Business Performance </font>
```
# calculate mean of sales
df91 = df9[['store', 'predictions']].groupby('store').agg(['sum', 'count']).reset_index().droplevel(level=0, axis=1)
df91.columns = ['store', 'predictions', 'count']
# MAE and MAPE
df9_mae = df9[['store', 'sales', 'predictions']].groupby('store').apply(
lambda x: mean_absolute_error(x['sales'], x['predictions'])).reset_index().rename(columns={0: 'MAE_1'})
df9_mape = df9[['store', 'sales', 'predictions']].groupby('store').apply(
lambda x: mean_absolute_percentage_error(x['sales'], x['predictions']) * 100).reset_index().rename(columns={0: 'MAPE %'})
# merge MAE_1
df91 = pd.merge(df91, df9_mae, how='left', on='store')
# multiply MAE_1 by the number of days open
df91['MAE'] = df91['count'] * df91['MAE_1']
# merge MAPE
df91 = pd.merge(df91, df9_mape, how='left', on='store')
# drop columns used to calculate total MAE
df91.drop(labels=['count', 'MAE_1'], axis=1, inplace=True)
# best and worst scenarios of sales
df91['worst_scenario'] = df91['predictions'] - df91['MAE']
df91['best_scenario'] = df91['predictions'] + df91['MAE']
# re-organize columns order
df91 = df91[['store', 'predictions', 'worst_scenario', 'best_scenario', 'MAE', 'MAPE %']].round(2)
# check predictions performance
df91.describe().T
# visually check the predictions erros
plt.figure(figsize=(20, 8))
plt.title('MAPE(%)-Error by Store No.', fontsize=20, pad =10)
sns.scatterplot(x='store', y='MAPE %', data=df91)
plt.xlabel('Store')
# plt.savefig('../img/error_mape_by_store.png')
plt.show()
# check worst predicitions
df91.sort_values(by='MAPE %', ascending=False).head(10)
```
## <font color='#200CF'> 9.2. Total Performance </font>
```
df92 = df91[['predictions', 'worst_scenario', 'best_scenario']].sum().reset_index().rename(columns={'index': 'Scenario', 0: 'Values'})
df92['Values'] = df92['Values'].map('$ {:,.2f}'.format)
df92
```
## <font color='#200CF'> 9.3. Machine Learning Performance </font>
```
df9['error'] = df9['sales'] - df9['predictions']
df9['error_rate'] = df9['predictions'] / df9['sales']
plt.figure(figsize=(22, 18))
plt.suptitle('Erros Analysis')
plt.subplot(2, 2, 1)
sns.lineplot(x='date', y='sales', data=df9, label='Sales')
sns.lineplot(x='date', y='predictions', data=df9, label='Predictions')
plt.xlabel('')
plt.ylabel('')
plt.xticks(fontsize=13)
plt.subplot(2, 2, 2)
sns.lineplot(x='date', y='error_rate', data=df9, label='Error Rate')
plt.axhline(y=1, ls='--', c='y')
plt.xlabel('')
plt.ylabel('')
plt.xticks(fontsize=13)
plt.subplot(2, 2, 3)
sns.histplot(x='error', data=df9, stat='proportion', bins=80, kde=True)
plt.subplot(2, 2, 4)
sns.scatterplot(x='predictions', y='error', data=df9)
# plt.savefig('../img/error_analysis.png')
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/Sharaborina/ChatBot/blob/main/Main_ChatBot_project.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!pip uninstall -y spacy --quiet
!pip install python-telegram-bot nltk geopy dateparser datefinder spacy deep_translator detectlanguage geotext
!python -m spacy download en_core_web_lg >out 2>log
!python -m spacy download da_core_news_lg >out 2>log
from google.colab import drive
drive.mount('/content/drive')
from telegram.ext import *
import telegram
import random
import pandas as pd
import requests
import geopy
import torch
import re
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from geopy.geocoders import Nominatim
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
#for intention classification
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
#telegram bot logging/debugging
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#for date analyser
# from date_extractor import extract_dates
import dateparser #text to date
from datetime import timedelta
from datetime import datetime
import datefinder
#for geo extraction
from geotext import GeoText #only in English
# NLU
import nltk
import spacy
# translate replicas
from deep_translator import GoogleTranslator, single_detection
# detect language
# import detectlanguage
import itertools
#bot token
BOT_KEY = '1880919831:AAEJFa4yGm57IKr68qXEHYS7t1nS_LnX8iw'
NER_MODEL_DIR='/content/drive/MyDrive/ColabNotebooks/Spacy_NER_Model'
GENERATIVE_MODEL_DIR='/content/drive/MyDrive/ColabNotebooks/Generative_model'
# data directory
DATA_DIR = '/content/drive/MyDrive/ColabNotebooks/MultiWoz/'
# vocabulary filename
VOCAB_FILE = 'en_50k_pruned.subword'
# vocabulary file directory
VOCAB_DIR = '/content/drive/MyDrive/ColabNotebooks/MultiWoz/'
VOCAB_SIZE = 50000
# load a cleaned translated train data from file DATA_DIR/TRAIN_FILENAME,
# otherwise generate a train data from DIALOGUE_ENG_DB
LOAD_TRAIN_DATA = False
# train filename
TRAIN_FILENAME = 'label_and_train_data.json'
# path to pretrained NER_model
NER_MODEL_DIR = '/content/drive/MyDrive/ColabNotebooks/Spacy_NER_Model'
GENERATIVE_MODEL_SH = '/content/drive/MyDrive/ColabNotebooks/Generative_model_Sharaborina_state_dict.pt'
USE_PRETRAINED_MODEL = True #use pretrained model, otherwise start from a blank model
LOAD_MODEL = True #load pretrained model
TRAIN = True
N_LAYERS = 6
TRAIN_STEPS = 100
```
# Booking API
First let's create a `geoloc` function to find out latitude and longitude of a city/town/village, etc. Because Booking API works only with such coordinates.
```
def geoloc(city):
geolocator = Nominatim(user_agent= 'sharaborinaly')
location = geolocator.geocode(city)
result = str(location.latitude-0.3)+'%2C'+str(location.latitude+0.3)+'%2C'+str(location.longitude-0.3)+'%2C'+str(location.longitude+0.3)
return result
```
`booking_request` function gives us scraped data from the booking site. It takes required fileds: the name of city, arrival and departure dates, the number of guests.
Also there is not mandatory fields: the number of children, number of rooms, number of guests
```
def booking_request(city, dates = None, rooms = 1, guest = 1, children = 0):
dates = sorted(dates)
arrival_date = str(dates[0].date())
departure_date = str(dates[1].date())
if arrival_date == None or departure_date == None:
arrival_date = datetime.today()
departure_date = arrival_date + 1
list_by_map_url = "https://apidojo-booking-v1.p.rapidapi.com/properties/list-by-map"
list_by_map_querystring = {
"search_id":"none",
"children_age":"",
"price_filter_currencycode":"EUR",
"languagecode":"da",
"travel_purpose":"leisure",
"categories_filter":"class%3A%3A1%2Cclass%3A%3A2%2Cclass%3A%3A3",
"children_qty":children,
"order_by":"popularity",
"guest_qty": guest,
"room_qty": rooms,
"departure_date": departure_date,
"bbox":"",
"arrival_date": arrival_date
}
list_by_map_querystring['bbox'] = geoloc(city)
list_by_map_headers = {
'x-rapidapi-host': "apidojo-booking-v1.p.rapidapi.com",
'x-rapidapi-key': "54d78e5c98mshd2b3a25b4adf763p1674f2jsnb7535d954daf"
}
list_by_map_response = requests.request("GET", list_by_map_url, headers=list_by_map_headers, params=list_by_map_querystring).json()
result = []
# prdic(list_by_map_response['result'])
try:
for list_result in list_by_map_response['result']:
result.append({'hotel_id': list_result['hotel_id'],
'hotel_name': list_result['hotel_name'],
'url':list_result['url'],
'main_photo_url' : list_result['main_photo_url'],
'min_total_price': list_result['min_total_price'],
'address': list_result['address'],
'review_score': list_result['review_score'],
'currencycode' : list_result['currencycode']
})
except:
pass
if len(result) == 0:
return 'Undskyld! Jeg kan ikke finde hoteller til de givne datoer. Prøv venligst andre datoer.'
elif len(result) <= 5:
return result
else:
return result[:5]
# !pip install print_dict
# from print_dict import pd as prdic
# # Let's check the output
booking_request('Moskva', [datetime.today(), datetime.today() + timedelta(days=3)])
```
# Intention classifier
Here let's build a simple classifier of an input phrase.
But first let us create BOT_CONFIG - it is a dictionary with intents, which have their phrase examples and some prepared answers.
We will classify an input phrase by intent, and if there will be returned some intent, the algorithm will use a prepared response. If not - a failure phrase will be used.
```
BOT_CONFIG = {
'intents':{
'hello':{'examples': ['hej', 'dav', 'hi', 'hello', 'goddag','hej bot', 'dav bot', 'hi bot', 'hello bot', 'goddag bot', 'hej du'], 'responses': ['Hej! Hvordan kan jeg hjælpe dig?', 'Goddag! Hvordan kan jeg hjælpe dig?', 'Hey! Welcome! Hvordan kan jeg hjælpe dig?']},
'bye':{'examples': ['hej-hej', 'bye', 'ha en god dag', 'bye bot', 'tak hav en god dag', ' hav en god dag', 'ha det godt', 'bye-bye'], 'responses': ['Jeg håber du vil have en vidunderlig dag!','Jeg hjælper gerne. Hav en god dag!','Hej-hej!', 'Hav en rigtig god dag!', 'Farvel og tak!', 'Farvel!']},
'name':{'examples': ['hvordan hedder du', 'hvad hedder du', 'hvad er dit navn', 'dit navn', 'fortæl mig dit navn', 'fortæl dit navn'],
'responses': ['Jeg hedder AirbnbBot, jeg kan hjælpe dig med at reservere et hotelværelse. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse', 'Jeg er AirbnbBot, jeg kan reservere et hotelværelse til dig. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse']},
'sorry': {'examples': ['undskyld', 'det må du undskyld', 'med fejl', 'min fejl', 'det er med fejl', 'det er min fejl', 'undskyld bot', 'oh undskyld', 'undskyld for det'], 'responses': ['Det er helt i orden', 'Det er i orden', 'Du behøver ikke at undskylde dig']},
'help': {'examples': ['jeg vil book et billigt hotel med parkering', 'vi leder efter et hotel med parkering', 'vil have et hotel med parkering', 'vil book et hotel med parkering','jeg vil book et hotel med parkering', 'jeg leder efter et billigt hotel', 'jeg leder efter et hotel med parkering', 'jeg har brug for et hotel', 'jeg leder efter et hotel i københavn','jeg leder efter et hotel i buenos aires',
'jeg leder efter et hotel i new york','jeg leder efter et hotel i moskva','jeg vil book et hotel i amsterdam', 'jeg vil book et hotel i buenos aires', 'jeg vil book et hotel i bangkok','jeg vil book et hotel i luxenburg', 'jeg vil book et hotel i københavn','jeg vil book et hotel','kan du book et hotel til mig', 'kan du booke hotel', 'jeg har også brug for at finde et sted at bo',
'jeg leder efter et gæstehus i centrum af byen', 'jeg har brug for et sted at bo syd for byen', 'jeg leder efter oplysninger om et hotel i','kan du venligst hjælpe mig med at finde et sted at bo','jeg leder efter et hotel at bo på i centrum, kan du slå dette op for mig','jeg leder efter et bestemt hotel','jeg leder efter et sted at bo, der har en stjerne på ','jeg leder efter informationom hoteler i',
'jeg leder efter et hotel i ','venligst book et hotel','jeg har brug for et sted at bo','kan du hjælpe dig med noget','jeg kunne ikke booke et hotel','jeg vil booke et hotel','jeg er på udkig efter et sted at bo','jeg vil reservere et hotel', 'reserver et hotelværelse i', 'kan du reservere et hotel', 'kan du reservere et hotelværelse', 'kan du reservere et hotelværelse for mig', 'kan du hjælpe mig', 'kan du hjælpe mig med at reservere',
'jeg har brug for hjælp', 'jeg har brug for din hjælp', 'hjælp mig med det'],
'responses': ['Jeg vil gerne hjælpe dig. Jeg kan reservere et hotelværelse til dig. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse', 'Jeg vil gerne reservere et hotelværelse til dig. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse']},
'answer': {'examples': ['jeg planlægger en tur til','jeg skal rejse til', 'jeg skal til', 'jeg skal til d og tilbage d', 'jeg skal til d', 'vi skal til', 'vi vil rejse til', 'vi skal rejse til'],
'responses': ['Det er fint, tak! Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse til dig.']},
'bad words':{'examples': ['bland dig udenom', 'hold kæft', 'hold kæft bot','din kælling', 'dit røvhul', 'for fanden', 'for fanden bot', 'for helvede'], 'responses': ['Du skal ikke sværge her. Jeg er en anstændig bot.', 'Vær så venlig ikke at sværge. Jeg er en anstændig bot.']},
'how are you':{'examples': ['er det i orden', 'hvordan går det', 'hvordan går det med dig', 'hvordan har du det', 'hvordan fyler du dig'],
'responses': ['Det går meget dodt, tak! Jeg er klar til at hjælpe dig med at reservere et hotelværelse. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse', 'Jeg har det godt, tak! Jeg er klar til at hjælpe dig med at reservere et hotel værelse. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse',
'Godt, mange tak! Jeg vil gerne hjælpe dig med at reservere et hotel værelse. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotelværelse']},
'thanks':{'examples': ['tak for hjælpen', 'okey mange tak','okej tak','okay tak','det er det tak','tak det er alt', 'tak for din hjælp', 'tak', 'mange tak', 'det ville være alt tak'], 'responses': ['Jeg er glad for, at jeg var i stand til at hjælpe','Du er velkommen. Tak!', 'Tak! Glad for at kunne hjælpe', 'Du er meget velkommen!']},
},
'failure_phrase': ['Undskyld, jeg kan ikke forstår det. Kan du skrive det igen? Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotel til dig.', 'Undskyld, jeg studerer bare at arbejde som bot og jeg kan ikke forstår nogle ting. Kan du venligst give mig følgende information: en by, en ankomsttid, en afgangstid. Og jeg vil finde et hotel til dig.']
}
```
Then we construct a long vector of input data (`X_text`) and corresponding output (`y`).
```
X_text = []
y = []
for intent, intent_data in BOT_CONFIG['intents'].items():
for example in intent_data['examples']:
X_text.append(example)
y.append(intent)
```
Vectorization from a text to a number vector. For each word, the algorithm constructs a column in a matrix (by default `analyzer='word'`).
But the experiments shows that n-gram method works better. Let's take 3-gram method. For example, `'Hello, world'` gives a list of subwords (3-grams)
`['Hel', 'ell', 'llo', 'wor', 'orl', 'rld']`
```
# vectorizer = CountVectorizer()
# vectorizer = TfidfVectorizer()
vectorizer = CountVectorizer(analyzer='char', ngram_range=(3,3))
# vectorizer = TfidfVectorizer(analyzer='char', ngram_range=(3,3))
X = vectorizer.fit_transform(X_text)
#let's shuffle before splitting into validational and
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
```
Let's use Linear classifier `LogisticRegression`
```
#training of the model
# clf = LogisticRegression(random_state = 0)
clf = LinearSVC(random_state = 0)
clf.fit(X,y)
#predict function
def classification(rep):
prediction = clf.predict(vectorizer.transform([rep]))
# print(prediction)
return prediction[0]
# Estimation of quality
from sklearn.metrics import precision_score
y_pred = clf.predict(X_test)
precision_score(y_test, y_pred, average='micro')
# clf.score(X_test, y_test)
#Let's check
classification('hej kan du hjæelpe mig'), classification('bvvvvvvvv')
```
Let us preprocess a input phrase - it is needed to transform it to lower case and remove sybmols
```
def clear(rep):
rep = rep.lower()
alphabet = '0123456789abcdefghijklmnopqrstuvwxyzåøæ- '
result = ''.join(symbol for symbol in rep if symbol in alphabet)
return result
def get_failure_phrase():
return random.choice(BOT_CONFIG['failure_phrase'])
def too_many_enity_failure_phrase():
answer = 'Du har skrevet mere oplystninger end det var nødvendigt. Vær så venlig at give mig disse oplystninger: en by, en ankomsttid, en afgangstid.'
return answer
```
And it is also necessary to add calculation of the Levenshtein edit-distance between two strings. It will help to take attention to small mistakes.
```
def classify_intent(rep):
rep = clear(rep)
intent = classification(rep) # classification algorithm always gives us an intention
# here we check the distance between answers of the intent and a user's replica
for intent, intent_data in BOT_CONFIG['intents'].items():
for example in intent_data['examples']:
example = clear(example)
distance = nltk.edit_distance(rep, example)
if example and distance/ len(example) < 0.45:
return intent
```
And if intent is returned by the function, the chatbot uses some prepared answers (by intent)
```
def get_answer_by_intent(intent):
if intent in BOT_CONFIG['intents']:
responses = BOT_CONFIG['intents'][intent]['responses']
if responses:
return random.choice(responses)
```
## Development of NER functionality
Let's load a model which is based on a Spacy model and trained on **MultiWoZ** dataset, especially on the hotel related dialogues.
```
#load the model
nlp = spacy.load(NER_MODEL_DIR)
# nlp = spacy.load('en_core_web_lg')
# nlp = spacy.load('da_core_news_lg')
ner = nlp.get_pipe('ner')
```
Let us create functions, which will help to identify date and location.
It can be difficult to identify location only on danish dataset, so I made a translation of danish text into English and used built-in function GeoText.
```
# Utility functions to get and print output entities
def get_ents(nlp, text):
docx = nlp(text)
out = []
for token in docx.ents:
out.append((token.text, token.start_char, token.end_char,token.label_))
return out
def print_ents(nlp, text):
docx = nlp(text)
for token in docx.ents:
print("text:{}, start:{}, end:{}, label:{}".format(token.text,token.start_char, token.end_char,token.label_))
# Translate text
def translate(text, target='en'):
if type(text) == list:
out = []
for t in text:
# print(t)
out.append(GoogleTranslator(source='auto', target=target).translate(t))
return out
return GoogleTranslator(source='auto', target=target).translate(text)
# Date extracting function
def extract_date(user_message, ents):
dates = []
for ent in ents:
if ent[3] == 'DATE':
parsed = dateparser.parse(ent[0])
if parsed:
dates.append(parsed)
# try to translate the message to english and use parser
translated_user_message = translate(user_message, target='en')
chars = "\|/`*_{}[]()>#+-.,:;!$"
for c in chars:
translated_user_message = translated_user_message.replace(c, ' to ')
# print(translated_user_message)
# a generator will be returned by the datefinder module.
# I'm typecasting it to a list.
matches = list(datefinder.find_dates(translated_user_message))
dates += matches
# print(str(dates[0].date()))
return sorted(dates)
#translate text to english and extract cities then return to source language
def extract_loc (src_text, ents=None):
eng_text = translate(src_text, target='en')
eng_places = GeoText(eng_text)
# print(eng_places)
places = translate(eng_places.cities, target='da')
if ents:
for ent in ents:
if ent[3] == 'GPE' or ent[3] == 'LOC':
places.append(ent[0])
# print(places.cities)
return list(set(places))
# test
print('entities: ', get_ents(nlp, "Jeg elsker Paris, men jeg kan ikke lide Frankfurt. 5. januar skal jeg besøge. december 8skal jeg besøge"))
s = 'Jeg elsker Paris, men jeg kan ikke lide Frankfurt. 5. januar skal jeg besøge.'
ents = get_ents(nlp, s)
print(extract_date(s, ents ), ents)
print(extract_loc(s, ents ), ents)
# print_ents(nlp, "Har du mulighed at finde et København?")
```
## Development of a generative model
```
class CharRNN(nn.Module):
def __init__(self, tokens, n_hidden=256, n_layers=2,
drop_prob=0.5, lr=0.001):
super().__init__()
self.drop_prob = drop_prob
self.n_layers = n_layers
self.n_hidden = n_hidden
self.lr = lr
self.vocab_size = len(tokens)
self.input_dim = n_hidden
self.output_size = len(tokens)
self.embedding = nn.Embedding(self.vocab_size, self.vocab_size)
# creating character dictionaries
self.chars = tokens
self.int2char = dict(enumerate(self.chars))
self.char2int = {ch: ii for ii, ch in self.int2char.items()}
# Define the LSTM layer
self.lstm = lstm_layer = nn.LSTM(self.input_dim, n_hidden, n_layers, dropout=drop_prob, batch_first=True)
# Define a dropout layer
self.dropout = nn.Dropout(drop_prob)
self.rnn = getattr(nn, 'LSTM')(len(self.chars), n_hidden, n_layers, dropout=drop_prob, batch_first=True)
# Define the final, fully-connected output layer
self.fc = nn.Linear(self.n_hidden, self.output_size)
self.sigmoid = nn.Sigmoid()
self.decoder = nn.Linear(n_hidden, len(self.chars))
self.init_weights()
self.cuda()
def forward(self, x, hidden):
''' Forward pass through the network '''
x, h = self.rnn(x, hidden)
x = self.dropout(x)
# x = x.view(x.size(0)*x.size(1), self.n_hidden)
x = x.reshape(x.size(0)*x.size(1), self.n_hidden)
x = self.decoder(x)
return x, h
def init_hidden(self, batch_size):
''' Initializes hidden state '''
# Create two new tensors with sizes n_layers x batch_size x n_hidden,
# initialized to zero, for hidden state and cell state of LSTM
weight = next(self.parameters()).data
if (train_on_gpu):
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(),
weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(),
weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden
def init_weights(self):
''' Initialize weights of decoder (fully connected layer) '''
# Apply bias tensor to all zeros
self.decoder.bias.data.fill_(0)
# Apply random uniform weights to decoder
self.decoder.weight.data.uniform_(-1, 1)
def one_hot_encode(arr, n_labels):
# Initialize the the encoded array
one_hot = np.zeros((np.multiply(*arr.shape), n_labels), dtype=np.float32)
# Fill the appropriate elements with ones
one_hot[np.arange(one_hot.shape[0]), arr.flatten()] = 1.
# Finally reshape it to get back to the original array
one_hot = one_hot.reshape((*arr.shape, n_labels))
return one_hot
import json
def load_json(directory, file):
with open(f'{directory}/{file}') as f:
db = json.load(f)
return db
def upload_json(directory, file, db):
with open(f'{directory}/{file}', mode='w') as f:
json.dump(db,f)
chars = load_json('/content/drive/MyDrive/ColabNotebooks/MultiWoz', 'chars.txt')
# Set model hyperparameters
n_hidden = 256
n_layers = 5
# check if GPU is available
train_on_gpu = torch.cuda.is_available()
if(train_on_gpu):
print('Training on GPU')
else:
print('No GPU available, training on CPU; consider making n_epochs very small.')
net = CharRNN(chars, n_hidden, n_layers)
print(net)
net.load_state_dict(torch.load(GENERATIVE_MODEL_SH))
net.eval()
def predict(net, char, h=None, top_k=None):
''' Given a character, predict the next character.
Returns the predicted character and the hidden state.
'''
# tensor inputs
x = np.array([[net.char2int[char]]])
x = one_hot_encode(x, len(net.chars))
inputs = torch.from_numpy(x)
if(train_on_gpu):
inputs = inputs.cuda()
# detach hidden state from history
h = tuple([each.data for each in h])
# get the output of the model
out, h = net(inputs, h)
# get the character probabilities
p = F.softmax(out, dim=1).data
if(train_on_gpu):
p = p.cpu() # move to cpu
# get top characters
if top_k is None:
top_ch = np.arange(len(net.chars))
else:
p, top_ch = p.topk(top_k)
top_ch = top_ch.numpy().squeeze()
# select the likely next character with some element of randomness
p = p.numpy().squeeze()
char = np.random.choice(top_ch, p=p/p.sum())
# return the encoded value of the predicted char and the hidden state
return net.int2char[char], h
def sample(net, size = 500, prime='The', top_k=None):
if(train_on_gpu):
net.cuda()
else:
net.cpu()
net.eval() # eval mode
# First off, run through the prime characters
chars = [ch for ch in prime]
h = net.init_hidden(1)
for ch in prime:
char, h = predict(net, ch, h, top_k=top_k)
chars.append(char)
# Now pass in the previous character and get a new one
for ii in range(size):
char, h = predict(net, chars[-1], h, top_k=top_k)
chars.append(char)
answer = ''.join(chars)
# print(answer)
a = re.search(r'\b(Person 2)\b', answer)
slice1 = a.start() + 9
answer = answer[slice1:]
# print(answer)
try:
b = re.search(r'\b(Person 1)\b', answer)
slice2 = b.start()
# print(answer, answer[slice1 : slice2])
return answer[: slice2]
except:
return answer
def generate_answer(replica):
return sample(net, size = 500, prime = replica, top_k=3)
print(sample(net, 300, prime= 'Jeg skal finde er restaurant til at spise', top_k=5))
```
# ChatBot response function
```
context_dict ={} # {chat_id:{'text':[], 'dates':[], 'locs':[], 'last_session':datetime() }}
def clear_context_dict(chat_id):
return {'text':[], 'dates':[], 'locs':[], 'ents':[], 'last_session': datetime.today(), 'failure_qty':0 }
def bot_responses(input_text, update, chat_id):
# store all messages in context_dict
context_dict.setdefault(chat_id, clear_context_dict(chat_id))
context_dict[chat_id]['text'].append(update.message.text)
# NER and add new entitie to entity_dict
ents = get_ents(nlp, input_text)
dates = extract_date(input_text, ents)
locations = extract_loc (input_text, ents)
context_dict[chat_id]['ents'] += ents
context_dict[chat_id]['dates'] += dates
context_dict[chat_id]['locs'] += locations
#Check last session
if datetime.today() - context_dict[chat_id]['last_session'] > timedelta( hours=20):
context_dict[chat_id] = clear_context_dict(chat_id)
# remove copies
context_dict[chat_id]['locs'] = list(set(context_dict[chat_id]['locs']))
context_dict[chat_id]['dates'] = list(set(context_dict[chat_id]['dates']))
print('context_dict:', context_dict)
entities_qty = len(context_dict[chat_id]['locs']) + len(context_dict[chat_id]['dates'])
if entities_qty > 3:
context_dict[chat_id] = clear_context_dict(chat_id)
# context_dict[chat_id]['failure_qty'] += 1
return too_many_enity_failure_phrase()
# booking API
elif entities_qty == 3:
if len(context_dict[chat_id]['locs'])==1 and len(context_dict[chat_id]['dates'])==2:
city = context_dict[chat_id]['locs'][-1]
dates_travel = context_dict[chat_id]['dates']
context_dict[chat_id] = clear_context_dict(chat_id)
return booking_request(city, dates_travel)
else:
context_dict[chat_id] = clear_context_dict(chat_id)
context_dict[chat_id]['failure_qty'] += 1
return too_many_enity_failure_phrase()
# generate answer
elif context_dict[chat_id]['failure_qty'] >= 3:
# Using generative model
# answer = generate_answer(user_message)
# if answer:
# return answer + user_message + out_text
return generate_answer(input_text)
else:
# NLU
user_message = clear(input_text)
intent = classify_intent(user_message)
# print(intent)
# Answer generation - choose an answer
if intent:
answer = get_answer_by_intent(intent)
if answer:
return answer
# failure answer if bot doesn't catch a user
context_dict[chat_id]['failure_qty'] += 1
return get_failure_phrase()
```
## ChatBot commands
```
def start_command(update, context):
update.message.reply_text('Jeg er AirBnb Bot, jeg kan hjælpe dig med at finde et hotel i alle lande. Skriv noget til at begynde!')
def help_command(update, context):
update.message.reply_text('Hvis du har brugt for hjælp, kan du ringe til +1222-345-6789')
def handle_message(update, context):
chat_id = update.message.chat_id
print(update, context)
print(update.message, context)
text = str(update.message.text)
response = bot_responses(text, update, chat_id)
print(response)
if type(response) == list:
update.message.reply_text('Her kan du se flere hoteller, der måske passer dig! Hav en rigtig god dag!')
for elem in response:
text=elem['hotel_name'] + ' (Bedømmelse: ' + str(elem['review_score']) + ') minimumspris=' + str(elem['min_total_price']) + ' ' + elem['currencycode']
update.message.reply_text(text,
reply_markup = telegram.InlineKeyboardMarkup([
[telegram.InlineKeyboardButton(text='link', url=elem['url'])],
]))
# update.message.send_photo(chat_id=chat_id,
# photo=elem['main_photo_url']
# )
else:
update.message.reply_text(response)
def error(update, context):
print(f'Update {update} caused error {context.error}')
def main():
updater = Updater(BOT_KEY, use_context = True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start_command))
dp.add_handler(CommandHandler('help', help_command))
dp.add_handler(MessageHandler(Filters.text, handle_message))
dp.add_error_handler(error)
updater.start_polling()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
updater.idle()
```
# Call the ChatBot
```
main()
```
| github_jupyter |

[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/5.3_Transformers_for_Sequence_Classification_in_Spark_NLP.ipynb)
# BertForSequenceClassification
BertForSequenceClassification can load Bert Models with sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for multi-class document classification tasks.
Pretrained models can be loaded with `pretrained()` of the companion object.
<br/><br/>
### **Here are Bert Based Sequence Classification models available in Spark NLP**
<br/>
| title | name | language |
|:-------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------|:-----------|
| BERT Sequence Classification Base - DBpedia14 (bert_base_sequence_classifier_dbpedia_14) | bert_base_sequence_classifier_dbpedia_14 | en |
| BERT Sequence Classification Base - IMDB (bert_base_sequence_classifier_imdb) | bert_base_sequence_classifier_imdb | en |
| BERT Sequence Classification Large - IMDB (bert_large_sequence_classifier_imdb) | bert_large_sequence_classifier_imdb | en |
| BERT Sequence Classification Multilingual - AlloCine (bert_multilingual_sequence_classifier_allocine) | bert_multilingual_sequence_classifier_allocine | fr |
| BERT Sequence Classification Base - AG News (bert_base_sequence_classifier_ag_news) | bert_base_sequence_classifier_ag_news | en |
| BERT Sequence Classification - Spanish Emotion Analysis (bert_sequence_classifier_beto_emotion_analysis) | bert_sequence_classifier_beto_emotion_analysis | es |
| BERT Sequence Classification - Spanish Sentiment Analysis (bert_sequence_classifier_beto_sentiment_analysis) | bert_sequence_classifier_beto_sentiment_analysis | es |
| BERT Sequence Classification - Detecting Hate Speech (bert_sequence_classifier_dehatebert_mono) | bert_sequence_classifier_dehatebert_mono | en |
| BERT Sequence Classification - Financial Sentiment Analysis (bert_sequence_classifier_finbert) | bert_sequence_classifier_finbert | en |
| BERT Sequence Classification - Japanese Sentiment (bert_sequence_classifier_japanese_sentiment) | bert_sequence_classifier_japanese_sentiment | ja |
| BERT Sequence Classification Multilingual Sentiment | bert_sequence_classifier_multilingual_sentiment | xx |
| BERT Sequence Classification - Russian Sentiment Analysis (bert_sequence_classifier_rubert_sentiment) | bert_sequence_classifier_rubert_sentiment | ru |
| BERT Sequence Classification - German Sentiment Analysis (bert_sequence_classifier_sentiment) | bert_sequence_classifier_sentiment | de |
| BERT Sequence Classification - Turkish Sentiment (bert_sequence_classifier_turkish_sentiment) | bert_sequence_classifier_turkish_sentiment | tr |
| Bert for Sequence Classification (Question vs Statement) | bert_sequence_classifier_question_statement | en |
| Bert for Sequence Classification (Clinical Question vs Statement) | bert_sequence_classifier_question_statement_clinical | en |
| BERT Sequence Classification - Identify Antisemitic texts | bert_sequence_classifier_antisemitism | en |
| BERT Sequence Classification - Detecting Hate Speech (bert_sequence_classifier_hatexplain) | bert_sequence_classifier_hatexplain | en |
| BERT Sequence Classification - Identify Trec Data Classes | bert_sequence_classifier_trec_coarse | en |
| BERT Sequence Classification - Classify into News Categories | bert_sequence_classifier_age_news | en |
| BERT Sequence Classification - Classify Banking-Related texts | bert_sequence_classifier_banking77 | en |
| BERT Sequence Classification - Detect Spam SMS | bert_sequence_classifier_sms_spam | en |
| BERT Sequence Classifier - Classify the Music Genre | bert_sequence_classifier_song_lyrics | en |
| DistilBERT Sequence Classification Base - AG News (distilbert_base_sequence_classifier_ag_news) | distilbert_base_sequence_classifier_ag_news | en |
| DistilBERT Sequence Classification - Amazon Polarity (distilbert_base_sequence_classifier_amazon_polarity) | distilbert_base_sequence_classifier_amazon_polarity | en |
| DistilBERT Sequence Classification - IMDB (distilbert_base_sequence_classifier_imdb) | distilbert_base_sequence_classifier_imdb | en |
| DistilBERT Sequence Classification - Urdu IMDB (distilbert_base_sequence_classifier_imdb) | distilbert_base_sequence_classifier_imdb | ur |
| DistilBERT Sequence Classification French - AlloCine (distilbert_multilingual_sequence_classifier_allocine) | distilbert_multilingual_sequence_classifier_allocine | fr |
| DistilBERT Sequence Classification - Banking77 (distilbert_sequence_classifier_banking77) | distilbert_sequence_classifier_banking77 | en |
| DistilBERT Sequence Classification - Emotion (distilbert_sequence_classifier_emotion) | distilbert_sequence_classifier_emotion | en |
| DistilBERT Sequence Classification - Industry (distilbert_sequence_classifier_industry) | distilbert_sequence_classifier_industry | en |
| DistilBERT Sequence Classification - Policy (distilbert_sequence_classifier_policy) | distilbert_sequence_classifier_policy | en |
| DistilBERT Sequence Classification - SST-2 (distilbert_sequence_classifier_sst2) | distilbert_sequence_classifier_sst2 | en |
| ALBERT Sequence Classification Base - AG News (albert_base_sequence_classifier_ag_news) | albert_base_sequence_classifier_ag_news | en |
| ALBERT Sequence Classification Base - IMDB (albert_base_sequence_classifier_imdb) | albert_base_sequence_classifier_imdb | en |
| Longformer Sequence Classification Base - AG News (longformer_base_sequence_classifier_ag_news) | longformer_base_sequence_classifier_ag_news | en |
| Longformer Sequence Classification Base - IMDB (longformer_base_sequence_classifier_imdb) | longformer_base_sequence_classifier_imdb | en |
| RoBERTa Sequence Classification Base - AG News (roberta_base_sequence_classifier_ag_news) | roberta_base_sequence_classifier_ag_news | en |
| RoBERTa Sequence Classification Base - IMDB (roberta_base_sequence_classifier_imdb) | roberta_base_sequence_classifier_imdb | en |
| XLM-RoBERTa Sequence Classification Base - AG News (xlm_roberta_base_sequence_classifier_ag_news) | xlm_roberta_base_sequence_classifier_ag_news | en |
| XLM-RoBERTa Sequence Classification Multilingual - AlloCine (xlm_roberta_base_sequence_classifier_allocine) | xlm_roberta_base_sequence_classifier_allocine | fr |
| XLM-RoBERTa Sequence Classification Base - IMDB (xlm_roberta_base_sequence_classifier_imdb) | xlm_roberta_base_sequence_classifier_imdb | en |
| XLNet Sequence Classification Base - AG News (xlnet_base_sequence_classifier_ag_news) | xlnet_base_sequence_classifier_ag_news | en |
| XLNet Sequence Classification Base - IMDB (xlnet_base_sequence_classifier_imdb) | xlnet_base_sequence_classifier_imdb | en |
## Colab Setup
```
! pip install -q pyspark==3.2.0 spark-nlp
import sparknlp
spark = sparknlp.start(spark32=True)
from sparknlp.base import *
from sparknlp.annotator import *
from pyspark.ml import Pipeline,PipelineModel
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
import pandas as pd
print("Spark NLP version", sparknlp.version())
print("Apache Spark version:", spark.version)
spark
```
## BertForSequenceClassification Pipeline
Now, let's create a Spark NLP Pipeline with `bert_base_sequence_classifier_imdb` model and check the results.
This model is a fine-tuned BERT model that is ready to be used for Sequence Classification tasks such as sentiment analysis or multi-class text classification and it achieves state-of-the-art performance.
This model has been trained to recognize two types of entities: negative (neg), positive (pos)
```
document_assembler = DocumentAssembler() \
.setInputCol('text') \
.setOutputCol('document')
tokenizer = Tokenizer() \
.setInputCols(['document']) \
.setOutputCol('token')
sequenceClassifier = BertForSequenceClassification \
.pretrained('bert_base_sequence_classifier_imdb', 'en') \
.setInputCols(['token', 'document']) \
.setOutputCol('pred_class') \
.setCaseSensitive(True) \
.setMaxSentenceLength(512)
pipeline = Pipeline(stages=[
document_assembler,
tokenizer,
sequenceClassifier
])
sample_text= [["I really liked that movie!"], ["The last movie I watched was awful!"]]
sample_df= spark.createDataFrame(sample_text).toDF("text")
model = pipeline.fit(sample_df)
result= model.transform(sample_df)
model.stages
```
We can check the classes of `bert_base_sequence_classifier_imdb` model by using `getClasses()` function.
```
sequenceClassifier.getClasses()
result.columns
result.printSchema()
result_df= result.select(F.explode(F.arrays_zip(result.document.result, result.pred_class.result)).alias("col"))\
.select(F.expr("col['0']").alias("sentence"),
F.expr("col['1']").alias("prediction"))
result_df.show(truncate=False)
```
## DistilBertForSequenceClassification By Using LightPipeline
Now, we will use `distilbert_base_sequence_classifier_ag_news` model with LightPipeline and fullAnnotate it with sample data.
```
document_assembler = DocumentAssembler() \
.setInputCol('text') \
.setOutputCol('document')
tokenizer = Tokenizer() \
.setInputCols(['document']) \
.setOutputCol('token')
sequenceClassifier = DistilBertForSequenceClassification \
.pretrained('distilbert_base_sequence_classifier_ag_news', 'en') \
.setInputCols(['token', 'document']) \
.setOutputCol('class') \
.setCaseSensitive(True) \
.setMaxSentenceLength(512)
pipeline = Pipeline(stages=[
document_assembler,
tokenizer,
sequenceClassifier
])
empty_data= spark.createDataFrame([[""]]).toDF("text")
model = pipeline.fit(empty_data)
light_model= LightPipeline(model)
light_result= light_model.fullAnnotate("Manchester United forward Cristiano Ronaldo on Saturday made his 181st appearance for Portugal.")[0]
light_result
```
Let's check the classes that `distilbert_base_sequence_classifier_ag_news` model can predict
```
sequenceClassifier.getClasses()
light_result.keys()
```
Let's check the prediction
```
pd.set_option('display.max_colwidth', None)
text= []
pred= []
for i, k in list(zip(light_result["document"], light_result["class"])):
text.append(i.result)
pred.append(k.result)
result_df= pd.DataFrame({"text": text, "prediction": pred})
result_df.head()
```
| github_jupyter |
<h1> 1. Exploring natality dataset </h1>
This notebook illustrates:
<ol>
<li> Exploring a BigQuery dataset using Datalab
</ol>
```
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml' # CHANGE this to a globally unique value. Your project name is a good option to try.
PROJECT = 'cloud-training-demos' # CHANGE this to your project name
REGION = 'us-central1' # CHANGE this to one of the regions supported by Cloud ML Engine https://cloud.google.com/ml-engine/docs/tensorflow/regions
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REGION} gs://${BUCKET}
fi
```
<h2> Explore data </h2>
The data is natality data (record of births in the US). My goal is to predict the baby's weight given a number of factors about the pregnancy and the baby's mother. Later, we will want to split the data into training and eval datasets. The hash of the year-month will be used for that -- this way, twins born on the same day won't end up in different cuts of the data.
```
# Create SQL query using natality data after the year 2000
query = """
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ABS(FARM_FINGERPRINT(CONCAT(CAST(YEAR AS STRING), CAST(month AS STRING)))) AS hashmonth
FROM
publicdata.samples.natality
WHERE year > 2000
"""
# Call BigQuery and examine in dataframe
from google.cloud import bigquery
df = bigquery.Client().query(query + " LIMIT 100").to_dataframe()
df.head()
```
## Lab Task #1
Using the above code as an example, write a query to find the unique values for each of the columns and the count of those values for babies born after the year 2000.
For example, we want to get these values:
<pre>
is_male num_babies avg_wt
False 16245054 7.104715
True 17026860 7.349797
</pre>
This is important to ensure that we have enough examples of each data value, and to verify our hunch that the parameter has predictive value.
Hint (highlight to see): <p style='color:white'>Use COUNT(), AVG() and GROUP BY. For example:
<pre style='color:white'>
SELECT
is_male,
COUNT(1) AS num_babies,
AVG(weight_pounds) AS avg_wt
FROM
publicdata.samples.natality
WHERE
year > 2000
GROUP BY
is_male
</pre>
</p>
## Lab Task #2
Which factors seem to play a part in the baby's weight?
<b>Bonus:</b> Draw graphs to illustrate your conclusions
Hint (highlight to see): <p style='color:white'> The simplest way to plot is to use Pandas' built-in plotting capability
<pre style='color:white'>
from google.cloud import bigquery
df = bigquery.Client().query(query).to_dataframe()
df.plot(x='is_male', y='num_babies', logy=True, kind='bar');
df.plot(x='is_male', y='avg_wt', kind='bar');
</pre>
Copyright 2017-2018 Google Inc. 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 http://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
| github_jupyter |
# Import Libraries
```
from fairlearn.metrics import (
MetricFrame,
count
)
import numpy as np
import pandas as pd
from jiwer import wer
import matplotlib.pyplot as plt
import seaborn as sns
import logging
import warnings
warnings.simplefilter(action="ignore")
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
```
# Speech-to-Text Fairness Assessment
In this notebook, we walk through a scenario of assessing a *speech-to-text* service for fairness-related disparities. For this fairness assessment, we consider various `sensitive features`, such as `native language`, `sex`, and `country` where the speaker is located.
For this audit, we will be working with a CSV file `stt_testing_data.csv` that contains 2138 speech samples. Each row in the dataset represents a person reading a particular reading passage in English. A machine system is used to generate a transcription from the audio of person reading the passage.
If you wish to run this notebook with your speech data, you can use the `run_stt.py` provided to query the Microsoft Cognitive Service Speech API. You can also run this notebook with a dataset generated from other speech-to-text systems.
```
stt_results_csv = "stt_testing_data.csv"
```
In this dataset, `ground_truth_text` represents the English passage the participant was asked to read. `predicted_text` represents the transcription produced by the automated service. In an ideal scenario, the `ground_truth_text` would represent the transcription produced by a human transcriber, so we could compare the output of the automated transcription to the one produced by the human transcriber. We will also look at demographic features, such as `sex` of the participant and the `country` where the participant is located.
```
df = pd.read_csv(f"{stt_results_csv}",
usecols=["age", "native_language", "sex", "country", "ground_truth_text", "predicted_text"]
)
df.shape
```
The goal of a fairness assessment is to *understand which groups of people may be disproportionately negatively impacted by an AI system and in which ways*?
For our fairness assessment, we perform the following tasks:
1. Idenfity harms and which groups may be harmed.
2. Define fairness metrics to quantify harms
3. Compare our quantified harms across the relevant groups.
## 1.) Identify Harms and groups who may be harmed
The first step of the fairness assessment is identifying the types of fairness-related harms we expect users of the systems to experience. From the harms taxonomy in the [Fairlearn User Guide]( https://fairlearn.org/v0.7.0/user_guide/fairness_in_machine_learning.html#types-of-harms), we expect our *speech-to-text* system produces *quality of service* harms to users.
*Quality-of-service* harms occur when an AI system does not work as well for one person as it does for others, even when no resources or opportunities are withheld.
There have been several studies demonstrating that speech-to-text systems achieve different levels of performance based on the speaker's gender and language dialect (Add link to papers). In this assessment, we will explore how the performance of our speech-to-text system differs based on language dialect (proxied by `country`) and `sex` for speakers in three English-speaking countries.
```
sensitive_country = ["country"]
sensitive_country_sex = ["country", "sex"]
countries = ["usa", "uk", "canada"]
filtered_df = df.query(f"country in {countries} and native_language == 'english'")
filtered_df.head()
```
One challenge for our fairness assessment is the small group sample sizes. Our filtered dataset consists primarily of English speakers in the USA, so we expect higher uncertainty for our metrics on speakers from the other two countries. The smaller sample sizes for *UK* and *Canadian* speakers means we may not be able to find significant differences once we also account for `sex`.
```
display(filtered_df.groupby(["country"])["sex"].count())
```
## 2.) Define fairness metrics to quantify harms
To measure differences in performance, we will be looking at the `word_error_rate`. The `word_error_rate` represented the fraction of words that are transcribed incorrectly compared to a ground truth text. A higher `word_error_rate` reflects that the system achieves worse performance for a particular group.
Compared to the human transcription (what speaker said is different to ground truth text).
```
DISPARITY_BASE = 0.5
def word_error_rate(y_true, y_pred):
return wer(str(y_true), str(y_pred))
def wer_abs_disparity(y_true, y_pred, disparity=DISPARITY_BASE):
return (word_error_rate(y_true, y_pred) - disparity)
def wer_rel_disparity(y_true, y_pred, disparity=DISPARITY_BASE):
return wer_abs_disparity(y_true, y_pred, disparity)/disparity
```
WER as a disparity from some base. Might be better to compute maximal difference between groups.
```
fairness_metrics = {
"count": count,
"word_error_rate": word_error_rate,
"word_error_rate_abs_disparity": wer_abs_disparity,
"word_error_rate_rel_disparity": wer_rel_disparity
}
```
## 3.) Compare quantifed harms across different groups
In the final part of our fairness assessment, we use the `MetricFrame` object in the `fairlearn` package to compare our system's performance across our `sensitive features`.
To instanstiate a `MetricFrame`, we pass in four parameters:
- `metrics`: The `fairness_metrics` to evaluate each group on.
- `y_true`: The `ground_truth_text`
- `y_pred`: The `predicted_text`
- `sensitive_features`: Our groups for fairness assessment
For our first analysis, we look at the system's performance with repsect to `country`.
```
metricframe_country = MetricFrame(
metrics=fairness_metrics,
y_true=filtered_df.loc[:, "ground_truth_text"],
y_pred=filtered_df.loc[:, "predicted_text"],
sensitive_features=filtered_df.loc[:, sensitive_country]
)
```
Using the `MetricFrame`, we can easily compute the `word_error_rate differences` between our three countries.
```
display(metricframe_country.by_group[["count", "word_error_rate"]])
display(metricframe_country.difference())
```
We see the maximal `word_error_rate difference` (between`UK` and `Canada`) is 0.05. Since the `MetricFrame` is built on top of the `Pandas DataFrame` object, we can take advantage of `Pandas`'s plotting capabilities to visualize the `word_error_rate` by `country`.
```
metricframe_country.by_group.sort_values(by="word_error_rate", ascending=False).plot(kind="bar", y="word_error_rate", ylabel="Word Error Rate", title="Word Error Rate by Country", figsize=[12,8])
```
Next, let's explore how our system performs with respect to `sex` of the speaker. Similar to what we did for `country`, we create another `MetricFrame` except passing in the `sex` column as our `sensitive_features`.
```
metricframe_sex = MetricFrame(
metrics=fairness_metrics,
y_true=filtered_df.loc[:, "ground_truth_text"],
y_pred=filtered_df.loc[:, "predicted_text"],
sensitive_features=filtered_df.loc[:, "sex"]
)
display(metricframe_sex.by_group[["count", "word_error_rate"]])
display(metricframe_sex.difference())
```
In our `sex`-based analysis, we see there is a `0.06` difference in the *WER* between `male` and `female` speakers. If we added uncertainty quantification, such as *confidence intervals*, to our analysis, we could perform statistical tests to determine if the difference is statistically significant or not.
```
metricframe_sex.by_group.sort_values(by="word_error_rate", ascending=False).plot(kind="bar", y="word_error_rate", ylabel="Word Error Rate", title="Word Error Rate by Sex", figsize=[12,8])
```
### Intersectional Analysis
One key aspect to remember when performing a fairness analysis is to explore the intersection of different groups. For this final analysis, we would look at groups at the intersection of `country` and `sex`.
In particular, we are interested in seeing the `word_error_rate difference` by `sex` for each `country`. That is, we want to compare the `WER difference` between `Canada male` and `Canada female` to the `WER difference` between `males` and `females` of the other two countries.
When we instantiate our `MetricFrame` this time, we pass in the `country` column as a `control_feature`. Now when we call the `difference` method for our `MetricFrame`, it will compute the `WER difference` for `male` and `female` by each country.
```
# Make country a control feature
metricframe_country_sex_control = MetricFrame(
metrics=fairness_metrics,
y_true=filtered_df.loc[:, "ground_truth_text"],
y_pred=filtered_df.loc[:, "predicted_text"],
sensitive_features=filtered_df.loc[:, "sex"],
control_features=filtered_df.loc[:, "country"]
)
display(metricframe_country_sex_control.difference())
```
If we call the `by_group` attribute, we get the `MultiIndex DataFrame` showing the `count` and `word_error_rate` for each intersectional group.
```
display(metricframe_country_sex_control.by_group[["count", "word_error_rate"]])
```
Now, let's explore our `word_error_rate` disparity by `sex` within each country. Plotting the absolute `word_error_rates` for each intersectional group shows us that the disparity betwen `UK male` and `UK female` is noticeably larger compared to the other countries.
```
group_metrics = metricframe_country_sex_control.by_group[["count", "word_error_rate"]]
group_metrics["word_error_rate"].unstack(level=-1).plot(
kind="bar",
ylabel="Word Error Rate",
title="Word Error Rate by Country and Sex")
plt.legend(bbox_to_anchor=(1.3,1))
def plot_controlled_features(multiindexframe, title, xaxis, yaxis, order):
"""
Helper function to plot the visualization for the
"""
plt.figure(figsize=[12,8])
disagg_metrics = multiindexframe["word_error_rate"].unstack(level=0).loc[:, order].to_dict()
male_scatter = []
female_scatter = []
countries = disagg_metrics.keys()
for country, sex_wer in disagg_metrics.items():
male_point, female_point = sex_wer.get("male"), sex_wer.get("female")
plt.vlines(country, female_point, male_point, linestyles="dashed", alpha=0.45)
#Need to pair X-axis (Country) with each point
male_scatter.append(male_point)
female_scatter.append(female_point)
plt.scatter(countries, male_scatter, marker="^", color="b", label="Male")
plt.scatter(countries, female_scatter, marker="s", color="r", label="Female")
plt.title(title)
plt.legend(bbox_to_anchor=(1,1))
plt.xlabel(xaxis)
plt.ylabel(yaxis)
```
We can also visualize the relative disparity by `sex` for each `country`. From these plots, we see the difference between `UK male` and `UK female` is ~0.09. This is larger than the disparity between `US male` and `US female` (0.06) and the disparity between `Canada male` and `Canada female` (> 0.01).
```
plot_controlled_features(group_metrics,
"Word Error Rate by Country and Sex",
"Country",
"Word Error Rate",
order=["uk", "usa", "canada"])
metricframe_country_sex_control.difference().sort_values(by="word_error_rate", ascending=False).plot(
kind="bar",
y="word_error_rate",
title="Word Error Rate between Sex by Country",
figsize=[12,8])
```
# Conclusion
With this fairness assessment, we explored how `country` and `sex` affect the quality of a speech-to-text transcription in three English-speaking countries. Through an intersectional analysis, we found a higher disparity in the *quality-of-service* between `UK male` and `UK female` compared to males and females of other countries.
| github_jupyter |
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
MAX_EVALUE = 1e-2
```
# Data Overview
This notebook provides an overview of source datasets - training, testing and 3k bacteria.
# Training data
## ClusterFinder BGCs (positives)
** Used for: Model training **
CSV file with protein domains in genomic order. Contigs (samples) are defined by the `contig_id` column.
```
domains = pd.read_csv('../data/training/positive/CF_bgcs.csv')
domains = domains[domains['evalue'] <= MAX_EVALUE]
domains.head()
num_contigs = len(domains['contig_id'].unique())
num_contigs
contig_proteins = domains.groupby("contig_id")['protein_id'].nunique()
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
ax = contig_proteins.hist(bins=40, ax=axes[0])
ax.set_xlabel('# proteins in BGC sample')
ax.set_ylabel('Frequency')
ax = contig_proteins.hist(bins=100, ax=axes[1], cumulative=True)
ax.set_xlabel('# proteins in BGC sample')
ax.set_ylabel('Cumulative frequency')
plt.tight_layout()
contig_domains = domains.groupby("contig_id")['pfam_id'].size()
ax = contig_domains.hist(bins=20)
ax.set_xlabel('# domains in BGC sample')
ax.set_ylabel('Frequency')
```
## MIBiG BGCs (positives)
** Used for: LCO validation, 10-fold Cross-validation **
CSV file with protein domains in genomic order. Contigs (samples) are defined by the `contig_id` column.
```
domains = pd.read_csv('../data/training/positive/mibig_bgcs_all.csv')
domains = domains[domains['evalue'] <= MAX_EVALUE]
domains.head()
num_contigs = len(domains['contig_id'].unique())
num_contigs
contig_proteins = domains.groupby("contig_id")['protein_id'].nunique()
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
ax = contig_proteins.hist(bins=40, ax=axes[0])
ax.set_xlabel('# proteins in BGC sample')
ax.set_ylabel('Frequency')
ax = contig_proteins.hist(bins=100, ax=axes[1], cumulative=True)
ax.set_xlabel('# proteins in BGC sample')
ax.set_ylabel('Cumulative frequency')
plt.tight_layout()
contig_domains = domains.groupby("contig_id")['pfam_id'].size()
ax = contig_domains.hist(bins=20)
ax.set_xlabel('# domains in BGC sample')
ax.set_ylabel('Frequency')
contig_domains.describe(percentiles=np.arange(0, 1, 0.05))
properties = pd.read_csv('../data/mibig/mibig_properties.csv')
properties.head()
properties['classes'].value_counts().plot.barh(figsize=(5, 10))
classes_split = properties['classes'].apply(lambda c: c.split(';'))
class_counts = pd.Series([c for classes in classes_split for c in classes]).value_counts()
class_counts.plot.barh()
print(class_counts)
```
# GeneSwap negatives
** Used for: Model training, LCO validation **
```
domains = pd.read_csv('../data/training/negative/geneswap_negatives.csv')
domains = domains[domains['evalue'] <= MAX_EVALUE]
domains.head()
num_contigs = len(domains['contig_id'].unique())
num_contigs
contig_proteins = domains.groupby("contig_id")['protein_id'].nunique()
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
ax = contig_proteins.hist(bins=40, ax=axes[0])
ax.set_xlabel('# proteins in negative sample')
ax.set_ylabel('Frequency')
ax = contig_proteins.hist(bins=100, ax=axes[1], cumulative=True)
ax.set_xlabel('# proteins in negative sample')
ax.set_ylabel('Cumulative frequency')
plt.tight_layout()
contig_domains = domains.groupby("contig_id")['pfam_id'].size()
ax = contig_domains.hist(bins=20)
ax.set_xlabel('# domains in negative sample')
ax.set_ylabel('Frequency')
```
# Validation and testing data
## ClusterFinder labelled contigs
** Used for: Model validation - ROC curves **
10 labelled genomes (13 contigs) with non-BGC and BGC regions (stored in `in_cluster` column for each domain)
```
contigs = pd.read_csv('../data/clusterfinder/labelled/CF_labelled_contig_summary.csv', sep=';')
contigs
domains = pd.read_csv('../data/clusterfinder/labelled/CF_labelled_contigs_domains.csv')
domains = domains[domains['evalue'] <= MAX_EVALUE]
domains.head()
def count_y_clusters(y):
prev = 0
clusters = 0
for val in y:
if val == 1 and prev == 0:
clusters += 1
prev = val
return clusters
```
### non-BGC and BGC regions
```
for contig_id, contig_domains in domains.groupby('contig_id'):
in_cluster = contig_domains.reset_index()['in_cluster']
num_bgcs = count_y_clusters(in_cluster)
title = '{} ({} BGCs)'.format(contig_id, num_bgcs)
ax = in_cluster.plot(figsize=(15, 1), title=title, color='grey', lw=1)
in_cluster.plot(kind='area', ax=ax, color='grey', alpha=0.2)
plt.show()
```
## ClusterFinder 75 BGCs in genomic context
** Used for: Model validation - TPR evaluation **
6 labelled genomes with annotated BGC regions. Remaining regions are not known.
75 BGCs are annotated (10 are duplicates found twice, so only 65 are unique)
```
bgc75_locations = pd.read_csv('../data/clusterfinder/74validation/74validation_locations.csv')
bgc75_locations.head()
fig, axes = plt.subplots(len(bgc75_locations['Accession'].unique()), figsize=(8, 8))
i = 0
for contig_id, contig_bgcs in bgc75_locations.groupby('Accession'):
num_bgcs = len(contig_bgcs)
title = '{} ({} BGCs)'.format(contig_id, num_bgcs)
axes[i].set_title(title)
axes[i].set_ylim([0, 1.2])
for b, bgc in contig_bgcs.iterrows():
axes[i].plot([bgc['BGC_start'], bgc['BGC_stop']], [1, 1], color='grey')
axes[i].fill_between([bgc['BGC_start'], bgc['BGC_stop']], [1, 1], color='grey', alpha=0.3)
i += 1
plt.tight_layout()
bgc75_domains = pd.read_csv('../data/clusterfinder/74validation/74validation_domains.csv')
bgc75_domains = bgc75_domains[bgc75_domains['evalue'] <= MAX_EVALUE]
bgc75_domains.head()
```
# 3k reference genomes
3376 bacterial genomes, preprocessed using Prodigal & Pfam Hmmscan.
## Reference genomes species
```
bac_species = pd.read_csv('../data/bacteria/species.tsv', sep='\t').set_index('contig_id')
bac_species['family'] = bac_species['species'].apply(lambda species: species.split('_')[0])
bac_species['subspecies'] = bac_species['species'].apply(lambda species: ' '.join(species.split('_')[:2]))
bac_species.head()
bac_families_top = bac_species['family'].value_counts()[:20]
print('Unique families:', len(bac_species['family'].unique()))
bac_families_top
bac_species_top = bac_species['subspecies'].value_counts()[:20]
print('Unique species:', len(bac_species['subspecies'].unique()))
bac_species_top
```
## Reference genomes domains
** Used for: Pfam2vec corpus generation, Novel BGC candidate prediction **
Domain CSV files, one for each bacteria.
```
bac_domains = pd.read_csv('../data/bacteria/domains/AE000511.1.domains.csv', nrows=10)
bac_domains.head()
```
## Reference genomes pfam corpus
** Used for: Pfam2vec training **
Corpus of 23,425,967 pfams domains (words) used to train the pfam2vec embedding using the word2vec algorithm.
Corpus contains pfam domains from one bacteria per line, separated by space.
```
corpus = pd.read_csv('../data/bacteria/corpus/corpus-1e-02.txt', nrows=10, header=None)
corpus.head()
corpus_counts = pd.read_csv('../data/bacteria/corpus/corpus-1e-02.counts.csv').set_index('pfam_id')
corpus_counts[:10][::-1].plot.barh()
```
The pfam counts have a very long-tail distribution with a median of only 101 occurences.
```
corpus_counts.plot.hist(bins=100)
print(corpus_counts.describe())
```
| github_jupyter |
<body>
<section style="border:1px solid RoyalBlue;">
<section style="background-color:White; font-family:Georgia;text-align:center">
<h1 style="color:RoyalBlue">Introduction to Data Science</h1>
<h2 style="color:RoyalBlue">Dr. Casey Kennington</h1>
<h2 style="font-family:Courier; text-align:center;">CS-533</h2>
<br>
<h2 style="font-family:Garamond;">Gerardo Caracas Uribe</h2>
<h2 style="font-family:Garamond;">Student ID: 114104708</h2>
<h2 style="font-family:Courier;">Homework #3 tabular-numeric-data</h2>
<hr/>
</section>
</section>
</body>
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 21</h2>
<h3 style="font-family:Garamond;">Creating Arrays</h3>
<hr/>
</section>
</body>
```
import numpy as np
numbers = np.array(range(1,11), copy=True)
numbers
ones = np.ones([2, 4], dtype=np.float64)
ones
zeros = np.zeros([2,4], dtype=np.float64)
zeros
empty = np.empty([2,4], dtype=np.float64)
empty
ones.shape
numbers.ndim
zeros.dtype
eye = np.eye(3, k=1)
eye
np_numbers = np.arange(2, 5, 0.25)
np_numbers
np_numbers = np_numbers.astype(np.int)
np_numbers
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 22</h2>
<h3 style="font-family:Garamond;">Transposing and Reshaping</h3>
<hr/>
</section>
</body>
```
sap = np.array(['MMM', 'ABT', 'ABBV', 'ACN', 'ACE', 'ATVI', 'ADBE', 'ADT'])
sap
sap2d = sap.reshape(2,4)
sap2d
sap3d = sap.reshape(2, 2, 2)
sap3d
sap2d.T
sap3d.swapaxes(1,2)
sap3d.transpose((0, 2, 1))
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 23</h2>
<h3 style="font-family:Garamond;">Indexing and Slicing</h3>
<hr/>
</section>
</body>
```
dirty = np.array([9, 4, 1, -0.01, -0.02, 0.001])
whos_dirty = dirty < 0 # Boolean array, to be used as Boolean index
whos_dirty
dirty[whos_dirty] = 0 # Change all negative values to 0
dirty
linear = np.arange(-1, 1.1, 0.2)
(linear <= 0.5) & (linear >= -0.5)
sap[[1, 2, -1]]
sap2d[:, [1]]
sap2d[:, 1]
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 24</h2>
<h3 style="font-family:Garamond;">Broadcasting</h3>
<hr/>
</section>
</body>
```
a = np.arange(4)
b = np.arange(1,5)
a + b
a*5
noise = np.eye(4) + 0.01 * np.ones((4,))
noise
noise=np.eye(4) + 0.01 * np.random.random([4, 4])
noise
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 25</h2>
<h3 style="font-family:Garamond;">Demystifying Universal Functions</h3>
<hr/>
</section>
</body>
```
stocks = np.array([140.49, 0.97, 40.68, 41.53, 55.7, 57.21, 98.2, 99.19, 109.96, 111.47, 35.71, 36.27, 87.85, 89.11, 30.22, 30.91])
stocks
stocks = stocks.reshape(8,2).T
stocks
fall = np.greater(stocks[0], stocks[1])
fall
sap[fall]
# Pretend the new MMM quote is missing
stocks[1,0] = np.nan
np.isnan(stocks)
# Repair the damage; it can't get worse than this
stocks[np.isnan(stocks)] = 0
stocks
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 26</h2>
<h3 style="font-family:Garamond;">Understanding Conditional Functions</h3>
<hr/>
</section>
</body>
```
changes = np.where(np.abs(stocks[1] - stocks[0]) > 1.00, stocks[1]-stocks[0], 0)
changes
sap[np.nonzero(changes)]
sap[np.abs(stocks[1] - stocks[0]) > 1.00]
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 27</h2>
<h3 style="font-family:Garamond;">Aggregating and Ordering Arrays</h3>
<hr/>
</section>
</body>
```
sap[np.abs(stocks[0] - stocks[1]) > np.mean(np.abs(stocks[0] - stocks[1]))]
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h2 style="font-family:Garamond; color:solid #229954">Unit 28</h2>
<h3 style="font-family:Garamond;">Treating Arrays as Sets</h3>
<hr/>
</section>
</body>
```
dna = "AGTCCGCAATACAGGCTCGGT"
dna_as_array=np.array(list(dna))
dna_as_array
np.unique(dna_as_array)
np.in1d(["MSFT","MMM","AAPL"], sap)
```
<body>
<section style="border:1px solid RoyalBlue;">
<section style="background-color:White; font-family:Georgia;text-align:center">
<h1 style="color:RoyalBlue">Array Differentiator</h1><br/>
<h2 style="color:RoyalBlue">Section "Your Turn"</h2><br/>
<h2 style="color:RoyalBlue">Chapter 5</h2><br/>
<h2 style="color:RoyalBlue">Page: 82</h2><br/>
</section>
</section>
</body>
```
import pandas as pd
import numpy as np
fn = "./dset.csv"
t = pd.read_csv(fn, sep='\n', delimiter=',')
t
from math import *
longitud = t['LONGITUD']
latitud = t['LATITUDE']
```
The longitud and lattitud columns have dirty data on them. In some cases we have a dot "." instead of a number. In order to get the degrees and make an average we should not consider these fields because number one, they don't have numbers, also if we fill them with either 0, max, or mid values, they will bias the end result of the mean, therefore we won't use them for calculation.<br>
Instead we will get an array if indexes for the valid fields and calculate using only them.
```
validLongitud = np.where(longitud != '.')
validLatitud = np.where(latitud != '.')
```
Now we will convert the latitud series into numpy<br>
Then before we can do broadcasting, we need to make an multidimentional array, in this case nx1. For this we will reshape the numpy array.
```
latitudNp = latitud.values
latitudNp = latitudNp.reshape(latitudNp.shape[0],1)
```
Now we will convert the longitud series into numpy<br>
Then before we can do broadcasting, we need to make an multidimentional array, in this case nx1. For this we will reshape the numpy array.
```
longitudNp = longitud.values
longitudNp = longitudNp.reshape(longitudNp.shape[0],1)
```
Now let's convert each one of the longitud and latitud into degrees, minutes and seconds. Let's make a function that returns this
```
def convertFromDecimalDegreesToDMS(inputData):
inputData = inputData.reshape(inputData.shape[0],1)
degreesf = inputData.real.astype(np.float, copy=True, casting='unsafe')
degrees = degreesf.astype(np.int, copy=True)
minutesf = (degreesf - degrees)*60
minutes = minutesf.astype(np.int, copy=True)
seconds = (minutesf - minutes) * 60
return degrees, minutes, seconds
degreesLongitud, minutesLongitud, secondsLongitud = convertFromDecimalDegreesToDMS(longitudNp[validLongitud])
degreesLatitud, minutesLatitud, secondsLatitud = convertFromDecimalDegreesToDMS(latitudNp[validLatitud])
longDegMean=int(np.round(degreesLongitud.mean(), decimals=0))
longMinMean=int(np.round(minutesLongitud.mean(), decimals=0))
longsecMean=secondsLongitud.mean()
latDegMean=int(np.round(degreesLatitud.mean(), decimals=0))
latMinMean=int(np.round(minutesLatitud.mean(), decimals=0))
latSecMean=secondsLatitud.mean()
print("The mean longitud is ",abs(longDegMean),"deg",abs(longMinMean),"'",abs(longsecMean),"\"W")
print("The mean latitude is ",abs(latDegMean),"deg",abs(latMinMean),"'",abs(latSecMean),"\"N")
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h3 style="font-family:Garamond;">In the image below, you can see in the red drop mark, where our average is located
</h3>
<hr/>
</section>
</body>

```
#zeros = list(np.zeros([t.shape[0]], dtype=np.int))
zeros = np.zeros([t.shape[0]], dtype=np.int)
degreesLongitud = degreesLongitud[:,0]
zeros[validLongitud]=degreesLongitud
zeros = zeros.tolist()
t['degreesLongitud'] = pd.Series(zeros, index=t.index)
zeros = np.zeros([t.shape[0]], dtype=np.int)
minutesLongitud = minutesLongitud[:,0]
zeros[validLongitud]=minutesLongitud
zeros = zeros.tolist()
t['minutesLongitud'] = pd.Series(zeros, index=t.index)
zeros = np.zeros([t.shape[0]], dtype=np.int)
secondsLongitud = secondsLongitud[:,0]
zeros[validLongitud]=secondsLongitud
zeros = zeros.tolist()
t['secondsLongitud'] = pd.Series(zeros, index=t.index)
zeros = np.zeros([t.shape[0]], dtype=np.int)
degreesLatitud = degreesLatitud[:,0]
zeros[validLatitud]=degreesLatitud
zeros = zeros.tolist()
t['degreesLatitude'] = pd.Series(zeros, index=t.index)
zeros = np.zeros([t.shape[0]], dtype=np.int)
minutesLatitud = minutesLatitud[:,0]
zeros[validLatitud]=minutesLatitud
zeros = zeros.tolist()
t['minutesLatitud'] = pd.Series(zeros, index=t.index)
zeros = np.zeros([t.shape[0]], dtype=np.int)
secondsLatitud = secondsLatitud[:,0]
zeros[validLatitud]=secondsLatitud
zeros = zeros.tolist()
t['secondsLatitud'] = pd.Series(zeros, index=t.index)
t
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h3 style="font-family:Garamond;">Now that we have all the table setup, we will locate the nearest locations using the seconds part of the coordinate, therefore we will filter by using the degrees and minutes for both, latitude and longitud first. The result will be the ones that less than a minute away from our median reference.
</h3>
<hr/>
</section>
</body>
```
type(t)
#query = "degreesLongitud=="+str(longDegMean)+str(longMinMean)+" and degreesLatitude =="+str(latDegMean)
minLatD=latDegMean-2
maxLatD=latDegMean+2
minLongD=longDegMean-2
maxLongD=longDegMean+2
minLatM=latMinMean-50
maxLatM=latMinMean+50
minLongM=latDegMean-50
maxLongM=latDegMean+50
query = "(degreesLatitude > "+str(minLatD)+" and degreesLatitude < "+str(maxLatD)+") and ("+"degreesLongitud > "\
+str(minLongD)+" and degreesLongitud < "+str(maxLongD)+") and "+\
"(minutesLatitud > "+str(minLatM)+" and minutesLatitud < "+str(maxLatM)+") and ("+"minutesLongitud > "\
+str(minLongM)+" and minutesLongitud < "+str(maxLongM)+")"
#query = "degreesLatitude > 35 and degreesLatitude < 39"
print(query)
df_filtered = t.query(query)
df_filtered
```
We just got a great subset, but we got 11, let's discard the furthes one
```
df_filtered.sort_index
df_filtered.sort_values(by=['degreesLongitud'])
result = df_filtered[1:]
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h1 style="font-family:Garamond;color:solid #A93226">Results</h1>
<hr/>
</section>
</body>
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h3 style="font-family:Garamond;">The table below shows the 10 nearest institutions nearby the median point
</h3>
<hr/>
</section>
</body>
```
result
```
<body>
<section style="background-color:White; font-family:Georgia;text-align:center">
<h3 style="font-family:Garamond;">The image below show in a map where the median is as a green landmark, and as blue the 10 nearby institutions.
</h3>
<hr/>
</section>
</body>

| github_jupyter |
# Homework: Understanding Performance using a LinkedIn Dataset
This homework focuses on understanding performance using a LinkedIn dataset. It is the same dataset that was used in the module entitled "Modeling Data and Knowledge".
```
!pip install pandas
!pip install numpy
!pip install matplotlib
!pip install pymongo[tls,srv]
!pip install lxml
import pandas as pd
import numpy as np
import json
import sqlite3
from lxml import etree
import urllib
import zipfile
import time
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError, OperationFailure
from sklearn.utils import shuffle
```
# Step 1: Acquire and load the data
We will pull a zipfile with the LinkedIn dataset from an url / Google Drive so that it can be efficiently parsed locally. The detailed steps are covered by "Modeling Data and Knowledge" Module, and you should refer to the instructor notes of that module if you haven't done so.
The cell below will download/open the file, and may take a while.
```
url = 'https://raw.githubusercontent.com/chenleshang/OpenDS4All/master/Module3/homework3filewrapper.py'
urllib.request.urlretrieve(url,filename='homework3filewrapper.py')
# url = 'https://upenn-bigdataanalytics.s3.amazonaws.com/linkedin.zip'
# filehandle, _ = urllib.request.urlretrieve(url,filename='local.zip')
```
The next cell creates a pointer to the (abbreviated) LinkedIn dataset, and imports a script that will be used to prepare the dataset to manipulate in this homework.
```
def fetch_file(fname):
zip_file_object = zipfile.ZipFile(filehandle, 'r')
for file in zip_file_object.namelist():
file = zip_file_object.open(file)
if file.name == fname: return file
return None
# linked_in = fetch_file('test_data_10000.json')
from homework3filewrapper import *
```
The next cell replays the data preparation for the LinkedIn dataset done in the module "Modeling Data and Knowledge". After this, you should have eleven dataframes with the following names. The first nine are as in the lecture notebook; the last two are constructed using queries over the first nine, and their meanings are given below.
1. `people_df`
2. `names_df`: Stores the first and last name of each person indexed by ID.
3. `education_df`
4. `groups_df`
5. `skills_df`
6. `experience_df`
7. `honors_df`
8. `also_view_df`
9. `events_df`
10. `recs_df`: 20 pairs of people with the most shared/common skills in descending order. We will use this to make a recommendation for a potential employer and position to each person.
11. `last_job_df`: Person name, and the title and org corresponding to the person's last (most recent) employment experience (a three column dataframe).
The number of rows that are extracted from the dataset can be changed using LIMIT. Here, we are limiting it to 10,000; you can set it to something much smaller (e.g. 1,000) while debugging your code.
The data is also being stored in an SQLite database so that you can see the effect of indexing on the performance of queries.
```
# If use a file on Google Drive, then mount it to Colab.
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
# use open() to open a local file, or to use fetch_file() to get that file from a remote zip file.
people_df, names_df, education_df, groups_df, skills_df, experience_df, honors_df, also_view_df, events_df, recs_df, last_job_df =\
data_loading(file=open('/content/drive/My Drive/Colab Notebooks/test_data_10000.json'), dbname='linkedin.db', filetype='localobj', LIMIT=10000)
conn = sqlite3.connect('linkedin.db')
# Sanity Check 1.1 - please do not modify or delete this cell!
recs_df
# Sanity Check 1.2 - please do not modify or delete this cell!
names_df
# Sanity Check 1.3 - please do not modify or delete this cell!
last_job_df
```
# Step 2: Compare Evaluation Orders using DataFrames
We will now explore the effect of various optimizations, including reordering execution steps and (in the case of database operations) creating indices.
We'll start with the code from our lecture notebooks, which does joins between dataframes. The next cell creates two functions, merge and merge_map, which we explore in terms of efficiency. **You do not need to modify this cell.**
```
# Join using nested loops
def merge(S,T,l_on,r_on):
ret = pd.DataFrame()
count = 0
S_ = S.reset_index().drop(columns=['index'])
T_ = T.reset_index().drop(columns=['index'])
for s_index in range(0, len(S)):
for t_index in range(0, len(T)):
count = count + 1
if S_.loc[s_index, l_on] == T_.loc[t_index, r_on]:
ret = ret.append(S_.loc[s_index].append(T_.loc[t_index].drop(labels=r_on)), ignore_index=True)
print('Merge compared %d tuples'%count)
return ret
# Join using a *map*, which is a kind of in-memory index
# from keys to (single) values
def merge_map(S,T,l_on,r_on):
ret = pd.DataFrame()
T_map = {}
count = 0
# Take each value in the r_on field, and
# make a map entry for it
T_ = T.reset_index().drop(columns=['index'])
for t_index in range(0, len(T)):
# Make sure we aren't overwriting an entry!
assert (T_.loc[t_index,r_on] not in T_map)
T_map[T_.loc[t_index,r_on]] = T_.loc[t_index]
count = count + 1
# Now find matches
S_ = S.reset_index().drop(columns=['index'])
for s_index in range(0, len(S)):
count = count + 1
if S_.loc[s_index, l_on] in T_map:
ret = ret.append(S_.loc[s_index].append(T_map[S_.loc[s_index, l_on]].drop(labels=r_on)), ignore_index=True)
print('Merge compared %d tuples'%count)
return ret
```
## Step 2.1: Find a good order of evaluation.
The following function, `recommend_jobs_basic`, takes as input `recs_df`, `names_df` and `last_job_df` and returns the name of each `person_1` and the most recent `title` and `org` of each `person_2`.
We will time how long it takes to execute `recommend_jobs_basic` using the ordering `recs_df`, `names_df` and `last_job_df`.
Your task is to improve this time by changing the join ordering used in `recommend_jobs_basic`.
```
def recommend_jobs_basic(recs_df, names_df, last_job_df):
return merge(merge(recs_df,names_df,'person_1','person')[['family_name','given_name','person_1','person_2']],
last_job_df,'person_2','person')[['family_name','given_name','person_2','org','title']].sort_values('family_name')
```
```
%%time
recs_new_df = recommend_jobs_basic(recs_df, names_df, last_job_df)
if(len(recs_new_df.columns) != 5):
raise AssertionError('Wrong number of columns in recs_new_df')
```
Modify the function `recommend_jobs_basic` in the cell below. See if it is possible to improve the efficiency by changing the join ordering to reduce the number of comparisons made in the `merge` function.
```
# TODO: modify the order of joins to reduce comparisons
def recommend_jobs_basic_reordered(recs_df, names_df, last_job_df):
# YOUR CODE HERE
%%time
recs_new_df = recommend_jobs_basic_reordered(recs_df, names_df, last_job_df)
if(len(recs_new_df.columns) != 5):
raise AssertionError('Wrong number of columns in recs_new_df')
names_df
recs_df
last_job_df
```
## Step 2.2: Perform selections early using `merge` and `merge_map`
Reimplement `recommend_jobs_basic` using the `merge` and `merge_map` functions instead of Pandas' merge. Try to find the **most efficient** way by also considering the ordering.
```
# TODO: Reimplement recommend jobs using our custom merge and merge_map functions
def recommend_jobs_new(recs_df, names_df, last_job_df):
# YOUR CODE HERE
# Sanity Check 2.1 - please do not modify or delete this cell!
%%time
recs_new_df = recommend_jobs_new(recs_df, names_df, last_job_df)
if(len(recs_new_df.columns) != 5):
raise AssertionError('Wrong number of columns in recs_new_df')
```
# Step 3. Query Optimization in Databases
Relational databases optimize queries by performing selections (and projections) as early as possible, and finding a good join ordering. We will therefore implement the recommend_jobs function using SQLite and see if it is faster.
Dataframes `names_df`, `rec_df` and `last_job_df` are already stored in database `linkedin.db` with table name `names`, `recs` and `lastjob`.
## Step 3.1
In the cell below, implement the `recommend_jobs_basic` function in SQL. Since the query is very fast, we will run the query 100 times to get an accurate idea of the execution time.
```
%%time
for i in range(0, 100):
# YOUR CODE HERE
```
## Step 3.2
Altough the execution is pretty fast, we can also create indices to make it even faster. Use the syntax `CREATE INDEX I ON T(C)` to create index on the three tables `recs`, `names`, and `lastjob`. Replace `I` with the name of the index that you wish to use, `T` with the name of the table and `C` with the name of the column.
If you need to change the indices, you must drop them first using the following syntax:
`conn.execute('drop index if exists I')`
where I is the name of the index to be dropped.
```
conn.execute('begin transaction')
# YOUR CODE HERE
conn.execute('commit')
```
In the cell below, rerun the query that you defined in Step 3.1 100 times get a new timing. The database will now use the indices that you created if they are beneficial to the execution.
Is the query faster?
```
%%time
for i in range(0, 100):
# YOUR CODE HERE
```
| github_jupyter |
# **Assignment 5 Solutions** #
### **Q1. Implement a Union-Find Data Structure** ###
In lecture 6 we discussed Union-Find Data structures. The lecture was based on these [slides](https://www.cs.princeton.edu/courses/archive/spr09/cos226/lectures/01UnionFind.pdf). The slides contain Java code fo the Union-Find operations. For this assignment you should implement a Python class that implements a Union-Find Data Structure that uses weighting and path compression. Essentially this amounts to translating the code in the slides using the same specifications. Make sure you review the material and understand what the code does, and how it works.
```
# your implementation goes here
class UnionFind:
def __init__(self, n):
self.id = list(range(n))
self.sz = [1]*n
def root(self,i):
while (i != self.id[i]):
id[i] = id[id[i]]; #this is for path compression
i = self.id[i]
return i
def find(self,p,q):
return (self.root(p) == self.root(q))
def unite(self,p,q):
i = self.root(p)
j = self.root(q)
# weighted version
if self.sz[i]<self.sz[j]:
self.id[i] = j
self.sz[j] = self.sz[j]+self.sz[i]
else:
self.id[j] = i
self.sz[i] = self.sz[i]+self.sz[j]
S = UnionFind(5)
print(S.id)
print(S.sz)
print(S.find(3,2))
S.unite(3,2)
print(S.id)
print(S.sz)
```
### **Q2. Random Permutation**
Implement a function *randperm* that takes as input a number $n$, and returns a random permutation of the numbers [0...n-1]. This was covered in lecture 7. Your implementation should use $O(1)$ space in addition to the space needed for the output. (Note: you can use any random number generator functions from Python's *random* module, but you have to give you own implementation for randperm)
```
# your implementation goes here
import random
def randperm(n):
prm = list(range(n))
for j in range(n):
# random number in (0,n-j)
k = random.randrange(n-j)
tmp = prm[k]
prm[k] = prm[n-1-j]
prm[n-1-j] = tmp
return prm
randperm(5)
```
### **Q3. Adjacency matrices, powers, numpy** <br>
(this exercise should be useful for your mini-project)

Consider the above graph [(also here)](https://drive.google.com/file/d/1tIyXRGiQvMv-1EcJxzkQS2MpMNL9hUOA/view?usp=sharing).
The following exercise should be **repeated twice**. For the given directed graph and for the same graph where all edges have no directions.
**(a)** Create a numpy array containing the adjacency matrix $A$ for the graph.
**(b)** A sequence of nodes $v_1,v_2,...,v_k$ is called a walk on graph $G$, if $(v_i,v_{i+1})$ is an edge in $G$. The length of a walk with $k$ vertices is defined to be $k-1$. In the above graph pick a pair of nodes $(i,j)$, and report all different walks of length 3 from $i$ to $j$. (That is find, all the ways of going from $i$ to $j$ in 3 steps).
**(c)** Using numpy, calculate $A^3$, the third power of the adjacency matrix. Read the entry $(i,j)$ of this matrix. What do you observe?
```
# the following demonstrates the answer for the directed graph
# your code goes here
import numpy as np
A = np.zeros([10,10])
A[0,2] = 1
A[1,9] = 1
A[2,7] = 1
A[3,0] = 1
A[3,5] = 1
A[4,1] = 1
A[4,2] = 1
A[5,4] = 1
A[6,4] = 1
A[7,1] = 1
A[7,8] = 1
A[8,5] = 1
A[8,9] = 1
A[9,6] = 1
A[9,8] = 1
A3 = np.linalg.matrix_power(A,3)
# A3(i,j) is equal to the number of walks of length 3 between (i,j)
print(A3)
# the following demonstrates the answer for the undirected graph
# to avoid re-typing all opposite edges, I will use the matrix transpose
# transpose(A) is the array with the edges flipped
# then summing up the two matrices gives all edges
# because edge [8,9] has already both directions, its weight has to be halved in A_u
A_u = A + np.transpose(A)
A_u[8,9] = 1
A_u[9,8] = 1
A3_u = np.linalg.matrix_power(A_u,3)
print(A3_u)
```
### **Q4. A theoretical question**
Suppose a Python module contains an implementation of a function *maxSpanningTree(G)* that takes as input the adjacency list of graph $G$, with **positive** edge weights, and returns the edges of a maximum weight spanning tree. Further suppose that you can run this function, but you cannot access the code.
Explain how to use *maxSpanningTree(G)* in order to implement a *minSpanningTree(G)* function.
Make a copy $G'$ of $G$. Take all weights of $G'$, find the largest weight $w$, and then: negate all weights of $G'$ and add $w+1$. Running *maxSpanningTree(G)* on $G'$ will now give a tree $T'$, which contains the edges of a min spanning tree of $G$.
| github_jupyter |
# Evaluation Phase II Modell M2
```
import arrow
import numpy as np
import os
import glob
import pickle
import pandas as pd
import matplotlib.pyplot as plt
import torch
%run -i ./scripts/setConfigs.py
from matplotlib import rc
rc('text', usetex=True)
os.chdir(os.path.join(exp_data_path, 'experiment', 'fine_tuning'))
extension = 'csv'
result = glob.glob('*.{}'.format(extension))
result_fns = []
for res in result:
if 'tVPII' in res:
result_fns.append(res)
len(result_fns)
df_experiments = pd.read_csv(result_fns[0], sep=';')
df_experiments.head()
for file in result_fns[1:]:
df = pd.read_csv(file, sep=';')
df_experiments = df_experiments.append(df)
len(df_experiments)
os.chdir('..')
os.chdir('..')
os.chdir('..')
print(os.getcwd())
df_experiments.head()
result_cols_x_test = ['Accuracy_x_test', 'Precision_x_test', 'Specifity_x_test', 'Sensitivity_x_test']
result_cols_x_drifted_ano = ['Accuracy_x_drifted_ano', 'Precision_x_drifted_ano', 'Specifity_x_drifted_ano', 'Sensitivity_x_drifted_ano']
df_res_x_test = df_experiments[result_cols_x_test]
df_res_x_drifted_ano = df_experiments[result_cols_x_drifted_ano]
fig, ax= plt.subplots(2,2, figsize=(20,10))
#df_res_x_test['Accuracy_x_test'].value_counts().sort_index().plot.bar(ax=ax[0][0])
ax[0][0].hist(df_res_x_test['Accuracy_x_test'], bins=20)
ax[0][0].set_title('Accuracy',fontsize=30)
ax[0][0].tick_params(axis='both', which='major', labelsize=22)
ax[0][1].hist(df_res_x_test['Precision_x_test'], bins=20)
ax[0][1].set_title('Precision',fontsize=30)
ax[0][1].tick_params(axis='both', which='major', labelsize=22)
ax[1][0].hist(df_res_x_test['Specifity_x_test'], bins=20)
ax[1][0].set_title('Specifity',fontsize=30)
ax[1][0].tick_params(axis='both', which='major', labelsize=22)
ax[1][1].hist(df_res_x_test['Sensitivity_x_test'], bins=20)
ax[1][1].set_title('Sensitivity',fontsize=30)
ax[1][1].tick_params(axis='both', which='major', labelsize=22)
#fig.suptitle('Histogramme der Kennzahlen der Modelle des Versuchsplans $\displaystyle tVP^{I}_{M_1}$ auf $X_{test}$', fontsize=30)
fig.tight_layout(rect=[0, 0.03, 1, 0.93])
save = True
if save:
fn = os.path.join(os.getcwd(), 'figs', '{}_results_tvp_2_m2_hists_x_test.pdf'.format(arrow.now().format('YYYYMMDD')))
fig.savefig(fn, bbox_inches='tight', pad_inches=0)
fig, ax= plt.subplots(2,2, figsize=(20,10))
ax[0][0].hist(df_res_x_drifted_ano['Accuracy_x_drifted_ano'], bins=20, color='orange')
ax[0][0].set_title('Accuracy',fontsize=30)
ax[0][0].tick_params(axis='both', which='major', labelsize=22)
ax[0][1].hist(df_res_x_drifted_ano['Precision_x_drifted_ano'], bins=20, color='orange')
ax[0][1].set_title('Precision',fontsize=30)
ax[0][1].tick_params(axis='both', which='major', labelsize=22)
ax[1][0].hist(df_res_x_drifted_ano['Specifity_x_drifted_ano'], bins=20, color='orange')
ax[1][0].set_title('Specifity',fontsize=30)
ax[1][0].tick_params(axis='both', which='major', labelsize=22)
ax[1][1].hist(df_res_x_drifted_ano['Sensitivity_x_drifted_ano'], bins=20, color='orange')
ax[1][1].set_title('Sensitivity',fontsize=30)
ax[1][1].tick_params(axis='both', which='major', labelsize=22)
#fig.suptitle('Histogramme der Kennzahlen der Modelle des Versuchsplans $\displaystyle tVP^{I}_{M_1}$ auf $X_{drifted,ano}$', fontsize=30)
fig.tight_layout(rect=[0, 0.03, 1, 0.93])
save = True
if save:
fn = os.path.join(os.getcwd(), 'figs', '{}_results_tvp_2_m2_hists_x_drifted_ano.pdf'.format(arrow.now().format('YYYYMMDD')))
fig.savefig(fn, bbox_inches='tight', pad_inches=0)
df_res_x_drifted_ano.describe()
df_res_x_test.describe()
```
| github_jupyter |
# Lab 3 - MapReduce
In this lab, we practice the MapReduce programming paradigm.
We will complete the tasks using the accompanied *mapreduce* package (as **mapreduce.py**) and MRJob. Please download the **mapreduce.py** file from our online class resource page, and place it in the same folder with your notebook.
For each invocation of an MapReduce job (with mr.run()), you are expected to supply a mapper, a reducer and/or a combiner as needed. Below are sample usage of the package:
```python
# Run on input1 using your mapper1 and reducer1 function
output = list(mr.run(input1, mapper1, reducer1))
# Run on input2 using only your mapper2, no reduce phase
output = list(mr.run(enumerate(input2), mapper2, combiner2))
# Run on input3 using 2 nested MapReduce jobs
output = mr.run(mr.run(input3, mapper3, reducer3), mapper4)
```
Please note that the input must be an iteratable of **key/value pairs**. If your inpu tdata does not have a key, you can simply add a null or index key through **enumerator(input)**. The output of the mr.run() is always a **generator**. You have to cast it to a list if you'd like to view, index or print it out.
We will also need **book.txt** and **citibike.csv** to be downloaded.
```
!pip install mrjob
!gdown --id 1sq4-zXn2Z82mdLSBBegEgsUsfqtgza-C -O mapreduce.py
!gdown --id 1qCQ6edyhTA1kqFWZf1y65ogidivDbBIT -O book.txt
!gdown --id 1I8eqA1Zy3vFq4mN8z0ZRl7ABXrdzCRYI -O citibike.csv
import csv
import mapreduce as mr
```
## Task 0
Here is another concrete example on "Word Count" using the package. Assuming we have a text file named *book.txt*. Our task is to count the frequency of words in this document, and print the top 10. For illustration purposes, we use only the first 1000 lines of the book for counting.
```
with open('book.txt', 'r') as fi:
lines = [(i,line.strip()) for i,line in enumerate(fi) if i<1000]
### After this, 'lines' stores a list of 1000 text lines
def mapper(k1, line):
for word in line.strip().split(' '):
if len(word)>0:
yield (word, 1)
def reducer(word, counts):
yield (word, sum(counts))
wCounts = list(mr.run(lines, mapper, reducer))
sortedCounts = sorted(wCounts, key=lambda x: -x[1])
sortedCounts[:10]
!head -n 2 citibike.csv
```
## Task 1
We would like to write a MapReduce job to count the total number of trips involved at each station. For example, if a trip starts at station A and stops at station B, the trip will count for both A and B. The output must be tuples, each consisting of a station name and a count.
```
def mapper1(station, row):
<CODE_HERE>
def reducer1(station, counts):
<CODE_HERE>
with open('citibike.csv', 'r') as fi:
reader = enumerate(csv.DictReader(fi))
output1 = list(mr.run(reader, mapper1, reducer1))
output1[:10]
```
## Task 2
Below is an example of showing how to use nested jobs and jobs with mappers only using the mapreduce package, thus, no points are included. Our task here is that we would like to filter the output of Task 1 to display only those stations with more than 1000 trips involved, of course, using the MapReduce paradigm.
```
def mapper2(station, count):
<CODE_HERE>
with open('citibike.csv', 'r') as fi:
reader = enumerate(csv.DictReader(fi))
output2 = list(mr.run(mr.run(reader, mapper1, reducer1), mapper2))
output2
```
## Task 3
We would like to count the number of trips taken between pairs of stations. Trips taken from station A to station B or from station B to station A are both counted towards the station pair A and B. Please note that the station pair shoud be identified by station names, as a tuple, and in lexical order, i.e. (A,B) instead of (B,A) in this case. The output must be tuples, each consisting of the station pair identification and a count.
```
def mapper3(_, row):
<CODE_HERE>
def reducer3(station_pair, counts):
<CODE_HERE>
with open('citibike.csv', 'r') as fi:
reader = enumerate(csv.DictReader(fi))
output3 = list(mr.run(reader, mapper3, reducer3))
output3[:10]
```
## Task 4
In this task, you are asked to compute the station with the most riders started from, per each gender of the *'Subscriber'* user. Meaning, what was the station name with the highest number of bike pickups for female riders, for male riders and for unknown riders.
The output will be a list of tuples, each includes a gender label (as indicated below) and another tuple consisting of a station name, and the total number of trips started at that station for that gender.
The label mapping for the gender column in citibike.csv is: (Zero=<b>Unknown</b>; 1=<b>Male</b>; 2=<b>Female</b>)
```
from mrjob.job import MRJob
from mrjob.step import MRStep
import re
WORD_RE = re.compile(r"[\w']+")
class MRTask4(MRJob):
def mapper4(self, _, line):
row = line.split(',')
if row[14] == 'Subscriber':
gender_station = (row[16], row[6])
yield (gender_station, 1)
def reducer4(self, gender_station, counts):
stations = (gender_station[1], sum(counts))
yield (gender_station[0], stations)
def mapper5(self, gender, station_count):
genderLabel = ('Unknown', 'Male', 'Female')[int(gender)]
yield (genderLabel, station_count)
def reducer5(self, genderLabel, station_counts):
yield (genderLabel, max(station_counts, key=lambda x: x[1]))
def steps(self):
return [
MRStep(mapper=self.mapper4, reducer=self.reducer4),
MRStep(mapper=self.mapper5, reducer=self.reducer5),
]
task4 = MRTask4(args=[])
with open('citibike.csv', 'r') as fi:
reader = enumerate(fi)
output5 = list(mr.runJob(reader, task4))
output5[:10]
!python task4.py citibike.csv | head
```
## Task 5
MRJob is a convenient package for simplifying the execution of MapReduce jobs on clusters. However, it doesn't work in a notebook. We're going to convert some of the examples of MRJob into our notebooks so that we can test our code before deploying them on Hadoop.
The two examples are available at:
https://mrjob.readthedocs.io/en/latest/guides/quickstart.html
https://mrjob.readthedocs.io/en/latest/guides/writing-mrjobs.html
```
!python mr_word_count.py book.txt
list(enumerate(next(open('citibike.csv', 'r')).strip().split(',')))
from mrjob.job import MRJob
class MRTask1(MRJob):
def mapper(self, _, line):
record = line.split(',')
yield (record[6],1)
yield (record[10],1)
def reducer(self, station, counts):
yield (station,sum(counts))
task1 = MRTask1(args=[])
with open('citibike.csv', 'r') as fi:
reader = enumerate(fi)
output1 = list(mr.runJob(reader, task1))
output1[:10]
!python task1.py citibike.csv | head
```
## Task 6
Let's try to run the above MRJob examples as stand-alone applications. Please check again:
https://mrjob.readthedocs.io/en/latest/guides/writing-mrjobs.html#defining-steps
```
from mrjob.job import MRJob
from mrjob.step import MRStep
import re
WORD_RE = re.compile(r"[\w']+")
class MRMostUsedWord(MRJob):
def mapper_get_words(self, _, line):
# yield each word in the line
for word in WORD_RE.findall(line):
yield (word.lower(), 1)
def combiner_count_words(self, word, counts):
# sum the words we've seen so far
yield (word, sum(counts))
def reducer_count_words(self, word, counts):
# send all (num_occurrences, word) pairs to the same reducer.
# num_occurrences is so we can easily use Python's max() function.
yield None, (sum(counts), word)
# discard the key; it is just None
def reducer_find_max_word(self, _, word_count_pairs):
# each item of word_count_pairs is (count, word),
# so yielding one results in key=counts, value=word
yield max(word_count_pairs)
def steps(self):
return [
MRStep(mapper=self.mapper_get_words,
combiner=self.combiner_count_words,
reducer=self.reducer_count_words),
MRStep(reducer=self.reducer_find_max_word)
]
with open('')
taskMostUsed = MRMostUsedWord(args=[])
mostUsed = mr.runJob(lines, taskMostUsed)
list(mostUsed)
```
| 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.
```
# Beyond Hello World, A Computer Vision Example
In the previous exercise you saw how to create a neural network that figured out the problem you were trying to solve. This gave an explicit example of learned behavior. Of course, in that instance, it was a bit of overkill because it would have been easier to write the function Y=2x-1 directly, instead of bothering with using Machine Learning to learn the relationship between X and Y for a fixed set of values, and extending that for all values.
But what about a scenario where writing rules like that is much more difficult -- for example a computer vision problem? Let's take a look at a scenario where we can recognize different items of clothing, trained from a dataset containing 10 different types.
## Start Coding
Let's start with our import of TensorFlow.
(**Note:** You can run the notebook using TensorFlow 2.5.0)
```
#!pip install tensorflow==2.5.0
import tensorflow as tf
print(tf.__version__)
```
The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this:
```
mnist = tf.keras.datasets.fashion_mnist
```
Calling load_data on this object will give you two sets of two lists, these will be the training and testing values for the graphics that contain the clothing items and their labels.
```
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
```
What does these values look like? Let's print a training image, and a training label to see...Experiment with different indices in the array. For example, also take a look at index 42...that's a a different boot than the one at index 0
```
import numpy as np
np.set_printoptions(linewidth=200)
import matplotlib.pyplot as plt
plt.imshow(training_images[789])
print(training_labels[789])
print(training_images[789])
```
You'll notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it's easier if we treat all values as between 0 and 1, a process called '**normalizing**'...and fortunately in Python it's easy to normalize a list like this without looping. You do it like this:
```
training_images = training_images / 255.0
test_images = test_images / 255.0
```
Now you might be wondering why there are 2 sets...training and testing -- remember we spoke about this in the intro? The idea is to have 1 set of data for training, and then another set of data...that the model hasn't yet seen...to see how good it would be at classifying values. After all, when you're done, you're going to want to try it out with data that it hadn't previously seen!
Let's now design the model. There's quite a few new concepts here, but don't worry, you'll get the hang of them.
```
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
```
**Sequential**: That defines a SEQUENCE of layers in the neural network
**Flatten**: Remember earlier where our images were a square, when you printed them out? Flatten just takes that square and turns it into a 1 dimensional set.
**Dense**: Adds a layer of neurons
Each layer of neurons need an **activation function** to tell them what to do. There's lots of options, but just use these for now.
**Relu** effectively means "If X>0 return X, else return 0" -- so what it does it it only passes values 0 or greater to the next layer in the network.
**Softmax** takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0,0,0,0,1,0,0,0,0] -- The goal is to save a lot of coding!
The next thing to do, now the model is defined, is to actually build it. You do this by compiling it with an optimizer and loss function as before -- and then you train it by calling **model.fit ** asking it to fit your training data to your training labels -- i.e. have it figure out the relationship between the training data and its actual labels, so in future if you have data that looks like the training data, then it can make a prediction for what that data would look like.
```
model.compile(optimizer = tf.optimizers.Adam(),
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
```
Once it's done training -- you should see an accuracy value at the end of the final epoch. It might look something like 0.9098. This tells you that your neural network is about 91% accurate in classifying the training data. I.E., it figured out a pattern match between the image and the labels that worked 91% of the time. Not great, but not bad considering it was only trained for 5 epochs and done quite quickly.
But how would it work with unseen data? That's why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back the loss for each. Let's give it a try:
```
model.evaluate(test_images, test_labels)
```
For me, that returned a accuracy of about .8838, which means it was about 88% accurate. As expected it probably would not do as well with *unseen* data as it did with data it was trained on! As you go through this course, you'll look at ways to improve this.
To explore further, try the below exercises:
# Exploration Exercises
```
#import tensorflow as tf
```
### Exercise 1:
For this first exercise run the below code: It creates a set of classifications for each of the test images, and then prints the first entry in the classifications. The output, after you run it is a list of numbers. Why do you think this is, and what do those numbers represent?
```
classifications = model.predict(test_images)
print(classifications[0])
```
**Hint:** try running `print(test_labels[0])` -- and you'll get a `9`. Does that help you understand why this list looks the way it does?
```
print(test_labels[0])
```
### E1Q1: What does this list represent?
1. It's 10 random meaningless values
2. It's the first 10 classifications that the computer made
3. It's the probability that this item is each of the 10 classes
#### Answer:
The correct answer is (3)
The output of the model is a list of 10 numbers. These numbers are a probability that the value being classified is the corresponding value (https://github.com/zalandoresearch/fashion-mnist#labels), i.e. the first value in the list is the probability that the image is of a '0' (T-shirt/top), the next is a '1' (Trouser) etc. Notice that they are all VERY LOW probabilities.
For index 9 (Ankle boot), the probability was in the 90's, i.e. the neural network is telling us that the image is most likely an ankle boot.
### E1Q2: How do you know that this list tells you that the item is an ankle boot?
1. There's not enough information to answer that question
2. The 10th element on the list is the biggest, and the ankle boot is labelled 9
2. The ankle boot is label 9, and there are 0->9 elements in the list
#### Answer
The correct answer is (2). Both the list and the labels are 0 based, so the ankle boot having label 9 means that it is the 10th of the 10 classes. The list having the 10th element being the highest value means that the Neural Network has predicted that the item it is classifying is most likely an ankle boot
### Exercise 2:
Let's now look at the layers in your model. Experiment with different values for the dense layer with 512 neurons. What different results do you get for loss, training time etc? Why do you think that's the case?
```
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1024, activation=tf.nn.relu), # Try experimenting with this layer
tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy')
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
print(classifications[0])
print(test_labels[0])
```
### E2Q1: Increase to 1024 Neurons -- What's the impact?
1. Training takes longer, but is more accurate
2. Training takes longer, but no impact on accuracy
3. Training takes the same time, but is more accurate
#### Answer
The correct answer is (1) by adding more Neurons we have to do more calculations, slowing down the process, but in this case they have a good impact -- we do get more accurate. That doesn't mean it's always a case of 'more is better', you can hit the law of diminishing returns very quickly!
### Exercise 3:
### E3Q1: What would happen if you remove the Flatten() layer. Why do you think that's the case?
#### Answer
You get an error about the shape of the data. It may seem vague right now, but it reinforces the rule of thumb that the first layer in your network should be the same shape as your data. Right now our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of writng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.
```
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), #Try removing this layer
tf.keras.layers.Dense(64, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy')
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
print(classifications[0])
print(test_labels[0])
model.evaluate(test_images,test_labels)
```
### Exercise 4:
Consider the final (output) layers. Why are there 10 of them? What would happen if you had a different amount than 10? For example, try training the network with 5.
#### Answer
You get an error as soon as it finds an unexpected value. Another rule of thumb -- the number of neurons in the last layer should match the number of classes you are classifying for. In this case it's the digits 0-9, so there are 10 of them, hence you should have 10 neurons in your final layer.
```
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation=tf.nn.relu),
tf.keras.layers.Dense(8, activation=tf.nn.softmax) # Try experimenting with this layer
])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
print(classifications[0])
print(test_labels[0])
```
### Exercise 5:
Consider the effects of additional layers in the network. What will happen if you add another layer between the one with 512 and the final layer with 10.
#### Answer
There isn't a significant impact -- because this is relatively simple data. For far more complex data (including color images to be classified as flowers that you'll see in the next lesson), extra layers are often necessary.
```
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(712,activation=tf.nn.softmax),
tf.keras.layers.Dense(256, activation=tf.nn.relu),
tf.keras.layers.Dense(10,activation=tf.nn.softmax)
])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
print(classifications[0])
print(test_labels[0])
```
### Exercise 6:
### E6Q1: Consider the impact of training for more or less epochs. Why do you think that would be the case?
- Try 15 epochs -- you'll probably get a model with a much better loss than the one with 5
- Try 30 epochs -- you might see the loss value stops decreasing, and sometimes increases.
This is a side effect of something called 'overfitting' which you can learn about later and it's something you need to keep an eye out for when training neural networks. There's no point in wasting your time training if you aren't improving your loss, right! :)
```
mnist = tf.keras.datasets.mnist
(training_images, training_labels) , (test_images, test_labels) = mnist.load_data()
training_images = training_images/255.0
test_images = test_images/255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy')
model.fit(training_images, training_labels, epochs=5) # Experiment with the number of epochs
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
print(classifications[34])
print(test_labels[34])
```
### Exercise 7:
Before you trained, you normalized the data, going from values that were 0-255 to values that were 0-1. What would be the impact of removing that? Here's the complete code to give it a try. Why do you think you get different results?
```
mnist = tf.keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
#training_images=training_images/255.0 # Experiment with removing this line
#test_images=test_images/255.0 # Experiment with removing this line
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)
classifications = model.predict(test_images)
print(classifications[0])
print(test_labels[0])
```
### Exercise 8:
Earlier when you trained for extra epochs you had an issue where your loss might change. It might have taken a bit of time for you to wait for the training to do that, and you might have thought 'wouldn't it be nice if I could stop the training when I reach a desired value?' -- i.e. 95% accuracy might be enough for you, and if you reach that after 3 epochs, why sit around waiting for it to finish a lot more epochs....So how would you fix that? Like any other program...you have callbacks! Let's see them in action...
```
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy') >= 0.6): # Experiment with changing this value
print("\nReached 60% accuracy so cancelling training!")
self.model.stop_training = True
callbacks = myCallback()
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images/255.0
test_images=test_images/255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks])
```
| github_jupyter |
# An Introduction to Models in Pyro
The basic unit of probabilistic programs is the _stochastic function_.
This is an arbitrary Python callable that combines two ingredients:
- deterministic Python code; and
- primitive stochastic functions that call a random number generator
Concretely, a stochastic function can be any Python object with a `__call__()` method, like a function, a method, or a PyTorch `nn.Module`.
Throughout the tutorials and documentation, we will often call stochastic functions *models*, since stochastic functions can be used to represent simplified or abstract descriptions of a process by which data are generated. Expressing models as stochastic functions means that models can be composed, reused, imported, and serialized just like regular Python callables.
```
import torch
import pyro
pyro.set_rng_seed(101)
```
## Primitive Stochastic Functions
Primitive stochastic functions, or distributions, are an important class of stochastic functions for which we can explicitly compute the probability of the outputs given the inputs. As of PyTorch 0.4 and Pyro 0.2, Pyro uses PyTorch's [distribution library](http://pytorch.org/docs/master/distributions.html). You can also create custom distributions using [transforms](http://pytorch.org/docs/master/distributions.html#module-torch.distributions.transforms).
Using primitive stochastic functions is easy. For example, to draw a sample `x` from the unit normal distribution $\mathcal{N}(0,1)$ we do the following:
```
loc = 0. # mean zero
scale = 1. # unit variance
normal = torch.distributions.Normal(loc, scale) # create a normal distribution object
x = normal.rsample() # draw a sample from N(0,1)
print("sample", x)
print("log prob", normal.log_prob(x)) # score the sample from N(0,1)
```
Here, `torch.distributions.Normal` is an instance of the `Distribution` class that takes parameters and provides sample and score methods. Pyro's distribution library `pyro.distributions` is a thin wrapper around `torch.distributions` because we want to make use of PyTorch's fast tensor math and autograd capabilities during inference.
## A Simple Model
All probabilistic programs are built up by composing primitive stochastic functions and deterministic computation. Since we're ultimately interested in probabilistic programming because we want to model things in the real world, let's start with a model of something concrete.
Let's suppose we have a bunch of data with daily mean temperatures and cloud cover. We want to reason about how temperature interacts with whether it was sunny or cloudy. A simple stochastic function that describes how that data might have been generated is given by:
```
def weather():
cloudy = torch.distributions.Bernoulli(0.3).sample()
cloudy = 'cloudy' if cloudy.item() == 1.0 else 'sunny'
mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]
scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[cloudy]
temp = torch.distributions.Normal(mean_temp, scale_temp).rsample()
return cloudy, temp.item()
```
Let's go through this line-by-line. First, in lines 2-3 we define a binary random variable 'cloudy', which is given by a draw from the bernoulli distribution with a parameter of `0.3`. Since the bernoulli distributions returns `0`s or `1`s, in line 4 we convert the value `cloudy` to a string so that return values of `weather` are easier to parse. So according to this model 30% of the time it's cloudy and 70% of the time it's sunny.
In lines 5-6 we define the parameters we're going to use to sample the temperature in lines 7-9. These parameters depend on the particular value of `cloudy` we sampled in line 2. For example, the mean temperature is 55 degrees (Fahrenheit) on cloudy days and 75 degrees on sunny days. Finally we return the two values `cloudy` and `temp` in line 10.
However, `weather` is entirely independent of Pyro - it only calls PyTorch. We need to turn it into a Pyro program if we want to use this model for anything other than sampling fake data.
## The `pyro.sample` Primitive
To turn `weather` into a Pyro program, we'll replace the `torch.distribution`s with `pyro.distribution`s and the `.sample()` and `.rsample()` calls with calls to `pyro.sample`, one of the core language primitives in Pyro. Using `pyro.sample` is as simple as calling a primitive stochastic function with one important difference:
```
x = pyro.sample("my_sample", pyro.distributions.Normal(loc, scale))
print(x)
```
Just like a direct call to `torch.distributions.Normal().rsample()`, this returns a sample from the unit normal distribution. The crucial difference is that this sample is _named_. Pyro's backend uses these names to uniquely identify sample statements and _change their behavior at runtime_ depending on how the enclosing stochastic function is being used. As we will see, this is how Pyro can implement the various manipulations that underlie inference algorithms.
Now that we've introduced `pyro.sample` and `pyro.distributions` we can rewrite our simple model as a Pyro program:
```
def weather():
cloudy = pyro.sample('cloudy', pyro.distributions.Bernoulli(0.3))
cloudy = 'cloudy' if cloudy.item() == 1.0 else 'sunny'
mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]
scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[cloudy]
temp = pyro.sample('temp', pyro.distributions.Normal(mean_temp, scale_temp))
return cloudy, temp.item()
for _ in range(3):
print(weather())
```
Procedurally, `weather()` is still a non-deterministic Python callable that returns two random samples. Because the randomness is now invoked with `pyro.sample`, however, it is much more than that. In particular `weather()` specifies a joint probability distribution over two named random variables: `cloudy` and `temp`. As such, it defines a probabilistic model that we can reason about using the techniques of probability theory. For example we might ask: if I observe a temperature of 70 degrees, how likely is it to be cloudy? How to formulate and answer these kinds of questions will be the subject of the next tutorial.
## Universality: Stochastic Recursion, Higher-order Stochastic Functions, and Random Control Flow
We've now seen how to define a simple model. Building off of it is easy. For example:
```
def ice_cream_sales():
cloudy, temp = weather()
expected_sales = 200. if cloudy == 'sunny' and temp > 80.0 else 50.
ice_cream = pyro.sample('ice_cream', pyro.distributions.Normal(expected_sales, 10.0))
return ice_cream
```
This kind of modularity, familiar to any programmer, is obviously very powerful. But is it powerful enough to encompass all the different kinds of models we'd like to express?
It turns out that because Pyro is embedded in Python, stochastic functions can contain arbitrarily complex deterministic Python and randomness can freely affect control flow. For example, we can construct recursive functions that terminate their recursion nondeterministically, provided we take care to pass `pyro.sample` unique sample names whenever it's called. For example we can define a geometric distribution that counts the number of failures until the first success like so:
```
def geometric(p, t=None):
if t is None:
t = 0
x = pyro.sample("x_{}".format(t), pyro.distributions.Bernoulli(p))
if x.item() == 1:
return 0
else:
return 1 + geometric(p, t + 1)
print(geometric(0.5))
```
Note that the names `x_0`, `x_1`, etc., in `geometric()` are generated dynamically and that different executions can have different numbers of named random variables.
We are also free to define stochastic functions that accept as input or produce as output other stochastic functions:
```
def normal_product(loc, scale):
z1 = pyro.sample("z1", pyro.distributions.Normal(loc, scale))
z2 = pyro.sample("z2", pyro.distributions.Normal(loc, scale))
y = z1 * z2
return y
def make_normal_normal():
mu_latent = pyro.sample("mu_latent", pyro.distributions.Normal(0, 1))
fn = lambda scale: normal_product(mu_latent, scale)
return fn
print(make_normal_normal()(1.))
```
Here `make_normal_normal()` is a stochastic function that takes one argument and which, upon execution, generates three named random variables.
The fact that Pyro supports arbitrary Python code like this—iteration, recursion, higher-order functions, etc.—in conjuction with random control flow means that Pyro stochastic functions are _universal_, i.e. they can be used to represent any computable probability distribution. As we will see in subsequent tutorials, this is incredibly powerful.
It is worth emphasizing that this is one reason why Pyro is built on top of PyTorch: dynamic computational graphs are an important ingredient in allowing for universal models that can benefit from GPU-accelerated tensor math.
## Next Steps
We've shown how we can use stochastic functions and primitive distributions to represent models in Pyro. In order to learn models from data and reason about them we need to be able to do inference. This is the subject of the [next tutorial](intro_part_ii.ipynb).
| github_jupyter |
# Initialization
```
!pip install -U sentence-transformers
from sentence_transformers import SentenceTransformer, util
import torch
import json
import numpy as np
import pandas as pd
ISSUES_FILE = 'drive/MyDrive/bugs_data/eall.csv'
CUSTOM_MODEL_PATH = 'drive/MyDrive/bugs_data/models/paraphrase-distilroberta-base-v1-eall-40000'
```
# Issues Helper Methods
```
def get_issues(issues_file):
issues = pd.read_csv(issues_file)
issues['full_description'] = issues['short_desc'].astype(str) + '\n' + issues['description'].astype(str)
return issues
```
# Model Helper Methods
```
def get_base_model():
return SentenceTransformer('paraphrase-distilroberta-base-v1')
def get_custom_model(name):
return SentenceTransformer(name)
```
# Main
```
issues = get_issues(ISSUES_FILE)
issues = issues.iloc[-10000:].reset_index(drop=True)
len(issues)
model = get_custom_model(CUSTOM_MODEL_PATH)
model
model = get_base_model()
```
Gather the newest duplicates from the issues set
```
issues_new_duplicates = issues.iloc[-1500:].loc[issues['dup_id'] == issues['dup_id']].reset_index(drop=True)
!nvidia-smi
```
Ensure that the newest duplicates gathered are not in the set of issues from which we will try to retrieve top-k similar issues
```
issues_pool = issues[~issues['bug_id'].isin(issues_new_duplicates['bug_id'])].reset_index(drop=True)
```
Calculate embeddings for the issues pool
```
embeddings = model.encode(np.array(issues_pool['full_description']), convert_to_tensor=True)
```
# Top-K Retrieval Methods
```
def get_top_k_similar_issues(query_embedding, embeddings, top_k):
return util.semantic_search(query_embedding, embeddings, top_k=top_k)[0]
def evaluate_recall_at_top_k(model, query_issues, pool_issues, embeddings, top_k):
count = 0
correct = 0
for index, row in query_issues.iterrows():
count += 1
query_embedding = model.encode(row['full_description'], convert_to_tensor=True)
results = get_top_k_similar_issues(query_embedding, embeddings, top_k)
correct_prediction_found = False
for result in results:
result_issue = pool_issues.iloc[result['corpus_id']]
if result_issue['master_id'] == row['master_id']:
correct_prediction_found = True
if correct_prediction_found:
correct += 1
print(correct / count)
return correct / count
evaluate_recall_at_top_k(model, issues_new_duplicates, issues_pool, embeddings, 25)
```
# Fine-Tuning with OnlineContrastiveLoss
```
!pip install -U sentence-transformers
from sentence_transformers import SentenceTransformer, InputExample, losses, evaluation
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import torch
PAIRS_FILE = 'drive/MyDrive/bugs_data/uall_pairs_40000.csv'
MODEL_OUTPUT_PATH = 'drive/MyDrive/bugs_data/models/paraphrase-distilroberta-base-v1-uall-40000'
pairs = pd.read_csv(PAIRS_FILE)
pairs_train, pairs_test = train_test_split(pairs, test_size=0.1)
train_data = []
for index, pair in pairs_train.iterrows():
train_sample = InputExample(texts=[pair['description_1'], pair['description_2']], label=float(pair['label']))
train_data.append(train_sample)
descriptions_1 = pairs_test['description_1'].to_list()
descriptions_2 = pairs_test['description_2'].to_list()
scores = pairs_test['label'].to_list()
model = SentenceTransformer('paraphrase-distilroberta-base-v1')
model
distance_metric = losses.SiameseDistanceMetric.COSINE_DISTANCE
margin = 0.5
evaluator = evaluation.EmbeddingSimilarityEvaluator(descriptions_1, descriptions_2, scores, write_csv=True)
train_dataloader = DataLoader(train_data, shuffle=True, batch_size=64)
train_loss = losses.OnlineContrastiveLoss(model=model, distance_metric=distance_metric, margin=margin)
model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=5, warmup_steps=100, evaluator=evaluator, evaluation_steps=50, output_path=MODEL_OUTPUT_PATH, save_best_model=True)
model.save(MODEL_OUTPUT_PATH)
```
Evaluate Embeddings
```
import matplotlib.pyplot as plt
model_to_evaluate = SentenceTransformer('paraphrase-distilroberta-base-v1')
def evaluate_embeddings(model, pairs):
evaluations_list = []
for index, row in pairs.iterrows():
embedding_1 = model.encode(row['description_1'], convert_to_tensor=True)
embedding_2 = model.encode(row['description_2'], convert_to_tensor=True)
cos_similarity = torch.nn.CosineSimilarity(dim=0, eps=1e-6)
similarity = cos_similarity(embedding_1, embedding_2)
evaluations_list.append({
'prediction': similarity.item(),
'label': row['label']
})
df = pd.DataFrame(evaluations_list)
df['prediction'] = (df['prediction'] - df['prediction'].min()) / (df['prediction'].max() - df['prediction'].min())
colors = {0: '#ff6361', 1: '#58508d'}
plt.scatter(df.index, df['prediction'], c=df['label'].map(colors), s=5)
plt.xticks([])
plt.savefig('temp.png', dpi=300)
plt.show()
evaluate_embeddings(model_to_evaluate, pairs_test[-2000:])
```
| github_jupyter |
```
%%capture
import os
import site
os.sys.path.insert(0, '/home/schirrmr/code/reversible/reversible2/')
os.sys.path.insert(0, '/home/schirrmr/braindecode/code/braindecode/')
os.sys.path.insert(0, '/home/schirrmr/code/explaining/reversible//')
%cd /home/schirrmr/
%load_ext autoreload
%autoreload 2
import numpy as np
import logging
log = logging.getLogger()
log.setLevel('INFO')
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s',
level=logging.INFO, stream=sys.stdout)
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import cm
%matplotlib inline
%config InlineBackend.figure_format = 'png'
matplotlib.rcParams['figure.figsize'] = (12.0, 1.0)
matplotlib.rcParams['font.size'] = 14
import seaborn
seaborn.set_style('darkgrid')
from reversible.sliced import sliced_from_samples
from numpy.random import RandomState
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import copy
import math
import itertools
from reversible.plot import create_bw_image
import torch as th
from braindecode.torch_ext.util import np_to_var, var_to_np
from reversible.revnet import ResidualBlock, invert, SubsampleSplitter, ViewAs, ReversibleBlockOld
from spectral_norm import spectral_norm
from conv_spectral_norm import conv_spectral_norm
def display_text(text, fontsize=18):
fig = plt.figure(figsize=(12,0.1))
plt.title(text, fontsize=fontsize)
plt.axis('off')
display(fig)
plt.close(fig)
from braindecode.datasets.bbci import BBCIDataset
from braindecode.mne_ext.signalproc import mne_apply
# we loaded all sensors to always get same cleaning results independent of sensor selection
# There is an inbuilt heuristic that tries to use only EEG channels and that definitely
# works for datasets in our paper
#train_loader = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/train/13.mat')
#test_loader = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/test/13.mat')
start_cnt = BBCIDataset('/data/schirrmr/schirrmr/HGD-public/reduced/train/4.mat',).load()
start_cnt = start_cnt.drop_channels(['STI 014'])
def car(a):
return a - np.mean(a, keepdims=True, axis=0)
start_cnt = mne_apply(
car, start_cnt)
start_cnt = start_cnt.reorder_channels(['C3', 'C4'])
from collections import OrderedDict
from braindecode.datautil.trial_segment import create_signal_target_from_raw_mne
marker_def = OrderedDict([('Right Hand', [1]), ('Left Hand', [2],),
('Rest', [3]), ('Feet', [4])])
ival = [500,1500]
from braindecode.mne_ext.signalproc import mne_apply, resample_cnt
from braindecode.datautil.signalproc import exponential_running_standardize, bandpass_cnt
log.info("Resampling train...")
cnt = resample_cnt(start_cnt, 250.0)
log.info("Standardizing train...")
cnt = mne_apply(lambda a: exponential_running_standardize(a.T ,factor_new=1e-3, init_block_size=1000, eps=1e-4).T,
cnt)
cnt = resample_cnt(cnt, 2.0)
cnt = resample_cnt(cnt, 4.0)
#cnt = mne_apply(
# lambda a: bandpass_cnt(a, 0, 2, cnt.info['sfreq'],
# filt_order=10,
# axis=1), cnt)
train_set = create_signal_target_from_raw_mne(cnt, marker_def, ival)
x_right = train_set.X[train_set.y == 0]
x_rest = train_set.X[train_set.y == 2]
inputs_a = np_to_var(x_right[:160,0:1,:,None], dtype=np.float32).cuda()
inputs_b = np_to_var(x_rest[:160,0:1,:,None], dtype=np.float32).cuda()
inputs = [inputs_a, inputs_b]
fig = plt.figure(figsize=(8,4))
for i_class in range(2):
ins = var_to_np(inputs[i_class].squeeze())
bps = np.abs(np.fft.rfft(ins.squeeze()))
plt.plot(np.fft.rfftfreq(ins.squeeze().shape[1], d=1/ins.squeeze().shape[1]), np.median(bps, axis=0))
plt.title("Spectrum")
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')
plt.legend(['Real Right', 'Fake Right', 'Real Rest', 'Fake Rest'])
display(fig)
plt.close(fig)
fig, axes = plt.subplots(16,20, figsize=(14,14), sharex=True, sharey=True)
for i_class in range(2):
for i_example in range(len(inputs[i_class])):
i_row = i_example // 10
i_col = i_example % 10
i_col += i_class * 10
axes[i_row][i_col].plot(var_to_np(inputs[i_class][i_example]).squeeze(),
color=seaborn.color_palette()[i_class])
fig.suptitle('Input signals')
from matplotlib.lines import Line2D
lines = [Line2D([0], [0], color=seaborn.color_palette()[i_class],) for i_class in range(2)]
labels = ['Right', 'Rest',]
axes[0][-1].legend(lines, labels, bbox_to_anchor=(1,1,0,0))
from matplotlib.lines import Line2D
plt.figure(figsize=(10,6))
for i_class in range(2):
plt.plot(var_to_np(inputs[i_class].squeeze()).T, color=seaborn.color_palette()[i_class],lw=0.5);
lines = [Line2D([0], [0], color=seaborn.color_palette()[i_class],) for i_class in range(2)]
plt.legend(lines, ['Right', 'Rest',], bbox_to_anchor=(1,1,0,0))
plt.title('Input signals')
def rev_block(n_c, n_i_c):
return ReversibleBlockOld(
nn.Sequential(
nn.Conv2d(n_c // 2, n_i_c,(3,1), stride=1, padding=(1,0),bias=True),
nn.ReLU(),
nn.Conv2d(n_i_c, n_c // 2,(3,1), stride=1, padding=(1,0),bias=True)),
nn.Sequential(
nn.Conv2d(n_c // 2, n_i_c,(3,1), stride=1, padding=(1,0),bias=True),
nn.ReLU(),
nn.Conv2d(n_i_c, n_c // 2,(3,1), stride=1, padding=(1,0),bias=True))
)
def res_block(n_c, n_i_c):
return ResidualBlock(
nn.Sequential(
nn.Conv2d(n_c, n_i_c, (3,1), stride=1, padding=(1,0),bias=True),
nn.ReLU(),
nn.Conv2d(n_i_c, n_c, (3,1), stride=1, padding=(1,0),bias=True)),
)
from discriminator import ProjectionDiscriminator
from reversible.revnet import SubsampleSplitter, ViewAs
from reversible.util import set_random_seeds
from reversible.revnet import init_model_params
from torch.nn import ConstantPad2d
import torch as th
from conv_spectral_norm import conv_spectral_norm
from disttransform import DSFTransform
set_random_seeds(2019011641, True)
feature_model = nn.Sequential(
SubsampleSplitter(stride=[2,1],chunk_chans_first=False),
rev_block(2,32),
rev_block(2,32),
SubsampleSplitter(stride=[2,1],chunk_chans_first=False),
rev_block(4,32),
rev_block(4,32),
ViewAs((-1,4,1,1), (-1,4))
)
feature_model.cuda()
from braindecode.torch_ext.util import set_random_seeds
adv_model = nn.Sequential(
nn.Conv2d(1,16, (3,1), stride=1, padding=(1,0),bias=True),
res_block(16,32),
res_block(16,32),
nn.AvgPool2d((2,1)),
res_block(16,32),
res_block(16,32),
ViewAs((-1,16,2,1), (-1,32)),
)
adv_model = ProjectionDiscriminator(adv_model,32,2,)
adv_model.cuda()
from reversible.training import hard_init_std_mean
n_dims = inputs_b.shape[2]
n_clusters = 2
means_per_cluster = [th.autograd.Variable(th.ones(n_dims).cuda(), requires_grad=True)
for _ in range(n_clusters)]
# keep in mind this is in log domain so 0 is std 1
stds_per_cluster = [th.autograd.Variable(th.zeros(n_dims).cuda(), requires_grad=True)
for _ in range(n_clusters)]
for i_class in range(2):
this_outs = feature_model(inputs[i_class])
means_per_cluster[i_class].data = th.mean(this_outs, dim=0).data
stds_per_cluster[i_class].data = th.log(th.std(this_outs, dim=0)).data
# override phase
means_per_cluster[i_class].data[len(stds_per_cluster[i_class])//2:] = 0
stds_per_cluster[i_class].data[len(stds_per_cluster[i_class])//2:] = 0
dsf = DSFTransform(4,100)
dsf.cuda()
from copy import deepcopy
optimizer = th.optim.Adam(
[
{'params': list(feature_model.parameters()),
'lr': 1e-3,
'weight_decay': 0},], betas=(0,0.9))
optim_dist = th.optim.Adam(
[
{'params': means_per_cluster + stds_per_cluster + list(dsf.parameters()),
'lr': 1e-2,
'weight_decay': 0},], betas=(0,0.9))
optim_adv = th.optim.Adam([{
'params': adv_model.parameters(),
'lr': 4e-3, 'weight_decay': 0.00}],#lr 0.0004
betas=(0,0.9))
from reversible.gaussian import get_gauss_samples
from reversible.uniform import get_uniform_samples
from ampphase import (amp_phase_to_x_y, get_amp_phase_samples, amp_phase_sample_to_x_y,
outs_to_amp_phase, to_amp_phase,
switch_to_other_class, get_transformed_amp_phase_xy_samples)
def get_transformed_amp_phase_xy_samples(n_samples, mean, std, truncate_to,
dsf_transform):
amps, phases = get_amp_phase_samples(n_samples, mean, std, truncate_to)
amps, phases = th.chunk(dsf_transform(th.cat((amps,phases), dim=1)),2, dim=1)
amps = th.abs(amps)
x, y = amp_phase_to_x_y(amps, phases)
samples = th.cat((x,y), dim=1)
return samples
from reversible.gaussian import get_gauss_samples
from reversible.uniform import get_uniform_samples
from reversible.revnet import invert
import pandas as pd
from gradient_penalty import gradient_penalty
import time
df = pd.DataFrame()
g_loss = np_to_var([np.nan],dtype=np.float32)
g_grad = np.nan
d_loss = np_to_var([np.nan],dtype=np.float32)
d_grad = np.nan
n_epochs = 10001
for i_epoch in range(n_epochs):
start_time = time.time()
optim_adv.zero_grad()
optimizer.zero_grad()
optim_dist.zero_grad()
for i_class in range(len(inputs)):
mean = means_per_cluster[i_class]
log_std = stds_per_cluster[i_class]
std = th.exp(log_std)
this_inputs = inputs[i_class]
y = np_to_var([i_class]).cuda()
samples = get_transformed_amp_phase_xy_samples(len(this_inputs), mean, std, truncate_to=3,
dsf_transform=dsf)
#other_outs = featureget_transformed_amp_phase_xy_samples_model(inputs[1-i_class])
# move to this class
#other_outs = switch_to_other_class(other_outs, means_per_cluster, stds_per_cluster, 1-i_class,
# n_examples_per_out=10)
#samples = th.cat((samples, other_outs), dim=0)
inverted = invert(feature_model, samples)
score_fake = adv_model(inverted, y)
if (i_epoch % 10) != 0:
score_real = adv_model(this_inputs, y)
gradient_loss = gradient_penalty(adv_model, this_inputs, inverted[:(len(this_inputs))], y)
d_loss = -score_real.mean() + score_fake.mean() + gradient_loss * 10
d_loss.backward()
d_grad = np.mean([th.sum(p.grad **2).item() for p in adv_model.parameters()])
else:
g_loss = -th.mean(score_fake)
g_loss.backward()
g_grad = np.mean([th.sum(p.grad **2).item() for p in feature_model.parameters()])
if (i_epoch % 10) != 0:
optim_adv.step()
else:
optimizer.step()
optim_dist.step()
with th.no_grad():
sample_wd_row = {}
for i_class in range(len(inputs)):
this_inputs = inputs[i_class]
mean = means_per_cluster[i_class]
log_std = stds_per_cluster[i_class]
std = th.exp(log_std)
y = np_to_var([i_class]).cuda()
samples = get_transformed_amp_phase_xy_samples(len(this_inputs), mean, std, truncate_to=3,
dsf_transform=dsf)
inverted = invert(feature_model, samples)
in_np = var_to_np(this_inputs).reshape(len(this_inputs), -1)
fake_np = var_to_np(inverted).reshape(len(inverted), -1)
import ot
dist = np.sqrt(np.sum(np.square(in_np[:,None] - fake_np[None]), axis=2))
match_matrix = ot.emd([],[], dist)
cost = np.sum(dist * match_matrix)
score_fake = adv_model(inverted, y)
score_real = adv_model(inputs[i_class], y)
wd_dist = th.mean(score_real) - th.mean(score_fake)
sample_wd_row.update({
'wd_dist_' + str(i_class): wd_dist.item() ,
'sampled_wd' + str(i_class): cost,
'wd_diff' + str(i_class): cost - wd_dist.item(),
})
end_time = time.time()
epoch_row = {
'd_loss': d_loss.item(),
'g_loss': g_loss.item(),
'o_real': th.mean(score_real).item(),
'o_fake': th.mean(score_fake).item(),
'g_grad': g_grad,
'd_grad': d_grad,
'runtime': end_time -start_time,}
epoch_row.update(sample_wd_row)
df = df.append(epoch_row, ignore_index=True)
if i_epoch % (max(1,n_epochs // 100)) == 0:
display_text("Epoch {:d}".format(i_epoch))
display(df.iloc[-5:])
if i_epoch % (n_epochs // 20) == 0:
print("stds\n", var_to_np(th.exp(th.stack(stds_per_cluster))))
fig = plt.figure(figsize=(8,4))
for i_class in range(2):
ins = var_to_np(inputs[i_class].squeeze())
bps = np.abs(np.fft.rfft(ins.squeeze()))
plt.plot(np.fft.rfftfreq(ins.squeeze().shape[1], d=1/ins.squeeze().shape[1]), np.median(bps, axis=0))
mean = means_per_cluster[i_class]
log_std = stds_per_cluster[i_class]
std = th.exp(log_std)
y = np_to_var([i_class]).cuda()
samples = get_transformed_amp_phase_xy_samples(5000, mean, std, truncate_to=3,
dsf_transform=dsf)
inverted = var_to_np(invert(feature_model, samples).squeeze())
bps = np.abs(np.fft.rfft(inverted.squeeze()))
plt.plot(np.fft.rfftfreq(inverted.squeeze().shape[1], d=1/ins.squeeze().shape[1]), np.median(bps, axis=0),
color=seaborn.color_palette()[i_class], ls='--')
plt.title("Spectrum")
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')
plt.legend(['Real Right', 'Fake Right', 'Real Rest', 'Fake Rest'])
display(fig)
plt.close(fig)
for i_class in range(2):
fig = plt.figure(figsize=(5,5))
mean = means_per_cluster[i_class]
log_std = stds_per_cluster[i_class]
std = th.exp(log_std)
y = np_to_var([i_class]).cuda()
samples = get_transformed_amp_phase_xy_samples(5000, mean, std, truncate_to=3,
dsf_transform=dsf)
inverted = var_to_np(invert(feature_model, samples).squeeze())
plt.plot(inverted.squeeze()[:,0], inverted.squeeze()[:,1],
ls='', marker='o', color=seaborn.color_palette()[i_class + 2], alpha=0.5, markersize=2)
plt.plot(var_to_np(inputs[i_class].squeeze())[:,0], var_to_np(inputs[i_class].squeeze())[:,1],
ls='', marker='o', color=seaborn.color_palette()[i_class])
display(fig)
plt.close(fig)
n_classes = len(stds_per_cluster)
n_f_values = 9
image_grid = np.zeros((len(std), n_f_values, n_classes, inputs[i_class].shape[2]))
for i_class in range(len(stds_per_cluster)):
mean = means_per_cluster[i_class]
log_std = stds_per_cluster[i_class]
std = th.exp(log_std)
for i_std in range(len(std)):
if i_std < len(std) // 2:
feature_a_values = np.concatenate((np.linspace(
float(abs(mean[i_std].data) + 2 * std[i_std].data), float(abs(mean[i_std].data)),
n_f_values// 2 + 1)[:-1],
np.linspace(float(abs(mean[i_std].data)),
float(abs(mean[i_std].data) + 2 * std[i_std].data), n_f_values // 2 + 1),
))
else:
feature_a_values = th.linspace(float(mean[i_std].data - np.pi * std[i_std].data),
float(mean[i_std].data + np.pi * std[i_std].data), n_f_values)
for i_f_a_val, f_a_val in enumerate(feature_a_values):
this_out = mean.clone()
this_out.data[:len(std) // 2] = th.abs(this_out.data[:len(std) // 2])
this_out.data[i_std] = f_a_val
this_out = amp_phase_sample_to_x_y(dsf(this_out.unsqueeze(0)))
inverted = var_to_np(invert(feature_model, this_out)[0]).squeeze()
image_grid[i_std, i_f_a_val, i_class] = np.copy(inverted)
fig, axes = plt.subplots(image_grid.shape[0], image_grid.shape[1],
sharex=True, sharey=True,
figsize=(int(image_grid.shape[1] * 1.5), int(image_grid.shape[0]) * 1.25))
plt.subplots_adjust(wspace=0, hspace=0.2)
axes[0][-1].legend(['Right', 'Rest'], bbox_to_anchor=[1,1,0,0])
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list(
'twoclasses', seaborn.color_palette()[:2][::-1])
log_ratios = stds_per_cluster[1] - stds_per_cluster[0]
max_abs_log_ratio = var_to_np(th.max(th.abs(log_ratios)))
_ , i_sorted_std = th.sort(log_ratios)
# image grid is stds x timepoints x classes
for i_row, i_std in enumerate(i_sorted_std):
std1 = th.exp(stds_per_cluster[0][i_std]).item()
std2 = th.exp(stds_per_cluster[1][i_std]).item()
log_ratio = stds_per_cluster[0][i_std] - stds_per_cluster[1][i_std]
ratio = th.exp(th.abs(log_ratio)).item()
axes[i_row][0].text(-0.7,0.5,"{:.1f}\n{:.1f}\n{:.1f}".format(
std1,
std2,
ratio), va='center',color=cmap((log_ratio.item() + max_abs_log_ratio) / (2*max_abs_log_ratio)),
transform=axes[i_row][0].transAxes)
axes[i_row][0].text(-1.,0.5, "A" if i_std < (len(i_sorted_std) // 2) else "P",
transform=axes[i_row][0].transAxes)
for i_f_val in range(image_grid.shape[1]):
curves = image_grid[i_std][i_f_val]
for i_class in range(n_classes):
axes[i_row,i_f_val].plot(
np.linspace(
0,1000, len(curves[i_class])),
curves[i_class], color=seaborn.color_palette()[i_class])
axes[0][0].text(-0.5,1.5, "Stds\nRatio", transform=axes[0][0].transAxes)
display(fig)
plt.close(fig)
class_samples = []
ins_samples = []
for i_class in range(2):
mean = means_per_cluster[i_class]
log_std = stds_per_cluster[i_class]
std = th.exp(log_std)
y = np_to_var([i_class]).cuda()
samples = get_transformed_amp_phase_xy_samples(5000, mean, std, truncate_to=3,
dsf_transform=dsf)
ins = invert(feature_model, samples)
class_samples.append(var_to_np(samples))
ins_samples.append(var_to_np(ins))
diffs = class_samples[0][:,None] - class_samples[1][None]
diffs = np.sqrt(np.sum(diffs * diffs, axis=2),)
import ot
coupling = ot.emd([],[], diffs, numItermax=200000)
mask = coupling > (1/(2*len(diffs) ))
assert np.sum(mask) == 5000
i_first, i_second = np.nonzero(mask)
assert np.array_equal(np.arange(len(mask)), i_first)
fig, axes = plt.subplots(10, 4,
sharex=True, sharey=True,
figsize=(12,12))
plt.subplots_adjust(wspace=0, hspace=0.2)
for ax, i_a, i_b in zip(axes.flatten(), i_first[:40], i_second[:40]):
ax.plot(ins_samples[0][i_a].squeeze())
ax.plot(ins_samples[1][i_b].squeeze())
```
| github_jupyter |
```
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from tqdm import tqdm
%matplotlib inline
from torch.utils.data import Dataset, DataLoader
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
m = 5 # 5, 50, 100, 500, 2000
train_size = 500 # 100, 500, 2000, 10000
desired_num = train_size + 1000
tr_i = 0
tr_j = train_size
tr_k = desired_num
tr_i, tr_j, tr_k
```
# Generate dataset
```
np.random.seed(12)
y = np.random.randint(0,10,5000)
idx= []
for i in range(10):
print(i,sum(y==i))
idx.append(y==i)
x = np.zeros((5000,2))
np.random.seed(12)
x[idx[0],:] = np.random.multivariate_normal(mean = [4,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[0]))
x[idx[1],:] = np.random.multivariate_normal(mean = [5.5,6],cov=[[0.01,0],[0,0.01]],size=sum(idx[1]))
x[idx[2],:] = np.random.multivariate_normal(mean = [4.5,4.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[2]))
x[idx[3],:] = np.random.multivariate_normal(mean = [3,3.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[3]))
x[idx[4],:] = np.random.multivariate_normal(mean = [2.5,5.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[4]))
x[idx[5],:] = np.random.multivariate_normal(mean = [3.5,8],cov=[[0.01,0],[0,0.01]],size=sum(idx[5]))
x[idx[6],:] = np.random.multivariate_normal(mean = [5.5,8],cov=[[0.01,0],[0,0.01]],size=sum(idx[6]))
x[idx[7],:] = np.random.multivariate_normal(mean = [7,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[7]))
x[idx[8],:] = np.random.multivariate_normal(mean = [6.5,4.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[8]))
x[idx[9],:] = np.random.multivariate_normal(mean = [5,3],cov=[[0.01,0],[0,0.01]],size=sum(idx[9]))
x[idx[0]][0], x[idx[5]][5]
for i in range(10):
plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
bg_idx = [ np.where(idx[3] == True)[0],
np.where(idx[4] == True)[0],
np.where(idx[5] == True)[0],
np.where(idx[6] == True)[0],
np.where(idx[7] == True)[0],
np.where(idx[8] == True)[0],
np.where(idx[9] == True)[0]]
bg_idx = np.concatenate(bg_idx, axis = 0)
bg_idx.shape
np.unique(bg_idx).shape
x = x - np.mean(x[bg_idx], axis = 0, keepdims = True)
np.mean(x[bg_idx], axis = 0, keepdims = True), np.mean(x, axis = 0, keepdims = True)
x = x/np.std(x[bg_idx], axis = 0, keepdims = True)
np.std(x[bg_idx], axis = 0, keepdims = True), np.std(x, axis = 0, keepdims = True)
for i in range(10):
plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
foreground_classes = {'class_0','class_1', 'class_2'}
background_classes = {'class_3','class_4', 'class_5', 'class_6','class_7', 'class_8', 'class_9'}
fg_class = np.random.randint(0,3)
fg_idx = np.random.randint(0,m)
a = []
for i in range(m):
if i == fg_idx:
b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1)
a.append(x[b])
print("foreground "+str(fg_class)+" present at " + str(fg_idx))
else:
bg_class = np.random.randint(3,10)
b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1)
a.append(x[b])
print("background "+str(bg_class)+" present at " + str(i))
a = np.concatenate(a,axis=0)
print(a.shape)
print(fg_class , fg_idx)
np.reshape(a,(2*m,1))
mosaic_list_of_images =[]
mosaic_label = []
fore_idx=[]
for j in range(desired_num):
np.random.seed(j)
fg_class = np.random.randint(0,3)
fg_idx = np.random.randint(0,m)
a = []
for i in range(m):
if i == fg_idx:
b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1)
a.append(x[b])
# print("foreground "+str(fg_class)+" present at " + str(fg_idx))
else:
bg_class = np.random.randint(3,10)
b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1)
a.append(x[b])
# print("background "+str(bg_class)+" present at " + str(i))
a = np.concatenate(a,axis=0)
mosaic_list_of_images.append(np.reshape(a,(2*m,1)))
mosaic_label.append(fg_class)
fore_idx.append(fg_idx)
mosaic_list_of_images = np.concatenate(mosaic_list_of_images,axis=1).T
mosaic_list_of_images.shape
mosaic_list_of_images.shape, mosaic_list_of_images[0]
for j in range(m):
print(mosaic_list_of_images[0][2*j:2*j+2])
def create_avg_image_from_mosaic_dataset(mosaic_dataset,labels,foreground_index,dataset_number, m):
"""
mosaic_dataset : mosaic_dataset contains 9 images 32 x 32 each as 1 data point
labels : mosaic_dataset labels
foreground_index : contains list of indexes where foreground image is present so that using this we can take weighted average
dataset_number : will help us to tell what ratio of foreground image to be taken. for eg: if it is "j" then fg_image_ratio = j/9 , bg_image_ratio = (9-j)/8*9
"""
avg_image_dataset = []
cnt = 0
counter = np.zeros(m) #np.array([0,0,0,0,0,0,0,0,0])
for i in range(len(mosaic_dataset)):
img = torch.zeros([2], dtype=torch.float64)
np.random.seed(int(dataset_number*10000 + i))
give_pref = foreground_index[i] #np.random.randint(0,9)
# print("outside", give_pref,foreground_index[i])
for j in range(m):
if j == give_pref:
img = img + mosaic_dataset[i][2*j:2*j+2]*dataset_number/m #2 is data dim
else :
img = img + mosaic_dataset[i][2*j:2*j+2]*(m-dataset_number)/((m-1)*m)
if give_pref == foreground_index[i] :
# print("equal are", give_pref,foreground_index[i])
cnt += 1
counter[give_pref] += 1
else :
counter[give_pref] += 1
avg_image_dataset.append(img)
print("number of correct averaging happened for dataset "+str(dataset_number)+" is "+str(cnt))
print("the averaging are done as ", counter)
return avg_image_dataset , labels , foreground_index
avg_image_dataset_1 , labels_1, fg_index_1 = create_avg_image_from_mosaic_dataset(mosaic_list_of_images[0:tr_j], mosaic_label[0:tr_j], fore_idx[0:tr_j] , 1, m)
test_dataset , labels , fg_index = create_avg_image_from_mosaic_dataset(mosaic_list_of_images[tr_j : tr_k], mosaic_label[tr_j : tr_k], fore_idx[tr_j : tr_k] , m, m)
avg_image_dataset_1 = torch.stack(avg_image_dataset_1, axis = 0)
# avg_image_dataset_1 = (avg - torch.mean(avg, keepdims= True, axis = 0)) / torch.std(avg, keepdims= True, axis = 0)
# print(torch.mean(avg_image_dataset_1, keepdims= True, axis = 0))
# print(torch.std(avg_image_dataset_1, keepdims= True, axis = 0))
print("=="*40)
test_dataset = torch.stack(test_dataset, axis = 0)
# test_dataset = (avg - torch.mean(avg, keepdims= True, axis = 0)) / torch.std(avg, keepdims= True, axis = 0)
# print(torch.mean(test_dataset, keepdims= True, axis = 0))
# print(torch.std(test_dataset, keepdims= True, axis = 0))
print("=="*40)
x1 = (avg_image_dataset_1).numpy()
y1 = np.array(labels_1)
plt.scatter(x1[y1==0,0], x1[y1==0,1], label='class 0')
plt.scatter(x1[y1==1,0], x1[y1==1,1], label='class 1')
plt.scatter(x1[y1==2,0], x1[y1==2,1], label='class 2')
plt.legend()
plt.title("dataset4 CIN with alpha = 1/"+str(m))
x1 = (test_dataset).numpy() / m
y1 = np.array(labels)
plt.scatter(x1[y1==0,0], x1[y1==0,1], label='class 0')
plt.scatter(x1[y1==1,0], x1[y1==1,1], label='class 1')
plt.scatter(x1[y1==2,0], x1[y1==2,1], label='class 2')
plt.legend()
plt.title("test dataset4")
test_dataset[0:10]/m
test_dataset = test_dataset/m
test_dataset[0:10]
test_dataset.shape
class MosaicDataset(Dataset):
"""MosaicDataset dataset."""
def __init__(self, mosaic_list_of_images, mosaic_label):
"""
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]
avg_image_dataset_1[0].shape
avg_image_dataset_1[0]
batch = 200
traindata_1 = MosaicDataset(avg_image_dataset_1, labels_1 )
trainloader_1 = DataLoader( traindata_1 , batch_size= batch ,shuffle=True)
testdata_1 = MosaicDataset(test_dataset, labels )
testloader_1 = DataLoader( testdata_1 , batch_size= batch ,shuffle=False)
# testdata_11 = MosaicDataset(test_dataset, labels )
# testloader_11 = DataLoader( testdata_11 , batch_size= batch ,shuffle=False)
class Whatnet(nn.Module):
def __init__(self):
super(Whatnet,self).__init__()
self.linear1 = nn.Linear(2,50)
self.linear2 = nn.Linear(50,3)
torch.nn.init.xavier_normal_(self.linear1.weight)
torch.nn.init.zeros_(self.linear1.bias)
torch.nn.init.xavier_normal_(self.linear2.weight)
torch.nn.init.zeros_(self.linear2.bias)
def forward(self,x):
x = F.relu(self.linear1(x))
x = (self.linear2(x))
return x
def calculate_loss(dataloader,model,criter):
model.eval()
r_loss = 0
with torch.no_grad():
for i, data in enumerate(dataloader, 0):
inputs, labels = data
inputs, labels = inputs.to("cuda"),labels.to("cuda")
outputs = model(inputs)
loss = criter(outputs, labels)
r_loss += loss.item()
return r_loss/(i+1)
def test_all(number, testloader,net):
correct = 0
total = 0
out = []
pred = []
with torch.no_grad():
for data in testloader:
images, labels = data
images, labels = images.to("cuda"),labels.to("cuda")
out.append(labels.cpu().numpy())
outputs= net(images)
_, predicted = torch.max(outputs.data, 1)
pred.append(predicted.cpu().numpy())
total += labels.size(0)
correct += (predicted == labels).sum().item()
pred = np.concatenate(pred, axis = 0)
out = np.concatenate(out, axis = 0)
print("unique out: ", np.unique(out), "unique pred: ", np.unique(pred) )
print("correct: ", correct, "total ", total)
print('Accuracy of the network on the %d test dataset %d: %.2f %%' % (total, number , 100 * correct / total))
def train_all(trainloader, ds_number, testloader_list, lr_list):
final_loss = []
for LR in lr_list:
print("--"*20, "Learning Rate used is", LR)
torch.manual_seed(12)
net = Whatnet().double()
net = net.to("cuda")
criterion_net = nn.CrossEntropyLoss()
optimizer_net = optim.Adam(net.parameters(), lr=0.001 ) #, momentum=0.9)
acti = []
loss_curi = []
epochs = 1000
running_loss = calculate_loss(trainloader,net,criterion_net)
loss_curi.append(running_loss)
print('epoch: [%d ] loss: %.3f' %(0,running_loss))
for epoch in range(epochs): # loop over the dataset multiple times
ep_lossi = []
running_loss = 0.0
net.train()
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
inputs, labels = inputs.to("cuda"),labels.to("cuda")
# zero the parameter gradients
optimizer_net.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion_net(outputs, labels)
# print statistics
running_loss += loss.item()
loss.backward()
optimizer_net.step()
running_loss = calculate_loss(trainloader,net,criterion_net)
if(epoch%200 == 0):
print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss))
loss_curi.append(running_loss) #loss per epoch
if running_loss<=0.05:
print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss))
break
print('Finished Training')
correct = 0
total = 0
with torch.no_grad():
for data in trainloader:
images, labels = data
images, labels = images.to("cuda"), labels.to("cuda")
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the %d train images: %.2f %%' % (total, 100 * correct / total))
for i, j in enumerate(testloader_list):
test_all(i+1, j,net)
print("--"*40)
final_loss.append(loss_curi)
return final_loss
train_loss_all=[]
testloader_list= [ testloader_1]
lr_list = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5 ]
fin_loss = train_all(trainloader_1, 1, testloader_list, lr_list)
train_loss_all.append(fin_loss)
%matplotlib inline
len(fin_loss)
for i,j in enumerate(fin_loss):
plt.plot(j,label ="LR = "+str(lr_list[i]))
plt.xlabel("Epochs")
plt.ylabel("Training_loss")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
```
| github_jupyter |
```
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics
import datetime as dt
import numpy as np
from census import Census # This is new...
import requests, io # internet and input tools
import zipfile as zf # zip file tools
import os
#import weightedcalcs as wc
#import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
print("")
print("**********************************************************************************")
print("Downloading and processing BLS file")
print("")
url = "https://data.bls.gov/cew/data/files/2017/csv/2017_annual_singlefile.zip"
# This will read in the annual, single file. It's big, but has all we want...
r = requests.get(url)
# convert bytes to zip file
bls_sf = zf.ZipFile(io.BytesIO(r.content))
print('Type of zipfile object:', type(bls_sf))
clist = ['area_fips', 'own_code', 'industry_code', 'agglvl_code', 'size_code',
'year', 'disclosure_code', 'annual_avg_estabs',
'annual_avg_emplvl', 'total_annual_wages','avg_annual_pay']
df = pd.read_csv(bls_sf.open(bls_sf.namelist()[0]), usecols= clist)
```
Then the file below cleans stuff up. The most important is the `NAICS_county_level` which selects the NAICS aggregation and then the county aggregation. Website describing this is here:
[https://data.bls.gov/cew/doc/titles/agglevel/agglevel_titles.htm](https://data.bls.gov/cew/doc/titles/agglevel/agglevel_titles.htm)
```
NAICS_county_level = 75
# This is the code that will select only counties at the 3 digit NAICS level
df_county = df[df.agglvl_code == NAICS_county_level].copy()
df_county = df_county[df_county.own_code == 5]
# Only grab private stuff
df_county = df_county[(df_county.area_fips.str[0:2] != "72") & (df_county.area_fips.str[0:2] != "78")
& (df_county.area_fips.str[0:2] != "02") & (df_county.area_fips.str[0:2] != "15")]
#Drop puerto rico, alaska, hawaii...this mayb not be doing what I think it is...as it looks like these guys are there
# Does not matter as analysis is performed withthem, drop them when do the map.
df_county["sup_ind"] = df_county.industry_code.str[1].astype(int)
# sometimes there are super industries floating around we want to drop them.
# not clear if this matters with the conditioning all ready
df_county = df_county[df_county["sup_ind"] > 0]
df_county.area_fips = df_county.area_fips.astype(str)
df_national = df_county.groupby("industry_code").agg({"annual_avg_emplvl": "sum"})
df_national.reset_index(inplace = True)
df_national.rename({"annual_avg_emplvl":"nat_emplvl"}, axis = 1, inplace = True)
```
Let's compute annual employment.
```
df_county.annual_avg_emplvl.sum()
```
which matches well with FRED (https://fred.stlouisfed.org/series/USPRIV) in 2017 (off by a couple million)
### Read in Trade Data and Merge
```
imports_by_naics = pd.read_csv(".//data//imports_by_naics.csv", dtype= {"naics3": str})
imports_by_naics.set_index(["naics3"], inplace = True)
dftrade_17_naics3 = pd.read_csv(".//data//2017_imports_by_naics.csv", dtype= {"naics3": str})
dftrade_17_naics3.set_index(["naics3"], inplace = True)
dftrade_17_naics3.head()
df_national = df_national.merge(dftrade_17_naics3["2017_china_trade"],
left_on = "industry_code", right_index = True, how = "left")
df_national["2017_china_trade"].replace(np.nan, 0, inplace = True)
df_national["trd_wts"] = (df_national["2017_china_trade"]/df_national["2017_china_trade"].sum())
```
Then check to make sure that the trade weights sum up to one.
```
df_national.trd_wts.sum()
```
---
### Step 3 Merge trade data with the county data
This is the most time consuming step (interms of compuation time). So start with the county data set, `groupby` county, then apply a function which will create (i) time varying exports (which are constructed with the 2017 weightes) and (ii) time varying tariffs (also constructed using the 2017) weights.
The final want is a big dataframe that has county, time, export exposure and tariff exposure.
```
print("")
print("**********************************************************************************")
print("Constructing County-Level Tariffs and Exports")
print("")
grp = df_county.groupby("area_fips")
# Let's just look at one of the groups...
#grp.get_group("1001").head()
```
Below are the two key functions that deliver this. Basically it does the following:
- Take a group at county level, merge it with the national level data set, so the resulting `df` has the county and nation.
- Create the weights.
- Then merge it with the exports, this will now be a df with exports varying over time, but with the fixed weights associated with each entry.
- Then aggregate the national exports by NAICS by the county level weights, giving a county level time series of exports.
---
**Updates**
- The tariff measure does the following: fix a county, take employment in industry $i$ and divide by total county employment, then sum up tariffs across industries with the weights being the county level share. The idea here is if all employment in a county is soy, then the "effective" tariff that the county faces is the soy tariff.
In equation terms: here $c$ is county, $s$ is industry, $n$, below is nation.
$\tau_{c,t} = \sum_{s\in S}\frac{L_{c,s}}{L_{c,S}} \tau_{s,t}$
Note that below, I make one further adjustment to make sure that $L_{c,S}$ is for all employment, not just the sum across $L_{c,s}$
- The export measure: What am I doing: take a county's employment in industry $i$ and divide by **national** level employment in industry $i$. Then a "county's" exports is the the sum across industries, weighted by the county's share of national employment in each industry. The idea here is, if a county's has all national level employment in an industry, all that industries exports will be assigned to that county.
$\mbox{EX}_{c,t} = \frac{1}{L_{c,S,2017}}\sum_{s\in S}\frac{L_{c,s,2017}}{L_{n,s,2017}} \mbox{EX}_{s,t}$
and then I divide by total employment in the county to have a county per worker measure. This is done for exports to China and then export in total. Note that below, I make one further adjustment to make sure that $L_{c,S}$ is for all employment, not just the sum across $L_{c,s}$
```
def create_trade_weights(df):
# Takes in the county groupings and will return, for each county, a time series of export
# exposure, tariffs, and other statistics.
new_df = df.merge(df_national[["nat_emplvl",
"industry_code", "trd_wts"]],
how = "outer", left_on = "industry_code", right_on = "industry_code")
# Merge the nation with the county, why, we want to make sure all the naics codes are lined up properly
new_df["emp_wts"] = (new_df.annual_avg_emplvl/new_df.nat_emplvl)
# create the weights...
foo_df = imports_by_naics.merge(new_df[["emp_wts","trd_wts",
"industry_code",
"annual_avg_emplvl"]], left_index = True, right_on = "industry_code")
# Now each weight is for a NAICS code, we will merge it with the export trade data set, so for all naics, all time...
# This is a big df whith all trade data and then the county's weights for each naics code
foo_grp = foo_df.groupby("time")
# group by time.
foo = foo_grp.apply(trade_by_naics)
# Then for each time gropuing, we aggregate across the naics codes according to the weights above.
foo = foo.droplevel(1)
foo["fips"] = df["area_fips"].astype(str).iloc[0]
# some cleaning of the df
foo["total_employment"] = new_df.annual_avg_emplvl.sum()
# get total employment.
return pd.DataFrame(foo)
def trade_by_naics(df):
# Simple function just to test about aggregation
china_imp_pc = (1/df["annual_avg_emplvl"].sum())*(df["china_trade"]*df["emp_wts"]).sum()
total_imp_pc = (1/df["annual_avg_emplvl"].sum())*(df["total_trade"]*df["emp_wts"]).sum()
# the first term multiplies trade by the county's share of national level employment
# then the outside term divides by number of workers in a county.
#tariff_nwt_pc = (1/df["annual_avg_emplvl"].sum())*(df["tariff_trd_w_avg"]*df["emp_wts"]).sum()
# This is the measure that makes most sense, need to justify it...
tariff = ((df["annual_avg_emplvl"]*df["tariff_trd_w_avg"])/df["annual_avg_emplvl"].sum()).sum()
# local employment share weighted tariff. So if all guys are in area are working in soy,
# then they are facing the soybean tariff....
foo = {"total_imp_pc": [total_imp_pc],
"china_imp_pc": [china_imp_pc],
"tariff": [tariff],
"emplvl_2017": df["annual_avg_emplvl"].sum()}
return pd.DataFrame(foo)
```
Then apply the function to the county groups
```
trade_county = grp.apply(create_trade_weights)
```
And we are done and output the file to where we want it
**One more adjustment.** Notice that in the function, when we are merging, we are droping all the NAICS codes without trade. So these measures (total trade, china trade, and tariffs) are only conditional on being traded. This only matters in so far as the denominator, the ``df["annual_avg_emplvl"].sum()`` is concerned.
To make the adjustment then, we multiply the employment measure in the denominator and then divide through by the ``total_employment`` measure.
```
trade_county["tariff"] = (trade_county["emplvl_2017"]/
trade_county["total_employment"])*trade_county["tariff"]
trade_county["china_imp_pc"] = (trade_county["emplvl_2017"]/
trade_county["total_employment"])*trade_county["china_imp_pc"]
trade_county["total_imp_pc"] = (trade_county["emplvl_2017"]/
trade_county["total_employment"])*trade_county["total_imp_pc"]
trade_county.sort_values(by = ["tariff","emplvl_2017"], ascending = False).head(25)
my_api_key = '34e40301bda77077e24c859c6c6c0b721ad73fc7'
# This is my api_key
c = Census(my_api_key)
# This will create an object c which has methods associated with it.
# We will see these below.
type(c)
# Per the discussion below, try c.tab and see the options.
code = ("NAME","B01001_001E","B19013_001E") # Same Codes:
county_2017 = pd.DataFrame(c.acs5.get(code,
{'for': 'county:*'}, year=2017))
# Same deal, but we specify county then the wild card
# On the example page, there are ways do do this, only by state
county_2017 = county_2017.rename(columns = {"B01001_001E":"2017_population", "B19013_001E":"2017_income"})
county_2017["GEOFIPS"] = (county_2017["state"] + county_2017["county"]).astype(int)
county_2017["2017_population"] = county_2017["2017_population"].astype(float)
county_2017["2017_income"] = county_2017["2017_income"].astype(float)
county_2017.set_index(["GEOFIPS"], inplace = True)
trade_county.reset_index(inplace = True)
trade_county["int_area_fips"] = trade_county["area_fips"].astype(int)
trade_county = trade_county.merge(county_2017[["2017_income","2017_population"]],
left_on = "int_area_fips", right_index = True, how = "left")
#trade_employ.drop(labels = "index", axis = 1, inplace = True)
trade_county.set_index(["area_fips", "time"],inplace = True)
trade_county.head()
file_path = ".\\data"+ "\\imports_trade_data_2020.parquet"
pq.write_table(pa.Table.from_pandas(trade_county.reset_index()), file_path)
```
| github_jupyter |
Uncertainty Sampling for Phases
===
Identifying sites for additional annotation based on the 'confidence' of the classifier.
```
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import sys
sys.path.append("../../annotation_data")
from phase import *
import pandas as pd
import numpy as np
import sklearn
import sklearn.metrics
import subprocess
import matplotlib.pyplot as plt
import matplotlib.dates as md
import matplotlib
import pylab as pl
vw_working_dir = "/home/srivbane/shared/caringbridge/data/projects/qual-health-journeys/classification/phases/vw"
```
# Utility functions
```
def compute_prediction_margin(pred, higher_class=0, lower_class=2):
# See page 14 of Settles et al. 2012 book on Active Learning
# This is the output margin, but because including two labels is perfectly valid for the phase classification task
# we instead formulate this as the output margin between the firsta nd third most likely predictions under the model
sorted_preds = sorted(pred, reverse=True)
margin = sorted_preds[higher_class] - sorted_preds[lower_class]
return margin
def compute_least_confident(pred, target=0):
# Compute the least confident by taking the instance with the score on any class that is closest to the target
return np.min(np.abs(pred - target))
def compute_max_margin_prediction_uncertainty(pred, threshold=0.5):
# See "Active Learning with Multi-Label SVM Classification" eq. 2
pos_pred = pred[pred > 0.5]
neg_pred = pred[pred < 0.5]
if len(pos_pred) == 0 or len(neg_pred) == 0:
# All or none of the labels were assigned using this threshold!
# Thus we say the margin is the distance to the threshold
return threshold - np.max(pred) if len(pos_pred) == 0 else np.min(pred) - threshold
min_pos_pred = np.min(pos_pred)
max_neg_pred = np.max(neg_pred)
sep_margin = min_pos_pred - max_neg_pred
return sep_margin
VALID_CLASS_LABELS = ([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1],
[1,1,0,0],[0,1,1,0],[0,1,0,1],[0,0,0,0])
def compute_pred_has_label_error(pred, threshold=0.5):
selected_classes = pred > threshold
if list(selected_classes.astype(np.int32)) in VALID_CLASS_LABELS:
return 0
else:
return 1
def compute_site_transition_error(site_preds, threshold=0.5):
"""
:param site_preds: should have shape (n_journals, n_classes=4)
"""
# This function should compute the number of invalid transitions in the sequence of preds, presumed to be
# from a single CaringBridge site
pass
```
# VW model outputs
```
classes_filepath = os.path.join(vw_working_dir, 'classes.npy')
labels = np.load(classes_filepath)
assert [labels[i] == phase_label for i, phase_label in enumerate(phase_labels)]
y_true_filepath = os.path.join(vw_working_dir, 'y_true.npy')
y_true = np.load(y_true_filepath)
y_score_filepath = os.path.join(vw_working_dir, 'y_score.npy')
y_score = np.load(y_score_filepath)
thresholds_filepath = os.path.join(vw_working_dir, 'class_thresholds.npy')
max_per_class_thresholds = np.load(thresholds_filepath)
y_pred = (y_score >= max_per_class_thresholds).astype(int)
weighted_f2_score = sklearn.metrics.fbeta_score(y_true, y_pred, 2, average='weighted')
weighted_f2_score
all_predictions_filepath = os.path.join(vw_working_dir, "vw_all_preds.pkl")
pred_df = pd.read_pickle(all_predictions_filepath)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import dill as pickle
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn import svm
from sklearn.utils import resample
from sklearn.externals import joblib
import sklearn.metrics as metrics
```
## Importing required functions
- For data cleaning and feature extraction
```
clean_columns = pickle.load(open("./outputs/models/87995/clean_columns.pickle", "rb"))
create_windows = pickle.load(open("./outputs/models/87995/create_windows.pickle", "rb"))
extract_features = pickle.load(open("./outputs/models/87995/extract_features.pickle", "rb"))
min_boundary = pickle.load(open("./outputs/models/87995/min_boundary.pickle", "rb"))
max_boundary = pickle.load(open("./outputs/models/87995/max_boundary.pickle", "rb"))
min_speed = pickle.load(open("./outputs/models/87995/min_speed.pickle", "rb"))
max_speed = pickle.load(open("./outputs/models/87995/max_speed.pickle", "rb"))
min_accuracy = pickle.load(open("./outputs/models/87995/min_accuracy.pickle", "rb"))
max_accuracy = pickle.load(open("./outputs/models/87995/max_accuracy.pickle", "rb"))
```
## Importing chosen model weights
- Imported best classifier from previous notebook
- Can assert to check
```
MODEL_PATH = "outputs/models/87995/Gradient Boosted Machine_0.74.pkl"
model = joblib.load(MODEL_PATH)
```
## Import Evaluation set
- Assumes that evaluation set will come in the same format as provided features
- Multiple .csv files
- Currently testing with provided training data
- To replace with evaluation feature data
```
# To insert the paths including file names for each .csv file in a list
SOURCE_LIST = [
"../grab-ai-safety-data/features/part-00001-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00002-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00003-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00003-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00004-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00005-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00006-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00007-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00008-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
"../grab-ai-safety-data/features/part-00009-e6120af0-10c2-4248-97c4-81baf4304e5c-c000.csv",
]
li = []
for csv in SOURCE_LIST:
df = pd.read_csv(csv)
li.append(df)
df = pd.concat(
li,
axis=0,
ignore_index=True
)
```
## Apply transformations
```
df = (
df.pipe(
clean_columns
).pipe(
create_windows
).pipe(
extract_features
)
)
```
## Predict using imported model
```
preds = pd.DataFrame(
model.predict(df),
columns=["label"]
)
```
## Export results to csv
```
# preds.to_csv("destination_path")
```
| github_jupyter |
# High Value Customers Identification (Champions) #
**By: Marx Cerqueira**
# IMPORTS
```
import re
import os
import s3fs
import inflection
import sqlite3
import pickle
import numpy as np
import pandas as pd
import seaborn as sns
import umap.umap_ as umap
from matplotlib import pyplot as plt
from sklearn import metrics as m
from sklearn import preprocessing as pp
from sklearn import decomposition as dd
from sklearn import ensemble as en
from sklearn import manifold as mn
from sklearn import mixture as mx
from sklearn import cluster as c
from scipy.cluster import hierarchy as hc
from plotly import express as px
from sqlalchemy import create_engine
```
## Loading Data
```
# get AWS environmnet access keys
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
# load data
path_s3 = 's3://mc-insiders-dataset/'
df_ecomm_raw = pd.read_csv(path_s3 + 'Ecommerce.csv',
encoding='iso-8859-1',
low_memory=False)
#drop extra column
df_ecomm_raw = df_ecomm_raw.drop(columns = ['Unnamed: 8'], axis = 1)
```
# DATA DISCRIPTION
```
# Copy dataset
df0 = df_ecomm_raw.copy()
```
## Rename Columns
```
cols_old = ['InvoiceNo','StockCode','Description','Quantity', 'InvoiceDate','UnitPrice','CustomerID','Country']
snakecase = lambda x: inflection.underscore(x)
col_news = list(map(snakecase, cols_old))
# Rename columns
df0.columns = col_news
```
## Data Dimension
```
print('Number of rows: {}.'.format(df0.shape[0]))
print('Number of cols: {}.'.format(df0.shape[1]))
```
## Data Types
```
df0.info()
```
## Check NA Values
```
missing_count = df0.isnull().sum() # the count of missing values
value_count = df0.isnull().count() # the total values count
missing_percentage = round(missing_count/value_count*100,2) # the percentage of missing values
missing_df = pd.DataFrame({'missing value count': missing_count, 'percentage': missing_percentage})
missing_df
barchart = missing_df.plot.bar(y='percentage')
for index, percentage in enumerate( missing_percentage ):
barchart.text( index, percentage, str(percentage)+'%')
```
## Fillout NA
```
# separate NA's in two different dataframe, one with NAs and other without it
df_missing = df0.loc[df0['customer_id'].isna(), :]
df_not_missing = df0.loc[~df0['customer_id'].isna(), :]
# create reference
df_backup = pd.DataFrame( df_missing['invoice_no'].drop_duplicates().copy() )
df_backup['customer_id'] = np.arange( 19000, 19000+len( df_backup ), 1) # Fillout NA stratety: creating customers_id to keep their behavior (25% of the database)
# merge original with reference dataframe
df0 = pd.merge( df0, df_backup, on='invoice_no', how='left' )
# coalesce
df0['customer_id'] = df0['customer_id_x'].combine_first( df0['customer_id_y'] )
# drop extra columns
df0 = df0.drop( columns=['customer_id_x', 'customer_id_y'], axis=1 )
```
## Change Types
```
# Transforme datatype of variable invoice_date to datetime
df0['invoice_date'] = pd.to_datetime(df0['invoice_date'])
df0['customer_id'] = df0['customer_id'].astype('int64')
```
## Descriptive Statistics
```
df0.describe().T
df0.describe(include = object).T
num_attributes = df0.select_dtypes(include = np.number)
cat_attributes = df0.select_dtypes(exclude = [np.number, np.datetime64])
```
### Numerical Attributes
```
# central tendency - mean, median
ct1 = pd.DataFrame(num_attributes.apply(np.mean)).T
ct2 = pd.DataFrame(num_attributes.apply(np.median)).T
# dispersion - desvio padrão, min, max, range, skew, kurtosis
d1 = pd.DataFrame(num_attributes.apply(np.std)).T
d2 = pd.DataFrame(num_attributes.apply(np.min)).T
d3 = pd.DataFrame(num_attributes.apply(np.max)).T
d4 = pd.DataFrame(num_attributes.apply(lambda x: x.max()-x.min())).T
d5 = pd.DataFrame(num_attributes.apply(lambda x: x.skew())).T
d6 = pd.DataFrame(num_attributes.apply(lambda x: x.kurtosis())).T
#concatenate
m1 = pd.concat([d2,d3,d4,ct1,ct2,d1,d5,d6]).T.reset_index()
m1.columns = ['attributes', 'min', 'max', 'range', 'mean', 'mediana','std', 'skew','kurtosis']
m1
```
### Categorical Attributes
#### Invoice_No
```
# problem: We got letters and numbers in invoice_no
#df1['invoice_no'].astype( int )
# identification:
df_letter_invoices = df0.loc[df0['invoice_no'].apply( lambda x: bool( re.search( '[^0-9]+', x ) ) ), :]
df_letter_invoices.head()
print( 'Total number of invoices: {}'.format( len( df_letter_invoices ) ) )
print( 'Total number of negative quantity: {}'.format( len( df_letter_invoices[ df_letter_invoices['quantity'] < 0 ] ) ) )
```
#### Stock_Code
```
# check stock codes only characters
df0.loc[df0['stock_code'].apply( lambda x: bool( re.search( '^[a-zA-Z]+$', x ) ) ), 'stock_code'].unique()
# Acão:
## 1. Remove stock_code in ['POST', 'D', 'M', 'PADS', 'DOT', 'CRUK']
```
# VARIABLE FILTERING
```
df1 = df0.copy()
# === Numerical attributes ====
df1 = df1.loc[df1['unit_price'] >= 0.04, :]
# === Categorical attributes ====
df1 = df1[~df1['stock_code'].isin( ['POST', 'D', 'DOT', 'M', 'S', 'AMAZONFEE', 'm', 'DCGSSBOY',
'DCGSSGIRL', 'PADS', 'B', 'CRUK'] )]
# description
df1 = df1.drop( columns='description', axis=1 )
# country
df1 = df1[~df1['country'].isin( ['European Community', 'Unspecified' ] ) ] #assuming this risk so we can use lat long parameters
# bad customers
df1 = df1[~df1['customer_id'].isin([16446, 12346, 15098])]
# quantity
df1_returns = df1.loc[df1['quantity'] < 0, :].copy()
df1_purchases = df1.loc[df1['quantity'] >= 0, :].copy()
```
# FEATURE ENGINEERING
```
df2 = df1.copy()
```
## Feature Creation
```
# data reference
# RFM Model, creating feature for it
df_ref = df2.drop(['invoice_no', 'stock_code',
'quantity', 'invoice_date', 'unit_price',
'country'], axis = 1).drop_duplicates(ignore_index = True).copy()
```
### Gross Revenue
```
# Gross Revenue ( Faturamento ) quantity * price
df1_purchases.loc[:, 'gross_revenue'] = df1_purchases.loc[:,'quantity'] * df1_purchases.loc[:, 'unit_price']
# Monetary (How much money a customer spends on purchases)
df_monetary = df1_purchases.loc[:, ['customer_id', 'gross_revenue']].groupby( 'customer_id' ).sum().reset_index()
df_ref = pd.merge( df_ref, df_monetary, on='customer_id', how='left' )
df_ref.isna().sum()
```
### Recency
```
# Recency - Day from last purchase
df_recency = df1_purchases.loc[:, ['customer_id', 'invoice_date']].groupby( 'customer_id' ).max().reset_index()
df_recency['recency_days'] = ( df1['invoice_date'].max() - df_recency['invoice_date'] ).dt.days
df_recency = df_recency[['customer_id', 'recency_days']].copy()
df_ref = pd.merge( df_ref, df_recency, on='customer_id', how='left' )
df_ref.isna().sum()
```
### Qty Invoice No
```
# Qty of invoice no per customer
df_invoice_no = df1_purchases[['customer_id', 'invoice_no']].drop_duplicates().groupby('customer_id').count().reset_index().rename(columns = {'invoice_no': 'qty_invoice_no'})
df_ref = pd.merge(df_ref, df_invoice_no, on = 'customer_id', how = 'left')
df_ref.isna().sum()
```
### Qty Items
```
# Quantity of items purchased by customer
df_freq = (df1_purchases.loc[:, ['customer_id', 'quantity']].groupby( 'customer_id' ).sum()
.reset_index()
.rename( columns={'quantity': 'qty_items'} ) )
df_ref = pd.merge( df_ref, df_freq, on='customer_id', how='left' )
df_ref.isna().sum()
```
### Qty Products (different stock codes by customer)
```
# Quantity of unique products purchased (Frequency: qntd of products over time)
# Number of products (different stock codes by customer)
df_freq = (df1_purchases.loc[:, ['customer_id', 'stock_code']].groupby( 'customer_id' ).count()
.reset_index()
.rename( columns={'stock_code': 'qty_products'} ) )
df_ref = pd.merge( df_ref, df_freq, on='customer_id', how='left' )
df_ref.isna().sum()
```
### Frequency
```
#Frequency Purchase (rate: purchases by day)
df_aux = ( df1_purchases[['customer_id', 'invoice_no', 'invoice_date']].drop_duplicates()
.groupby( 'customer_id')
.agg( max_ = ( 'invoice_date', 'max' ),
min_ = ( 'invoice_date', 'min' ),
days_= ( 'invoice_date', lambda x: ( ( x.max() - x.min() ).days ) + 1 ),
buy_ = ( 'invoice_no', 'count' ) ) ).reset_index()
# Frequency
df_aux['frequency'] = df_aux[['buy_', 'days_']].apply( lambda x: x['buy_'] / x['days_'] if x['days_'] != 0 else 0, axis=1 )
# Merge
df_ref = pd.merge( df_ref, df_aux[['customer_id', 'frequency']], on='customer_id', how='left' )
df_ref.isna().sum()
```
### Number of Returns
```
#Number of Returns
df_returns = df1_returns[['customer_id', 'quantity']].groupby( 'customer_id' ).sum().reset_index().rename( columns={'quantity':'qty_returns'} )
df_returns['qty_returns'] = df_returns['qty_returns'] * -1
df_ref = pd.merge( df_ref, df_returns, how='left', on='customer_id' )
df_ref.loc[df_ref['qty_returns'].isna(), 'qty_returns'] = 0 #customers with 0 returned items
df_ref.isna().sum()
```
# EXPLORATORY DATA ANALYSIS (EDA)
```
df3 = df_ref.dropna().copy()
```
## Space Study
```
# Original dataset
#df33 = df3.drop(columns = ['customer_id'], axis = '').copy()
# dataset with selected columns due feature selection based on its importance
cols_selected = ['customer_id', 'gross_revenue', 'recency_days', 'qty_invoice_no', 'qty_items' ,'qty_products', 'frequency', 'qty_returns']
df33 = df3[cols_selected].drop(columns = 'customer_id', axis = 1)
mm = pp.MinMaxScaler()
fs = s3fs.S3FileSystem(anon = False, key = AWS_ACCESS_KEY_ID, secret = AWS_SECRET_ACCESS_KEY)
# gross_revenue_scaler = pickle.load(open('../features/gross_revenue_scaler.pkl', 'rb')) #reading from local
gross_revenue_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/gross_revenue_scaler.pkl', 'rb')) #reading from S3
df33['gross_revenue'] = gross_revenue_scaler.transform(df33[['gross_revenue']])
# recency_days_scaler = pickle.load(open('../features/recency_days_scaler.pkl', 'rb'))
recency_days_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/recency_days_scaler.pkl', 'rb')) #reading from S3
df33['recency_days'] = recency_days_scaler.transform(df33[['recency_days']])
# qty_invoice_no_scaler = pickle.load(open('../features/qty_invoice_no_scaler.pkl', 'rb')) #reading from local
qty_invoice_no_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/qty_invoice_no_scaler.pkl', 'rb')) #reading from S3
df33['qty_invoice_no'] = qty_invoice_no_scaler.transform(df33[['qty_invoice_no']])
# qty_items_scaler = pickle.load(open('../features/qty_items_scaler.pkl', 'rb')) #reading from local
qty_items_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/qty_items_scaler.pkl', 'rb')) #reading from S3
df33['qty_items'] = qty_items_scaler.fit_transform(df33[['qty_items']])
# qty_products_scaler = pickle.load(open('../features/qty_products_scaler.pkl', 'rb'))
qty_products_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/qty_products_scaler.pkl', 'rb')) #reading from S3
df33['qty_products'] = qty_products_scaler.transform(df33[['qty_products']])
# frequency_scaler = pickle.load(open('../features/frequency_scaler.pkl', 'rb'))
frequency_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/frequency_scaler.pkl', 'rb')) #reading from S3
df33['frequency'] = frequency_scaler.transform(df33[['frequency']])
# qty_returns_scaler = pickle.load(open('../features/qty_returns_scaler.pkl', 'rb'))
qty_returns_scaler = pickle.load(fs.open('s3://mc-insiders-dataset/qty_returns_scaler.pkl', 'rb')) #reading from S3
df33['qty_returns'] = qty_returns_scaler.transform(df33[['qty_returns']])
```
#### Tree-Based Embedding
```
# training dataset
X = df33.drop(columns = ['gross_revenue'], axis = 1) #target variable
y = df33['gross_revenue']
# # model definition
# rf_model = en.RandomForestRegressor(n_estimators = 100, random_state = 42)
# # model training
# rf_model.fit(X,y)
# rf_model = pickle.load(open('../models/rf_model.pkl', 'rb'))
rf_model = pickle.load(fs.open('s3://mc-insiders-dataset/rf_model.pkl', 'rb'))
# leaf
df_leaf = pd.DataFrame(rf_model.apply( X )) # X will be the new clients that entered the base
# using UMAP to reduce the space study from 100 to 2
# reducer = umap.UMAP(random_state = 42)
# embedding = reducer.fit_transform(df_leaf) #gera o espaço projetado - embedding é a projeção gerada em outro espaço
# reducer = pickle.load(open('../features/umap_reducer.pkl', 'rb'))
reducer = pickle.load(fs.open('s3://mc-insiders-dataset/umap_reducer.pkl', 'rb'))
embedding = reducer.transform(df_leaf)
#embedding
df_tree = pd.DataFrame()
df_tree['embedding_X'] = embedding[:, 0]
df_tree['embedding_y'] = embedding[:, 1]
#plot UMAP - cluster projetado de alta dimencionalidade
sns.scatterplot(x = 'embedding_X', y = 'embedding_y',
data = df_tree);
```
# DATA PREPARATION
```
# Tree-Based Embbeding
df4 = df_tree.copy()
# # UMAP Embbeding
# df4 = df_umap.copy()
# # TSNE Embedding
# df4 = df_tsne.copy()
```
# HYPERPARAMETER FINE-TUNNING
```
X = df4.copy()
X.head()
clusters = np.arange(2, 31, 1) #silhouette was increasing, so we put more k points
clusters
```
## K-Means
```
kmeans_sil = []
for k in clusters:
# model definition
kmeans_model = c.KMeans( n_clusters = k, n_init = 100, random_state = 42 )
# model training
kmeans_model.fit(X)
# model predict
labels = kmeans_model.predict(X)
# model performance
sil = m.silhouette_score( X, labels, metric = 'euclidean')
kmeans_sil.append(sil)
plt.plot( clusters, kmeans_sil, linestyle = '--', marker = 'o', color = 'b' )
plt.xlabel( 'K' );
plt.ylabel('Silhouette Score');
plt.title('KMeans Silhouette Score per K ');
```
## GMM
```
gmm_sil = []
for k in clusters:
# model definition
gmm_model = mx.GaussianMixture(n_components = k, n_init = 100, random_state = 42)
# model training
gmm_model.fit(X)
# model prediction
labels = gmm_model.predict(X)
# model performance
sil = m.silhouette_score(X, labels, metric = 'euclidean')
gmm_sil.append(sil)
plt.plot(clusters, gmm_sil, linestyle = '--', marker = 'o', color = 'b')
plt.xlabel( 'K' );
plt.ylabel('Silhouette Score');
plt.title('GMM Silhouette Score per K ');
```
## Hierarchical Clustering
```
# model definition and training
hc_model = hc.linkage(X, 'ward')
```
### H-Clustering Silhouette Score
```
hc_sil = []
for k in clusters:
#model definition and training
hc_model = hc.linkage(X, 'ward')
# model predict
labels = hc.fcluster(hc_model, k, criterion = 'maxclust')
# metrics
sil = m.silhouette_score(X, labels, metric = 'euclidean')
hc_sil.append(sil)
plt.plot(clusters, hc_sil, linestyle = '--', marker = 'o', color = 'b')
```
## Results
```
## Results - Tree Based Embedding
df_results = pd.DataFrame({'KMeans:': kmeans_sil,
'GMM': gmm_sil,
'HC': hc_sil}
).T
df_results.columns = clusters
df_results.style.highlight_max(color = 'lightgreen', axis = 1)
```
# MACHINE LEARNING MODEL TRAINING
```
# definition of the number of clusters K
k = 9;
```
## K-Means
```
# # model definition
# kmeans = c.KMeans(init = 'random', n_clusters = k, n_init = 100, max_iter = 300, random_state = 42)
# # model training
# kmeans.fit(X)
# # clustering
# labels = kmeans.labels_
```
## GMM
```
# trying with GMM beacuse of its approach in the embedding space
# model definition
gmm_model = mx.GaussianMixture(n_components = k,n_init = 50, max_iter = 300 ,random_state=42)
# model training
gmm_model.fit(X)
# model prediction
labels = gmm_model.predict(X)
```
## Cluster Validation
```
# WSS (Within-cluster Sum of Square )
# print('WSS score: {}'.format(kmeans.inertia_))
# SS (Silhouette Score)
print('SS score: {}'.format(m.silhouette_score(X, labels, metric = 'euclidean')))
```
# CLUSTER ANALYSIS
```
df9 = X.copy()
df9['cluster'] = labels
```
## Visualization Inspection
```
# k = 9 for KMeans
sns.scatterplot(x = 'embedding_X', y = 'embedding_y', hue = 'cluster', data = df9, palette = 'deep')
```
## Cluster Profile
```
df92 = df3[cols_selected].copy()
df92['cluster'] = labels
df92.head()
# Explaining clusters profile based on this averages
# Number of customer
df_cluster = df92[['customer_id', 'cluster']].groupby( 'cluster' ).count().reset_index().rename(columns = {'customer_id': 'qty_customers'})
df_cluster['perc_customer'] = 100*( df_cluster['qty_customers'] / df_cluster['qty_customers'].sum() )
# Avg Gross revenue
df_avg_gross_revenue = df92[['gross_revenue', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_avg_gross_revenue, how='inner', on='cluster' )
# Avg recency days
df_avg_recency_days = df92[['recency_days', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_avg_recency_days, how='inner', on='cluster' )
# Qty invoice number
df_avg_invoice_no = df92[['qty_invoice_no', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_avg_invoice_no, how='inner', on='cluster' )
# Avg qty items
df_avg_qty_items = df92[['qty_items', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_avg_qty_items, how='inner', on='cluster' )
# Avg qty products
df_qty_products = df92[['qty_products', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_qty_products, how='inner', on='cluster' )
# Frequency
df_frequency = df92[['frequency', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_frequency, how='inner', on='cluster' )
# Avg qty returns
df_qty_returns = df92[['qty_returns', 'cluster']].groupby( 'cluster' ).mean().reset_index()
df_cluster = pd.merge( df_cluster, df_qty_returns, how='inner', on='cluster' )
df_cluster.sort_values('gross_revenue', ascending = False)
# during the new EDA we can do a analyse inside each cluster
```
* Cluster 6: Champions
* Cluster 4: Almost Champions
* Cluster 1: Must buy more frequently and more products
* Cluster 7: Must buy more expensive products
* Cluster 2: Must buy more items and different products
* Cluster 8: Churn 1
* Cluster 0: Churn 2
* Cluster 5: Churn 3
* Cluster 3: Churn 4
**High Value Customers Cluster(06):**
- Number of customers: 492 (8.64% of costumers)
- Avg Gross Revenue: **$10932.72**
- Avg Recency Average: **29 days**
- Avq of Qty of invoice no: **14.85**
- Avg of Qty of Items: **6429**
- Avg of Qty Products Purchased: **354 un**
- Purchase Frequency: **0.114 products per day**
- Avg of Qty of Retuned Items: **147 un**
# MODEL DEPLOYMENT
```
df92.dtypes
df92['recency_days'] = df92['recency_days'].astype(int)
df92['qty_invoice_no'] = df92['qty_invoice_no'].astype(int)
df92['qty_items'] = df92['qty_items'].astype(int)
df92['qty_products'] = df92['qty_products'].astype(int)
df92['qty_returns'] = df92['qty_returns'].astype(int)
```
## Local
```
# # create database
# conn = sqlite3.connect('insiders_db.sqlite')
# # create table
# query_create_insiders = """
# CREATE TABLE insiders (
# custer_id INTEGER,
# gross_revenue REAL,
# recency_days INTEGER,
# qty_products INTEGER,
# frequency INTEGER,
# qty_returns INTEGER,
# cluster INTEGER
# )
# """
# conn.execute(query_create_insiders)
# conn.commit()
# conn.close()
# # database connection
# conn = create_engine('sqlite:///insiders_db.sqlite')
# # # drop table
# # query_drop_insiders = """
# # DROP TABLE insiders
# # """
# #create table
# query_create_insiders = """
# CREATE TABLE insiders (
# customer_id INTEGER,
# gross_revenue REAL,
# recency_days INTEGER,
# qty_products INTEGER,
# frequency INTEGER,
# qty_returns INTEGER,
# cluster INTEGER
# )
# """
# conn.execute(query_create_insiders)
# # insert into data
# df92.to_sql('insiders', con = conn, if_exists = 'append', index = False)
# conn = sqlite3.connect('insiders_db.sqlite')
# # consulting database
# # get query
# query_collect = """
# SELECT * from insiders
# """
# df = pd.read_sql_query(query_collect, conn)
# df.head()
```
## AWS S3 / RDS / EC2
```
# get postgres RDS environmnet access keys
user = os.environ.get('user')
pwd = os.environ.get('pwd')
host = os.environ.get('host')
port = os.environ.get('port')
database = os.environ.get('database')
endpoint = 'postgresql' + '://' + user + ':' + pwd + '@' + host + '/' + database
# database connection
conn = create_engine(endpoint)
# # drop table
# query_drop_champions = """
# DROP TABLE champions
# """
# #create table
# query_create_champions = """
# CREATE TABLE champions (
# customer_id INTEGER,
# gross_revenue REAL,
# recency_days INTEGER,
# qty_invoice_no INTEGER,
# qty_items INTEGER,
# qty_products INTEGER,
# frequency INTEGER,
# qty_returns INTEGER,
# cluster INTEGER
# )
# """
# conn.execute(query_create_champions)
# insert into data
df92.to_sql('champions', con = conn, if_exists = 'append', index = False)
# # get query
# query_collect = """
# SELECT * FROM champions
# """
# df = pd.read_sql_query(query_collect, conn)
# df.head()
```
| github_jupyter |
<center>
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" />
</center>
# Tuples in Python
Estimated time needed: **15** minutes
## Objectives
After completing this lab you will be able to:
* Perform the basics tuple operations in Python, including indexing, slicing and sorting
<h2>Table of Contents</h2>
<div class="alert alert-block alert-info" style="margin-top: 20px">
<ul>
<li>
<a href="https://#dataset">About the Dataset</a>
</li>
<li>
<a href="https://#tuple">Tuples</a>
<ul>
<li><a href="https://index/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01">Indexing</a></li>
<li><a href="https://slice/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01">Slicing</a></li>
<li><a href="https://sort/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01">Sorting</a></li>
</ul>
</li>
<li>
<a href="https://#escape">Quiz on Tuples</a>
</li>
</ul>
</div>
<hr>
<h2 id="dataset">About the Dataset</h2>
Imagine you received album recommendations from your friends and compiled all of the recommendations into a table, with specific information about each album.
The table has one row for each movie and several columns:
* **artist** - Name of the artist
* **album** - Name of the album
* **released_year** - Year the album was released
* **length_min_sec** - Length of the album (hours,minutes,seconds)
* **genre** - Genre of the album
* **music_recording_sales_millions** - Music recording sales (millions in USD) on [SONG://DATABASE](http://www.song-database.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)
* **claimed_sales_millions** - Album's claimed sales (millions in USD) on [SONG://DATABASE](http://www.song-database.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)
* **date_released** - Date on which the album was released
* **soundtrack** - Indicates if the album is the movie soundtrack (Y) or (N)
* **rating_of_friends** - Indicates the rating from your friends from 1 to 10
<br>
<br>
The dataset can be seen below:
<font size="1">
<table font-size:xx-small>
<tr>
<th>Artist</th>
<th>Album</th>
<th>Released</th>
<th>Length</th>
<th>Genre</th>
<th>Music recording sales (millions)</th>
<th>Claimed sales (millions)</th>
<th>Released</th>
<th>Soundtrack</th>
<th>Rating (friends)</th>
</tr>
<tr>
<td>Michael Jackson</td>
<td>Thriller</td>
<td>1982</td>
<td>00:42:19</td>
<td>Pop, rock, R&B</td>
<td>46</td>
<td>65</td>
<td>30-Nov-82</td>
<td></td>
<td>10.0</td>
</tr>
<tr>
<td>AC/DC</td>
<td>Back in Black</td>
<td>1980</td>
<td>00:42:11</td>
<td>Hard rock</td>
<td>26.1</td>
<td>50</td>
<td>25-Jul-80</td>
<td></td>
<td>8.5</td>
</tr>
<tr>
<td>Pink Floyd</td>
<td>The Dark Side of the Moon</td>
<td>1973</td>
<td>00:42:49</td>
<td>Progressive rock</td>
<td>24.2</td>
<td>45</td>
<td>01-Mar-73</td>
<td></td>
<td>9.5</td>
</tr>
<tr>
<td>Whitney Houston</td>
<td>The Bodyguard</td>
<td>1992</td>
<td>00:57:44</td>
<td>Soundtrack/R&B, soul, pop</td>
<td>26.1</td>
<td>50</td>
<td>25-Jul-80</td>
<td>Y</td>
<td>7.0</td>
</tr>
<tr>
<td>Meat Loaf</td>
<td>Bat Out of Hell</td>
<td>1977</td>
<td>00:46:33</td>
<td>Hard rock, progressive rock</td>
<td>20.6</td>
<td>43</td>
<td>21-Oct-77</td>
<td></td>
<td>7.0</td>
</tr>
<tr>
<td>Eagles</td>
<td>Their Greatest Hits (1971-1975)</td>
<td>1976</td>
<td>00:43:08</td>
<td>Rock, soft rock, folk rock</td>
<td>32.2</td>
<td>42</td>
<td>17-Feb-76</td>
<td></td>
<td>9.5</td>
</tr>
<tr>
<td>Bee Gees</td>
<td>Saturday Night Fever</td>
<td>1977</td>
<td>1:15:54</td>
<td>Disco</td>
<td>20.6</td>
<td>40</td>
<td>15-Nov-77</td>
<td>Y</td>
<td>9.0</td>
</tr>
<tr>
<td>Fleetwood Mac</td>
<td>Rumours</td>
<td>1977</td>
<td>00:40:01</td>
<td>Soft rock</td>
<td>27.9</td>
<td>40</td>
<td>04-Feb-77</td>
<td></td>
<td>9.5</td>
</tr>
</table></font>
<hr>
<h2 id="tuple">Tuples</h2>
In Python, there are different data types: string, integer, and float. These data types can all be contained in a tuple as follows:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesType.png" width="750" align="center" />
Now, let us create your first tuple with string, integer and float.
```
# Create your first tuple
tuple1 = ("disco",10,1.2 )
tuple1
```
The type of variable is a **tuple**.
```
# Print the type of the tuple you created
type(tuple1)
```
<h3 id="index">Indexing</h3>
Each element of a tuple can be accessed via an index. The following table represents the relationship between the index and the items in the tuple. Each element can be obtained by the name of the tuple followed by a square bracket with the index number:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesIndex.gif" width="750" align="center">
We can print out each value in the tuple:
```
# Print the variable on each index
print(tuple1[0])
print(tuple1[1])
print(tuple1[2])
```
We can print out the **type** of each value in the tuple:
```
# Print the type of value on each index
print(type(tuple1[0]))
print(type(tuple1[1]))
print(type(tuple1[2]))
```
We can also use negative indexing. We use the same table above with corresponding negative values:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesNeg.png" width="750" align="center">
We can obtain the last element as follows (this time we will not use the print statement to display the values):
```
# Use negative index to get the value of the last element
tuple1[-1]
```
We can display the next two elements as follows:
```
# Use negative index to get the value of the second last element
tuple1[-2]
# Use negative index to get the value of the third last element
tuple1[-3]
```
<h3 id="concate">Concatenate Tuples</h3>
We can concatenate or combine tuples by using the **+** sign:
```
# Concatenate two tuples
tuple2 = tuple1 + ("hard rock", 10)
tuple2
```
We can slice tuples obtaining multiple values as demonstrated by the figure below:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesSlice.gif" width="750" align="center">
<h3 id="slice">Slicing</h3>
We can slice tuples, obtaining new tuples with the corresponding elements:
```
# Slice from index 0 to index 2
tuple2[0:3]
```
We can obtain the last two elements of the tuple:
```
# Slice from index 3 to index 4
tuple2[3:5]
```
We can obtain the length of a tuple using the length command:
```
# Get the length of tuple
len(tuple2)
```
This figure shows the number of elements:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesElement.png" width="750" align="center">
<h3 id="sort">Sorting</h3>
Consider the following tuple:
```
# A sample tuple
Ratings = (0, 9, 6, 5, 10, 8, 9, 6, 2)
```
We can sort the values in a tuple and save it to a new tuple:
```
# Sort the tuple
RatingsSorted = sorted(Ratings)
RatingsSorted
```
<h3 id="nest">Nested Tuple</h3>
A tuple can contain another tuple as well as other more complex data types. This process is called 'nesting'. Consider the following tuple with several elements:
```
# Create a nest tuple
NestedT =(1, 2, ("pop", "rock") ,(3,4),("disco",(1,2)))
```
Each element in the tuple, including other tuples, can be obtained via an index as shown in the figure:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesNestOne.png" width="750" align="center">
```
# Print element on each index
print("Element 0 of Tuple: ", NestedT[0])
print("Element 1 of Tuple: ", NestedT[1])
print("Element 2 of Tuple: ", NestedT[2])
print("Element 3 of Tuple: ", NestedT[3])
print("Element 4 of Tuple: ", NestedT[4])
```
We can use the second index to access other tuples as demonstrated in the figure:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesNestTwo.png" width="750" align="center">
We can access the nested tuples:
```
# Print element on each index, including nest indexes
print("Element 2, 0 of Tuple: ", NestedT[2][0])
print("Element 2, 1 of Tuple: ", NestedT[2][1])
print("Element 3, 0 of Tuple: ", NestedT[3][0])
print("Element 3, 1 of Tuple: ", NestedT[3][1])
print("Element 4, 0 of Tuple: ", NestedT[4][0])
print("Element 4, 1 of Tuple: ", NestedT[4][1])
```
We can access strings in the second nested tuples using a third index:
```
# Print the first element in the second nested tuples
NestedT[2][1][0]
# Print the second element in the second nested tuples
NestedT[2][1][1]
```
We can use a tree to visualise the process. Each new index corresponds to a deeper level in the tree:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesNestThree.gif" width="750" align="center">
Similarly, we can access elements nested deeper in the tree with a third index:
```
# Print the first element in the second nested tuples
NestedT[4][1][0]
# Print the second element in the second nested tuples
NestedT[4][1][1]
```
The following figure shows the relationship of the tree and the element <code>NestedT\[4]\[1]\[1]</code>:
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesNestFour.gif" width="750" align="center">
<h2 id="quiz">Quiz on Tuples</h2>
Consider the following tuple:
```
# sample tuple
genres_tuple = ("pop", "rock", "soul", "hard rock", "soft rock", \
"R&B", "progressive rock", "disco")
genres_tuple
```
Find the length of the tuple, <code>genres_tuple</code>:
```
# Write your code below and press Shift+Enter to execute
```
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/TuplesQuiz.png" width="1100" align="center">
<details><summary>Click here for the solution</summary>
```python
len(genres_tuple)
```
</details>
Access the element, with respect to index 3:
```
# Write your code below and press Shift+Enter to execute
```
<details><summary>Click here for the solution</summary>
```python
genres_tuple[3]
```
</details>
Use slicing to obtain indexes 3, 4 and 5:
```
# Write your code below and press Shift+Enter to execute
```
<details><summary>Click here for the solution</summary>
```python
genres_tuple[3:6]
```
</details>
Find the first two elements of the tuple <code>genres_tuple</code>:
```
# Write your code below and press Shift+Enter to execute
```
<details><summary>Click here for the solution</summary>
```python
genres_tuple[0:2]
```
</details>
Find the first index of <code>"disco"</code>:
```
# Write your code below and press Shift+Enter to execute
```
<details><summary>Click here for the solution</summary>
```python
genres_tuple.index("disco")
```
</details>
Generate a sorted List from the Tuple <code>C_tuple=(-5, 1, -3)</code>:
```
# Write your code below and press Shift+Enter to execute
```
<details><summary>Click here for the solution</summary>
```python
C_tuple = (-5, 1, -3)
C_list = sorted(C_tuple)
C_list
```
</details>
## Author
<a href="https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01" target="_blank">Joseph Santarcangelo</a>
## Other contributors
<a href="https://www.linkedin.com/in/jiahui-mavis-zhou-a4537814a?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01">Mavis Zhou</a>
## Change Log
| Date (YYYY-MM-DD) | Version | Changed By | Change Description |
| ----------------- | ------- | ---------- | ---------------------------------- |
| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |
| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |
| | | | |
| | | | |
## <h3 align="center"> © IBM Corporation 2020. All rights reserved. <h3/>
| github_jupyter |
# This notebook demonstrates how to download the netcdf POES data files (in netcdf format) for a given date range (there are multiple files per day), process them to get auroral boundary (equatorward) and plot it!
```
import os
import datetime
from poes import dwnld_poes, get_aur_bnd, poes_plot_utils
from davitpy import utils
import matplotlib.pyplot as plt
%pylab inline
# dates to download raw poes files
sTimePOES = datetime.datetime( 2015,4,9 )
eTimePOES = datetime.datetime( 2015,4,9 )
# dir to store raw poes files
dayCount = (eTimePOES - sTimePOES).days + 1
# Loop through the days and download files
for inpDate in (sTimePOES + \
datetime.timedelta(n) for n in range(dayCount)):
poesDwnldObj = dwnld_poes.PoesDwnld(inpDate)
# NOTE : set a proper outdir otherwise the data
# is saved in the working directory by default
poesFiles = poesDwnldObj.get_all_sat_data(outDir="/tmp/poes/raw")
# Read data from the POES files
# and get the auroral boundary location
# by fitting a circle
poesRdObj = get_aur_bnd.PoesAur()
( poesAllEleDataDF, poesAllProDataDF ) = poesRdObj.read_poes_data_files(\
poesRawDate=sTimePOES,\
poesRawDir="/tmp/poes/raw/" )
# Or you can uncomment the line below and read the data!
# ( poesAllEleDataDF, poesAllProDataDF ) = poesRdObj.read_poes_data_files(poesFiles)
# Get for a given time get the closest satellite passes
# We can do this at multiple instances for a given time range/step
timeRange = [ poesAllEleDataDF["date"].min(),\
poesAllEleDataDF["date"].max() ]
# aurPassDF contains closest passes for a given time
# for all the satellites in both the hemispheres!
aurPassDF = poesRdObj.get_closest_sat_passes( poesAllEleDataDF,\
poesAllProDataDF, timeRange )
# determine auroral boundaries from all the POES satellites
# at a given time. The procedure is described in the code!
# go over it!!!
eqBndLocsDF = poesRdObj.get_nth_ele_eq_bnd_locs( aurPassDF,\
poesAllEleDataDF )
# to get an estimate of the auroral boundary! fit a circle
# to the boundaries determined from each satellite!
# The fits are written to a file and can be stored in
# a given location
# NOTE : set a proper outdir otherwise the data
# is saved in the working directory by default
bndDF=poesRdObj.fit_circle_aurbnd(eqBndLocsDF, outDir="/tmp/poes/bnd/")
print "ESTIMATED BOUNDARY"
print bndDF.head()
print "ESTIMATED BOUNDARY"
# Plot selected satellite passes between a time range
pltDate = datetime.datetime(2015,4,9)
timeRange = [ datetime.datetime(2015,4,9,7),\
datetime.datetime(2015,4,9,8) ]
coords = "mlt"
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1,1,1)
m = utils.plotUtils.mapObj(boundinglat=40., coords=coords,\
lat_0=90., lon_0=0, datetime=timeRange[0])
poesPltObj = poes_plot_utils.PlotUtils(pltDate, pltCoords=coords)
poesPltObj.overlay_sat_pass(timeRange,m,ax,"/tmp/poes/raw/",\
satList=["m01", "n19"])
fig.savefig("figs/poes-demo1.pdf",bbox_inches='tight')
# Plot all closest (in time) satellite passes at a given time
# and also overlay the estimated auroral boundary
pltDate = datetime.datetime(2015,4,9)
selTime = datetime.datetime(2015,4,9,7,30)
coords = "mlt"
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1,1,1)
m = utils.plotUtils.mapObj(boundinglat=40., coords=coords,\
lat_0=90., lon_0=0, datetime=selTime)
poesPltObj = poes_plot_utils.PlotUtils(pltDate, pltCoords=coords)
poesPltObj.overlay_closest_sat_pass(selTime,m,ax,"/tmp/poes/raw/")
# two ways to overlay estimated boundary!
# poesPltObj.overlay_equ_bnd(selTime,m,ax,rawSatDir="/tmp/poes/raw/")
poesPltObj.overlay_equ_bnd(selTime,m,ax,\
inpFileName="/tmp/poes/bnd/poes-fit-20150409.txt")
fig.savefig("figs/poes-demo2.pdf",bbox_inches='tight')
```
| github_jupyter |
# Creating and Tuning Models
This notebook will create, tune, and store a KNN and SVM model.<br>
For this, the data extracted utilising the feature extraction notebook will be used for training and testing.<br>
The testing split of this data will be stored to a CSV for later use with the webservice too.<br>
## Importing libraries
All utilised libraries are imported at the beginning of the notebook to avoid out of scope errors.<br>
```
import csv
import pickle
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report, plot_confusion_matrix
import pandas as pd
from matplotlib import pyplot as plt
```
## Reading in CSV data
Reading the dataset from a CSV into a DataFrame for use with the model.<br>
Split into data and labels and carry out the train test split.<br>
The testing portion of the split will also be stored to CSV for later use with the webservice.<br>
```
music_df = pd.read_csv("extracted-features.csv")
# This will contain the data
data = music_df.iloc[:, 1:].values
# This will contain the labels corresponding to the data
labels = music_df.iloc[:, 0].values
# Split the data into training and testing sets
data_train, data_test, labels_train, labels_test = train_test_split(data, labels, test_size=0.30)
# Combine testing labels and data and store as a CSV to be used later
testing_data = []
for i in range(0, len(labels_test), 1):
testing_data.append([labels_test[i], data_test[i][0], data_test[i][1], data_test[i][2], data_test[i][3]])
with open("testing_data.csv", mode='w', newline='') as test_data_file:
test_data_writer = csv.writer(test_data_file, delimiter=',')
test_data_writer.writerow(["Genre", "MFCC", "ZCR", "Spectral Centroid", "Spectral Rolloff"])
for i in range(0, len(testing_data), 1):
test_data_writer.writerow(testing_data[i])
```
## Cross-validate KNN to find the best hyper-parameters
Use GridSearchCV to evaluate the optimal hyperparameters for the algorithm.<br>
Gridsearch utilises StratifiedKFold by default for cross validation.<br>
AUROC will be utilised as the metric for determining the best parameters for the model.<br>
```
knn_model = KNeighborsClassifier()
param_grid = {"n_neighbors": range(1, 25),
"weights": ["uniform", "distance"],
"metric": ["euclidean", "manhattan", "chebyshev", "minkowski"]}
# roc_auc_ovr sets the score to use roc_auc in one vs rest mode
scoring_metrics = {"Accuracy": "accuracy",
"AUC": "roc_auc_ovr",
"F1": "f1_macro"}
knn_grid_search_cv = GridSearchCV(knn_model,
param_grid,
scoring=scoring_metrics,
refit="AUC",
cv=5)
knn_grid_search_cv.fit(data_train, labels_train)
print(knn_grid_search_cv.best_params_)
knn_grid_predict = knn_grid_search_cv.predict(data_test)
print(classification_report(labels_test, knn_grid_predict))
plot_confusion_matrix(estimator=knn_grid_search_cv,
X=data_test, y_true=labels_test,
xticks_rotation="vertical")
plt.show()
print("ROC AUC: " + str(knn_grid_search_cv.best_score_))
```
## Cross-validate SVM to find the best hyper-parameters
Use GridSearchCV to evaluate the optimal hyperparameters for the algorithm.<br>
Gridsearch utilises StratifiedKFold by default for cross validation.<br>
AUROC will be utilised as the metric for determining the best parameters for the model.<br>
```
svm_model = SVC(probability=True, kernel="rbf")
param_grid = {"C": [0.1, 1, 10, 100, 1000],
"gamma": ["scale", "auto"]}
# roc_auc_ovr sets the score to use roc_auc in one vs rest mode
scoring_metrics = {"Accuracy": "accuracy",
"AUC": "roc_auc_ovr",
"F1": "f1_macro"}
svm_grid_search_cv = GridSearchCV(svm_model,
param_grid,
scoring=scoring_metrics,
refit="AUC",
cv=5)
svm_grid_search_cv.fit(data_train, labels_train)
print(svm_grid_search_cv.best_params_)
svm_grid_predict = svm_grid_search_cv.predict(data_test)
print(classification_report(labels_test, svm_grid_predict))
plot_confusion_matrix(estimator=svm_grid_search_cv,
X=data_test, y_true=labels_test,
xticks_rotation="vertical")
plt.show()
print("ROC AUC: " + str(svm_grid_search_cv.best_score_))
```
## Save models
Save the tuned KNN and SVM models to a file.<br>
Each model will be serialized to a binary representation using the Pickle library.<br>
Each model is saved in a pre-trained, pre-tuned state.<br>
```
with open("models/knn.pkl", mode="wb") as model_file:
pickle.dump(knn_grid_search_cv, model_file)
with open("models/svm.pkl", mode="wb") as model_file:
pickle.dump(svm_grid_search_cv, model_file)
```
| github_jupyter |
# Model-Centric Federated Learning for Mobile - MNIST Example
This notebook will walk you through creating a simple model and a training plan, and hosting both as a federated learning process
for further training using OpenMined mobile FL workers.
This notebook is similar to "[MCFL - Create Plan](mcfl_create_plan.ipynb)"
however due to mobile limitations, the training plan is different.
```
# stdlib
import base64
import json
# third party
import torch as th
# syft absolute
import syft as sy
from syft.core.plan.plan_builder import ROOT_CLIENT
from syft.core.plan.plan_builder import PLAN_BUILDER_VM
from syft.core.plan.plan_builder import make_plan
from syft.core.plan.translation.torchscript.plan_translate import (
translate as translate_to_ts,
)
from syft.federated.model_centric_fl_client import ModelCentricFLClient
from syft.lib.python.int import Int
from syft.lib.python.list import List
th.random.manual_seed(42)
```
## Step 1: Define the model
This model will train on MNIST data, it's very simple yet can demonstrate learning process.
There're 2 linear layers:
* Linear 784x100
* ReLU
* Linear 100x10
Note that the model contains additional methods for convenience of torch reference usage:
* `backward` - calculates backward pass gradients because autograd doesn't work on mobile (yet).
* `softmax_cross_entropy_with_logits` - loss function
* `accuracy` - calculates accuracy of prediction
```
class MLP(sy.Module):
"""
Simple model with method for loss and hand-written backprop.
"""
def __init__(self, torch_ref) -> None:
super(MLP, self).__init__(torch_ref=torch_ref)
self.fc1 = torch_ref.nn.Linear(784, 100)
self.relu = torch_ref.nn.ReLU()
self.fc2 = torch_ref.nn.Linear(100, 10)
def forward(self, x):
self.z1 = self.fc1(x)
self.a1 = self.relu(self.z1)
return self.fc2(self.a1)
def backward(self, X, error):
z1_grad = (error @ self.fc2.state_dict()["weight"]) * (self.a1 > 0).float()
fc1_weight_grad = z1_grad.t() @ X
fc1_bias_grad = z1_grad.sum(0)
fc2_weight_grad = error.t() @ self.a1
fc2_bias_grad = error.sum(0)
return fc1_weight_grad, fc1_bias_grad, fc2_weight_grad, fc2_bias_grad
def softmax_cross_entropy_with_logits(self, logits, target, batch_size):
probs = self.torch_ref.softmax(logits, dim=1)
loss = -(target * self.torch_ref.log(probs)).sum(dim=1).mean()
loss_grad = (probs - target) / batch_size
return loss, loss_grad
def accuracy(self, logits, targets, batch_size):
pred = self.torch_ref.argmax(logits, dim=1)
targets_idx = self.torch_ref.argmax(targets, dim=1)
acc = pred.eq(targets_idx).sum().float() / batch_size
return acc
```
## Step 2: Define Training Plan
```
def set_remote_model_params(module_ptrs, params_list_ptr):
"""Sets the model parameters into traced model"""
param_idx = 0
for module_name, module_ptr in module_ptrs.items():
for param_name, _ in PLAN_BUILDER_VM.store[
module_ptr.id_at_location
].data.named_parameters():
module_ptr.register_parameter(param_name, params_list_ptr[param_idx])
param_idx += 1
# Create the model
local_model = MLP(th)
# Dummy inputs
bs = 3
classes_num = 10
model_params_zeros = sy.lib.python.List(
[th.nn.Parameter(th.zeros_like(param)) for param in local_model.parameters()]
)
@make_plan
def training_plan(
xs=th.randn(bs, 28 * 28),
ys=th.nn.functional.one_hot(th.randint(0, classes_num, [bs]), classes_num),
batch_size=th.tensor([bs]),
lr=th.tensor([0.1]),
params=model_params_zeros,
):
# send the model to plan builder (but not its default params)
# this is required to build the model inside the Plan
model = local_model.send(ROOT_CLIENT, send_parameters=False)
# set model params from input
set_remote_model_params(model.modules, params)
# forward
logits = model(xs)
# loss
loss, loss_grad = model.softmax_cross_entropy_with_logits(
logits, ys, batch_size
)
# backward
grads = model.backward(xs, loss_grad)
# SGD step
updated_params = tuple(
param - lr * grad for param, grad in zip(model.parameters(), grads)
)
# accuracy
acc = model.accuracy(logits, ys, batch_size)
# return things
return (loss, acc, *updated_params)
```
Translate the training plan to torchscript so it can be used with mobile workers.
```
# Translate to torchscript
ts_plan = translate_to_ts(training_plan)
# Let's examine its contents
print(ts_plan.torchscript.code)
```
## Step 3: Define Averaging Plan
Averaging Plan is executed by PyGrid at the end of the cycle,
to average _diffs_ submitted by workers and update the model
and create new checkpoint for the next cycle.
_Diff_ is the difference between client-trained
model params and original model params,
so it has same number of tensors and tensor's shapes
as the model parameters.
We define Plan that processes one diff at a time.
Such Plans require `iterative_plan` flag set to `True`
in `server_config` when hosting FL model to PyGrid.
Plan below will calculate simple mean of each parameter.
```
@make_plan
def avg_plan(
avg=List(local_model.parameters()), item=List(local_model.parameters()), num=Int(0)
):
new_avg = []
for i, param in enumerate(avg):
new_avg.append((avg[i] * num + item[i]) / (num + 1))
return new_avg
```
## Step 4: Define Federated Learning Process Configuration
Before hosting the model and training plan to PyGrid,
we need to define some configuration parameters, such as
FL process name, version, workers configuration,
authentication method, etc.
```
name = "mnist"
version = "1.0"
client_config = {
"name": name,
"version": version,
"batch_size": 64,
"lr": 0.01,
"max_updates": 100, # number of updates to execute on workers
}
server_config = {
"num_cycles": 30, # total number of cycles (how many times global model is updated)
"cycle_length": 60*60*24, # max duration of the training cycle in seconds
"max_diffs": 1, # number of diffs to collect before updating global model
"minimum_upload_speed": 0,
"minimum_download_speed": 0,
"iterative_plan": True, # tells PyGrid that avg plan is executed per diff
}
```
This FL process will require workers to authenticate with signed JWT token.
Providing the `pub_key` in FL configuration allows PyGrid to verify JWT tokens.
```
def read_file(fname):
with open(fname, "r") as f:
return f.read()
public_key = read_file("example_rsa.pub").strip()
server_config["authentication"] = {
"type": "jwt",
"pub_key": public_key,
}
```
## Step 5: Host in PyGrid
Let's now host everything in PyGrid so that it can be accessed by worker libraries.
Note: assuming the PyGrid Domain is running locally on port 7000.
### Step 5.1: Start a PyGrid Domain
- Clone PyGrid Github repository from https://github.com/OpenMined/PyGrid
- Install poetry using pip:
```
$ pip install poetry
```
- Go to apps/domain and install requirements:
```
$ poetry install
```
- run a Grid domain using the command:
```
$ ./run.sh --name bob --port 7000 --start_local_db
```
```
from syft.grid.client.client import connect
from syft.grid.client.grid_connection import (GridHTTPConnection,)
PYGRID_HOST = "pygrid.datax.io"
PYGRID_PORT = 7000
domain = connect(
url=f"http://{PYGRID_HOST}:{PYGRID_PORT}",
conn_type=GridHTTPConnection,
)
domain.setup(
email="owner@openmined.org",
password="owerpwd",
domain_name="OpenMined Node",
token="9G9MJ06OQH",
)
grid_address = f"{PYGRID_HOST}:{PYGRID_PORT}"
grid = ModelCentricFLClient(address=grid_address, secure=False)
grid.connect()
```
Following code sends FL model, training plans, and configuration to the PyGrid:
```
response = grid.host_federated_training(
model=local_model,
client_plans={
# Grid can store both types of plans (regular for python worker, torchscript for mobile):
"training_plan": training_plan,
"training_plan:ts": ts_plan,
},
client_protocols={},
server_averaging_plan=avg_plan,
client_config=client_config,
server_config=server_config,
)
response
```
If you see successful response, you've just hosted your first FL process into PyGrid!
If you see error that FL process already exists,
this means FL process with such name and version is already hosted.
You might want to update name/version in configuration above, or cleanup PyGrid database.
To cleanup database, set path below correctly and run:
```
# !rm ~/Projects/PyGrid/apps/domain/src/nodedatabase.db
```
To train hosted model, use one of the existing mobile FL workers:
* [SwiftSyft](https://github.com/OpenMined/SwiftSyft) (see included worker example)
* [KotlinSyft](https://github.com/OpenMined/KotlinSyft) (see included worker example)
Support for javascript worker is coming soon:
* [syft.js](https://github.com/OpenMined/syft.js)
| github_jupyter |
```
# from IPython.core.display import display, HTML
# display(HTML("<style>.container { width:100% !important; }</style>"))
import torch
import gc
import os
import sys
%matplotlib notebook
import matplotlib.pyplot as plt
def printmem():
allocated = torch.cuda.memory_allocated()
cached = torch.cuda.memory_cached()
print('All|ocated:', str(allocated), '['+str(round(allocated/1000000000,3))+' GB]')
print(' Cached:', str(cached), '['+str(round(cached/1000000000,3))+' GB]')
module_path = os.path.abspath(os.path.join('.'))
if module_path not in sys.path:
sys.path.append(module_path)
printmem()
config = {
"model_params": {
"kernel_size": 5,
"padding": 0,
"dilation": 2,
"stride": 1,
"layer_dims": [
29,
23,
16,
9,
3
],
"class_dim": 2,
"class_layers": 1,
"noise_std": 0
},
"train_params": {
"lr": 0.01,
"batch_size": 99,
"epochs": 1,
"report": 5,
"crop": 81,
"clip": 1,
"decay": 0
},
"trial_name": "8ad2k6WoeQtxmXbcDKtgPzwV5CetoBJ7",
"dataset_params": {
"data_dir": "/home/hazmat/Documents/mayonoise/data/",
"train_dir": "train/",
"test_dir": "test/",
"labels": {
"early": 0,
"late": 1
},
"crop": 32,
"scale": 10,
"stride": 16
},
"output_params": {
"hyper_dir": "/home/hazmat/Documents/mayonoise/hypersearch/",
"results_dir": "/home/hazmat/Documents/mayonoise/hypersearch/results/"
},
"loss_params": {
"lambdas": [
1,
0.5,
0.25,
0.125,
0.0625
]
}
}
# owlnet = OwlNet.load_model('/home/hazmat/Documents/mayonoise/hypersearch/results/IPjCNbjTOjY7goYijeW6IPy6FQvJJsTf/', 'trial_0model')
# print(owlnet)
from Criteria import OwlNetLoss
from Helpers import Trainer
from Helpers import Logger
from Helpers import Trial
from MIBI_Dataloader import MIBIData
from Modules import OwlNet
import Utils
printmem()
# Load the data
main_dir = '/home/hazmat/Documents/mayonoise/'
train_dir = main_dir + 'data/train/'
test_dir = main_dir + 'data/test/'
modl_dir = main_dir + 'models/'
rslt_dir = main_dir + 'results/'
labels = {
'early': torch.tensor([0]),
'late' : torch.tensor([1])
}
train_ds = MIBIData(folder=train_dir, labels=labels, crop=32, scale=10, stride=16)
test_ds = MIBIData(folder=test_dir, labels=labels, crop=32, scale=10, stride=16)
printmem()
Trial.error_check(config, train_ds)
trial = Trial(config, 0)
trial.train(test_ds)
trial.test(test_ds)
# varbles = trial.model.ladder.variables[0]
# print(varbles.keys())
# for key in varbles.keys():
# print(key)
# print(varbles[key].shape)
owlnet_args = dict()
owlnet_args['kind'] = 'conv'
owlnet_args['kernel_size'] = [3,3,3,3,3]
owlnet_args['padding'] = [0,0,0,0,0]
owlnet_args['dilation'] = [1,1,1,1,1]
owlnet_args['stride'] = [1,1,1,1,1]
owlnet_args['layer_dims'] = [29, 32, 17, 9, 3]
# owlnet_args['num_layers'] = 5
# owlnet_args['in_dim'] = 29
owlnet_args['code_dim'] = 3
owlnet_args['class_dim'] = 2
owlnet_args['class_layers'] = 1
owlnet_args['noise_std'] = .2
torch.cuda.empty_cache()
owlnet = OwlNet(**owlnet_args)
owlnet.cuda()
# print(owlnet)
owlnet.ladder.suggested_in_size(20)
owlnet_trainer = Trainer()
owlnet_logger = Logger({'loss':(list(),list())})
# LadderNet training parameters
owlnet_train_args = dict()
owlnet_train_args['lr'] = .05
owlnet_train_args['batch_size'] = 99
owlnet_train_args['epochs'] = 1
owlnet_train_args['report'] = 5
owlnet_train_args['crop'] = 81
owlnet_train_args['clip'] = 1
owlnet_train_args['decay'] = 0
# LadderNet loss parameters
owlnet_loss_args = {
'lambdas': [2**0, 2**-1, 2**-2, 2**-3, 2**-4]
}
train_ds.set_crop(owlnet_train_args['crop'])
# owlnet_trainer.test(trial.model, train_ds, trial.criterion, trial.test_logger)
# for layer in trial.model.ladder.variables:
# print(layer)
lambdas = [2**0, 2**-1, 2**-2, 2**-3, 2**-4]
print(lambdas)
owlnet.set_noise_std(0.3)
owlnet.set_lateral_weight(1)
owlnet_criterion = OwlNetLoss(**owlnet_loss_args)
owlnet_trainer.train(owlnet, train_ds, owlnet_criterion, owlnet_logger, **owlnet_train_args)
print()
torch.cuda.empty_cache()
printmem()
# torch.cuda.empty_cache()
# printmem()
varbls = owlnet.ladder.variables
layer = 4
for key in varbls[layer].keys():
print(varbls[layer][key].shape)
import numpy as np
log_error = np.log10(owlnet_logger.list_vars['loss'][1][100:])
fig = plt.figure()
plt.plot(log_error)
plt.show()
owlnet_logger.list_vars['loss'][0]
epochs = owlnet_logger.list_vars['loss'][0]
lossvals = owlnet_logger.list_vars['loss'][1]
epochs = np.reshape(epochs, len(epochs), 1)
np.average(lossvals[-100::])
owlnet.eval()
owlnet.set_lateral_weight(1)
%matplotlib notebook
import matplotlib.pyplot as plt
import time
print(1024/81)
train_ds.set_crop(81*1)
batch = train_ds.get_batch(1, False)
output = owlnet(**batch)
torch.cuda.empty_cache()
printmem()
def print_diff2(output, model, channel, size):
# we'going to show clean, noisy, recon, clean-recon, and noisy-recon
fig = plt.figure(figsize=(3*size, 2*size))
clean = output['clean'][0][0,channel,:,:].detach().cpu()
noisy = model.ladder.variables[0]['z_tilda'][0,channel,:,:].detach().cpu()
recon = output['recon'][0][0,channel,:,:].detach().cpu()
# plot clean
ax1 = plt.subplot(2,3,1)
ax1.imshow(clean.numpy())
plt.title('Clean')
# plot noisy
ax2 = plt.subplot(2,3,2, sharex=ax1, sharey=ax1)
ax2.imshow(noisy.numpy())
plt.title('Noisy')
# plot clean-recon
ax3 = plt.subplot(2,3,4, sharex=ax1, sharey=ax1)
ax3.imshow((recon-clean).numpy())
plt.title('Clean - Recon')
# plot noisy-recon
ax4 = plt.subplot(2,3,5, sharex=ax1, sharey=ax1)
ax4.imshow((recon-noisy).numpy())
plt.title('Noisy - Recon')
# plot recon
ax5 = plt.subplot(2,3,3, sharex=ax1, sharey=ax1)
ax5.imshow(recon.numpy())
plt.title('Recon')
# plot adjustment
ax6 = plt.subplot(2,3,6, sharex=ax1, sharey=ax1)
noise = torch.abs(noisy-clean)
error = torch.abs(recon-clean)
ax6.imshow((error-noise).numpy(), cmap='bwr', vmin=-1, vmax=1)
plt.title('Adjustment')
L1_noisy_loss = torch.mean(torch.abs(noisy-clean)).item()
L1_recon_loss = torch.mean(torch.abs(recon-clean)).item()
L2_noisy_loss = torch.mean((noisy-clean)**2).item()
L2_recon_loss = torch.mean((recon-clean)**2).item()
print('L1 error:')
print(' Noisy:', L1_noisy_loss)
print(' Recon:', L1_recon_loss)
print('L2 error:')
print(' Noisy:', L2_noisy_loss)
print(' Recon:', L2_recon_loss)
def print_diff(output, channel, size):
fig = plt.figure(figsize=(3*size, size))
ax1 = plt.subplot(1,3,1)
recon = output['recon'][0][0,channel,:,:].detach().cpu()
ax1.imshow(recon.numpy())
plt.title('Reconstruction')
ax2 = plt.subplot(1,3,2, sharex=ax1, sharey=ax1)
original = output['clean'][0][0,channel,:,:].detach().cpu()
ax2.imshow(original.numpy())
plt.title('Original')
ax3 = plt.subplot(1,3,3, sharex=ax1, sharey=ax1)
difference = output['clean'][0][0,channel,:,:].detach().cpu() - output['recon'][0][0,channel,:,:].detach().cpu()
ax3.imshow(difference.numpy())
plt.title('Difference')
fig.show()
return recon, original, difference
def print_encoding(output, level, channels, size):
print(output['recon'][level][0,:,:,:].shape)
if isinstance(channels, list):
if len(channels)==3:
fig = plt.figure(figsize=(2*size, size))
z = output['recon'][level][0,channels,:,:].transpose(0,1).transpose(1,2).detach().cpu().numpy()
ax1 = plt.subplot(1,2,1)
ax1.imshow(z)
from mpl_toolkits.mplot3d import Axes3D
data = torch.tensor(z)
a = data[:,:,0].view(-1).numpy()
b = data[:,:,1].view(-1).numpy()
c = data[:,:,2].view(-1).numpy()
ax2 = plt.subplot(1,2,2, projection='3d')
ax2.scatter(a, b, c)
fig.show()
elif len(channels)==1:
fig = plt.figure(figsize=(size,size))
z = output['recon'][level][0,channels[0],:,:].detach().cpu().numpy()
plt.imshow(z)
fig.show()
else:
print('Invalid number of channels')
else:
fig = plt.figure(figsize=(size,size))
z = output['recon'][level][0,channels,:,:].detach().cpu().numpy()
plt.imshow(z)
fig.show()
print(z.shape)
# print_encoding(output, 2, [0,1,2], 5)
# recon0, orig0, diff0 = print_diff(output,0,4)
print_diff2(output, owlnet, 0, 4)
# plt.savefig('/home/hazmat/Documents/recon1.png')
# printmem()
# torch.cuda.empty_cache()
# printmem()
# print_encoding(output, 2, [0,1,2], 5)
import torch
dropout = torch.nn.Dropout2d(.2)
dropout.p=1
dropout
temp = torch.rand([1,2,4,4])
print(temp)
dropout(temp)
```
| github_jupyter |
```
import urllib3
from bs4 import BeautifulSoup
import pymongo
from pprint import pprint
import pandas as pd
import requests
from splinter import Browser
import json
import tweepy
import pymongo
import os
import time
from pprint import pprint
from selenium import webdriver
from pymongo import MongoClient
def TargetPlayerInfo(rank):
rank = rank + 1
xpath1 = f'/html/body/table[2]/tbody/tr[{rank}]/td[2]/a'
xpath2 = f'/html/body/table[2]/tbody/tr[{rank}]/td[3]/span'
xpath3 = f'/html/body/table[2]/tbody/tr[{rank}]/td[4]/img'
xpath4 = f'/html/body/table[2]/tbody/tr[{rank}]/td[5]'
xpath5 = f'/html/body/table[2]/tbody/tr[{rank}]/td[1]'
browser = Browser('chrome', headless=True)
url = 'https://www.goratings.org/en/'
browser.visit(url)
preserve_link = browser.find_by_xpath(xpath1) ## postion as ranking + 1
player_gender = browser.find_by_xpath(xpath2)
if player_gender.text == '♂':
gender = "Male"
else:
gender = "Female"
player_natinality = browser.find_by_xpath(xpath3)
players_Elo = browser.find_by_xpath(xpath4)
player_rank = browser.find_by_xpath(xpath5)
firstLayer = {
'Link' : preserve_link['href'],
'Name' : preserve_link.text,
"Gender" : gender,
"Nation" : player_natinality['alt'],
"Elo" : players_Elo.text,
"Rank": player_rank.text
}
time.sleep(3)
browser.quit()
time.sleep(3)
# start another link scraping
driver = Browser('chrome', headless=True)
url1 = firstLayer['Link']
driver.visit(url1)
html = driver.html
# soup = BeautifulSoup(html, "html.parser")
table = driver.find_by_xpath('/html/body/table[1]/tbody')
info = []
for i in table.find_by_tag("td"):
info.append(i.text)
firstLayer["Wins"] = info[0]
firstLayer["Losses"] = info[1]
firstLayer["Total"] = info[2]
firstLayer["Birthday"] = info[-1]
return firstLayer
def GamingRecordDetails(rank):
rank = rank + 1
xpath1 = f'/html/body/table[2]/tbody/tr[{rank}]/td[2]/a'
browser = Browser('chrome', headless=True)
url = 'https://www.goratings.org/en/'
browser.visit(url)
preserve_link = browser.find_by_xpath(xpath1) ## postion as ranking + 1
SecondLayer = {
'targeted link' : preserve_link['href'],
'targeted gamer' : preserve_link.text,
}
time.sleep(3)
browser.quit()
time.sleep(3)
# start another link scraping
driver = Browser('chrome', headless=True)
url1 = SecondLayer['targeted link']
driver.visit(url1)
html = driver.html
table = driver.find_by_xpath('/html/body/table[2]/tbody')
info = []
#table.find_by_tag('td')
for tr in table.find_by_tag('tr'):
info.append(tr.text.split(" "))
data = pd.DataFrame(info)
data = data.drop([0])
data['Opponant Name'] = data[[4, 5]].apply(lambda x: ' '.join(x), axis=1)
data = data.drop([4,5], axis=1)
data
data = data.rename(columns = {0: "Date", 1: "Gamer Rating", 2: "Color", 3: "Result", 'Opponant Name': "Opponent Name", 6: "Opponent Ranking",
7: "Opponent Gender"})
df = data[["Date", "Gamer Rating","Color", "Result", "Opponent Name", "Opponent Ranking","Opponent Gender"]]
df.head()
final_dict = {
'Date' : list(df['Date']),
'Rating': list(df['Gamer Rating']),
'Color': list(df['Color']),
'Result': list(df['Result']),
'Opponent': list(df['Opponent Name']),
'Op_Ranking': list(df['Opponent Ranking'])
}
driver.quit()
return final_dict
# define function to insert record to database
def Add_to_DB(record):
# Making a Connection with MongoClient
client = MongoClient()
# select/create database
db = client.GOplayers_db
# select/create collection
collection = db.players
# insert record into collection as a document
post = collection.insert_one(record)
# scrape top 3 players info and put into mongoDB: players_database
# change to range(1, 51) for top 50 players
for num in range(51, 101):
# use first two functions to scrape data
record = TargetPlayerInfo(num)
games = GamingRecordDetails(num)
# combine data into one record
record["Games"] = games
# insert record into database
Add_to_DB(record)
```

| github_jupyter |
## Classes for callback implementors
```
from fastai.gen_doc.nbdoc import *
from fastai.callback import *
from fastai.basics import *
```
fastai provides a powerful *callback* system, which is documented on the [`callbacks`](/callbacks.html#callbacks) page; look on that page if you're just looking for how to use existing callbacks. If you want to create your own, you'll need to use the classes discussed below.
A key motivation for the callback system is that additional functionality can be entirely implemented in a single callback, so that it's easily read. By using this trick, we will have different methods categorized in different callbacks where we will find clearly stated all the interventions the method makes in training. For instance in the [`LRFinder`](/callbacks.lr_finder.html#LRFinder) callback, on top of running the fit function with exponentially growing LRs, it needs to handle some preparation and clean-up, and all this code can be in the same callback so we know exactly what it is doing and where to look if we need to change something.
In addition, it allows our [`fit`](/basic_train.html#fit) function to be very clean and simple, yet still easily extended. So far in implementing a number of recent papers, we haven't yet come across any situation where we had to modify our training loop source code - we've been able to use callbacks every time.
```
show_doc(Callback)
```
To create a new type of callback, you'll need to inherit from this class, and implement one or more methods as required for your purposes. Perhaps the easiest way to get started is to look at the source code for some of the pre-defined fastai callbacks. You might be surprised at how simple they are! For instance, here is the **entire** source code for [`GradientClipping`](/train.html#GradientClipping):
```python
@dataclass
class GradientClipping(LearnerCallback):
clip:float
def on_backward_end(self, **kwargs):
if self.clip:
nn.utils.clip_grad_norm_(self.learn.model.parameters(), self.clip)
```
You generally want your custom callback constructor to take a [`Learner`](/basic_train.html#Learner) parameter, e.g.:
```python
@dataclass
class MyCallback(Callback):
learn:Learner
```
Note that this allows the callback user to just pass your callback name to `callback_fns` when constructing their [`Learner`](/basic_train.html#Learner), since that always passes `self` when constructing callbacks from `callback_fns`. In addition, by passing the learner, this callback will have access to everything: e.g all the inputs/outputs as they are calculated, the losses, and also the data loaders, the optimizer, etc. At any time:
- Changing self.learn.data.train_dl or self.data.valid_dl will change them inside the fit function (we just need to pass the [`DataBunch`](/basic_data.html#DataBunch) object to the fit function and not data.train_dl/data.valid_dl)
- Changing self.learn.opt.opt (We have an [`OptimWrapper`](/callback.html#OptimWrapper) on top of the actual optimizer) will change it inside the fit function.
- Changing self.learn.data or self.learn.opt directly WILL NOT change the data or the optimizer inside the fit function.
In any of the callbacks you can unpack in the kwargs:
- `n_epochs`, contains the number of epochs the training will take in total
- `epoch`, contains the number of the current
- `iteration`, contains the number of iterations done since the beginning of training
- `num_batch`, contains the number of the batch we're at in the dataloader
- `last_input`, contains the last input that got through the model (eventually updated by a callback)
- `last_target`, contains the last target that got through the model (eventually updated by a callback)
- `last_output`, contains the last output spitted by the model (eventually updated by a callback)
- `last_loss`, contains the last loss computed (eventually updated by a callback)
- `smooth_loss`, contains the smoothed version of the loss
- `last_metrics`, contains the last validation loss and metrics computed
- `pbar`, the progress bar
- [`train`](/train.html#train), flag to know if we're in training mode or not
- `stop_training`, that will stop the training at the end of the current epoch if True
- `stop_epoch`, that will break the current epoch loop
- `skip_step`, that will skip the next optimizer step
- `skip_zero`, that will skip the next zero grad
When returning a dictionary with those key names, the state of the [`CallbackHandler`](/callback.html#CallbackHandler) will be updated with any of those changes, so in any [`Callback`](/callback.html#Callback), you can change those values.
### Methods your subclass can implement
All of these methods are optional; your subclass can handle as many or as few as you require.
```
show_doc(Callback.on_train_begin)
```
Here we can initiliaze anything we need.
The optimizer has now been initialized. We can change any hyper-parameters by typing, for instance:
```
self.opt.lr = new_lr
self.opt.mom = new_mom
self.opt.wd = new_wd
self.opt.beta = new_beta
```
```
show_doc(Callback.on_epoch_begin)
```
This is not technically required since we have `on_train_begin` for epoch 0 and `on_epoch_end` for all the other epochs,
yet it makes writing code that needs to be done at the beginning of every epoch easy and more readable.
```
show_doc(Callback.on_batch_begin)
```
Here is the perfect place to prepare everything before the model is called.
Example: change the values of the hyperparameters (if we don't do it on_batch_end instead)
At the end of that event `xb`,`yb` will be set to `last_input`, `last_target` of the state of the [`CallbackHandler`](/callback.html#CallbackHandler).
```
show_doc(Callback.on_loss_begin)
```
Here is the place to run some code that needs to be executed after the output has been computed but before the
loss computation.
Example: putting the output back in FP32 when training in mixed precision.
At the end of that event the output will be set to `last_output` of the state of the [`CallbackHandler`](/callback.html#CallbackHandler).
```
show_doc(Callback.on_backward_begin)
```
Here is the place to run some code that needs to be executed after the loss has been computed but before the gradient computation.
Example: `reg_fn` in RNNs.
At the end of that event the output will be set to `last_loss` of the state of the [`CallbackHandler`](/callback.html#CallbackHandler).
```
show_doc(Callback.on_backward_end)
```
Here is the place to run some code that needs to be executed after the gradients have been computed but
before the optimizer is called.
If `skip_step` is `True` at the end of this event, the optimizer step is skipped.
```
show_doc(Callback.on_step_end)
```
Here is the place to run some code that needs to be executed after the optimizer step but before the gradients
are zeroed.
If `skip_zero` is `True` at the end of this event, the gradients are not zeroed.
```
show_doc(Callback.on_batch_end)
```
Here is the place to run some code that needs to be executed after a batch is fully done.
Example: change the values of the hyperparameters (if we don't do it on_batch_begin instead)
If `end_epoch` is `True` at the end of this event, the current epoch is interrupted (example: lr_finder stops the training when the loss explodes).
```
show_doc(Callback.on_epoch_end)
```
Here is the place to run some code that needs to be executed at the end of an epoch.
Example: Save the model if we have a new best validation loss/metric.
If `end_training` is `True` at the end of this event, the training stops (example: early stopping).
```
show_doc(Callback.on_train_end)
```
Here is the place to tidy everything. It's always executed even if there was an error during the training loop,
and has an extra kwarg named exception to check if there was an exception or not.
Examples: save log_files, load best model found during training
```
show_doc(Callback.get_state)
```
This is used internally when trying to export a [`Learner`](/basic_train.html#Learner). You won't need to subclass this function but you can add attribute names to the lists `exclude` or `not_min`of the [`Callback`](/callback.html#Callback) you are designing. Attributes in `exclude` are never saved, attributes in `not_min` only if `minimal=False`.
## Annealing functions
The following functions provide different annealing schedules. You probably won't need to call them directly, but would instead use them as part of a callback. Here's what each one looks like:
```
annealings = "NO LINEAR COS EXP POLY".split()
fns = [annealing_no, annealing_linear, annealing_cos, annealing_exp, annealing_poly(0.8)]
for fn, t in zip(fns, annealings):
plt.plot(np.arange(0, 100), [fn(2, 1e-2, o)
for o in np.linspace(0.01,1,100)], label=t)
plt.legend();
show_doc(annealing_cos)
show_doc(annealing_exp)
show_doc(annealing_linear)
show_doc(annealing_no)
show_doc(annealing_poly)
show_doc(CallbackHandler)
```
You probably won't need to use this class yourself. It's used by fastai to combine all the callbacks together and call any relevant callback functions for each training stage. The methods below simply call the equivalent method in each callback function in [`self.callbacks`](/callbacks.html#callbacks).
```
show_doc(CallbackHandler.on_backward_begin)
show_doc(CallbackHandler.on_backward_end)
show_doc(CallbackHandler.on_batch_begin)
show_doc(CallbackHandler.on_batch_end)
show_doc(CallbackHandler.on_epoch_begin)
show_doc(CallbackHandler.on_epoch_end)
show_doc(CallbackHandler.on_loss_begin)
show_doc(CallbackHandler.on_step_end)
show_doc(CallbackHandler.on_train_begin)
show_doc(CallbackHandler.on_train_end)
show_doc(CallbackHandler.set_dl)
show_doc(OptimWrapper)
```
This is a convenience class that provides a consistent API for getting and setting optimizer hyperparameters. For instance, for [`optim.Adam`](https://pytorch.org/docs/stable/optim.html#torch.optim.Adam) the momentum parameter is actually `betas[0]`, whereas for [`optim.SGD`](https://pytorch.org/docs/stable/optim.html#torch.optim.SGD) it's simply `momentum`. As another example, the details of handling weight decay depend on whether you are using `true_wd` or the traditional L2 regularization approach.
This class also handles setting different WD and LR for each layer group, for discriminative layer training.
```
show_doc(OptimWrapper.clear)
show_doc(OptimWrapper.create)
show_doc(OptimWrapper.new)
show_doc(OptimWrapper.read_defaults)
show_doc(OptimWrapper.read_val)
show_doc(OptimWrapper.set_val)
show_doc(OptimWrapper.step)
show_doc(OptimWrapper.zero_grad)
show_doc(SmoothenValue)
```
Used for smoothing loss in [`Recorder`](/basic_train.html#Recorder).
```
show_doc(SmoothenValue.add_value)
show_doc(Scheduler)
```
Used for creating annealing schedules, mainly for [`OneCycleScheduler`](/callbacks.one_cycle.html#OneCycleScheduler).
```
show_doc(Scheduler.step)
show_doc(AverageMetric)
```
See the documentation on [`metrics`](/metrics.html#metrics) for more information.
### Callback methods
You don't call these yourself - they're called by fastai's [`Callback`](/callback.html#Callback) system automatically to enable the class's functionality.
```
show_doc(AverageMetric.on_epoch_begin)
show_doc(AverageMetric.on_batch_end)
show_doc(AverageMetric.on_epoch_end)
```
## Undocumented Methods - Methods moved below this line will intentionally be hidden
## New Methods - Please document or move to the undocumented section
| github_jupyter |
# Work with Data
Data is the foundation on which machine learning models are built. Managing data centrally in the cloud, and making it accessible to teams of data scientists who are running experiments and training models on multiple workstations and compute targets is an important part of any professional data science solution.
In this notebook, you'll explore two Azure Machine Learning objects for working with data: *datastores*, and *datasets*.
## Connect to your workspace
To get started, connect to your workspace.
> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into Azure.
```
import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
```
## Work with datastores
In Azure ML, *datastores* are references to storage locations, such as Azure Storage blob containers. Every workspace has a default datastore - usually the Azure storage blob container that was created with the workspace. If you need to work with data that is stored in different locations, you can add custom datastores to your workspace and set any of them to be the default.
### View datastores
Run the following code to determine the datastores in your workspace:
```
# Get the default datastore
default_ds = ws.get_default_datastore()
# Enumerate all datastores, indicating which is the default
for ds_name in ws.datastores:
print(ds_name, "- Default =", ds_name == default_ds.name)
```
You can also view and manage datastores in your workspace on the **Datastores** page for your workspace in [Azure Machine Learning studio](https://ml.azure.com).
### Upload data to a datastore
Now that you have determined the available datastores, you can upload files from your local file system to a datastore so that it will be accessible to experiments running in the workspace, regardless of where the experiment script is actually being run.
```
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data
target_path='diabetes-data/', # Put it in a folder path in the datastore
overwrite=True, # Replace existing files of the same name
show_progress=True)
```
## Work with datasets
Azure Machine Learning provides an abstraction for data in the form of *datasets*. A dataset is a versioned reference to a specific set of data that you may want to use in an experiment. Datasets can be *tabular* or *file*-based.
### Create a tabular dataset
Let's create a dataset from the diabetes data you uploaded to the datastore, and view the first 20 records. In this case, the data is in a structured format in a CSV file, so we'll use a *tabular* dataset.
```
from azureml.core import Dataset
# Get the default datastore
default_ds = ws.get_default_datastore()
#Create a tabular dataset from the path on the datastore (this may take a short while)
tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv'))
# Display the first 20 rows as a Pandas dataframe
tab_data_set.take(20).to_pandas_dataframe()
```
As you can see in the code above, it's easy to convert a tabular dataset to a Pandas dataframe, enabling you to work with the data using common python techniques.
### Create a file Dataset
The dataset you created is a *tabular* dataset that can be read as a dataframe containing all of the data in the structured files that are included in the dataset definition. This works well for tabular data, but in some machine learning scenarios you might need to work with data that is unstructured; or you may simply want to handle reading the data from files in your own code. To accomplish this, you can use a *file* dataset, which creates a list of file paths in a virtual mount point, which you can use to read the data in the files.
```
#Create a file dataset from the path on the datastore (this may take a short while)
file_data_set = Dataset.File.from_files(path=(default_ds, 'diabetes-data/*.csv'))
# Get the files in the dataset
for file_path in file_data_set.to_path():
print(file_path)
```
### Register datasets
Now that you have created datasets that reference the diabetes data, you can register them to make them easily accessible to any experiment being run in the workspace.
We'll register the tabular dataset as **diabetes dataset**, and the file dataset as **diabetes files**.
```
# Register the tabular dataset
try:
tab_data_set = tab_data_set.register(workspace=ws,
name='diabetes dataset',
description='diabetes data',
tags = {'format':'CSV'},
create_new_version=True)
except Exception as ex:
print(ex)
# Register the file dataset
try:
file_data_set = file_data_set.register(workspace=ws,
name='diabetes file dataset',
description='diabetes files',
tags = {'format':'CSV'},
create_new_version=True)
except Exception as ex:
print(ex)
print('Datasets registered')
```
You can view and manage datasets on the **Datasets** page for your workspace in [Azure Machine Learning studio](https://ml.azure.com). You can also get a list of datasets from the workspace object:
```
print("Datasets:")
for dataset_name in list(ws.datasets.keys()):
dataset = Dataset.get_by_name(ws, dataset_name)
print("\t", dataset.name, 'version', dataset.version)
```
The ability to version datasets enables you to redefine datasets without breaking existing experiments or pipelines that rely on previous definitions. By default, the latest version of a named dataset is returned, but you can retrieve a specific version of a dataset by specifying the version number, like this:
```python
dataset_v1 = Dataset.get_by_name(ws, 'diabetes dataset', version = 1)
```
### Train a model from a tabular dataset
Now that you have datasets, you're ready to start training models from them. You can pass datasets to scripts as *inputs* in the estimator being used to run the script.
Run the following two code cells to create:
1. A folder named **diabetes_training_from_tab_dataset**
2. A script that trains a classification model by using a tabular dataset that is passed to it as an argument.
```
import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_from_tab_dataset'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
%%writefile $experiment_folder/diabetes_training.py
# Import libraries
import os
import argparse
from azureml.core import Run, Dataset
import pandas as pd
import numpy as np
import joblib
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
# Get the script arguments (regularization rate and training dataset ID)
parser = argparse.ArgumentParser()
parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')
parser.add_argument("--input-data", type=str, dest='training_dataset_id', help='training dataset')
args = parser.parse_args()
# Set regularization hyperparameter (passed as an argument to the script)
reg = args.reg_rate
# Get the experiment run context
run = Run.get_context()
# Get the training dataset
print("Loading Data...")
diabetes = run.input_datasets['training_data'].to_pandas_dataframe()
# Separate features and labels
X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values
# Split data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
# Train a logistic regression model
print('Training a logistic regression model with regularization rate of', reg)
run.log('Regularization Rate', np.float(reg))
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)
# calculate accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
print('Accuracy:', acc)
run.log('Accuracy', np.float(acc))
# calculate AUC
y_scores = model.predict_proba(X_test)
auc = roc_auc_score(y_test,y_scores[:,1])
print('AUC: ' + str(auc))
run.log('AUC', np.float(auc))
os.makedirs('outputs', exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
```
> **Note**: In the script, the dataset is passed as a parameter (or argument). In the case of a tabular dataset, this argument will contain the ID of the registered dataset; so you could write code in the script to get the experiment's workspace from the run context, and then get the dataset using its ID; like this:
>
> ```
> run = Run.get_context()
> ws = run.experiment.workspace
> dataset = Dataset.get_by_id(ws, id=args.training_dataset_id)
> diabetes = dataset.to_pandas_dataframe()
> ```
>
> However, Azure Machine Learning runs automatically identify arguments that reference named datasets and add them to the run's **input_datasets** collection, so you can also retrieve the dataset from this collection by specifying its "friendly name" (which as you'll see shortly, is specified in the argument definition in the script run configuration for the experiment). This is the approach taken in the script above.
Now you can run a script as an experiment, defining an argument for the training dataset, which is read by the script.
> **Note**: The **Dataset** class depends on some components in the **azureml-dataprep** package, so you need to include this package in the environment where the training experiment will be run. The **azureml-dataprep** package is included in the **azure-defaults** package.
```
from azureml.core import Experiment, ScriptRunConfig, Environment
from azureml.widgets import RunDetails
# Create a Python environment for the experiment (from a .yml file)
env = Environment.from_conda_specification("experiment_env", "environment.yml")
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes dataset")
# Create a script config
script_config = ScriptRunConfig(source_directory=experiment_folder,
script='diabetes_training.py',
arguments = ['--regularization', 0.1, # Regularizaton rate parameter
'--input-data', diabetes_ds.as_named_input('training_data')], # Reference to dataset
environment=env)
# submit the experiment
experiment_name = 'mslearn-train-diabetes'
experiment = Experiment(workspace=ws, name=experiment_name)
run = experiment.submit(config=script_config)
RunDetails(run).show()
run.wait_for_completion()
```
> **Note:** The **--input-data** argument passes the dataset as a *named input* that includes a *friendly name* for the dataset, which is used by the script to read it from the **input_datasets** collection in the experiment run. The string value in the **--input-data** argument is actually the registered dataset's ID. As an alternative approach, you could simply pass `diabetes_ds.id`, in which case the script can access the dataset ID from the script arguments and use it to get the dataset from the workspace, but not from the **input_datasets** collection.
The first time the experiment is run, it may take some time to set up the Python environment - subsequent runs will be quicker.
When the experiment has completed, in the widget, view the **azureml-logs/70_driver_log.txt** output log and the metrics generated by the run.
### Register the trained model
As with any training experiment, you can retrieve the trained model and register it in your Azure Machine Learning workspace.
```
from azureml.core import Model
run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'Tabular dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})
for model in Model.list(ws):
print(model.name, 'version:', model.version)
for tag_name in model.tags:
tag = model.tags[tag_name]
print ('\t',tag_name, ':', tag)
for prop_name in model.properties:
prop = model.properties[prop_name]
print ('\t',prop_name, ':', prop)
print('\n')
```
### Train a model from a file dataset
You've seen how to train a model using training data in a *tabular* dataset; but what about a *file* dataset?
When you're using a file dataset, the dataset argument passed to the script represents a mount point containing file paths. How you read the data from these files depends on the kind of data in the files and what you want to do with it. In the case of the diabetes CSV files, you can use the Python **glob** module to create a list of files in the virtual mount point defined by the dataset, and read them all into Pandas dataframes that are concatenated into a single dataframe.
Run the following two code cells to create:
1. A folder named **diabetes_training_from_file_dataset**
2. A script that trains a classification model by using a file dataset that is passed to is as an *input*.
```
import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_from_file_dataset'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
%%writefile $experiment_folder/diabetes_training.py
# Import libraries
import os
import argparse
from azureml.core import Dataset, Run
import pandas as pd
import numpy as np
import joblib
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
import glob
# Get script arguments (rgularization rate and file dataset mount point)
parser = argparse.ArgumentParser()
parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')
parser.add_argument('--input-data', type=str, dest='dataset_folder', help='data mount point')
args = parser.parse_args()
# Set regularization hyperparameter (passed as an argument to the script)
reg = args.reg_rate
# Get the experiment run context
run = Run.get_context()
# load the diabetes dataset
print("Loading Data...")
data_path = run.input_datasets['training_files'] # Get the training data path from the input
# (You could also just use args.dataset_folder if you don't want to rely on a hard-coded friendly name)
# Read the files
all_files = glob.glob(data_path + "/*.csv")
diabetes = pd.concat((pd.read_csv(f) for f in all_files), sort=False)
# Separate features and labels
X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values
# Split data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
# Train a logistic regression model
print('Training a logistic regression model with regularization rate of', reg)
run.log('Regularization Rate', np.float(reg))
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)
# calculate accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
print('Accuracy:', acc)
run.log('Accuracy', np.float(acc))
# calculate AUC
y_scores = model.predict_proba(X_test)
auc = roc_auc_score(y_test,y_scores[:,1])
print('AUC: ' + str(auc))
run.log('AUC', np.float(auc))
os.makedirs('outputs', exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
```
Just as with tabular datasets, you can retrieve a file dataset from the **input_datasets** collection by using its friendly name. You can also retrieve it from the script argument, which in the case of a file dataset contains a mount path to the files (rather than the dataset ID passed for a tabular dataset).
Next we need to change the way we pass the dataset to the script - it needs to define a path from which the script can read the files. You can use either the **as_download** or **as_mount** method to do this. Using **as_download** causes the files in the file dataset to be downloaded to a temporary location on the compute where the script is being run, while **as_mount** creates a mount point from which the files can be streamed directly from the datastore.
You can combine the access method with the **as_named_input** method to include the dataset in the **input_datasets** collection in the experiment run (if you omit this, for example by setting the argument to `diabetes_ds.as_mount()`, the script will be able to access the dataset mount point from the script arguments, but not from the **input_datasets** collection).
```
from azureml.core import Experiment
from azureml.widgets import RunDetails
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes file dataset")
# Create a script config
script_config = ScriptRunConfig(source_directory=experiment_folder,
script='diabetes_training.py',
arguments = ['--regularization', 0.1, # Regularizaton rate parameter
'--input-data', diabetes_ds.as_named_input('training_files').as_download()], # Reference to dataset location
environment=env) # Use the environment created previously
# submit the experiment
experiment_name = 'mslearn-train-diabetes'
experiment = Experiment(workspace=ws, name=experiment_name)
run = experiment.submit(config=script_config)
RunDetails(run).show()
run.wait_for_completion()
```
When the experiment has completed, in the widget, view the **azureml-logs/70_driver_log.txt** output log to verify that the files in the file dataset were downloaded to a temporary folder to enable the script to read the files.
### Register the trained model
Once again, you can register the model that was trained by the experiment.
```
from azureml.core import Model
run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'File dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})
for model in Model.list(ws):
print(model.name, 'version:', model.version)
for tag_name in model.tags:
tag = model.tags[tag_name]
print ('\t',tag_name, ':', tag)
for prop_name in model.properties:
prop = model.properties[prop_name]
print ('\t',prop_name, ':', prop)
print('\n')
```
> **More Information**: For more information about training with datasets, see [Training with Datasets](https://docs.microsoft.com/azure/machine-learning/how-to-train-with-datasets) in the Azure ML documentation.
| github_jupyter |
# 1. SETTINGS
```
# libraries
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
import lightgbm as lgb
import seaborn as sns
import matplotlib.pyplot as plt
# garbage collection
import gc
gc.enable()
# pandas options
pd.set_option("display.max_columns", None)
# ignore warnings
import warnings
warnings.filterwarnings("ignore")
# random settings
seed = 42
```
# 2. PREPARATIONS
```
# dataset
data = "v1"
# import data
train = pd.read_csv("../data/prepared/train_" + str(data) + ".csv")
test = pd.read_csv("../data/prepared/test_" + str(data) + ".csv")
y = pd.read_csv("../data/prepared/y_" + str(data) + ".csv")
# sort data
train = train.sort_values("SK_ID_CURR")
y = y.sort_values("SK_ID_CURR")
# extract target
y = y["TARGET"]
# exclude features
excluded_feats = ["SK_ID_CURR"]
features = [f for f in train.columns if f not in excluded_feats]
# check dimensions
print(train[features].shape)
print(test[features].shape)
### PARAMETERS
# parallel settings
cores = 10
# learner settings
metric = "auc"
verbose = 500
stopping = 300
# CV settings
num_folds = 5
shuffle = True
# lightGBM
gbm = lgb.LGBMClassifier(n_estimators = 10000,
learning_rate = 0.005,
num_leaves = 70,
colsample_bytree = 0.8,
subsample = 0.9,
max_depth = 7,
reg_alpha = 0.1,
reg_lambda = 0.1,
min_split_gain = 0.01,
min_child_weight = 2,
random_state = seed,
num_threads = cores)
```
# 3. CROSS-VALIDATION
## 3.1. ALL FEATURES
```
# data partitinoing
folds = StratifiedKFold(n_splits = num_folds, random_state = seed, shuffle = shuffle)
# placeholders
valid_aucs_cv = np.zeros(num_folds)
test_preds_cv = np.zeros(test.shape[0])
feature_importance_df = pd.DataFrame()
### CROSS-VALIDATION LOOP
for n_fold, (trn_idx, val_idx) in enumerate(folds.split(train, y)):
# data partitioning
trn_x, trn_y = train[features].iloc[trn_idx], y.iloc[trn_idx]
val_x, val_y = train[features].iloc[val_idx], y.iloc[val_idx]
# train lightGBM
gbm = gbm.fit(trn_x, trn_y,
eval_set = [(trn_x, trn_y), (val_x, val_y)],
eval_metric = metric,
verbose = verbose,
early_stopping_rounds = stopping)
# save number of iterations
num_iter_cv = gbm.best_iteration_
# predictions
valid_preds_cv = gbm.predict_proba(val_x, num_iteration = num_iter_cv)[:, 1]
valid_aucs_cv[n_fold] = roc_auc_score(val_y, valid_preds_cv)
test_preds_cv += gbm.predict_proba(test[features], num_iteration = num_iter_cv)[:, 1] / folds.n_splits
# importance
fold_importance_df = pd.DataFrame()
fold_importance_df["Feature"] = features
fold_importance_df["Importance"] = gbm.feature_importances_
fold_importance_df["Fold"] = n_fold + 1
feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis = 0)
# print performance
print("----------------------")
print("Fold%2d AUC: %.6f" % (n_fold + 1, valid_aucs_cv[n_fold]))
print("----------------------")
print("")
# clear memory
del trn_x, trn_y, val_x, val_y
gc.collect()
# print overall performance
auc = np.mean(valid_aucs_cv)
print("Cross-Validation AUC score %.6f" % np.mean(valid_aucs_cv))
##### VARIABLE IMPORTANCE
# load importance
top_feats = 50
cols = feature_importance_df[["Feature", "Importance"]].groupby("Feature").mean().sort_values(by = "Importance", ascending = False)[0:top_feats].index
importance = feature_importance_df.loc[feature_importance_df.Feature.isin(cols)]
# plot variable importance
plt.figure(figsize = (10, 10))
sns.barplot(x = "Importance", y = "Feature", data = importance.sort_values(by = "Importance", ascending = False))
plt.title('LightGBM Variable Importance (mean over CV folds)')
plt.tight_layout()
# save plot as pdf
plt.savefig("../var_importance.pdf")
```
## 3.2. TOP FEATURES
```
# keep top features
top = 500
cols = feature_importance_df[["Feature", "Importance"]].groupby("Feature").mean().sort_values(by = "Importance", ascending = False)[0:top].index
importance = feature_importance_df.loc[feature_importance_df.Feature.isin(cols)]
features = list(importance.groupby("Feature").Importance.mean().sort_values(ascending = False).index)
# check dimensions
print(train[features].shape)
print(test[features].shape)
### CROSS-VALIDATION LOOP
for n_fold, (trn_idx, val_idx) in enumerate(folds.split(train, y)):
# data partitioning
trn_x, trn_y = train[features].iloc[trn_idx], y.iloc[trn_idx]
val_x, val_y = train[features].iloc[val_idx], y.iloc[val_idx]
# train lightGBM
gbm = gbm.fit(trn_x, trn_y,
eval_set = [(trn_x, trn_y), (val_x, val_y)],
eval_metric = metric,
verbose = verbose,
early_stopping_rounds = stopping)
# save number of iterations
num_iter_cv = gbm.best_iteration_
# predictions
valid_preds_cv = gbm.predict_proba(val_x, num_iteration = num_iter_cv)[:, 1]
valid_aucs_cv[n_fold] = roc_auc_score(val_y, valid_preds_cv)
test_preds_cv += gbm.predict_proba(test[features], num_iteration = num_iter_cv)[:, 1] / folds.n_splits
# print performance
print("----------------------")
print("Fold%2d AUC: %.6f" % (n_fold + 1, valid_aucs_cv[n_fold]))
print("----------------------")
print("")
# clear memory
del trn_x, trn_y, val_x, val_y
gc.collect()
# print overall performance
auc = np.mean(valid_aucs_cv)
print("Cross-Validation AUC score %.6f" % auc)
```
# 4. SUBMISSION
```
# create submission
test["TARGET"] = test_preds_cv
subm = test[["SK_ID_CURR", "TARGET"]]
# check rank correlation with the best submission
from scipy.stats import spearmanr
best = pd.read_csv("../submissions/rmean_top7_03072018.csv")
spearmanr(test.TARGET, best.TARGET)
# export CSV
subm.to_csv("../submissions/auc" + str(round(auc, 6))[2:8] + "_bag_lgb_top" + str(top) + ".csv", index = False, float_format = "%.8f")
# no card, old features (560): 0.786941 | 0.783
# no card, new features (694): 0.788893 | 0.783
# with card, new features (1072): 0.790123 | 0.787
# with card and kernel features (1109): 0.790053 |
# card, kernel, factorize, no na (978): 0.790803 |
# card, kern, fac, nona, adummy (1193): 0.791321 |
# full data, one-hot ecoding (1844): 0.791850 |
# full data, one-hot, extra sums (2486): 0.791880 | 0.789
# full, one-hot, sums, buroscore (2501): 0.791761 |
# full, one-hot, clean, buroscore (1826): 0.791867 |
# last data + ext, age ratios (1828): 0.791808 |
# new app feats, remove weighted (1830): 0.794241 | 0.795
# previous data - top1000 LGB features: 0.794384 |
# select top1500 LGB features: 0.794384 |
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.