text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# Clinical Profile Calculations on JHU Diabetes Sample
### Steph Howson, JHU/APL, Data Scientist
This notebook calculates fields to be generated for the Clinical Profiles model. Once the values are calculated, the results will be dynamically put into the model with the fhir.resources implementation. The Clinical Profiles Python specification was built using fhir-parser. These forked Github repositories can be found (currently not much was done to add desired features for Clinical Profiles in particular, but the templating captures much of the functionality needed):
https://github.com/stephanie-howson/fhir-parser
https://github.com/stephanie-howson/fhir.resources
The Clinical Profile Python FHIR Class definition can be found at:
https://github.com/stephanie-howson/fhir.resources/blob/master/fhir/resources/clinicalprofile.py
### Imports
```
import pandas as pd
import numpy as np
import scipy.stats as ss
import math
import dask.dataframe as dd
import sys
```
### Reading in data from SAFE
```
# Want to specify dtypes for performance
demographics_DOB = ['DOB']
demographics_dtypes = {'PatientID':np.int64, 'Gender':'category','Race':'category','Ethnicity':'category'}
labs_dates = ['Ordering_datetime','Result_datetime']
labs_dtypes = {'PatientID':np.int64, 'EncounterID':np.int64, 'Result_numeric':np.float64,'Lab_Name':'category',
'Base_Name':'category','Loinc_Code':'category','LONG_COMMON_NAME':'category',
'status':'category','Category':'category','GroupId':'category','unit':'category',
'range':'category'}
diagnoses_hpo_dates = ['Entry_Date']
diagnoses_hpo_dtypes = {'PatientID':np.int64, 'icd_10':'category','icd_name':'category',
'hpo':'category','hpo_term':'category'}
encounter_dates = ['Encounter_date']
encounter_dtypes = {'PatientID': np.int64,'EncounterID': np.int64, 'Encounter_type':'category'}
meds_dates = ['Order_datetime','Start_date','End_date']
meds_dtypes = {'PatientID': np.int64,'EncounterID': np.int64, 'Medication_Name':'category','Dose':'category',
'Route':'category', 'Frequency':'category', 'Quantity':'category', 'RXNorm':np.float64,'Therapeutic_Class':'category',
'Pharmaceutical_Class':'category', 'Pharmaceutical_Subclass':'category'}
procedure_dtypes = {'PatidentID':np.int64,'EncounterID':np.int64, 'Procedure_ID':np.int64,'Procedure_Code':'category',
'Procedure_Name':'category'}
df_demographics = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_demographics.txt',sep='|',
dtype=demographics_dtypes, parse_dates=demographics_DOB)
print(sys.getsizeof(df_demographics)*10**(-9))
df_labs = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_labs.txt',sep='|',
dtype=labs_dtypes, parse_dates=labs_dates)
print(sys.getsizeof(df_labs)*10**(-9))
df_diagnoses_hpo = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_diagnoses_hpo.txt',sep='|',
dtype=diagnoses_hpo_dtypes, parse_dates=diagnoses_hpo_dates)
print(sys.getsizeof(df_diagnoses_hpo)*10**(-9))
df_encounter = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_encounter.txt',sep='|',
dtype=encounter_dtypes, parse_dates=encounter_dates)
print(sys.getsizeof(df_encounter)*10**(-9))
df_meds = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_meds.txt',sep='|',
dtype=meds_dtypes, parse_dates=meds_dates)
print(sys.getsizeof(df_meds)*10**(-9))
df_procedures = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_procedure.txt',sep='|',encoding='Latin-1',
dtype=procedure_dtypes)
print(sys.getsizeof(df_procedures)*10**(-9))
```
### Calculating Lab Information
#### Lesson learned: grab patient IDs from demographics and then drop not needed columns, not all patients will have all encounter types, e.g. labs, medications, etc.
```
df_labs_full = df_labs.merge(df_demographics, on='PatientID', how='right')
df_labs_full.head()
(len(df_labs_full)-len(df_labs) )
df_labs_full.drop(['Result_datetime','Base_Name','status','Category','GroupId'],axis=1,inplace=True)
print(sys.getsizeof(df_labs_full)*10**(-9))
code = df_labs_full.Loinc_Code.unique().dropna()
code[0]
count = df_labs_full.Loinc_Code.value_counts()
count.index[0]
df_labs_full['orderYear'] = pd.to_datetime(df_labs_full.Ordering_datetime).dt.year
frequencyPerYear = df_labs_full.groupby(['Loinc_Code','PatientID','orderYear']).PatientID.size().groupby(['Loinc_Code','orderYear']).aggregate(np.mean)
frequencyPerYear.head(20)
%time correlatedLabsCoefficients = df_labs_full.groupby('Loinc_Code').Result_numeric.apply(lambda x: pd.Series(x.values)).unstack().transpose().corr()
correlatedLabsCoefficients
abscorrelation = correlatedLabsCoefficients.abs()
fractionOfSubjects = df_labs_full.groupby(['Loinc_Code']).PatientID.nunique()/df_labs_full.PatientID.nunique()
fractionOfSubjects
units = df_labs_full.groupby(['Loinc_Code']).unit.unique()
minimum = df_labs_full.groupby(['Loinc_Code']).Result_numeric.min()
maximum = df_labs_full.groupby(['Loinc_Code']).Result_numeric.max()
mean = df_labs_full.groupby(['Loinc_Code']).Result_numeric.mean()
median = df_labs_full.groupby(['Loinc_Code']).Result_numeric.median()
stdDev = df_labs_full.groupby(['Loinc_Code']).Result_numeric.std()
nthDecile = df_labs_full.groupby('Loinc_Code').Result_numeric.quantile([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
def percentile(n):
def percentile_(x):
return x.quantile(n*0.01)
percentile_.__name__ = '%s' % n
return percentile_
stats = (df_labs_full.groupby(['Loinc_Code'])
.Result_numeric.agg(['min','max', 'mean','median','std',
percentile(10), percentile(20), percentile(30),
percentile(40), percentile(50), percentile(60),
percentile(70), percentile(80), percentile(90)]))
df_labs_full.info()
df_labs_full['range_high'] = (pd.to_numeric(df_labs_full.range.dropna()
.astype('str').str.split(',',expand=True)[1]).astype('float'))
df_labs_full['range_low'] = (pd.to_numeric(df_labs_full.range.dropna()
.astype('str').str.split(',',expand=True)[0]).astype('float'))
def fracsAboveBelowNormal(x):
aboveNorm = np.divide(np.sum(x.Result_numeric > x.range_high), x.Result_numeric.size)
belowNorm = np.divide(np.sum(x.Result_numeric < x.range_low), x.Result_numeric.size)
return pd.Series({'aboveNorm':aboveNorm, 'belowNorm':belowNorm})
%%time
aboveBelowNorm = (df_labs_full.groupby(['Loinc_Code'])
.apply(fracsAboveBelowNormal))
aboveBelowNorm.aboveNorm
```
**NOTE: Less than a minute to calculate all necessary lab information (~9 million rows)**
#### Printing out first 10 results from each calculated field as an example
*If you copy this file, feel free to remove .head(10) to see all results, by default pandas groupby sorts alphanumerically*
```
code.head(10)
count.head(10)
frequencyPerYear.head(10)
correlatedLabsCoefficients.head(10)
abscorrelation.head(10)
fractionOfSubjects.head(10)
units.head(10)
minimum.head(10)
maximum.head(10)
mean.head(10)
median.head(10)
stdDev.head(10)
nthDecile.head(20)
```
### Define Correlation Functions Needed for Categorical Data
```
def cramers_v(df, x, y):
confusion_matrix = (df.groupby([x,y])[y].size().unstack().fillna(0).astype(int))
chi2 = ss.chi2_contingency(confusion_matrix)[0]
n = confusion_matrix.sum().sum()
phi2 = chi2/n
r,k = confusion_matrix.shape
phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1))
rcorr = r-((r-1)**2)/(n-1)
kcorr = k-((k-1)**2)/(n-1)
return np.sqrt(phi2corr/min((kcorr-1), (rcorr-1)))
def uncertainty_coefficient(df, x, y):
df2 = df[[x,y]]
total = len(df2.dropna())
p_y = (df.groupby([y], sort=False)[y].size()/total).reindex(index=p_xy.index, level=1)
s_xy = sum(p_xy * (p_y/p_xy).apply(math.log))
p_x = df.groupby([x], sort=False)[x].size()/total
s_x = ss.entropy(p_x)
if s_x == 0:
return 1
else:
return ((s_x - s_xy) / s_x)
def correlation_ratio(df, x, y):
df2 = df.groupby([x],sort=False)[y].agg([np.size,np.mean])
ybar = df[y].mean()
numerator = np.nansum(np.multiply(df2['size'],np.square(df2['mean']-ybar)))
ssd = np.square(df[y]-ybar)
#ssd = df.groupby([x,y],sort=False)[y].apply(lambda y: np.nansum(np.square(y-ybar)))
denominator = np.nansum(ssd)
if numerator == 0:
return 0.0
else:
return np.sqrt(numerator/denominator)
```
### Join All DataFrames to "Correlate Everything to Everything"
```
df = (df_labs.merge(df_diagnoses_hpo, on='PatientID')
.merge(df_encounter, on=['PatientID','EncounterID'], how='outer')
.merge(df_meds, on=['PatientID','EncounterID'], how='outer'))
```
### Define Categorical Fields
```
categoricals = ['Lab_Name','Base_Name','Loinc_Code','LONG_COMMON_NAME','Category','GroupId','icd_10','icd_name',
'hpo','hpo_term','Encounter_type','Medication_Name','Dose','Route','Frequency','RXNorm',
'Therapeutic_Class','Pharmaceutical_Class','Pharmaceutical_Subclass']
```
## Work in Progress...
#### Need to Define Correlations More Precisely
## Will Add in Other Fields & Their Calculated Results Shortly.....
### Medications
```
df_meds_full = df_meds.merge(df_demographics, on='PatientID', how='outer')
(len(df_meds_full) - len(df_meds))
```
**Why is Medication Name nunique() > RXNorm nunique() ?**
```
medication = df_meds_full.RXNorm.unique()
uniqDropNA = lambda x: np.unique(x.dropna())
dosageInfo = df_meds_full.groupby('RXNorm').agg({'Route':uniqDropNA, 'Dose':uniqDropNA,'Quantity':uniqDropNA})#[['Route','Dose','Quantity']].apply(np.unique)
#dose = df_meds_full.groupby('RXNorm')['Dose'].unique()
#quantity = df_meds_full.groupby('RXNorm')['Quantity'].unique()
# How to calculate rateRatio?!
#treatmentDuration says need clarification in model!
df_meds_full['startYear'] = pd.to_datetime(df_meds_full.Start_date).dt.year
frequencyPerYear = df_meds_full.groupby(['RXNorm','startYear','PatientID']).PatientID.count().groupby(['RXNorm','startYear']).mean()
fractionOfSubjects = df_meds_full.groupby(['RXNorm']).PatientID.nunique()/df_meds_full.PatientID.nunique()
#correlatedLabsCoefficients = df_labs.groupby('LONG_COMMON_NAME').Result_numeric.apply(lambda x: pd.Series(x.values)).unstack().transpose().corr()
#abscorrelation = correlatedLabsCoefficients.abs()
dosageInfo
```
### Diagnosis
```
df_diagnoses_hpo_full = df_diagnoses_hpo.merge(df_demographics, on='PatientID', how='outer')
(len(df_diagnoses_hpo_full) - len(df_diagnoses_hpo))
code = df_diagnoses_hpo_full.icd_10.unique()
df_diagnoses_hpo_full['entryYear'] = pd.to_datetime(df_diagnoses_hpo_full.Entry_Date).dt.year
frequencyPerYear = df_diagnoses_hpo_full.groupby(['icd_10','entryYear','PatientID']).PatientID.count().groupby(['icd_10','entryYear']).mean()
fractionOfSubjects = df_diagnoses_hpo_full.groupby(['icd_10']).PatientID.nunique()/df_diagnoses_hpo_full.PatientID.nunique()
frequencyPerYear
```
### Procedures
```
df_procedures_full = df_procedures.merge(df_demographics, on='PatientID', how='right')
df_procedures_full.drop(['DOB','Gender','Race','Ethnicity'], axis=1, inplace=True)
```
**I need the encounter table to get a date**
```
encounter_dtypes = {'PatientID': np.int64, 'EncounterID': np.int64, 'Encounter_type': 'category'}
encounter_date = ['Encounter_date']
df_encounter = pd.read_csv(r'S:\NCATS\Clinical_Profiles\clean_data\Diabetes\jh_diabetes_encounter.txt',sep='|',
dtype=encounter_dtypes, parse_dates=encounter_date)
print(sys.getsizeof(df_encounter)*10**(-9))
df_procedures_full = df_procedures_full.merge(df_encounter, on=['EncounterID','PatientID'], how='left')
print(sys.getsizeof(df_procedures_full)*10**(-9))
(len(df_procedures_full) - len(df_procedures))
df_procedures_full.columns
# Oops don't need extra patient column
len(df_procedures_full.PatientID_x.dropna()) - len(df_procedures_full.PatientID_y.dropna())
df_procedures_full.drop('PatientID_y',axis=1,inplace=True)
df_procedures_full.rename(columns={'PatientID_x': 'PatientID'}, inplace=True)
```
procedure_dtypes = {'PatidentID':np.int64,'EncounterID':np.int64, 'Procedure_ID':np.int64,'Procedure_Code':'category',
'Procedure_Name':'category'}
```
code = df_procedures_full.Procedure_Code.unique()
df_procedures_full['encounterYear'] = pd.to_datetime(df_procedures_full.Encounter_date).dt.year
frequencyPerYear = (df_procedures_full.groupby(['Procedure_Code','encounterYear','PatientID']).PatientID.count()
.groupby(['Procedure_Code','encounterYear']).mean())
fractionOfSubjects = df_procedures_full.groupby(['Procedure_Code']).PatientID.nunique()/df_procedures_full.PatientID.nunique()
fractionOfSubjects
```
| github_jupyter |
# Load libraries and read data
```
!pip install shap
!pip install pyitlib
from google.colab import drive
drive.mount('/content/drive')
import os
os.path.abspath(os.getcwd())
os.chdir('/content/drive/My Drive/Protein project')
os.path.abspath(os.getcwd())
from __future__ import division ###for float operation
from collections import Counter
from numpy import *
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score ##tp / (tp + fn)
from sklearn.metrics import precision_score #tp / (tp + fp)
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import KFold, StratifiedKFold
from pyitlib import discrete_random_variable as drv
import time
import timeit
class NotFittedError(ValueError):
"""Raise if predict is called before fit."""
def __init__(self, class_name):
message = self.message(class_name)
super(NotFittedError, self).__init__(message)
@staticmethod
def message(class_name):
return ("This instance of " + class_name +
" has not been fitted yet. Please call "
"'fit' before you call 'predict'.")
```
This goes back to the amino acid sequence
vs the 8 blocks that we discussed last week.
The set of pairs [(254, 256), (52, 115), (215, 218), (72, 92), (146, 213),....] is talking about physical touch in
the amino acid sequence and it means positions
254 and 256, 52 and 115, 215 and 218, e.t.c
are physically touching.
The way the 8 x 8 matrix is calculated is to add
up all the positions within and between blocks that
are physically touching. For example, say 254 and
256 are both in block 4, the (254, 256) would add 1 to the [4,4]
entry of the 8 x 8 block matrix, if 52 was in block 1 and
115 was in block 2, the (52, 115) would add 1 to
the [1,2] and [2,1] entries of the matrix.
So to go from the set of pairs to the 8 x 8 contact
matrix, you need to go back to the alignments, use
the amino acid sequence pairs and add up how many
are in each pair of blocks.
-----by Garvesh
### P450
```
def readData(filename):
fr = open(filename)
returnData = []
headerLine=fr.readline()###move cursor
for line in fr.readlines():
lineStrip = line.strip().replace('"','')
lineList = lineStrip.split('\t')
returnData.append(lineList)###['3','2',...]
return returnData
"""first case P450 = [['1','1',....],[],[].....,[]] second case P450 = array([['1','1',....],[],[].....,[]]), third case P450 = """
P450 = readData('P450.txt') ### [[],[],[],....[]]
P450 = np.array(P450) ### either [['1','1',....],[],[].....,[]] or array([['1','1',....],[],[].....,[]]) works, but note that keys are '1', '0'
#P450 = P450.astype(int) ### for shap array [[1,1,....],[],[].....,[]], keys are 1, 0
M=matrix([[245, 9, 0, 3, 0, 2, 65, 8],
[9, 218, 17, 17, 49, 10, 50, 17],
[0, 17, 175, 16, 25, 13, 0, 46],
[3, 17, 16, 194, 19, 0, 0, 3],
[0, 49, 25, 19, 199, 10, 0, 3],
[2, 10, 13, 0, 10, 249, 50, 74],
[65, 50, 0, 0, 0, 50, 262, 11],
[8, 17, 46, 3, 3, 74, 11, 175]])
```
### lactamase
```
def readData2(filename):
fr = open(filename)
returnData = []
headerLine=fr.readline()###move cursor
for line in fr.readlines():
linestr = line.strip().replace(', ','')
lineList = list(linestr)
returnData.append(lineList)###['3','2',...]
return returnData
lactamase = readData2('lactamase.txt')
lactamase = np.array(lactamase)
#lactamase = lactamase.astype(int)
M2 = matrix([[101, 5, 0, 2, 0, 14, 4, 37],
[5 ,15, 14 ,1 ,7 ,7, 0 ,19],
[0, 14, 266, 15, 14, 2, 26, 4],
[2, 1, 15, 28, 2 ,15, 4, 0],
[0, 7, 14, 2, 32, 9 ,0, 8],
[14, 7, 2 ,15, 9, 29, 7, 9],
[4, 0, 26, 4 ,0 ,7 ,72, 21],
[37, 19, 4, 0, 8, 9, 21, 211]])
```
### lymph
```
def readarff(filename):
arrfFile = open(filename)
lines = [line.rstrip('\n') for line in arrfFile]
data = [[]]
index = 0
for line in lines :
if(line.startswith('@attribute')) :
index+=1
elif(not line.startswith('@data') and not line.startswith('@relation') and not line.startswith('%')) :
data.append(line.split(','))
del data[0]
return data
lymph_train = readarff("github_bn_code/lymph_train.arff.txt"); lymph_train = np.array(lymph_train)
lymph_test = readarff("github_bn_code/lymph_test.arff.txt") ;lymph_test = np.array(lymph_test)
lymph = np.concatenate((lymph_train,lymph_test))
```
### Vote
```
vote_train = readarff("github_bn_code/vote_train.arff.txt") ;vote_train = np.array(vote_train)
vote_test = readarff("github_bn_code/vote_test.arff.txt") ; vote_test = np.array(vote_test)
vote = np.concatenate((vote_train,vote_test))
```
# API Bayesian network class
For using shap purpose, write skilearn API class,
## Base class
```
"""
Bayesian network implementation
API inspired by SciKit-learn.
"""
class Bayes_net(object): ### DO I need object???
def __init__(self, alpha = 1):
"""Create a Bayesian classifier
alpha is the smoothing parameter
name is the class name of that classifier: Naive Bayes, Tree augmented naive Nayes
Dict_C, p , P_class_prior,C K,countDict are learned from fitting method. Initialized as empty list.
"""
self.alpha = alpha
self.name = self.get_name()
self.Dict_C = []
self.p = 0
self.P_class_prior = []
self.K = []
self.C = []
self.countDict = []
self._is_fitted = False
"""add training time """
self.training_time = 0
def get_name(self):
raise NotImplementedError
def get_Y(self,train):
"""Get target values from train data.
:param train: Training examples with dimension (p+1) x n,
where n is the number of examples,
and p is the number of features.
Last column is target.(dtype: list)
:return: target values(dtype: list/array)
"""
if isinstance(train,list):
return([ele[-1] for ele in train])
else: ### suppose it is array
return(train[:,-1])
def get_X(self,train):
"""Get feature values from train data.
:param train: Training examples with dimension (p+1) x n,
where n is the number of examples,
and p is the number of features.
Last column is target.(dtype: list)
:return: feature matrix(dtype: list[[ ],[ ],[ ],....[ ]] or array)
"""
if isinstance(train,list):
p = len(train[0]) - 1
return([ele[0:p] for ele in train])
else:
p = len(train[0]) - 1
return(train[:,0:p])
def prob_to_class_general(self,y_pred_prob,C):
"""convert predicted probabilities to class labels.
:param y_pred_prob: np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i]
:param C: Class labels
:return: predicted class labels.(dtype:array). if C = ['1','0'], then returns list like array(['1','1','0'])
"""
return( np.array([C[ele] for ele in np.argmax(y_pred_prob, axis=1)] ) )
def Conditional_log_likelihood_general(self,y_true,y_pred_prob,C):
"""Calculate the conditional log likelihood.
:param y_true: The true class labels. e.g ['1','1',.....'0','0']
:param y_pred_prob: np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i]
:param C: Class labels e.x ['1','0'], C has to use same labels as y_true.
:return: CLL. A scalar.
"""
cll = []
for i in range(len(y_true)):
cll.append( y_pred_prob[i,C.index(y_true[i])] ) ## \hat p(c_true|c_true)
cll = [np.log2(ele) for ele in cll]
cll = np.array(cll)
return(sum(cll))
def fit(self,train):
"""Reset the parameters to none, and Fit model according to train data.
:param train: Training examples with dimension (p+1) x n,
where n is the number of examples,
and p is the number of features.
Last column is target.(dtype: list)
:return: self
"""
raise NotImplementedError
def predict(self, test):
"""Predict prob values for test set for each class.
:param test_set: Test set with dimension (p or p+1) x n,
where n is the number of examples,
and p is the number of features.
:return: Predicted target values for test set with dimension n * |C|,
where n is the number of examples. |C| is the # of classes.
it is np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i]
"""
raise NotImplementedError
def predict_binary(self,test):
raise NotImplementedError
def predict_class(self, test):
"""Predict class labels for test set .
:param test_set: Test set with dimension (p or p+1) x n,
where n is the number of examples,
and p is the number of features.
:return: Predicted class labels for test set with dimension n ,
where n is the number of examples.
"""
Prob_C = self.predict(test) ## Prob_C is |C|*n np.array ,C is self.C
return(self.prob_to_class_general(Prob_C,self.C))
```
## Naive Bayes
```
class NB(Bayes_net):
def get_name(self):
return("NB")
def fit(self,train):
Y = self.get_Y(train)
t = time.process_time()
"""start timing"""
countDict = Counter(Y) ## {c1:n1,c2:n2,c3:n3} sorted by counts
C = list(countDict.keys()) ### [class1 , class2, class3] in appearing order
p = len(train[0]) - 1 ## num of features 8 ### .values same order as .keys()
P_class = [(ele+self.alpha)/(sum(list(countDict.values())) + self.alpha*len(C) ) for ele in countDict.values()] ### prior for each class [p1,p2,p3]
P_class = dict(zip(C, P_class)) ## {c1:p1,c2:p2,c3:p3} ## should in correct order, .keys .values.
Dict_C = {} ### {c1:[counter1, ....counter8], c2:[counter1, ....counter8], c3: [counter1, ....counter8]}
K = {} ## [x1 unique , x2 unique .... x8unique]
for c in C:
ListCounter_c = []
for i in range(p):
x_i_c = [ele[i] for ele in train if ele[-1] == c]
ListCounter_c.append(Counter(x_i_c))
if c == C[0]:
x_i = [ele[i] for ele in train]
K[i] = len(Counter(x_i))
Dict_C[c] = ListCounter_c
CP_time = time.process_time() - t; CP_time = np.array(CP_time)
self._is_fitted = True
self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict,self.training_time = Dict_C,p,P_class,K,C,countDict,CP_time
return self
def predict(self,X_test):
"""Predict prob values for test set for each class.
:param test_set: Test set with dimension (p or p+1) x n,
where n is the number of examples,
and p is the number of features.
:return: Predicted target values for test set with dimension n * |C|,
where n is the number of examples. |C| is the # of classes.
it is np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i]
"""
if not self._is_fitted:
raise NotFittedError(self.__class__.__name__)
Prob_C = []
for ins in X_test:
P_class = self.P_class_prior.copy() ### {c1:p1, c2:p2} #### !!!! dict1 = dict2 , change both simultaneously!!!
for c in self.C:
ListCounter_c = self.Dict_C[c]
for i in range(self.p):
P_class[c] = P_class[c] * (ListCounter_c[i][ins[i]]+self.alpha) / (self.countDict[c] + self.alpha*self.K[i])
## normalize P_class
P_class = {key: P_class[key]/sum(list(P_class.values())) for key in P_class.keys()}
Prob_C.append(list(P_class.values())) ### check the class order is correct
Prob_C = array(Prob_C) ### for shap !!!!
return Prob_C
def predict_binary(self,X_test):
Prob_C = self.predict(X_test) ### Prob_C is n*|C| np.array
return(Prob_C[:,0])
nb = NB()
nb.fit(P450)
nb.fit(P450)
nb.Dict_C
print(type(nb.training_time))
#nb.training_time
#nb.predict(P450)
#nb.predict_class(P450)
```
## TAN_MT
```
class TAN_MT(Bayes_net):
def __init__(self, alpha = 1,starting_node = 0):
self.starting_node = starting_node
self.alpha = alpha
self.name = "TAN_MT"
self.Dict_C = []
self.p = 0
self.P_class_prior = []
self.K = []
self.C = 0
self.countDict = []
self.parent = [] ### one more attribute than NB
self._is_fitted = False
"""add training time """
self.training_time = 0
self.mutual_inf_time = 0
self.prim_time = 0
self.CP_time = 0
def To_CAT(self, X_i):
"""For using CMI purpose, convert X_i e.g ['a','b','a']/['0','1','0'] to [0,1,0].
:param X_i: one feature column.
:return: list(type int)
"""
X_i_list = list(set(X_i));X_i_dict = dict(zip(X_i_list, arange(len(X_i_list)) ))
return([X_i_dict[ele] for ele in X_i])
def get_mutual_inf(self,train):
"""get conditional mutual inf of all pairs of features, part of training
:return: np.array matrix.
"""
t = time.process_time()
p = len(train[0]) - 1
M = np.zeros((p,p))
Y = self.get_Y(train); Y = self.To_CAT(Y)
X = self.get_X(train)
for i in range(p):
X_i = [ele[i] for ele in X]
X_i = self.To_CAT(X_i)
for j in range(p):
X_j = [ele[j] for ele in X];
X_j = self.To_CAT(X_j)
M[i,j] = drv.information_mutual_conditional(X_i,X_j,Y)
self.mutual_inf_time = time.process_time() - t
return M
def Findparent(self,train):
M = self.get_mutual_inf(train)
t = time.process_time()
fill_diagonal(M,0)
p = int(M.shape[0])
V = range(p) #### . set of all nodes
st = self.starting_node
Vnew = [st] #### vertex that already found their parent. intitiate it with starting node. TAN randomly choose one
parent = {st:None} ## use a dict to show nodes' interdepedency
while set(Vnew) != set(V): ### when their are still nodes whose parents are unknown.
index_i = [] ### after for loop, has same length as Vnew, shows the closest node that not in Vnew with Vnew.
max_inf = [] ### corresponding distance
for i in range(len(Vnew)): ## can be paralelled
vnew = Vnew[i]
ListToSorted = [int(e) for e in M[:,vnew]]###
index = sorted(range(len(ListToSorted)),key = lambda k: ListToSorted[k],reverse = True)
index_i.append([ele for ele in index if ele not in Vnew][0])
max_inf.append(M[index_i[-1],vnew])
index1 = sorted(range(len(max_inf)),key = lambda k: max_inf[k],reverse = True)[0] ## relative position, Vnew[v1,v2] index_i[v4,v5] max_inf[s1,s2] index1 is the position in those 3 list
Vnew.append(index_i[index1]) ### add in that node
parent[index_i[index1]] = Vnew[index1] ## add direction, it has to be that the new added node is child, otherwise some nodes has 2 parents which is wrong.
self.prim_time = time.process_time() - t
return parent
def fit(self,train): ### this is based on trainning data !!!
parent = self.Findparent(train)
y = self.get_Y(train)
t = time.process_time()
""" start timing"""
countDict = Counter(y)
C = list(countDict.keys()) ### [class1 , class2, class3] in appearing order
p = len(train[0]) - 1
P_class = [(ele+self.alpha)/(sum(list(countDict.values())) + self.alpha*len(C) ) for ele in list(countDict.values())] ### prior for each class [p1,p2,p3], ### .values same order as .keys()
P_class = dict(zip(C, P_class)) ## {c1:p1,c2:p2,c3:p3} ## should in correct order, .keys .values.
Dict_C = {} ### {c1:[counter1, ....counter8], c2:[counter1, ....counter8], c3: [counter1, ....counter8]}
K = {}
root_i = self.starting_node ## 0 ,1 ,2 shows the position, thus int
x_i = [ele[root_i] for ele in train]
K[root_i] = len(Counter(x_i))
for c in C: ### c origianl class label '1' not 1
ListCounter_c = {}
x_i_c = [ele[root_i] for ele in train if ele[-1] == c]
ListCounter_c[root_i] = Counter(x_i_c) ### list_counter_c keys are 0,1,2,3... showing position hence int. Counter(x_i_c) keys are original values of x, not position. hence not necesarily int
for i in [e for e in range(0,p) if e != root_i]:
if c == C[0]:
x_i = [ele[i] for ele in train]
K[i] =len(Counter(x_i))
x_parent = [ele[parent[i]] for ele in train] ## will duplicate C times.
x_parent_counter = Counter(x_parent)
x_parent_counter_length = len(x_parent_counter)
x_parent_value = list(x_parent_counter.keys())
dict_i_c = {}
for j in range(x_parent_counter_length):
x_i_c_p_j = [ele[i] for ele in train if ele[-1] == c and ele[parent[i]] == x_parent_value[j] ]
dict_i_c[x_parent_value[j]] = Counter(x_i_c_p_j) ### x_parent_value[j] can make sure it is right key.
ListCounter_c[i] = dict_i_c
Dict_C[c] = ListCounter_c
CP_time = time.process_time() - t
self._is_fitted = True
self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict, self.parent,self.CP_time = Dict_C,p,P_class,K,C,countDict,parent,CP_time
self.training_time = np.array([self.mutual_inf_time,self.prim_time,self.CP_time])
return self
def predict(self,test):
"""Predict prob values for test set for each class.
:param test_set: Test set with dimension (p or p+1) x n,
where n is the number of examples,
and p is the number of features.
:return: Predicted target values for test set with dimension n * |C|,
where n is the number of examples. |C| is the # of classes.
it is np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i]
"""
if not self._is_fitted:
raise NotFittedError(self.__class__.__name__) ### after fitting, self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict, self.parent
Prob_C = []
root_i = self.starting_node
for ins in test:
P_class = self.P_class_prior.copy()
for c in self.C:
ListCounter_c = self.Dict_C[c]
P_class[c] = P_class[c] * (ListCounter_c[root_i][ins[root_i]]+self.alpha) / (self.countDict[c]+self.alpha*self.K[root_i])
for i in [e for e in range(0,self.p) if e != root_i]:
pValue = ins[self.parent[i]] ### replicate C times
try:### ListCounter_c[i][pValue],pavlue does show in training
Deno = sum(list(ListCounter_c[i][pValue].values() )) ## number of y =1, xparent = pvalue , ListCounter_c[i][pValue], pavlue does not show in training , keyerror
P_class[c] = P_class[c] * (ListCounter_c[i][pValue][ins[i]] + self.alpha) / (Deno + self.alpha*self.K[i]) ## ListCounter1[i][pValue][ins[i]] = number of y =1 xparent = pvalue, xi = xi
except: ##ListCounter_c[i][pValue],pavlue does not show in training
Deno = 0 ## ListCounter_c[i] this is when class == c, ith feature, >> {parent(i) == value1: Counter, parent(i) == value2: Counter }, counter shows the distribution of x_i when class ==c and parent == pvalue
P_class[c] = P_class[c] * (0 + self.alpha) / (Deno + self.alpha*self.K[i])
P_class = {key: P_class[key]/sum(list(P_class.values())) for key in P_class.keys()} ### normalize p_class
Prob_C.append(list(P_class.values())) ### check the class order is correct
Prob_C = array(Prob_C) ### for shap !!!!
return Prob_C
def predict_binary(self,test):
Prob_C = self.predict(test)
return(Prob_C[:,0])
tan_mt = TAN_MT()
print(tan_mt.parent)
tan_mt.fit(P450)
print(tan_mt.parent)
print(type(tan_mt.training_time))
tan_mt.countDict
#tan_mt.Dict_C['1']
tan_mt.predict(P450)
#tan_mt.training_time
```
##TAN
```
class TAN(Bayes_net):
def __init__(self,Matrix,alpha = 1,starting_node = 0):
self.starting_node = starting_node
self.alpha = alpha
self.name = "TAN"
self.M = Matrix
self.parent = self.Findparent() ## prim_time is not part from training,so I did not inlude it in training time
""" training part"""
self.Dict_C = []
self.p = 0
self.P_class_prior = []
self.K = []
self.C = 0
self.countDict = []
self._is_fitted = False
"""add training time """
self.training_time = 0
self.CP_time = 0
def Findparent(self):
M = self.M.copy()
fill_diagonal(M,0)
p = int(M.shape[0])
V = range(p) #### . set of all nodes
st = self.starting_node
Vnew = [st] #### vertex that already found their parent. intitiate it with starting node. TAN randomly choose one
parent = {st:None} ## use a dict to show nodes' interdepedency
while set(Vnew) != set(V): ### when their are still nodes whose parents are unknown.
index_i = [] ### after for loop, has same length as Vnew, shows the closest node that not in Vnew with Vnew.
max_inf = [] ### corresponding distance
for i in range(len(Vnew)): ## can be paralelled
vnew = Vnew[i]
ListToSorted = [int(e) for e in M[:,vnew]]###
index = sorted(range(len(ListToSorted)),key = lambda k: ListToSorted[k],reverse = True)
index_i.append([ele for ele in index if ele not in Vnew][0])
max_inf.append(M[index_i[-1],vnew])
index1 = sorted(range(len(max_inf)),key = lambda k: max_inf[k],reverse = True)[0] ## relative position, Vnew[v1,v2] index_i[v4,v5] max_inf[s1,s2] index1 is the position in those 3 list
Vnew.append(index_i[index1]) ### add in that node
parent[index_i[index1]] = Vnew[index1] ## add direction, it has to be that the new added node is child, otherwise some nodes has 2 parents which is wrong.
return parent
def fit(self,train): ### this is based on trainning data !!!
y = self.get_Y(train)
t = time.process_time()
""" start timing"""
countDict = Counter(y)
C = list(countDict.keys()) ### [class1 , class2, class3] in appearing order
p = len(train[0]) - 1
P_class = [(ele+self.alpha)/(sum(list(countDict.values())) + self.alpha*len(C) ) for ele in list(countDict.values())] ### prior for each class [p1,p2,p3], ### .values same order as .keys()
P_class = dict(zip(C, P_class)) ## {c1:p1,c2:p2,c3:p3} ## should in correct order, .keys .values.
Dict_C = {} ### {c1:[counter1, ....counter8], c2:[counter1, ....counter8], c3: [counter1, ....counter8]}
K = {}
root_i = self.starting_node ## 0 ,1 ,2 shows the position, thus int
x_i = [ele[root_i] for ele in train]
K[root_i] = len(Counter(x_i))
for c in C: ### c origianl class label '1' not 1
ListCounter_c = {}
x_i_c = [ele[root_i] for ele in train if ele[-1] == c]
ListCounter_c[root_i] = Counter(x_i_c) ### list_counter_c keys are 0,1,2,3... showing position hence int. Counter(x_i_c) keys are original values of x, not position. hence not necesarily int
for i in [e for e in range(0,p) if e != root_i]:
if c == C[0]:
x_i = [ele[i] for ele in train]
K[i] =len(Counter(x_i))
x_parent = [ele[self.parent[i]] for ele in train] ## will duplicate C times.
x_parent_counter = Counter(x_parent)
x_parent_counter_length = len(x_parent_counter)
x_parent_value = list(x_parent_counter.keys())
dict_i_c = {}
for j in range(x_parent_counter_length):
x_i_c_p_j = [ele[i] for ele in train if ele[-1] == c and ele[self.parent[i]] == x_parent_value[j] ]
dict_i_c[x_parent_value[j]] = Counter(x_i_c_p_j) ### x_parent_value[j] can make sure it is right key.
ListCounter_c[i] = dict_i_c
Dict_C[c] = ListCounter_c
CP_time = time.process_time() - t; CP_time = np.array(CP_time)
self._is_fitted = True
self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict,self.CP_time = Dict_C,p,P_class,K,C,countDict,CP_time
self.training_time = CP_time
return self
def predict(self,test):
"""Predict prob values for test set for each class.
:param test_set: Test set with dimension (p or p+1) x n,
where n is the number of examples,
and p is the number of features.
:return: Predicted target values for test set with dimension n * |C|,
where n is the number of examples. |C| is the # of classes.
it is np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i]
"""
if not self._is_fitted:
raise NotFittedError(self.__class__.__name__) ### after fitting, self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict, self.parent
Prob_C = []
root_i = self.starting_node
for ins in test:
P_class = self.P_class_prior.copy()
for c in self.C:
ListCounter_c = self.Dict_C[c]
P_class[c] = P_class[c] * (ListCounter_c[root_i][ins[root_i]]+self.alpha) / (self.countDict[c]+self.alpha*self.K[root_i])
for i in [e for e in range(0,self.p) if e != root_i]:
pValue = ins[self.parent[i]] ### replicate C times
try:### ListCounter_c[i][pValue],pavlue does show in training
Deno = sum(list(ListCounter_c[i][pValue].values() )) ## number of y =1, xparent = pvalue , ListCounter_c[i][pValue], pavlue does not show in training , keyerror
P_class[c] = P_class[c] * (ListCounter_c[i][pValue][ins[i]] + self.alpha) / (Deno + self.alpha*self.K[i]) ## ListCounter1[i][pValue][ins[i]] = number of y =1 xparent = pvalue, xi = xi
except: ##ListCounter_c[i][pValue],pavlue does not show in training
Deno = 0 ## ListCounter_c[i] this is when class == c, ith feature, >> {parent(i) == value1: Counter, parent(i) == value2: Counter }, counter shows the distribution of x_i when class ==c and parent == pvalue
P_class[c] = P_class[c] * (0 + self.alpha) / (Deno + self.alpha*self.K[i])
P_class = {key: P_class[key]/sum(list(P_class.values())) for key in P_class.keys()} ### normalize p_class
Prob_C.append(list(P_class.values())) ### check the class order is correct
Prob_C = array(Prob_C) ### for shap !!!!
return Prob_C
def predict_binary(self,test):
Prob_C = self.predict(test)
return(Prob_C[:,0])
M=matrix([[245, 9, 0, 3, 0, 2, 65, 8],
[9, 218, 17, 17, 49, 10, 50, 17],
[0, 17, 175, 16, 25, 13, 0, 46],
[3, 17, 16, 194, 19, 0, 0, 3],
[0, 49, 25, 19, 199, 10, 0, 3],
[2, 10, 13, 0, 10, 249, 50, 74],
[65, 50, 0, 0, 0, 50, 262, 11],
[8, 17, 46, 3, 3, 74, 11, 175]])
tan = TAN(M)
print(tan.parent)
tan.fit(P450)
print(tan.parent)
print(type(tan.training_time))
tan.predict(P450)## parent
```
# Ensemble :Bagging
## Bagging TAN_MT
```
class TAN_MT_bagging(Bayes_net):
def __init__(self, alpha = 1):
self.alpha = alpha
self.name = "TAN_MT_bagging"
"""base models, each having different starting node"""
self.models = []
self.p = 0
self.C = []
self._is_fitted = False
"""add training time """
self.training_time = 0
def fit(self,train):
"""initialize model = [] . and training time."""
p = len(train[0]) -1 ### number of features
self.p = p
"""fit base models"""
training_time = 0
models = []
for i in range(p):
model = TAN_MT(self.alpha, starting_node= i)
model.fit(train)
models.append(model)
training_time += model.training_time
self.models = models
self.training_time = training_time/p ### the fitting can be paralelled, hence define averge training time for this bagging
self._is_fitted = True
self.C = model.C
return self
def predict(self,test):
if not self._is_fitted:
raise NotFittedError(self.__class__.__name__) ### after fitting, self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict, self.parent
Prob_C = 0
for model in self.models:
Prob_C += model.predict(test) ### get np array here
Prob_C = Prob_C/self.p
return(Prob_C)
def predict_binary(self,test):
Prob_C = self.predict(test)
return(Prob_C[:,0])
tan_mt_bag = TAN_MT_bagging()
tan_mt_bag.fit(P450)
#tan_mt_bag.fit(P450)
len(tan_mt_bag.models)
print(tan_mt_bag.models[0].parent)
print(tan_mt_bag.models[2].parent)
print(tan_mt_bag.models[7].parent)
tan_mt_bag.predict(P450) ### get_cv change behaviour
#nb.predict(P450)
#tan_mt_bag.predict_class(P450)
#tan_mt_bag.models[0].Dict_C
```
## Bagging TAN
```
class TAN_bagging(Bayes_net):
def __init__(self,Matrix,alpha = 1):
self.alpha = alpha
self.name = "TAN_bagging"
self.M = Matrix
"""base models, each having different starting node"""
self.models = []
self.p = 0
self.C = []
self._is_fitted = False
"""add training time """
self.training_time = 0
def fit(self,train):
"""initialize models = [] . and training time."""
p = len(train[0]) -1 ### number of features
self.p = p
"""fit base models"""
training_time = 0
models = []
for i in range(p):
model = TAN(self.M, self.alpha, starting_node= i)
model.fit(train)
models.append(model)
training_time += model.training_time
self.models = models
self.training_time = training_time/p ### the fitting can be paralelled, hence define averge training time for this bagging
self._is_fitted = True
self.C = model.C
return self
def predict(self,test):
if not self._is_fitted:
raise NotFittedError(self.__class__.__name__) ### after fitting, self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict, self.parent
Prob_C = 0
for model in self.models:
Prob_C += model.predict(test) ### get np array here
Prob_C = Prob_C/self.p
return(Prob_C)
def predict_binary(self,test):
Prob_C = self.predict(test)
return(Prob_C[:,0])
tan_bag = TAN_bagging(M)
tan_bag.fit(P450)
print(tan_bag.models[0].parent)
print(tan_bag.models[2].parent)
print(tan_bag.models[7].parent)
tan_bag.predict(P450)
```
## TAN + TAN_MT
TAN very robust, different starting node does not make much difference. Hence randomly choose a starting node, then ensemble p TAN_MT with different starting nodes.
```
class TAN_TAN_MT_bagging(Bayes_net):
def __init__(self,Matrix,alpha = 1):
self.alpha = alpha
self.name = "TAN_TAN_MT_bagging"
self.M = Matrix
"""base models, each having different starting node"""
self.models = []
self.p = 0
self.C = []
self._is_fitted = False
"""add training time """
self.training_time = 0
def fit(self,train):
"""initialize models = [] . and training time."""
p = len(train[0]) -1 ### number of features
self.p = p
"""fit base models"""
training_time = 0
models = []
for i in range(p):
model = TAN_MT(self.alpha, starting_node= i)
model.fit(train)
models.append(model)
training_time += model.training_time
"""append TAN"""
model = TAN(self.M,self.alpha, starting_node= 0) ### starting node not importance for TAN, very robust
model.fit(train)
models.append(model)
self.models = models
self.training_time = training_time/p ### only consider average of p TAN_MT, ignore TAN since it takes less time than TAN_MT
self._is_fitted = True
self.C = model.C
return self
def predict(self,test):
if not self._is_fitted:
raise NotFittedError(self.__class__.__name__) ### after fitting, self.Dict_C,self.p,self.P_class_prior,self.K,self.C,self.countDict, self.parent
Prob_C = 0
for model in self.models:
Prob_C += model.predict(test) ### get np array here
Prob_C = Prob_C/(self.p+1)
return(Prob_C)
def predict_binary(self,test):
Prob_C = self.predict(test)
return(Prob_C[:,0])
M=matrix([[245, 9, 0, 3, 0, 2, 65, 8],
[9, 218, 17, 17, 49, 10, 50, 17],
[0, 17, 175, 16, 25, 13, 0, 46],
[3, 17, 16, 194, 19, 0, 0, 3],
[0, 49, 25, 19, 199, 10, 0, 3],
[2, 10, 13, 0, 10, 249, 50, 74],
[65, 50, 0, 0, 0, 50, 262, 11],
[8, 17, 46, 3, 3, 74, 11, 175]])
tan_mt_tan_bag = TAN_TAN_MT_bagging(M)
tan_mt_tan_bag.fit(P450)
#tan_mt_tan_bag.fit(P450)
len(tan_mt_tan_bag.models)
tan_mt_tan_bag.predict(P450)
```
# SHAP value
### P450
```
import shap
P450 = P450.astype(int)
lactamase = lactamase.astype(int)
#print(P450)
np.random.shuffle(P450)
np.random.shuffle(lactamase)
X = P450[:,0:8]
Y = P450[:,-1]
X2 = lactamase[:,0:8]
Y2 = lactamase[:,-1]
nb = NB()
nb.fit(lactamase)
explainer1 = shap.KernelExplainer(nb.predict_binary, X2[0:50,], link="logit")
shap_values1 = explainer1.shap_values(X2,nsamples = 20)
tan_mt = TAN_MT()
tan_mt.fit(lactamase)
explainer2 = shap.KernelExplainer(tan_mt.predict_binary, X2[0:50,], link="logit")
shap_values2 = explainer2.shap_values(X2,nsamples = 20)
tan = TAN(M2)
tan.fit(lactamase)
explainer3 = shap.KernelExplainer(tan.predict_binary, X2[0:50,], link="logit")
shap_values3 = explainer3.shap_values(X2,nsamples = 20)
shap.summary_plot(shap_values1, X2)
shap.summary_plot(shap_values1, X2, plot_type="bar")
shap.summary_plot(shap_values2, X2)
shap.summary_plot(shap_values2, X2, plot_type="bar")
shap.summary_plot(shap_values3, X2)
shap.summary_plot(shap_values3, X2, plot_type="bar")
```
# Cross validation function
```
def get_cv(model,data,n_splits=10,cv_type = "KFold",verbose = True):
""" Cross validation to get CLL and accuracy and training time.
:param data: data with dimension p+1 x n, to be cross validated.
where n is the number of examples,
and p is the number of features. Last column is target. data has to be a list [[ ], [ ], [ ].... ]
:return CLL, accuracy, training time for each folds.
"""
if cv_type == "StratifiedKFold":
cv = StratifiedKFold(n_splits= n_splits, shuffle=True, random_state=42)##The folds are made by preserving the percentage of samples for each class.
else:
cv = KFold(n_splits=n_splits, shuffle=True, random_state=42)
X = np.array(model.get_X(data))## if data is array, then get_X return array. if data is list, get_X return list
Y = np.array(model.get_Y(data)) ### Y array['1','0','']
binarizer = MultiLabelBinarizer() ## for using recall and precision score
binarizer.fit(Y)
Accuracy = []
Precision = []
Recall = []
CLL = []
training_time = []
for folder, (train_index, val_index) in enumerate(cv.split(X, Y)):#### X,Y are array, data is list
X_val = X[val_index]
y_val = Y[val_index]
model.fit(data[train_index]) ### whether data is list or array does not matter, only thing matters is label has to be same.
y_pred_prob= model.predict(X_val)
training_time.append(model.training_time)
y_pred_class = model.prob_to_class_general(y_pred_prob,model.C)
accuracy = accuracy_score(y_val, y_pred_class)
precision = precision_score(binarizer.transform(y_val),
binarizer.transform(y_pred_class),
average='macro')
recall = recall_score(binarizer.transform(y_val),
binarizer.transform(y_pred_class),
average='macro')
cll = model.Conditional_log_likelihood_general(y_val,y_pred_prob,model.C)
if verbose:
print("accuracy in %s fold is %s" % (folder+1,accuracy))
print("CLL in %s fold is %s" % (folder+1,cll))
print("precision in %s fold is %s" % (folder+1,precision))
print("recall in %s fold is %s" % (folder+1,recall))
print("training time in %s fold is %s" % (folder+1,training_time[-1]))
print(10*'__')
CLL.append(cll)
Accuracy.append(accuracy)
Recall.append(recall)
Precision.append(precision)
return Accuracy, CLL, training_time,Precision,Recall
```
## P450
#### 10 folds stratified
```
nb = NB()
Accuracy, CLL, training_time,Precision,Recall= get_cv(nb,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(mean(array(training_time)))
tan_mt = TAN_MT()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(sum(mean(array(training_time),axis=0)))
#print(mean(array(training_time), axis=0))
tan = TAN(M2)
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(mean(array(training_time)))
tan_mt_bag = TAN_MT_bagging()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt_bag,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(sum(mean(array(training_time),axis=0)))
tan_bag = TAN_bagging(M2)
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_bag,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(mean(array(training_time)))
tan_tan_mt_bag = TAN_TAN_MT_bagging(M2)
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_tan_mt_bag,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(sum(mean(array(training_time),axis=0)))
```
#### 10 folds K-folds
```
nb = NB()
Accuracy, CLL, training_time,Precision,Recall= get_cv(nb,lactamase)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(mean(array(training_time)))
tan_mt = TAN_MT()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt,lactamase)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(sum(mean(array(training_time),axis=0)))
tan = TAN(M2)
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan,lactamase)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(mean(array(training_time)))
tan_mt_bag = TAN_MT_bagging()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt_bag,lactamase)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(sum(mean(array(training_time),axis=0)))
tan_bag = TAN_bagging(M2)
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_bag,lactamase)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(mean(array(training_time)))
tan_tan_mt_bag = TAN_TAN_MT_bagging(M2)
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_tan_mt_bag,lactamase)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
print(sum(mean(array(training_time),axis=0)))
```
## lactamase
### 10 folds stratified
```
nb = NB()
Accuracy, CLL, _,Precision,Recall= get_cv(nb,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
tan_mt = TAN_MT()
Accuracy, CLL, _,Precision,Recall= get_cv(tan_mt,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
tan = TAN(M2)
Accuracy, CLL, _,Precision,Recall= get_cv(tan,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
tan_mt_bag = TAN_MT_bagging()
Accuracy, CLL, _,Precision,Recall= get_cv(tan_mt_bag,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
tan_bag = TAN_bagging(M2)
Accuracy, CLL, _,Precision,Recall= get_cv(tan_bag,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
tan_tan_mt_bag = TAN_TAN_MT_bagging(M2)
Accuracy, CLL, _,Precision,Recall= get_cv(tan_tan_mt_bag,lactamase,cv_type="StratifiedKFold")
print(mean(Accuracy))
print(mean(CLL))
print(mean(Precision))
print(mean(Recall))
```
### 10 folds K-folds
```
Accuracy, CLL, _ = get_cv(nb,lactamase)
print(mean(Accuracy))
print(mean(CLL))
Accuracy, CLL, _ = get_cv(tan_mt,lactamase)
print(mean(Accuracy))
print(mean(CLL))
Accuracy, CLL, _ = get_cv(tan,lactamase)
print(mean(Accuracy))
print(mean(CLL))
Accuracy, CLL, _ = get_cv(tan_mt_bag,lactamase)
print(mean(Accuracy))
print(mean(CLL))
Accuracy, CLL, _ = get_cv(tan_bag,lactamase)
print(mean(Accuracy))
print(mean(CLL))
Accuracy, CLL, _ = get_cv(tan_mt_tan_bag,lactamase)
print(mean(Accuracy))
print(mean(CLL))
```
## Lymph
### 10 folds K-folds
```
nb = NB()
Accuracy, CLL, training_time, Precision,Recall = get_cv(nb,lymph)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Recall))
print(mean(Precision))
print(mean(training_time))
tan_mt = TAN_MT()
Accuracy, CLL, training_time, Precision,Recall = get_cv(tan_mt,lymph)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Recall))
print(mean(Precision))
print(sum(mean(array(training_time),axis=0)))
tan_mt_bag = TAN_MT_bagging()
Accuracy, CLL, _, Precision,Recall = get_cv(tan_mt_bag,lymph)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Recall))
print(mean(Precision))
print(sum(mean(array(training_time),axis=0)))
```
## Vote
### 10 folds K fold
```
nb = NB()
Accuracy, CLL, training_time, Precision,Recall = get_cv(nb,vote)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Recall))
print(mean(Precision))
print(mean(training_time))
tan_mt = TAN_MT()
Accuracy, CLL, training_time, Precision,Recall = get_cv(tan_mt,vote)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Recall))
print(mean(Precision))
print(sum(mean(array(training_time),axis=0)))
tan_mt_bag = TAN_MT_bagging()
Accuracy, CLL, training_time, Precision,Recall = get_cv(tan_mt_bag,vote)
print(mean(Accuracy))
print(mean(CLL))
print(mean(Recall))
print(mean(Precision))
print(sum(mean(array(training_time),axis=0)))
```
# TAN training time: MT + Prim + CP
```
tan_mt = TAN_MT()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt,P450,cv_type="StratifiedKFold",verbose=False)
print(list(np.mean(array(training_time), axis = 0)))
print(sum(np.mean(array(training_time), axis = 0)))
tan_mt = TAN_MT()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt,lactamase,cv_type="StratifiedKFold",verbose=False)
print(list(np.mean(array(training_time), axis = 0)))
print(sum(np.mean(array(training_time), axis = 0)))
tan_mt = TAN_MT()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt,vote,cv_type="StratifiedKFold",verbose=False)
print(list(np.mean(array(training_time), axis = 0)))
print(sum(np.mean(array(training_time), axis = 0)))
tan_mt = TAN_MT()
Accuracy, CLL, training_time,Precision,Recall= get_cv(tan_mt,lymph,cv_type="StratifiedKFold",verbose=False)
print(list(np.mean(array(training_time), axis = 0)))
print(sum(np.mean(array(training_time), axis = 0)))
lymph.shape
```
| github_jupyter |

# Weather prediction using Recurrent Neural Network
### Dr. Tirthajyoti Sarkar, Fremont, CA ([LinkedIn](https://www.linkedin.com/in/tirthajyoti-sarkar-2127aa7/), [Github](https://tirthajyoti.github.io))
For more tutorial-style notebooks on deep learning, **[here is my Github repo](https://github.com/tirthajyoti/Deep-learning-with-Python)**.
For more tutorial-style notebooks on general machine learning, **[here is my Github repo](https://github.com/tirthajyoti/Machine-Learning-with-Python)**.
---
In this Notebook, we show how the long-term trend of key weather parameters (humidity, temperature, atmospheric pressure, etc.) can be predicted with decent accuracy using simple recurrent neural network (RNN). We don't even need to use any sophisticated memory module like GRU or LSTM for this. A simple one-layer RNN based model seems sufficient to be able to predict long-term trends from limited training data surprisingly well.
This is almost a proof of what Andrej Karpathy famously called **["The unusual effectiveness of recurrent neural networks"](http://karpathy.github.io/2015/05/21/rnn-effectiveness/)**
### The dataset
The dataset consists of historical weather parameters (temperature, pressure, relative humidity) for major North American and other cities around the world over an extended time period of 2012 to 2017. Hourly data points are recorded, giving, over 45000 data points, in total.
By attepmpting to do a time-series prediction, we are implicitly assuming that the past weather pattern is a good indicator of the future.
For this analysis, we focus only on the data for the city of San Francisco.
The full dataset can be found here: https://www.kaggle.com/selfishgene/historical-hourly-weather-data
## Data loading and pre-processing
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('mode.chained_assignment', None)
from keras.models import Sequential
from keras.layers import Dense, SimpleRNN
from keras.optimizers import RMSprop
from keras.callbacks import Callback
humidity = pd.read_csv("../Data/historical-hourly-weather-data/humidity.csv")
temp = pd.read_csv("../Data/historical-hourly-weather-data/temperature.csv")
pressure = pd.read_csv("../Data/historical-hourly-weather-data/pressure.csv")
humidity_SF = humidity[['datetime','San Francisco']]
temp_SF = temp[['datetime','San Francisco']]
pressure_SF = pressure[['datetime','San Francisco']]
humidity_SF.head(10)
humidity_SF.tail(10)
print(humidity_SF.shape)
print(temp_SF.shape)
print(pressure_SF.shape)
```
### There are many `NaN` values (blanck) in the dataset
```
print("How many NaN are there in the humidity dataset?",humidity_SF.isna().sum()['San Francisco'])
print("How many NaN are there in the temperature dataset?",temp_SF.isna().sum()['San Francisco'])
print("How many NaN are there in the pressure dataset?",pressure_SF.isna().sum()['San Francisco'])
```
### Choosing a point in the time-series for training data
We choose Tp=7000 here which means we will train the RNN with only first 7000 data points and then let it predict the long-term trend (for the next > 35000 data points or so). That is not a lot of training data compared to the number of test points, is it?
```
Tp = 7000
def plot_train_points(quantity='humidity',Tp=7000):
plt.figure(figsize=(15,4))
if quantity=='humidity':
plt.title("Humidity of first {} data points".format(Tp),fontsize=16)
plt.plot(humidity_SF['San Francisco'][:Tp],c='k',lw=1)
if quantity=='temperature':
plt.title("Temperature of first {} data points".format(Tp),fontsize=16)
plt.plot(temp_SF['San Francisco'][:Tp],c='k',lw=1)
if quantity=='pressure':
plt.title("Pressure of first {} data points".format(Tp),fontsize=16)
plt.plot(pressure_SF['San Francisco'][:Tp],c='k',lw=1)
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
plot_train_points('humidity')
plot_train_points('temperature')
plot_train_points('pressure')
```
### Interpolate data points to fill up `NaN` values
We observed some `NaN` values in the dataset. We could just eliminate these points. But assuming that the changes in the parameters are not extremely abrupt, we could try to fill them using simple linear interpolation.
```
humidity_SF.interpolate(inplace=True)
humidity_SF.dropna(inplace=True)
temp_SF.interpolate(inplace=True)
temp_SF.dropna(inplace=True)
pressure_SF.interpolate(inplace=True)
pressure_SF.dropna(inplace=True)
print(humidity_SF.shape)
print(temp_SF.shape)
print(pressure_SF.shape)
```
### Train and test splits on the `Tp=7000`
```
train = np.array(humidity_SF['San Francisco'][:Tp])
test = np.array(humidity_SF['San Francisco'][Tp:])
print("Train data length:", train.shape)
print("Test data length:", test.shape)
train=train.reshape(-1,1)
test=test.reshape(-1,1)
plt.figure(figsize=(15,4))
plt.title("Train and test data plotted together",fontsize=16)
plt.plot(np.arange(Tp),train,c='blue')
plt.plot(np.arange(Tp,45252),test,c='orange',alpha=0.7)
plt.legend(['Train','Test'])
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
```
### Choose the embedding or step size
RNN model requires a step value that contains n number of elements as an input sequence.
Suppose x = {1,2,3,4,5,6,7,8,9,10}
for step=1, x input and its y prediction become:
| x | y |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| ... | ... |
| 9 | 10 |
for step=3, x and y contain:
| x | y |
|---|---|
| 1,2,3 | 4 |
| 2,3,4 | 5 |
| 3,4,5 | 6 |
| ... | ... |
| 7,8,9 | 10 |
Here, we choose `step=8`. In more complex RNN and in particular for text processing, this is also called _embedding size_. The idea here is that **we are assuming that 8 hours of weather data can effectively predict the 9th hour data, and so on.**
```
step = 8
# add step elements into train and test
test = np.append(test,np.repeat(test[-1,],step))
train = np.append(train,np.repeat(train[-1,],step))
print("Train data length:", train.shape)
print("Test data length:", test.shape)
```
### Converting to a multi-dimensional array
Next, we'll convert test and train data into the matrix with step value as it has shown above example.
```
def convertToMatrix(data, step):
X, Y =[], []
for i in range(len(data)-step):
d=i+step
X.append(data[i:d,])
Y.append(data[d,])
return np.array(X), np.array(Y)
trainX,trainY =convertToMatrix(train,step)
testX,testY =convertToMatrix(test,step)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
print("Training data shape:", trainX.shape,', ',trainY.shape)
print("Test data shape:", testX.shape,', ',testY.shape)
```
## Modeling
### Keras model with `SimpleRNN` layer
We build a simple function to define the RNN model. It uses a single neuron for the output layer because we are predicting a real-valued number here. As activation, it uses the ReLU function. Following arguments are supported.
- neurons in the RNN layer
- embedding length (i.e. the step length we chose)
- nenurons in the densely connected layer
- learning rate
```
def build_simple_rnn(num_units=128, embedding=4,num_dense=32,lr=0.001):
"""
Builds and compiles a simple RNN model
Arguments:
num_units: Number of units of a the simple RNN layer
embedding: Embedding length
num_dense: Number of neurons in the dense layer followed by the RNN layer
lr: Learning rate (uses RMSprop optimizer)
Returns:
A compiled Keras model.
"""
model = Sequential()
model.add(SimpleRNN(units=num_units, input_shape=(1,embedding), activation="relu"))
model.add(Dense(num_dense, activation="relu"))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer=RMSprop(lr=lr),metrics=['mse'])
return model
model_humidity = build_simple_rnn(num_units=128,num_dense=32,embedding=8,lr=0.0005)
model_humidity.summary()
```
### A simple Keras `Callback` class to print progress of the training at regular epoch interval
Since the RNN training is usually long, we want to see regular updates about epochs finishing. However, we may not want to see this update every epoch as that may flood the output stream. Therefore, we write a simple custom `Callback` function to print the finishing update every 50th epoch. You can think of adding other bells and whistles to this function to print error and other metrics dynamically.
```
class MyCallback(Callback):
def on_epoch_end(self, epoch, logs=None):
if (epoch+1) % 50 == 0 and epoch>0:
print("Epoch number {} done".format(epoch+1))
```
### Batch size and number of epochs
```
batch_size=8
num_epochs = 1000
```
### Training the model
```
model_humidity.fit(trainX,trainY,
epochs=num_epochs,
batch_size=batch_size,
callbacks=[MyCallback()],verbose=0)
```
### Plot RMSE loss over epochs
Note that the `loss` metric available in the `history` attribute of the model is the MSE loss and you have to take a square-root to compute the RMSE loss.
```
plt.figure(figsize=(7,5))
plt.title("RMSE loss over epochs",fontsize=16)
plt.plot(np.sqrt(model_humidity.history.history['loss']),c='k',lw=2)
plt.grid(True)
plt.xlabel("Epochs",fontsize=14)
plt.ylabel("Root-mean-squared error",fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
```
## Result and analysis
### What did the model see while training?
We are emphasizing and showing again what exactly the model see during training. If you look above, the model fitting code is,
```
model_humidity.fit(trainX,trainY,
epochs=num_epochs,
batch_size=batch_size,
callbacks=[MyCallback()],verbose=0)
```
So, the model was fitted with `trainX` which is plotted below, and `trainY` which is just the 8 step shifted and shaped vector.
```
plt.figure(figsize=(15,4))
plt.title("This is what the model saw",fontsize=18)
plt.plot(trainX[:,0][:,0],c='blue')
plt.grid(True)
plt.show()
```
### Now predict the future points
Now, we can generate predictions for the future by passing `testX` to the trained model.
```
trainPredict = model_humidity.predict(trainX)
testPredict= model_humidity.predict(testX)
predicted=np.concatenate((trainPredict,testPredict),axis=0)
```
### See the magic!
When we plot the predicted vector, we see it matches closely the true values and that is amazing given how little training data was used and how far in the _future_ it had to predict. Time-series techniques like ARIMA, Exponential smoothing, cannot predict very far into the future and their confidence interval quickly grows beyond being useful.
**Note carefully how the model is able to predict sudden increase in humidity around time-points 12000. There was no indication of such shape or pattern of the data in the training set, yet, it is able to predict the general shape pretty well from the first 7000 data points!**
```
plt.figure(figsize=(10,4))
plt.title("This is what the model predicted",fontsize=18)
plt.plot(testPredict,c='orange')
plt.grid(True)
plt.show()
```
### Plotting the ground truth and model predictions together
We plot the ground truth and the model predictions together to show that it follows the general trends in the ground truth data pretty well. Considering less than 25% data was used for training, this is sort of amazing. The boundary between train and test splits is denoted by the vertical red line.
There are, of course, some obvious mistakes in the model predictions, such as humidity values going above 100 and some very low values. These can be pruned with post-processing or a better model can be built with propoer hyperparameter tuning.
```
index = humidity_SF.index.values
plt.figure(figsize=(15,5))
plt.title("Humidity: Ground truth and prediction together",fontsize=18)
plt.plot(index,humidity_SF['San Francisco'],c='blue')
plt.plot(index,predicted,c='orange',alpha=0.75)
plt.legend(['True data','Predicted'],fontsize=15)
plt.axvline(x=Tp, c="r")
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.ylim(-20,120)
plt.show()
```
## Modeling the temperature data
Since we have covered modeling the humidity data step-by-step in detail, we will show the modeling with other two parameters - temperature and pressure - quickly with similar code but not with detailed text.
```
train = np.array(temp_SF['San Francisco'][:Tp])
test = np.array(temp_SF['San Francisco'][Tp:])
train=train.reshape(-1,1)
test=test.reshape(-1,1)
step = 8
# add step elements into train and test
test = np.append(test,np.repeat(test[-1,],step))
train = np.append(train,np.repeat(train[-1,],step))
trainX,trainY =convertToMatrix(train,step)
testX,testY =convertToMatrix(test,step)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
model_temp = build_simple_rnn(num_units=128,num_dense=32,embedding=8,lr=0.0005)
batch_size=8
num_epochs = 2000
model_temp.fit(trainX,trainY,
epochs=num_epochs,
batch_size=batch_size,
callbacks=[MyCallback()],verbose=0)
plt.figure(figsize=(7,5))
plt.title("RMSE loss over epochs",fontsize=16)
plt.plot(np.sqrt(model_temp.history.history['loss']),c='k',lw=2)
plt.grid(True)
plt.xlabel("Epochs",fontsize=14)
plt.ylabel("Root-mean-squared error",fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
trainPredict = model_temp.predict(trainX)
testPredict= model_temp.predict(testX)
predicted=np.concatenate((trainPredict,testPredict),axis=0)
index = temp_SF.index.values
plt.figure(figsize=(15,5))
plt.title("Temperature: Ground truth and prediction together",fontsize=18)
plt.plot(index,temp_SF['San Francisco'],c='blue')
plt.plot(index,predicted,c='orange',alpha=0.75)
plt.legend(['True data','Predicted'],fontsize=15)
plt.axvline(x=Tp, c="r")
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
```
## Modeling the atmospheric pressure data
```
train = np.array(pressure_SF['San Francisco'][:Tp])
test = np.array(pressure_SF['San Francisco'][Tp:])
train=train.reshape(-1,1)
test=test.reshape(-1,1)
step = 8
# add step elements into train and test
test = np.append(test,np.repeat(test[-1,],step))
train = np.append(train,np.repeat(train[-1,],step))
trainX,trainY =convertToMatrix(train,step)
testX,testY =convertToMatrix(test,step)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
model_pressure = build_simple_rnn(num_units=128,num_dense=32,embedding=8,lr=0.0005)
batch_size=8
num_epochs = 500
model_pressure.fit(trainX,trainY,
epochs=num_epochs,
batch_size=batch_size,
callbacks=[MyCallback()],verbose=0)
plt.figure(figsize=(7,5))
plt.title("RMSE loss over epochs",fontsize=16)
plt.plot(np.sqrt(model_pressure.history.history['loss']),c='k',lw=2)
plt.grid(True)
plt.xlabel("Epochs",fontsize=14)
plt.ylabel("Root-mean-squared error",fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
trainPredict = model_pressure.predict(trainX)
testPredict= model_pressure.predict(testX)
predicted=np.concatenate((trainPredict,testPredict),axis=0)
index = pressure_SF.index.values
plt.figure(figsize=(15,5))
plt.title("Pressure: Ground truth and prediction together",fontsize=18)
plt.plot(index,pressure_SF['San Francisco'],c='blue')
plt.plot(index,predicted,c='orange',alpha=0.75)
plt.legend(['True data','Predicted'],fontsize=15)
plt.axvline(x=Tp, c="r")
plt.grid(True)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.show()
```
**Again note how the model is able to predict sudden increase in pressure around time-points 18000-22000. There was no indication of such shape or pattern of the data in the training set (the boundary is denoted by the vertical red line), yet, it is able to predict the general shape pretty well from the first 7000 data points!**
| github_jupyter |
```
#imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
```
### Robustness to Noise in Dataset and Class Imbalance tests
```
# We use logistic regression and one-layer MLP for the analysis
class LogisticRegression(nn.Module):
def __init__(self, n_input_features, n_classes):
super(LogisticRegression, self).__init__()
self.linear = nn.Linear(n_input_features, n_classes)
def forward(self, x):
outputs = self.linear(x)
return outputs
class MLP(torch.nn.Module):
def __init__(self, n_input_features, hidden_dim, output_dim):
super(MLP, self).__init__()
self.fc1 = torch.nn.Linear(n_input_features, hidden_dim)
self.fc2 = torch.nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
# Create a dataset with noise
from sklearn.datasets import make_classification
from sklearn.metrics import f1_score
sys.path.append('..')
from optimizers.optim import SGD_C, SGD, Adam_C, Adam, RMSprop, RMSprop_C
from optimizers.optimExperimental import SAGA
# Plot and verify the dataset
# change flip_y to flip the targets at random ~~ to noise
# weights = [0.8,0.2] (n_classes-1 length to induce class imbalance)
from itertools import combinations
from math import ceil
data3 = make_classification(n_samples=400, n_features=3, n_informative=2, n_redundant=0, n_repeated=0,
n_classes=2, n_clusters_per_class=2, weights=None, flip_y=0.01, class_sep=2.5,
hypercube=True, shift=0.4, scale=1.0, shuffle=True, random_state=42)
X, y = data3
df3 = pd.DataFrame(data3[0],columns=['x'+str(i) for i in range(1,4)])
df3['y'] = data3[1]
lst_var=list(combinations(df3.columns[:-1],2))
len_var = len(lst_var)
plt.figure(figsize=(18,10))
for i in range(1,len_var+1):
plt.subplot(2,ceil(len_var/2),i)
var1 = lst_var[i-1][0]
var2 = lst_var[i-1][1]
plt.scatter(df3[var1],df3[var2],s=200,c=df3['y'],edgecolor='k')
plt.xlabel(var1,fontsize=14)
plt.ylabel(var2,fontsize=14)
plt.grid(True)
del data3
# Train function
def trainModel(model_ = 'LR', optimizer_ = 'Adam', seed = '100', class_imbalance = None, noise = 0.01, class_sep = 1.0, loss_log = {}, Best = {}, exp = 'class_sep'):
# noise [0,1] : 0.01 is the default
# higher values of class sep allows the classification task to be way easier [0,3] in 0.5 increments :1.0 is the default.
# class_imbalance [0,1] fraction of samples in a class : None is the default
num_epochs = 10
learning_rate = 0.001
criterion = nn.CrossEntropyLoss()
data3 = make_classification(n_samples=500, n_features=10, n_informative=7, n_redundant=0, n_repeated=0,
n_classes=2, n_clusters_per_class=1, weights=class_imbalance, flip_y=noise, class_sep= 0.5,
hypercube=True, shift=0.4, scale=1.0, shuffle=True, random_state=1403)
#X, y = datasets.load_digits(return_X_y=True)#data3
X, y = data3
if model_ == 'LR':
model = LogisticRegression(X.shape[1], max(y)+1 )
elif model_ == 'MLP':
model = MLP(X.shape[1],(max(y)+1)//2, max(y)+1)
if optimizer_ == 'SGD':
optimizer = SGD(model.parameters(),lr = 1e-3)
elif optimizer_ == 'SGDM_C':
optimizer = SGD_C(model.parameters(),lr = 1e-3, decay = 0.7, momentum = 0.9, kappa = 1.0, topC = 10)
elif optimizer_ == 'SGDM':
optimizer = SGD(model.parameters(),lr = 1e-3, momentum = 0.9)
elif optimizer_ == 'Adam_C':
optimizer = Adam_C(model.parameters(), lr = 1e-3, decay = 0.7, topC = 5)
elif optimizer_ == 'Adam':
optimizer = Adam(model.parameters(), lr = 1e-3)
elif optimizer_ == 'SGD_C':
optimizer = SGD_C(model.parameters(),lr = 1e-3, decay=0.7, topC = 5)
elif optimizer_ == 'SGD_C_Only':
optimizer = SGD_C_Only(model.parameters(),lr = 1e-3, decay=0.7, topC = 5)
elif optimizer_ == 'RMSprop':
optimizer = RMSprop(model.parameters(), lr = 1e-3)
elif optimizer_ == 'RMSprop_C':
optimizer = RMSprop_C(model.parameters(), lr = 1e-3, decay=0.7, topC = 5)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)
# Preprocessing step
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
X_train = torch.from_numpy(X_train.astype(np.float32))
X_test = torch.from_numpy(X_test.astype(np.float32))
y_train = torch.from_numpy(y_train.astype(np.float32)).long()
y_test = torch.from_numpy(y_test.astype(np.float32)).long()
# 3) Training loop
for epoch in range(num_epochs):
# Forward pass and loss
for e in range(X_train.shape[0]):
y_pred = model(X_train[e]).view(1,-1)
loss = criterion(y_pred, y_train[e].view(-1))
# Backward pass and update
loss.backward()
optimizer.step()
# zero grad before new step
optimizer.zero_grad()
y_predicted = model(X_train).argmax(dim=1, keepdim=True) # get the index of the max log-probability
acc = y_predicted.eq(y_train.view_as(y_predicted)).sum() *100. / float(y_train.shape[0])
train_acc = f1_score(y_train, y_predicted.view_as(y_train), average='micro')#acc.item()
with torch.no_grad():
y_predicted = model(X_test).argmax(dim=1, keepdim=True) # get the index of the max log-probability
acc = y_predicted.eq(y_test.view_as(y_predicted)).sum() *100. / float(y_test.shape[0])
test_acc = f1_score(y_test, y_predicted.view_as(y_test), average='micro')#acc.item()
if seed in loss_log:
if epoch+1 in loss_log[seed]:
loss_log[seed][epoch+1].update({optimizer_: {'train_f1':"{:.2f}".format(train_acc), 'test_f1':"{:.2f}".format(test_acc), 'g_error':"{:.2f}".format(abs(test_acc-train_acc))}})
else:
loss_log[seed].update({epoch+1:{optimizer_: {'train_f1':"{:.2f}".format(train_acc), 'test_f1':"{:.2f}".format(test_acc), 'g_error':"{:.2f}".format(abs(test_acc-train_acc))}}})
else:
loss_log.update({seed:{epoch+1:{optimizer_: {'train_f1':"{:.2f}".format(train_acc), 'test_f1':"{:.2f}".format(test_acc), 'g_error':"{:.2f}".format(abs(test_acc-train_acc))}}}})
val = eval(exp)[0] if exp == 'class_imbalance' else eval(exp)
if seed in Best:
if optimizer_ in Best[seed]:
if val in Best[seed][optimizer_]:
if float(Best[seed][optimizer_][val]['f1']) < test_acc:
Best[seed][optimizer_][val]['f1'] = "{:.2f}".format(test_acc)
Best[seed][optimizer_][val]['epoch'] = epoch
else:
Best[seed][optimizer_].update({val:{'f1':"{:.2f}".format(test_acc), 'epoch': epoch}})
else:
Best[seed].update({optimizer_:{val:{'f1':"{:.2f}".format(test_acc), 'epoch': epoch}}})
else:
Best.update({seed:{optimizer_:{val:{'f1':"{:.2f}".format(test_acc), 'epoch': epoch}}}})
return loss_log, Best
import seaborn as sns
import csv
sns.set()
def plotLoss(model_ = 'LR', title = 'Variance to Noise', exp = 'class_sep', opts = ['Adam_C','Adam']):
if exp != None:
fieldnames=['Seed','Optimizer', exp, 'F1 score']
else:
fieldnames=['Seed','Optimizer', 'Epochs', 'F1 score']
target = open("temp.csv", "w")
writer = csv.DictWriter(target, fieldnames=fieldnames)
writer.writerow(dict(zip(fieldnames, fieldnames)))
loss_log = {} # Used to sanity check.
Best = {}
for s in [100, 101, 102, 103, 104]:
# noise [0,1] : 0.01 is the default
# higher values of class sep allows the classification task to be way easier [0,3] in 0.5 increments :1.0 is the default.
# class_imbalance [0,1] fraction of samples in a class : None is the default
torch.manual_seed(s)
for o in opts:
if exp == 'Units_of_Separation':
for it_ in range(1,37,5): # (1,102) for noise (1,32) for class imbalance, (1,102) for noise , (1,37) for class sep
_, Best = trainModel(model_ = model_, optimizer_ = o , seed = s, class_imbalance = None , noise = 0.01, class_sep = float("{:.2f}".format(0.1*(it_-1))), loss_log = loss_log, Best = Best, exp = 'class_sep')
if exp == 'Fraction_of_Minority_Class':
for it_ in range(11,52,10):
_, Best = trainModel(model_ = model_, optimizer_ = o , seed = s, class_imbalance = [float("{:.2f}".format(0.01*(it_-1)))] , noise = 0.01, class_sep = 1.0, loss_log = loss_log, Best = Best, exp = 'class_imbalance')
if exp == '$\mathcal{P}_{noise}$':
for it_ in range(1,102,10):
_, Best = trainModel(model_ = model_, optimizer_ = o , seed = s, class_imbalance = None , noise = float("{:.2f}".format(0.01*(it_-1))), class_sep = 0.1, loss_log = loss_log, Best = Best, exp = 'noise')
if exp == None:
loss_log, Best = trainModel(model_ = model_, optimizer_ = o , seed = s, class_imbalance = None , noise = 0.01, class_sep = 0.1, loss_log = loss_log, Best = Best, exp = 'noise')
if exp == None:
for seed, s_rest in loss_log.items():
for epoch, e_rest in s_rest.items():
for opt, o_rest in e_rest.items():
writer.writerow(dict([
('Seed', seed),
('Optimizer', opt),
('Epochs', epoch),
('F1 score',o_rest['test_f1'])])
)
target.close()
sns.lineplot(x = 'Epochs', y = 'F1 score', hue = 'Optimizer',data = pd.read_csv('temp.csv'))
plt.legend(loc=0., borderaxespad=0.)
plt.show()
else:
for seed, s_rest in Best.items():
for optimizer, o_rest in s_rest.items():
for val, v_rest in o_rest.items():
writer.writerow(dict([
('Seed', seed),
('Optimizer', '$\mathrm{'+optimizer+'}$'),
(exp, val),
('F1 score',v_rest['f1'])])
)
target.close()
df = pd.read_csv('temp.csv')
plt.figure(figsize=(3, 3))
rc = {'axes.labelsize': 12,
'axes.linewidth': 1.0,
'axes.titlesize': 12,
'font.size': 12,
'grid.linewidth': 0.8,
'legend.fontsize': 14,
'legend.title_fontsize': 14,
'lines.linewidth': 1.2000000000000002,
'lines.markersize': 4.800000000000001,
'patch.linewidth': 0.8,
'xtick.labelsize': 12,
'xtick.major.size': 5,
'xtick.major.width': 1.5,
'xtick.minor.size': 0,
'xtick.minor.width': 0.8,
'ytick.labelsize': 12,
'ytick.major.size': 5,
'ytick.major.width': 5,
'ytick.minor.size': 0,
'ytick.minor.width': 0.8}
sns.set(rc=rc)
sns.set_style('whitegrid')
known_optims = ['$\mathrm{SGD}$', '$\mathrm{SGD_C}$', '$\mathrm{SGDM}$', '$\mathrm{SGDM_C}$', '$\mathrm{RMSprop}$', '$\mathrm{RMSprop_C}$', '$\mathrm{Adam}$', '$\mathrm{Adam_C}$']
colors = sns.color_palette("colorblind", 2)
palette = {}
for optim in known_optims:
if "_C" in optim:
palette[optim] = colors[0]
else:
palette[optim] = colors[1]
dashes = {'$\mathrm{SGD_C}$': "", '$\mathrm{SGD}$': (3, 2), '$\mathrm{SGDM_C}$': "", '$\mathrm{SGDM}$': (3, 2), '$\mathrm{RMSprop_C}$': "", '$\mathrm{RMSprop}$': (3, 2), '$\mathrm{Adam_C}$': "", '$\mathrm{Adam}$': (3, 2)}
ax = sns.lineplot(x = exp, y = 'F1 score', hue = 'Optimizer', data = df, palette = palette, style = 'Optimizer', dashes= dashes)
plt.legend(loc=0, borderaxespad=0.)
plt.tight_layout()
if not os.path.exists('Figures'):
os.makedirs('Figures')
save_name = exp
if 'noise' in save_name:
save_name = "noise"
plt.savefig(os.path.join('Figures', save_name+'-'+'_'.join(opts)+'.png'))
plotLoss(title = 'Variance to Noise', exp = '$\mathcal{P}_{noise}$', opts = ['SGD_C','SGD'])
plotLoss(title = 'Variance to Noise', exp = '$\mathcal{P}_{noise}$', opts = ['RMSprop_C','RMSprop'])
plotLoss(title = 'Variance to Noise', exp = '$\mathcal{P}_{noise}$', opts = ['Adam_C','Adam'])
plotLoss(title = 'Variance to Noise', exp = '$\mathcal{P}_{noise}$', opts = ['SGDM_C','SGDM'])
```
### Comparing Optimizers on different loss surfaces
```
from matplotlib import cm
import sys
from optimizer_classes import Optimizer
import pylab as plt
import matplotlib
matplotlib.use
import matplotlib.animation as anim
import numpy as np
import torch
import matplotlib.pyplot as mpl
from matplotlib.colors import LogNorm
import seaborn as sns
from collections import OrderedDict
from matplotlib.animation import FuncAnimation
import os
%matplotlib inline
def set_figsize(figw, figh, fig=None):
if not fig:
fig = plt.gcf()
w, h = fig.get_size_inches()
l = fig.subplotpars.left
r = fig.subplotpars.right
t = fig.subplotpars.top
b = fig.subplotpars.bottom
hor = 1.-w/float(figw)*(r-l)
ver = 1.-h/float(figh)*(t-b)
fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)
def init_plot(compute_loss, func_name):
fig = plt.figure(figsize=(3, 3))
sns.set_style('whitegrid')
sns.set_context("paper")
ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])
plt.axis('off')
# visualize cost function as a contour plot
if func_name == 'Beale':
x_points = np.linspace(-2.0, 3.5, 50)
y_points = np.linspace(-3.0, 3.0, 50)
if func_name == 'SixHumpCamel':
x_points = np.linspace(-3.0, 3.5, 50)
y_points = np.linspace(-3.0, 3.0, 50)
if func_name == 'GoldsteinPrice':
x_points = np.linspace(-2.0, 1.0, 50)
y_points = np.linspace(-2.0, 1.0, 50)
w1_val_mesh, w2_val_mesh = np.meshgrid(x_points, y_points)
z = np.array([compute_loss([torch.tensor(xps), torch.tensor(yps)]).detach().numpy() for xps, yps in zip(w1_val_mesh, w2_val_mesh)])
ax.contour(w1_val_mesh, w2_val_mesh, z, levels=np.logspace(-.5, 5, 35), norm=LogNorm(), cmap=plt.cm.jet)
return fig, ax
def getGif(func_name = 'Beale', n_epochs = 1000, opts = ['SGD', 'SGD_C', 'Adam', 'Adam_C', 'RMSprop', 'RMSprop_C', 'SGDM'], no_anim = False):
optimizer_list = [Optimizer(name, func_name = func_name) for name in opts]#, "SGD"]]
fig, ax = init_plot(optimizer_list[0].loss_func.get_func_val, func_name = func_name)
for o in optimizer_list:
ln, = ax.plot([], [], o.color+'+', label = o.name)
ax.set_xlabel('x', size=22)
ax.set_ylabel('y', size=22)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
def update(i, optimizer_list):
for k in range(100):
for j in range(len(optimizer_list)):
model = optimizer_list[j]
loss = model.train_step()
ln = optimizer_list[j].plot(ax)
ax.set_title(func_name + '\n'+'After '+str(i)+' updates')
return ln
def main(func_name = 'Beale',n_epochs = 1000, opts = ['SGD_C', 'SGD', 'SGD_C_Only']):
optimizer_list = [Optimizer(name, func_name = func_name) for name in opts]#, "SGD"]]
fig, ax = init_plot(optimizer_list[0].loss_func.get_func_val, func_name = func_name)
M_list = {} # minimum loss observed thus far
for i in range(n_epochs):
d = {}
for j in range(len(optimizer_list)):
model = optimizer_list[j]
loss = model.train_step()
ln = optimizer_list[j].plot(ax)
d.update({opts[j]: float(loss)})
if i%100 == 0:
handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())
plt.savefig(os.path.join('Figures',func_name+'_'+str(i)+'.png'))
M_list.update({i:d})
plt.close()
return M_list
m = main(func_name = 'SixHumpCamel',n_epochs = 501, opts = ['SGD_C', 'Adam_C'])
import seaborn as sns
import csv
import pandas as pd
sns.set()
color = ['b','y','r']
opts = ['SGD_C', 'SGD', 'SGD_C_Only']
def CompareOpts(func_name = 'Beale', opts = ['SGD_C', 'SGD', 'Adam_C', 'RMSprop', 'RMSprop_C', 'SGDM']):
M_list = main(func_name, opts = opts )
fieldnames=['Epoch','Optimizer', 'Loss']
target = open("temp.csv", "w")
writer = csv.DictWriter(target, fieldnames=fieldnames)
writer.writerow(dict(zip(fieldnames, fieldnames)))
for i, rest in M_list.items():
for opt_name, loss in rest.items():
writer.writerow(dict([
('Epoch', i),
('Optimizer', opt_name),
('Loss',loss)])
)
target.close()
sns.lineplot(x = 'Epoch', y = 'Loss', hue = 'Optimizer',data = pd.read_csv('temp.csv'))
plt.title(func_name)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
for fn in ['Beale','SixHumpCamel','GoldsteinPrice']:
CompareOpts(func_name = fn, opts = ['SGD_C', 'SGD', 'Adam_C', 'RMSprop', 'RMSprop_C', 'SGDM'])
```
| github_jupyter |
# InstaBot Introduction - Part 1
Your friend has opened a new Food Blogging handle on Instagram and wants to get famous. He wants to follow a lot of people so that he can get noticed quickly but it is a tedious task so he asks you to help him. As you have just learned automation using Selenium, you decided to help him by creating an Instagram Bot.
You need to create different functions for each task.
```
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
import time
#opening the browser, change the path as per location of chromedriver in your system
driver = webdriver.Chrome(executable_path = 'C:/Users/admin/Downloads/Chromedriver/chromedriver.exe')
driver.maximize_window()
#opening instagram
driver.get('https://www.instagram.com/')
#update your username and password here
username = 'SAMPLE USERNAME'
password = 'SAMPLE PASSWORD'
#initializing wait object
wait = WebDriverWait(driver, 10)
```
### Problem 1 : Login to your Instagram
Login to your Instagram Handle
Submit with sample username and password
```
def LogIn(username, password):
try :
#locating username textbox and sending username
user_name = wait.until(EC.presence_of_element_located((By.NAME,'username')))
user_name.send_keys(username)
#locating password box and sending password
pwd = driver.find_element_by_name('password')
pwd.send_keys(password)
#locating login button
button = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="loginForm"]/div[1]/div[3]/button/div')))
button.submit()
#Save Your Login Info? : Not Now
pop = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="react-root"]/section/main/div/div/div/div/button')))
pop.click()
except TimeoutException :
print ("Something went wrong! Try Again")
#Login to your Instagram Handle
LogIn(username, password)
```
### Problem 2 : Type for “food” in search bar
Type for “food” in search bar and print all the names of the Instagram Handles that are displayed in list after typing “food”
Note : Make sure to avoid printing hashtags
```
def search(s):
try:
#locating serch bar and sending text
search_box = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'XTCLo')))
search_box.send_keys(s)
#waiting till all searched is located
wait.until(EC.presence_of_element_located((By.CLASS_NAME,'yCE8d')))
#extracting all serched handle
handle_names = driver.find_elements_by_class_name('yCE8d')
names = []
#extracting username
for i in handle_names :
if i.text[0] != '#' :
names.append(i.text.split('\n')[0])
time.sleep(5)
#clearing search bar
driver.find_element_by_class_name('coreSpriteSearchClear').click()
return names
except TimeoutException :
print('No Search Found!')
#extracting all the names of the Instagram Handles that are displayed in list after typing “food” usimg search('food')
name_list = search('food')
for i in name_list :
print(i)
```
### Problem 3 : Searching and Opening a profile
Searching and Opening a profile using
Open profile of “So Delhi”
```
def search_open_profile(s):
try:
#locatong search box bar and sending text
search_box = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'XTCLo')))
search_box.send_keys(s)
#locating serched result
res = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'yCE8d')))
res.click()
time.sleep(5)
#driver.back()
except TimeoutException :
print('No Search Found!')
search_open_profile('So Delhi')
```
### Problem 4 : Follow/Unfollow given handle
Follow/Unfollow given handle -
1.Open the Instagram Handle of “So Delhi”
2.Start following it. Print a message if you are already following
3.After following, unfollow the instagram handle. Print a message if you have already unfollowed.
```
def follow():
try :
#locating follow button
btn = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'_5f5mN')))
#checking for text
if btn.text == 'Follow' :
btn.click()
time.sleep(3)
else :
print('Already Following')
except TimeoutException :
print("Something Went Wrong!")
def unfollow():
try :
#locating follow button
btn = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'_5f5mN')))
#checking for text
if btn.text !='Follow' :
btn.click()
time.sleep(2)
#locating popup window (when you click on follow button)
pop_up = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'aOOlW')))
pop_up.click()
time.sleep(3)
else :
print('Already Unfollowed')
except TimeoutException :
print("Something Went Wrong!")
#for search and open 'dilsefoodie' instagram handle
search_open_profile('So Delhi')
#for following this instgram handle
follow()
#for unfollowing this instgram handle
unfollow()
```
### Problem 5 : Like/Unlike posts
Like/Unlike posts
1.Liking the top 30 posts of the ‘dilsefoodie'. Print message if you have already liked it.
2.Unliking the top 30 posts of the ‘dilsefoodie’. Print message if you have already unliked it.
```
def Like_Post():
try :
#scrolling for locating post
driver.execute_script('window.scrollTo(0, 6000);')
time.sleep(3)
driver.execute_script('window.scrollTo(0, -6000);')
time.sleep(3)
#locating post
posts = driver.find_elements_by_class_name('v1Nh3')
for i in range(30):
posts[i].click()
time.sleep(2)
#locating like/unke button
like = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'fr66n')))
st = BeautifulSoup(like.get_attribute('innerHTML'),"html.parser").svg['aria-label']
if st == 'Like' :
like.click()
time.sleep(2)
else :
print('You have already LIKED Post Number :', i+1)
time.sleep(2)
#locating cross button for closing post
driver.find_element_by_class_name('yiMZG').click()
time.sleep(2)
except TimeoutException :
print("Something Went Wrong!")
def Unlike_Post():
try :
#scrolling for locating post
driver.execute_script('window.scrollTo(0, 6000);')
time.sleep(3)
driver.execute_script('window.scrollTo(0, -6000);')
time.sleep(3)
#locating post
posts = driver.find_elements_by_class_name('v1Nh3')
for i in range(30):
posts[i].click()
time.sleep(2)
#locating like/unke button
like = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'fr66n')))
st = BeautifulSoup(like.get_attribute('innerHTML'),"html.parser").svg['aria-label']
if st == 'Unlike' :
like.click()
time.sleep(2)
else :
print('You have already UNLIKED Post Number', i+1)
time.sleep(2)
#locating cross button for closing post
driver.find_element_by_class_name('yiMZG').click()
time.sleep(2)
except TimeoutException :
print("Something Went Wrong!")
#for search and open 'dilsefoodie' instagram handle
search_open_profile('dilsefoodie')
#Liking the top 30 posts
Like_Post()
#Unliking the top 30 posts
Unlike_Post()
```
### Problem 6 : Extract list of followers
Extract list of followers
1.Extract the usernames of the first 500 followers of ‘foodtalkindia’ and ‘sodelhi’.
2.Now print all the followers of “foodtalkindia” that you are following but those who don’t follow you.
```
def Extract_Followers():
try :
# locating followers button and click on it
followers_btn = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME,'g47SY')))
followers_btn[1].click()
#locating followers list
frame = driver.find_element_by_class_name('isgrP')
#scrolling untill first 500 user is located
for i in range(50):
time.sleep(1)
driver.execute_script("arguments[0].scrollTop=arguments[0].scrollHeight",frame)
names = []
#extracting userdata
followers = driver.find_elements_by_class_name('d7ByH')
#extracting username
for i in followers[:500] :
names.append(i.text.split('\n')[0])
return names
except TimeoutException :
print("Something Went Wrong!")
```
##### First 500 followers of ‘foodtalkindia’
```
#for search and open 'foodtalkindia' instagram handle
search_open_profile('foodtalkindia')
# Extracting followers using Extract_Followers() function
users = Extract_Followers()
ind = 1
for username in users:
print(ind,username)
ind += 1
```
##### First 500 followers of ‘sodelhi’
```
#for search and open 'sodelhi' instagram handle
search_open_profile('sodelhi')
# Extracting followers using Extract_Followers() function
users = Extract_Followers()
ind = 1
for username in users:
print(ind,username)
ind += 1
```
##### Print all the followers of “foodtalkindia” that you are following but those who don’t follow you.
```
def Following():
try :
# locating following button and click on it
followers_btn = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME,'-nal3')))
followers_btn[2].click()
#locating followers list
frame = driver.find_element_by_class_name('isgrP')
#scrolling untill all users are located
for i in range(20):
time.sleep(1)
driver.execute_script("arguments[0].scrollTop=arguments[0].scrollHeight",frame)
names = []
#extracting userdata
following = driver.find_elements_by_class_name('d7ByH')
#extracting username
for i in following :
names.append(i.text.split('\n')[0])
return names
except TimeoutException :
print("Something Went Wrong!")
#for search and open 'foodtalkindia' instagram handle
search_open_profile('foodtalkindia')
# Extracting followers using Extract_Followers() function
followers_of_foodind = Extract_Followers()
#casting into set
followers_of_foodind = set(followers_of_foodind)
#now finding all user followed by me for that I'll use search_open_profile() after that using Following() I will extrat all user
#followed by me
search_open_profile(username)
followed_by_me = Following()
followed_by_me = set(followed_by_me)
#taking intersection so s1 contains only that user who followed by me
s1=(followers_of_foodind).intersection(followed_by_me)
if len(s1) == 0:
print('No such users found')
else:
#now extracting my followers
my_follower = Extract_Followers()
my_follower = set(my_follower)
#taking intersection with s1, so s2 contains only users that I am following them but they don’t follow me
s2=s1.intersection(my_follower)
if len(s2) == 0:
print('No such users found')
else:
for user in s2:
print(user)
```
### Problem 7 : Check the story of ‘coding.ninjas’
Check the story of ‘coding.ninjas’. Consider the following Scenarios and print error messages accordingly -
1.If You have already seen the story.
2.Or The user has no story.
3.Or View the story if not yet seen.
```
def Check_Story():
try:
#locating story or profile pic
story = wait.until(EC.presence_of_element_located((By.CLASS_NAME,"RR-M-.h5uC0")))
#check the Profile photo size to find out story is available or not
height = driver.find_element_by_class_name('CfWVH').get_attribute('height')
if int(height) == 166:
print("Already seen the story")
else:
print("Viewing the story")
driver.execute_script("arguments[0].click();",story)
except:
print("No story is available to view")
#searching 'coding.ninjas' using search_open_profile() function
search_open_profile('coding.ninjas')
#for checking story
Check_Story()
```
| github_jupyter |
# The Electromagnetic Spectrum
People having been staring at the night sky for millenia, and (we now know) interpreting an incoming stream of photons roughly in the 380 to 760 nm range. Modern astronomers have bigger and better instruments, so the usable frequency / wavelength / energy range covers more like 20 orders of magnitude.
This is a relatively simple notebook to help visualize where things fit on the spectrum.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, Layout, Output
import ipywidgets as w
from astropy import units as u
from astropy.constants import c, h
from wavelength_rgb import wavelength_RGB # local file
plt.rcParams.update({'font.size': 16})
```
We can characterize a photon by wavelength $\lambda$ (m), frequency $\nu$ (Hz) or energy (eV). In practice, conventions about which is most useful differ for work in the various regions of the spectrum, and it is useful to be able to interconvert.
Calculations are based on the formulae $\lambda \nu = c$ and $E = h \nu$, where $c$ is the speed of light and $h$ is the Planck constant.
Define a function to take a value in one unit and calculate the other two:
```
def calcPhotonVals(value, unit):
returnValues = {}
if unit == 'Hz':
returnValues['freq'] = value * u.Hz
returnValues['wlen'] = (c / returnValues['freq']).to(u.m)
returnValues['energy'] = (h * returnValues['freq']).to(u.eV)
elif unit == 'm':
returnValues['wlen'] = value * u.m
returnValues['freq'] = (c / returnValues['wlen']).to(u.Hz)
returnValues['energy'] = (h * returnValues['freq']).to(u.eV)
elif unit == 'eV':
returnValues['energy'] = value * u.eV
returnValues['freq'] = (returnValues['energy'] / h).to(u.Hz)
returnValues['wlen'] = (c / returnValues['freq']).to(u.m)
else:
raise Exception("unit {} is not in ['Hz', 'm', 'eV']".format(unit))
return returnValues
```
Labelling the various parts of the spectrum is imprecise and there are no hard boundaries, but let's define approximate ranges:
```
def makeSpectrumDict():
""" Data dictionary entries are tuples of wavelength in m
(lower, upper, position), where position is just a hint for
where to print the label along the graph's x-axis
return: data dictionary and a list of boundary wavelengths
"""
dd = {'gamma': (0, 1e-11, 1e-12),
'X-ray': (1e-11, 1e-8, 1e-10),
'UV': (1e-8, 3.8e-7, 1e-7),
'vis': (3.8e-7, 7.6e-7, 3.3e-7),
'NIR': (7.6e-7, 2.5e-6, 9e-7),
'MIR': (2.5e-6, 1e-5, 3e-6),
'FIR': (1e-5, 1e-3, 3e-5),
'microwave': (1e-3, 0.1, 2e-3),
'radio': (0.1, 1e8, 1) } # top end arbitrary
boundaries = [v[0] for v in dd.values()]
return (dd, boundaries)
```
Next define the plot routine. The x-axis is important (log scale), the y-axis is just dummy values to define vertical positions.
```
def plotPhotonData(value, unit):
valDict = calcPhotonVals(value, unit)
spectrumDict, boundaries = makeSpectrumDict()
# set up the full gamma-to-radio range
fig = plt.figure(figsize=(18,5))
ax = plt.axes()
plt.plot((1e-12,1e3), (0.1, 0.1))
for boundary in boundaries:
plt.plot(boundary, 0.1, 'o', color='lightgray', markersize = 10)
for name, limits in spectrumDict.items():
plt.text(limits[2], 0.15, name)
# show the current input value graphically
curr_wlen = valDict['wlen'].value
# for visible, try to represent the actual color (all others black)
# wavelength_RGB() needs wavelength in nm, returns 0-255 integers
wlen_color = [c/255.0 for c in wavelength_RGB(curr_wlen*1e9)]
# an arrow would be good, but I didn't get that working correctly yet
plt.plot((curr_wlen, curr_wlen), (0.3, 0.45), color=wlen_color)
# matplotlib housekeeping
plt.xscale("log", nonposx='clip')
plt.xticks([10**n for n in (-12, -9, -6, -3, 0, 3)])
plt.xlabel('wavelength $\lambda$ (m)')
plt.ylim(bottom=0, top=1)
ax.yaxis.set_visible(False)
plt.title('Electromagnetic Spectrum')
# add results for current input as text
plt.text(1e-11, 0.8, 'Wavelength: {:.3e}'.format(valDict['wlen']))
plt.text(1e-11, 0.7, 'Frequency: {:.3e}'.format(valDict['freq']))
plt.text(1e-11, 0.6, 'Energy: {:.3e}'.format(valDict['energy']))
```
Now define some simple interactive widgets. The Value box just needs to be something Python can interpret as a floating-point number. Given the range of useful numbers, either scientific notation (`1.2e-3`) or an expression (`1.2*10**(-3)`) may be useful. ___No___ units in here!
TODO: Handling related units (nm, MeV) would be a useful future enhancement.
```
interact(plotPhotonData, value = w.FloatText(description="Value:",
value=4.7e-7,
disabled=False),
unit = w.RadioButtons(description='units:',
options=['Hz', 'm', 'eV'],
value='m',
disabled=False
));
```
In the visible range (an extremely narrow part of the above plot!), how do the various wavelengths look to our eyes? That soulds like a simple question but it really isn't! There is no single, accurate answer (after a lot of scientific study, not least by computer graphics card manufacturers such as Nvidia).
One rough, approximate answer is implemented in `wavelength_RGB()`, in the external file `wavelength_rgb.py` (it's mostly a lot of long and boring if..elif..else statements).
```
from PIL import Image
from matplotlib.pyplot import imshow
lmin = 380 # nm
lmax = 780
lambdas = np.arange(lmin,lmax,0.5)
colors = [wavelength_RGB(l) for l in lambdas]
h = 80 # pixel height for plot
# Create a new black image
img = Image.new( 'RGB', (len(colors),h), "black")
pixels = img.load()
# set the colors
for i in range(len(colors)):
pixels[i,0] = colors[i]
for j in range(1,h):
pixels[i,j] = pixels[i,0]
fig, ax = plt.subplots(figsize=(30, 2))
ims = ax.imshow(np.asarray(img), extent = [lmin,lmax,0,h]);
ims.axes.get_yaxis().set_visible(False);
```
| github_jupyter |
# Evaluation Metrics
So far, we have mainly used the $R^2$ metric to evaluate our models. There are many other evaluation metrics that are provided by scikit-learn and are all found in the metrics module.
### Score vs Error/Loss metrics
Take a look at the [metrics module][1] in the API. You will see a number of different evaluation metrics for classification, clustering, and regression. Most of these end with either the word 'score' or 'error'/'loss'. Those functions that end in 'score' return a metric where **greater is better**. For example, the `r2_score` function returns $R^2$ in which a greater value corresponds with a better model.
Other metrics that end in 'error' or 'loss' return a metric where **lesser is better**. That should make sense intuitively, as minimizing error or loss is what we naturally desire for our models.
### Regression Metrics
Take a look at the regression metrics section of the scikit-learn API. These are all functions that accept the ground truth y values along with the predicted y values and return a metric. Let's see a few of these in action. We will read in the data, build a model with a few variables using one of the supervised regression models we've covered and then use one of the metric functions.
[1]: https://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics
```
import pandas as pd
import numpy as np
housing = pd.read_csv('../data/housing_sample.csv')
X = housing[['GrLivArea', 'GarageArea', 'FullBath']]
y = housing['SalePrice']
X.head()
```
Let's use a random forest to model the relationship between the input and sale price and complete our standard three-step process.
```
from sklearn.ensemble import RandomForestRegressor
rfr = RandomForestRegressor(n_estimators=50)
rfr.fit(X, y);
```
First, use the built-in `score` method which always returns the $R^2$ for every regression estimator.
```
rfr.score(X, y)
```
Let's verify that we can get the same result with the corresponding `r2_score` function from the metrics module. We need to get the predicted y-values and pass it along with the ground truth to the function.
```
from sklearn.metrics import r2_score
y_pred = rfr.predict(X)
r2_score(y, y_pred)
```
Let's use a different metric such as mean squared error (MSE).
```
from sklearn.metrics import mean_squared_error
mean_squared_error(y, y_pred)
```
### Easy to construct our own function
Most of these metrics are easy to compute on your own. The function below computes the same result from above.
```
def mse(y_true, y_pred):
error = y_true - y_pred
return np.mean(error ** 2)
mse(y, y_pred)
```
Taking the square root of the MSE computes the root mean squared error (RMSE) which provides insight as to what the average error is, though it is theoretically going to be slightly larger than the average error. Therer is no function in scikit-learn to compute the RMSE. We can use the numpy `sqrt` function to calculate it.
```
rmse = np.sqrt(mean_squared_error(y, y_pred))
rmse
```
The units of this metric are the same as the target variable, so we can think of our model as "averaging" about $18,000. The word averaging is in quotes because this isn't the actual average error, but will be somewhat near it. Use the `mean_absolute_error` to calculate the actual average error per observation.
```
from sklearn.metrics import mean_absolute_error
mean_absolute_error(y, y_pred)
```
We can compute this manually as well.
```
(y - y_pred).abs().mean()
```
## Different metrics with cross validation
It is possible to use these scores when doing cross validation with the `cross_val_score` function. It has a `scoring` parameter that you can pass a string to represent the type of score you want returned. Let's see an example with the default $R^2$ and then with other metrics. We use a linear regression here and continue to keep the data shuffled as before by setting the `random_state` parameter to 123.
```
from sklearn.model_selection import cross_val_score, KFold
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
kf = KFold(n_splits=5, shuffle=True, random_state=123)
```
By default, if no scoring method is given, `cross_val_score` uses the same metric as what the `score` method of the estimator uses.
```
cross_val_score(lr, X, y, cv=kf).round(2)
```
Use the string 'r2' to return $R^2$ values, which is the default and will be the same as above.
```
cross_val_score(lr, X, y, cv=kf, scoring='r2').round(2)
```
### Use the documentation to find the string names
The possible strings for each metric are found in the [user guide section of the official documentation][1]. The string 'neg_mean_squared_error' is used to return the negative of the mean squared error.
[1]: https://scikit-learn.org/stable/modules/model_evaluation.html#common-cases-predefined-values
```
cross_val_score(lr, X, y, cv=kf, scoring='neg_mean_squared_error')
```
### Why are negative values returned?
In an upcoming chapter, we cover model selection. scikit-learn selects models based on their scores and treats higher scores as better. But, with mean squared error, lower scores are better. In order to make this score work with model selection, scikit-learn negates this value when doing cross validation so that higher scores are indeed better. For instance, a score of -9 is better than -10.
### Mean squared log error
Another popular regression scoring metric is the mean squared log error. This works by computing the natural logarithm of both the predicted value and the ground truth, then calculates the error, squares it and takes the mean. Let's import the function from the metrics module and use it.
```
from sklearn.metrics import mean_squared_log_error
mean_squared_log_error(y, y_pred)
```
We can use the metric with `cross_val_score` by passing it the string 'neg_mean_squared_log_error'. Again, greater scores here are better.
```
cross_val_score(lr, X, y, cv=kf, scoring='neg_mean_squared_log_error')
```
### Finding the error metrics
You can find all the error metrics by navigating to the scikit-learn API or the user guide, but you can also find them directly in the `SCORERS` dictionary in the `metrics` module. The keys of the dictionary are the string names of the metrics. If you are on Python 3.7 or later, the dictionary will be ordered. There are eight (as of now) regression metrics and they are listed first. Let's take a look at their names.
```
from sklearn.metrics import SCORERS
list(SCORERS)[:8]
```
Let's use the maximum error as our cross validation metric, which simply returns the maximum error of all the predictions.
```
cross_val_score(lr, X, y, cv=kf, scoring='max_error').round(-3)
```
Most of the built-in scoring metrics are for classification or clustering and not for regression. Let's find the total number of scoring metrics.
```
len(SCORERS)
```
### Custom scoring functions
If you desire to use a scoring metric not built into scikit-learn, you can create your own custom scoring function. This is a bit more advanced and will be presented in a later chapter.
## Exercises
### Exercise 1
<span style="color:green; font-size:16px">Use some of the available regression scoring metrics available in the `metrics` module to compute scores on various models. Use these metrics again when doing cross validation.</span>
### Exercise 2
<span style="color:green; font-size:16px">Write a function that computes the mean squared log error. scikit-learn adds one first before taking the log.</span>
| github_jupyter |
```
import pandas as pd
import data_quality_config as dqconfig
from datetime import datetime
from goodtables import validate
df = pd.read_csv('debug_parsed_catalogue.csv', encoding='utf-8')
df.head(10)
import data_quality_utils as dqutils
# Other type analysis
def prepare_format(u):
t = dqutils.get_filename_from_url(u).split('.')[-1]
try:
t = t.split('?')[1]
if 'db_project' in t:
t = 'db_project querystring'
if 'id=' in t:
t = 'id querystring'
if 'lang=' in t:
t = 'lang querystring'
if 'cat=' in t:
t = 'cat querystring'
except:
t2 = 'meh'
return t
df_other = df[df['resource_type'] == 'dataset']
df_other = df_other[df_other['source_format'] == 'other']
df_other['format_from_url'] = df_other['url'].apply(lambda x: prepare_format(x))
df_other[['record_id', 'frequency', 'owner_org', 'maintainer_email', 'resource_id', 'source_format', 'resource_type', 'state', 'url', 'format_from_url']].to_csv('debug_other_source_format.csv', index=None, header=True, encoding=dqconfig.encoding_type)
list_of_ids = [
'a35cf382-690c-4221-a971-cf0fd189a46f'
]
df_query = df.loc[df['record_id'].isin(list_of_ids)]
df_query.head(1)
# Goodtables validation
# WARNING: This takes a while to run on large collections.
df_goodtables = df_query[df_query['resource_type'] == 'dataset']
for index, row in df_goodtables.iterrows():
gt_report = validate(row['url'])
try:
print('Valid:\t{0}\n'.format(gt_report['tables'][0]['valid']))
except:
print(gt_report)
#print(gt_report) # Print full report
#gt_report['tables'][0]['encoding']
# Check File Type
import data_quality_utils as dqutils
df_ftype = df_query
df_ftype['type_from_url'] = df_ftype['url'].apply(lambda x: dqutils.get_filename_from_url(x).split('.')[-1].lower())
df_ftype['type_from_source'] = df_ftype['source_format'].apply(lambda x: x.lower())
df_ftype['tail_url'] = df_ftype['url'].apply(lambda x: '...' + str(x)[-25:])
df_ftype[['resource_type', 'type_from_source', 'type_from_url', 'tail_url']]
# Check Update Frequency
df_frequency = df_query
df_frequency['max_days_allowed_since_update'] = df_frequency['frequency'].apply(lambda x: dqconfig.frequency_lookup[x])
df_frequency['updated_date'] = df_frequency['created'].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f'))
df_frequency['time_since_update_created'] = df_frequency['created'].apply(lambda x: dqconfig.snapshot_end_date - datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f'))
df_frequency['time_since_update_meta_mod'] = df_frequency['metadata_modified'].apply(lambda x: dqconfig.snapshot_end_date - datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f'))
#df_frequency['valid_update_frequency'] = df_frequency.apply(lambda x: dq.validate_update_frequency(x['frequency'], x['created'], x['metadata_modified']), axis=1)
df_query[['frequency', 'metadata_created', 'metadata_modified', 'date_published', 'date_modified', 'created', 'last_modified', 'max_days_allowed_since_update', 'time_since_update_created', 'time_since_update_meta_mod']] #, 'time_since_update_date_mod'
# Check Maintainer Email
df_email = df_query
#df_email[['owner_org', 'maintainer_email']].to_csv('debug_mismatched_email.csv', index=None, header=True, encoding=dqconfig.encoding_type)
df_email[['owner_org', 'maintainer_email']]
# Check Readability
df_read = df_query
df_query[[]]
```
| github_jupyter |
```
import torch, torchvision
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import tqdm
import os
```
This notebook accompanies the [week15] practice. Refer to the classwork for more details.
Your last and ultimate task is to implement and train __Convolutional Conditional VAE__. Simple VAE is available in week 15. For details about conditional VAE one can refer to [week 15 lecture](https://github.com/ml-mipt/ml-mipt/tree/advanced/week15_generative) or [this habr post (ru)](https://habr.com/ru/post/331664/)
If it seems too easy, you can use [Fashion-MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset instead of MNIST.
The code in general duplicates the one from the in-class practice.
Do not forget to __use GPU acceleration during training__.
```
%matplotlib inline
from torchsummary import summary
import seaborn as sns
sns.set()
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
```
__Currently you are using device:__
```
print(device)
# It's dangerous to walk alone. Take these ;)
class Rescale(object):
def __call__(self, image):
image = image - image.min()
image = image/image.max()
return image
class Flatten(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return torch.flatten(x, start_dim=1, end_dim=-1)
class RestoreShape(nn.Module):
def __init__(self, initial_shape):
super().__init__()
self.initial_shape = initial_shape
def forward(self, x):
return x.view([-1]+list(self.initial_shape))
```
__Data loading stuff is done for you ;)__
```
mnist_transformations = transforms.Compose([
transforms.ToTensor(),
Rescale()
])
BATCH_SIZE = 256
SHUFFLE_DATASET = True
NUM_DATALOADER_WORKERS = 1
data_root = './'
train_loader = torch.utils.data.DataLoader(
dataset=torchvision.datasets.MNIST(
root=data_root,
train=True,
transform=mnist_transformations,
download=True
),
batch_size=BATCH_SIZE,
shuffle=SHUFFLE_DATASET,
num_workers=NUM_DATALOADER_WORKERS
)
test_loader = torch.utils.data.DataLoader(
dataset=torchvision.datasets.MNIST(
root=data_root,
train=False,
transform=mnist_transformations
),
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=NUM_DATALOADER_WORKERS
)
```
__The code below is simple VAE. Your task is to make in convolutional (both encoder and decoder) and add class label information.__
```
class ConvolutionalCVAE(nn.Module):
def __init__(self, intermediate_dims, latent_dim, input_shape):
super().__init__()
self.register_buffer('_initial_mu', torch.zeros((latent_dim)))
self.register_buffer('_initial_sigma', torch.ones((latent_dim)))
self.latent_distribution = torch.distributions.normal.Normal(
loc=self._initial_mu,
scale=self._initial_sigma
)
input_dim = np.prod(input_shape)
self.encoder = nn.Sequential(*[
Flatten(),
nn.Linear(input_dim, intermediate_dims[0]),
nn.ReLU(),
nn.BatchNorm1d(intermediate_dims[0]),
nn.Dropout(0.3),
nn.Linear(intermediate_dims[0], intermediate_dims[1]),
nn.ReLU(),
nn.BatchNorm1d(intermediate_dims[1]),
nn.Dropout(0.3)
])
self.mu_repr = # <YOUR CODE HERE>
self.log_sigma_repr = # <YOUR CODE HERE>
self.decoder = nn.Sequential(*[
nn.Linear(latent_dim, intermediate_dims[1]),
nn.LeakyReLU(),
nn.BatchNorm1d(intermediate_dims[1]),
nn.Dropout(0.3),
nn.Linear(intermediate_dims[1], intermediate_dims[0]),
nn.LeakyReLU(),
nn.BatchNorm1d(intermediate_dims[0]),
nn.Dropout(0.3),
nn.Linear(intermediate_dims[0], input_dim),
nn.Sigmoid(),
RestoreShape(input_shape)
])
def _encode(self, x):
latent_repr = self.encoder(x)
mu_values = self.mu_repr(latent_repr)
log_sigma_values = self.log_sigma_repr(latent_repr)
return mu_values, log_sigma_values, latent_repr
def _reparametrize(self, sample, mu_values, log_sigma_values):
latent_sample = # <YOUR CODE HERE>
return latent_sample
def forward(self, x, raw_sample=None):
mu_values, log_sigma_values, latent_repr = self._encode(x)
if raw_sample is None:
raw_sample = torch.randn_like(mu_values)
latent_sample = self._reparametrize(raw_sample, mu_values, log_sigma_values)
reconstructed_repr = self.decoder(latent_sample)
return reconstructed_repr, latent_sample, mu_values, log_sigma_values
def plot_digits(*args):
args = [x.squeeze() for x in args]
n = min([x.shape[0] for x in args])
fig = plt.figure(figsize=(2*n, 2*len(args)))
for j in range(n):
for i in range(len(args)):
ax = plt.subplot(len(args), n, i*n + j + 1)
plt.imshow(args[i][j])
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# plt.show()
return fig
example_batch = next(iter(train_loader))
example_batch = [x.to(device) for x in example_batch]
example_x = example_batch[0][0]
model = VariationalAutoEncoder([256, 128], 2, example_x.shape).to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-4)
loss_func = torch.nn.modules.loss.BCELoss()
reconstructed_repr, latent_sample, mu_values, log_sigma_values = model(example_batch[0][:15].to(device))
summary(model, example_x.shape)
kl_loss = # <YOUR CODE HERE>
kl_loss
test_batch = next(iter(test_loader))
def get_test_predictions(model, test_loader):
model.eval()
reconstructed_repr_list, latent_samples_list, mu_values_list, log_sigma_values_list = [], [], [], []
for test_batch in tqdm.tqdm_notebook(test_loader, leave=False):
out = model(test_batch[0].to(device))
reconstructed_repr, latent_sample, mu_values, log_sigma_values = [x.detach().cpu() for x in out]
reconstructed_repr_list.append(reconstructed_repr)
latent_samples_list.append(latent_sample)
mu_values_list.append(mu_values)
log_sigma_values_list.append(log_sigma_values)
return [
torch.cat(_list, dim=0)
for _list in [reconstructed_repr_list, latent_samples_list, mu_values_list, log_sigma_values_list]
]
reconstructed_repr, latent_sample, mu_values, log_sigma_values = get_test_predictions(model, test_loader)
n = 15 # to generate image with 15x15 examples
digit_size = 28
latent_dim = 2
from scipy.stats import norm
grid_x = norm.ppf(np.linspace(0.05, 0.95, n))
grid_y = norm.ppf(np.linspace(0.05, 0.95, n))
def draw_manifold(model, show=True):
figure = np.zeros((digit_size * n, digit_size * n))
for i, yi in enumerate(grid_x):
for j, xi in enumerate(grid_y):
z_sample = np.zeros((1, latent_dim))
z_sample[:, :2] = np.array([[xi, yi]])
z_torch = torch.from_numpy(z_sample).type(torch.FloatTensor).to(device)
x_decoded = model.decoder(z_torch).detach().cpu().numpy()
digit = x_decoded[0].squeeze()
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size] = digit
if show:
plt.figure(figsize=(15, 15))
plt.imshow(figure, cmap='Greys_r')
# plt.grid(None)
ax = plt.gca()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
return figure
model.eval()
_img = draw_manifold(model, True)
def on_epoch_end(epoch):
# Saving manifold and z distribution to build plots and animation afterwards
figure = draw_manifold(model, show=False)
reconstructed_repr, latent_sample, mu_values, log_sigma_values = get_test_predictions(model, test_loader)
return figure, reconstructed_repr, latent_sample, mu_values, log_sigma_values
def train(num_epochs):
epochs, figs, latent_distrs = [], [], []
for epoch_num in tqdm.tnrange(num_epochs):
model.train()
loss_accumulator = 0.
bce_acc = 0.
kl_acc = 0.
for batch_x, batch_label in tqdm.tqdm_notebook(train_loader, leave=False):
batch_x = batch_x.to(device)
predictions, latent, mu_values, log_sigma_values = model(batch_x)
kl_loss = # <YOUR CODE HERE>
bce_loss = 28*28*loss_func(predictions, batch_x)
loss = (bce_loss + kl_loss)/2./28./28.
loss.backward()
opt.step()
opt.zero_grad()
loss_accumulator += loss.item()/(len(train_loader.dataset))
bce_acc += bce_loss.item()/(len(train_loader.dataset))
kl_acc += kl_loss.item()/(len(train_loader.dataset))
if epoch_num % 5 == 0:
print('Epoch num: {}\nTraining loss={:.4f}, KL divergence={:.4f}, BCE Loss={:.4f}'.format(
epoch_num,
loss_accumulator,
kl_acc,
bce_acc
))
model.eval()
figure, reconstructed_repr_test, latent_sample_test, mu_values_test, log_sigma_values_test = on_epoch_end(epoch_num)
epochs.append(epoch_num)
figs.append(figure)
latent_distrs.append((mu_values_test, log_sigma_values_test))
return epochs, figs, latent_distrs
epochs, figs, latent_distrs = train(50)
test_labels = []
for b in test_loader:
test_labels.append(b[1])
test_labels = torch.cat(test_labels, dim=0).numpy()
import os
os.makedirs('my_figs', exist_ok=True)
from matplotlib.animation import FuncAnimation
from matplotlib import cm
import matplotlib
def make_2d_figs_gif(figs, epochs, fname, fig):
norm = matplotlib.colors.Normalize(vmin=0, vmax=1, clip=False)
im = plt.imshow(np.zeros((28,28)), cmap='Greys_r', norm=norm)
plt.grid(None)
plt.title("Epoch: " + str(epochs[0]))
def update(i):
im.set_array(figs[i])
im.axes.set_title("Epoch: " + str(epochs[i]))
im.axes.get_xaxis().set_visible(False)
im.axes.get_yaxis().set_visible(False)
return im
anim = FuncAnimation(fig, update, frames=range(len(figs)), interval=100)
anim.save(fname, dpi=80, writer='imagemagick')
def make_2d_scatter_gif(zs, epochs, c, fname, fig):
im = plt.scatter(zs[0][:, 0], zs[0][:, 1], c=c, cmap=cm.coolwarm)
plt.colorbar()
plt.title("Epoch: " + str(epochs[0]))
def update(i):
fig.clear()
im = plt.scatter(zs[i][:, 0], zs[i][:, 1], c=c, cmap=cm.coolwarm)
im.axes.set_title("Epoch: " + str(epochs[i]))
im.axes.set_xlim(-5, 5)
im.axes.set_ylim(-5, 5)
return im
anim = FuncAnimation(fig, update, frames=range(len(zs)), interval=150)
anim.save(fname, dpi=80, writer='imagemagick')
make_2d_figs_gif(figs, epochs, "./my_figs/manifold2.gif", plt.figure(figsize=(10,10)))
make_2d_scatter_gif([x[0].numpy() for x in latent_distrs], epochs, test_labels, "./my_figs/z_distr2.gif", plt.figure(figsize=(10,10)))
```
You can find your brand gifs in `./my_figs/` directory ;)
Optionally you can also implement GAN for this task. Good luck!
| github_jupyter |
# <center><strong><font color="blue">Pendahuluan Text Mining & NLP</font></strong></center>
<center><img alt="" src="images/SocMed.png"/> </center>
## <center>(C) Taufik Sutanto - 2021<br><strong><font color="blue"> tau-data Indonesia ~ https://tau-data.id</font></strong></center>
## Outline :
* Pendahuluan NLP & Text Mining
* Text Preprocessing
* Document Representation
* Sentiment Analysis
* Topic Modelling
# Natural Language Processing (NLP) - Pemrosesan Bahasa Alami (PBA):
<p>
"<big><em>Sebuah cabang ilmu (AI/Computational Linguistik) yang mempelajari bagaimana bahasa (alami) manusia (terucap/tertulis) dapat dipahami dengan baik oleh komputer dan komputer dapat merespon dengan cara yang serupa ke manusia</em></big>".</p>
<p><img alt="" src="images/1_jarvis.jpg" style="height: 450px; width: 600px;" /></p>
<p><a href="https://www.turn-on.de/lifestyle/topliste/zehn-film-gadgets-die-wir-uns-im-wahren-leben-wuenschen-4413" target="_blank"><strong>[Image Source]: https://www.turn-on.de/primetime/topliste/zehn-film-gadgets-die-wir-uns-im-wahren-leben-wuenschen-4413</strong></a></p>
# Aplikasi Umum NLP:
* Speech Recognition dan Classification
* Machine Translation (Misal https://translate.google.com/ )
* Information Retrieval (IR) (misal www.google.com, bing, elasticsearch, etc.)
* Man-Machine Interface (misal Chatbot, Siri, cortana, atau Alexa)
* Sentiment Analysis
# Apakah Perbedaan antara NLP dan Text Mining (TM)?
<p>TM (terkadang disebut Text Analytics) adalah sebuah pemrosesan teks (biasanya dalam skala besar) untuk menghasilkan (generate) informasi atau insights. Untuk menghasilkan informasi TM menggunakan beberapa metode, termasuk NLP. TM mengolah teks secara eksplisit, sementara NLP mencoba mencari makna latent (tersembunyi) lewat aturan bahasa (e.g. grammar/idioms/Semantics).<br /></p><p>
<strong>Contoh aplikasi TM</strong> : Social Media Analytics (SMA), Insights from customer's review, Sentiment Analysis, Topic Modelling, dsb.</p>
<p><img alt="https://www.kdnuggets.com/2017/11/framework-approaching-textual-data-tasks.html" src="images/1_NLP_TextMining.jpg" style="height: 470px; width: 600px;" /></p>
<p>[image source: <a href="https://www.elsevier.com/books/practical-text-mining-and-statistical-analysis-for-non-structured-text-data-applications/miner/978-0-12-386979-1" target="_blank">Gary M.:"Practical Text Mining and Statistical Analysis for Non-structured Text Data Applications"</a>]</p>
<p><img alt="" src="images/1_Text_Analytics.jpg" style="height: 451px; width: 600px;" /></p>
<p>[Image Source: <a href="http://www.pearson.com.au/products/S-Z-Turban-Sharda/Business-Intelligence-and-Analytics-Systems-for-Decision-Support-Global-Edition/9781292009209?R=9781292009209" target="_blank">Efraim T. "Business Intelligence and Analytics: Systems for Decision Support, Global Edition (10e)</a>"]</p>
# Modul-modul yang digunakan di Lesson ini
## Silahkan install melalui terminal jika dijalankan secara lokal (PC/Laptop)
### Perhatian: Anda harus menjalankan setiap cell secara berurutan dari paling atas, tanpa terlewat satu cell-pun.
```
# Jalankan Cell ini "HANYA" jika anda menggunakan Google Colab
# Jika di jalankan di komputer local, silahkan lihat NLPTM-02 untuk instalasinya.
import warnings; warnings.simplefilter('ignore')
import logging; logging.captureWarnings(True)
import nltk
try:
import google.colab
IN_COLAB = True
!wget https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/taudataNlpTm.py
!mkdir data
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/slang.txt
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/stopwords_id.txt
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/stopwords_en.txt
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/kata_dasar.txt
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/wn-ind-def.tab
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/wn-msa-all.tab
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/ind_SA.csv
!wget -P data/ https://raw.githubusercontent.com/taudata-indonesia/eLearning/master/data/all_indo_man_tag_corpus_model.crf.tagger
!pip install spacy python-crfsuite unidecode textblob sastrawi pyLDAvis graphviz
!python -m spacy download xx_ent_wiki_sm
!python -m spacy download en_core_web_sm
nltk.download('popular')
except:
IN_COLAB = False
print("Running the code locally, please make sure all the python module versions agree with colab environment and all data/assets downloaded")
# Importing Modules untuk Notebook ini
import itertools, re, pickle, pyLDAvis, pyLDAvis.sklearn, spacy
import time, numpy as np, matplotlib.pyplot as plt, pandas as pd, seaborn as sns
from matplotlib.colors import ListedColormap
from tqdm import tqdm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from nltk.tag import CRFTagger
from gensim.models import Phrases
from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
from nltk.corpus import stopwords
from gensim.models import Word2Vec, FastText
from bs4 import BeautifulSoup as bs
import taudataNlpTm as tau
pyLDAvis.enable_notebook()
sns.set(style="ticks", color_codes=True)
random_state = 99
'Done'
```
## Tokenisasi
<p>Tokenisasi adalah pemisahan kata, simbol, frase, dan entitas penting lainnya (yang disebut sebagai token) dari sebuah teks untuk kemudian di analisa lebih lanjut. Token dalam NLP sering dimaknai dengan "sebuah kata", walau tokenisasi juga bisa dilakukan ke kalimat, paragraf, atau entitas penting lainnya (misal suatu pola string DNA di Bioinformatika).</p>
<p><strong>Mengapa perlu tokenisasi?</strong></p>
<ul>
<li>Langkah penting dalam preprocessing, menghindari kompleksitas mengolah langsung pada string asal.</li>
<li>Menghindari masalah (semantic) saat pemrosesan model-model natural language.</li>
<li>Suatu tahapan sistematis dalam merubah unstructured (text) data ke bentuk terstruktur yang lebih mudah di olah.</li>
</ul>
<p><img alt="" src="images\2_Pipeline_Tokenization.png" style="height:300px; width:768px" /><br />
[<a href="https://www.softwareadvice.com/resources/what-is-text-analytics/" target="_blank"><strong>Image Source</strong></a>]: https://www.softwareadvice.com/resources/what-is-text-analytics/</p>
<h2 id="Tokenisasi-dengan-modul-NLTK">Tokenisasi dengan modul NLTK</h2>
<p><strong>Kelebihan</strong>:</p>
<ol>
<li>Well established dengan dukungan bahasa yang beragam</li>
<li>Salah satu modul NLP dengan fungsi terlengkap, termasuk WordNet</li>
<li>Free dan mendapat banyak dukungan akademis.</li>
</ol>
<p><strong>Kekurangan</strong>:</p>
<ol>
<li>"Tidak support" bahasa Indonesia</li>
<li>Murni Python: relatif lebih lambat</li>
</ol>
<p><big><strong><a href="https://www.nltk.org/" target="_blank">https://www.nltk.org/</a></strong></big></p>
```
T = "Hello, Mr. Man. He smiled!! This, i.e. that, is it."
Word_Tokens = nltk.word_tokenize(T)
print(Word_Tokens) # tokenisasi kata
# Bandingkan jika menggunakan fungsi split di Python, apakah bedanya?
print(T.split())
# Apakah kesimpulan yang bisa kita tarik?
# Split() ==> Bukan Tokenisasi!.
Sentence_Tokens = nltk.sent_tokenize(T)
print(Sentence_Tokens) # Tokenisasi kalimat
# Perhatikan hasilnya, ada berapa kalimat yang di deteksi? setuju?
```
## Tokenisasi dengan <font color="blue"> TextBlob</font>
<strong>Kelebihan</strong>:</p>
<ol>
<li>Sederhana & mudah untuk digunakan/pelajari.</li>
<li>Textblob objects punya behaviour/properties yang sama dengan string di Python.</li>
<li>TextBlob dibangun dari kombinasi modul NLTK dan (Clips) Pattern</li>
</ol>
<p><strong>Kekurangan</strong>:</p>
<ol>
<li>Tidak secepat Spacy dan NLTK</li>
<li>Language Model terbatas: English, German, French</li>
</ol>
<p>*Blob : Binary large Object</p>
```
# Tokenizing di TextBlob
from textblob import TextBlob
T = "Hello, Mr. Man. He smiled!! This, i.e. that, is it."
print(TextBlob(T).words)
kalimatS = TextBlob(T).sentences
print([str(kalimat) for kalimat in kalimatS])
```
## Tokenisasi tidak hanya language dependent, tapi juga environment dependent
<p>Tokenization sebenarnya tidak sesederhana memisahkan berdasarkan spasi dan removing symbol. Sebagai contoh dalam bahasa Jepang/Cina/Arab suatu kata bisa terdiri dari beberapa karakter.</p>
<p><img alt="" src="images/2_Tokenization_Complexity.jpg" style="height:500px; width:686px" /><br />
[<a href="http://aclweb.org/anthology/Y/Y11/Y11-1038.pdf" target="_blank"><strong>Image Source</strong></a>]</p>
## Tokenisasi (NLP) Bahasa Indonesia:
<p>NLTK belum support Bahasa Indonesia, bahkan module NLP Python yang support bahasa Indonesia secara umum masih sangat langka. Beberapa <u><strong>resources </strong></u>yang dapat digunakan:</p>
<ol>
<li><strong><a href="https://github.com/kirralabs/indonesian-NLP-resources" target="_blank">KirraLabs</a></strong>: Mix of NLP-TextMining resources</li>
<li><strong><a href="https://pypi.python.org/pypi/Sastrawi/1.0.1" target="_blank">Sastrawi 1.0.1</a>:</strong> untuk "stemming" & <strong><a href="https://devtrik.com/python/stopword-removal-bahasa-indonesia-python-sastrawi/" target="_blank">stopwords </a></strong>bahasa Indonesia.</li>
<li><strong><a href="http://stop-words-list-bahasa-indonesia.blogspot.co.id/2012/09/daftar-kata-dasar-bahasa-indonesia.html" target="_blank">Daftar Kata Dasar Indonesia</a></strong>: Bisa di load sebagai dictionary di Python</li>
<li><strong><a href="https://id.wiktionary.org/wiki/Wiktionary:ProyekWiki_bahasa_Indonesia/Daftar_kata" target="_blank">Wiktionary</a></strong>: ProyekWiki bahasa Indonesia [termasuk Lexicon]</li>
<li><a href="http://wn-msa.sourceforge.net/" target="_blank"><strong>WordNet Bahasa Indonesia</strong></a>: Bisa di load sebagai dictionary (atau NLTK<em>*</em>) di Python.</li>
<li><strong><a href="http://kakakpintar.com/daftar-kata-baku-dan-tidak-baku-a-z-dalam-bahasa-indonesia/" target="_blank">Daftar Kata Baku-Tidak Baku</a></strong>: Bisa di load sebagai dictionary di Python.</li>
<li><strong><a href="https://spacy.io/" target="_blank">Spacy</a></strong>: Cepat/efisien, MIT License, tapi language model Indonesia masih terbatas.</li>
<li><a href="http://ufal.mff.cuni.cz/udpipe" target="_blank"><strong>UdPipe</strong></a>: Online request & restricted license (support berbagai bahasa - pemrograman).</li>
</ol>
```
# Contoh Tokenisasi dalam bahasa Indonesia dengan Spacy
from spacy.lang.id import Indonesian
nlp_id = Indonesian() # Language Model
teks = 'Sore itu, Hamzah melihat kupu-kupu di taman. Ibu membeli oleh-oleh di pasar'
tokenS_id = nlp_id(teks)
print([t for t in tokenS_id])
# Jika menggunakan Language model English:
from spacy.lang.en import English
nlp_en = English()
tokenS_en = nlp_en(teks)
print([token.text for token in tokenS_en])
```
<p><u><big><strong>Word Case</strong></big></u><big> (Huruf BESAR/kecil):</big></p>
<ul>
<li>Untuk menganalisa makna (<em>semantic</em>) dari suatu (frase) kata dan mencari informasi dalam proses textmining, seringnya (*) kita tidak membutuhkan informasi huruf besar/kecil dari kata tersebut.</li>
<li><em>Text case normaliation</em> dapat dilakukan pada string secara efisien tanpa melalui tokenisasi (mengapa?).</li>
<li>Namun, bergantung pada analisa teks yang akan digunakan pengguna harus berhati-hati dengan urutan proses (pipelining) dalam preprocessing. Mengapa dan apa contohnya?</li>
</ul>
<p>(*) Coba temukan minimal 2 pengecualian dimana huruf kapital/kecil (case) mempengaruhi makna/pemrosesan teks.</p>
```
# Ignore case (huruf besar/kecil)
T = "Hi there!, I am a student. Nice to meet you :)"
print(T.lower())
print(T.upper())
# Perintah ini sangat efisien karena hanya merubah satu bit di setiap (awal) bytes dari setiap karakter
# Sehingga tetap efisien jika ingin dilakukan sebelum tokenisasi
```
## Morphological-Linguistic Normalization: Stemming & Lemmatization
(Canonical Representation)
<p><img alt="" src="images/2_yoda.jpg" style="height:400px; width:400px" /></p>
## <font color="blue">Stemming dan Lemma</font>
<ol>
<li>
<p><strong>Stemmer</strong> akan menghasilkan sebuah bentuk kata yang disepakati oleh suatu sistem tanpa mengindahkan konteks kalimat. Syaratnya beberapa kata dengan makna serupa hanya perlu dipetakan secara konsisten ke sebuah kata baku. Banyak digunakan di IR & komputasinya relatif sedikit. Biasanya dilakukan dengan menghilangkan imbuhan (suffix/prefix).</p>
</li>
<li>
<p><strong>lemmatisation</strong> akan menghasilkan kata baku (dictionary word) dan bergantung konteks.</p>
</li>
<li>
<p>Lemma & stemming bisa jadi sama-sama menghasilkan suatu akar kata (root word). Misal : <em>Melompat </em>==> <em>lompat</em></p>
</li>
</ol>
<p><strong>Mengapa melakukan Stemming & Lemmatisasi</strong>?</p>
<ol>
<li>Sering digunakan di IR (Information Retrieval) agar ketika seseorang mencari kata tertentu, maka seluruh kata yang terkait juga diikutsertakan.<br />
Misal: <em>organize</em>, <em>organizes</em>, and <em>organizing </em> dan <em>democracy</em>, <em>democratic</em>, and <em>democratization</em>.</li>
<li>Di Text Mining Stemming dan Lemmatisasi akan mengurangi dimensi (mengurangi variasi morphologi), yang terkadang akan meningkatkan akurasi.</li>
<li>Tapi di IR efeknya malah berkebalikan: <strong><font color="blue">meningkatkan recall, tapi menurunkan akurasi </font></strong>[<a href="https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html" target="_blank"><strong>Link</strong></a>]. Contoh: kata <em>operate, operating, operates, operation, operative, operatives, dan operational</em> jika di stem menjadi <em>operate</em>, maka ketika seseorang mencari "<em>operating system</em>", maka entry seperti <em>operational and research</em> dan <em>operative and dentistry</em> akan muncul sebagai entry dengan relevansi yang cukup tinggi.</li>
</ol>
```
# Contoh Lemmatizer di NLTK
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
T = "apples and oranges are similar. boots and hippos aren't, don't you think?"
print('Sentence: ', T)
print('Lemmatize: ',' '.join(lemmatizer.lemmatize(t) for t in T.split()))
# Lemma case sensitive. Dengan kata lain string harus diubah ke dalam bentuk huruf kecil (lower case)
# Lemmatizer menggunakan informasi pos. "pos" (part-of-speech) akan dibahas di segmen berikutnya
print(lemmatizer.lemmatize("better", pos="a")) # adjective
print(lemmatizer.lemmatize("better", pos="v")) # verb
# TextBlob Stemming & Lemmatizer
from textblob import Word
# Stemming
print(Word('running').stem()) # menggunakan NLTK Porter stemmer
# Lemmatizer
print(Word('went').lemmatize('v'))
# default Noun, plural akan menjadi singular dari akar katanya
# Juga case sensitive
# Spacy Lemmatizer English
import spacy
nlp = spacy.load("en_core_web_sm")
E = "I am sure apples and oranges are similar"
doc = nlp(E)
for token in doc:
print(token.text, token.lemma_)
# Perhatikan huruf besar/kecil
```
### Spacy "tidak" (bukan belum) support Stemming:
<p><strong><img alt="" src="images/2_Spacy_Pipelines.jpg" style="height:400px; width:487px" /></strong></p>
<p>[<a href="https://spacy.io/usage/spacy-101#lightning-tour" target="_blank"><strong>Image Source</strong></a>]</p>
```
# Lemmatizer dengan Sastrawi
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
stemmer = StemmerFactory().create_stemmer()
I = "perayaan itu Berbarengan dengan saat kita bepergian ke Makassar"
print(stemmer.stem(I))
print(stemmer.stem("Perayaan Bepergian Menyuarakan"))
# Ada beberapa hal yang berbeda antara Sastrawi dan modul-modul diatas.
# Apa sajakah?
```
## Text Level Normalization: StopWords
<p><u>Di Text Mining</u> kata-kata yang <strong>sering muncul </strong>(dan jarang sekali muncul) memiliki sedikit sekali informasi (signifikansi) terhadap model (machine learning) yang digunakan. Hal ini di karenakan kata-kata tersebut muncul di semua kategori (di permasalahan klasifikasi) atau di semua cluster (di permasalahan pengelompokan/clustering). Kata-kata yang sering muncul ini biasa disebut "StopWords". Stopwords berbeda-beda bergantung dari Bahasa dan Environment (aplikasi)-nya.<br />
<strong>Contoh</strong>:<br />
<ul>
<li>Stopwords bahasa Inggris: am, is, are, do, the, of, etc.</li>
<li>Stopwords bahasa Indonesia: adalah, dengan, yang, di, ke, dsb</li>
<li>Stopwords twitter: RT, ...<br />
<img alt="" src="images/2_StopWords.png" style="height:250px; width:419px" /></li>
</ul>
```
# Loading Stopwords: Ada beberapa cara
from nltk.corpus import stopwords
from Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory
factory = StopWordRemoverFactory()
NLTK_StopWords = stopwords.words('english')
Sastrawi_StopWords_id = factory.get_stop_words()
df=open('data/stopwords_en.txt',"r",encoding="utf-8", errors='replace')
en_stop = df.readlines()
df.close()
en_stop = [t.strip().lower() for t in en_stop]
df=open('data/stopwords_id.txt',"r",encoding="utf-8", errors='replace')
id_stop = df.readlines()
df.close()
id_stop = [t.strip().lower() for t in id_stop]
N = 10
print(NLTK_StopWords[:N])
print(Sastrawi_StopWords_id[:N])
print(en_stop[:N])
print(id_stop[:N])
print(len(Sastrawi_StopWords_id), len(id_stop), len(NLTK_StopWords), len(en_stop))
```
### Diskusi: Apakah sebaiknya kita menggunakan daftar stopwords bawaan modul atau custom milik kita sendiri?
```
# Tipe variabel memiliki aplikasi optimal yang berbeda-beda, misal
L = list(range(10**7))
S = set(range(10**7)) # selain unik dan tidak memiliki keterurutan, set memiliki fungsi lain.
%%timeit
99000000 in L
%%timeit
99000000 in S
# Tips: selalu rubah list stopwords ke bentuk set, karena di Python jauh lebih cepat untuk cek existence di set ketimbang list
NLTK_StopWords = set(NLTK_StopWords)
Sastrawi_StopWords_id = set(Sastrawi_StopWords_id)
en_stop = set(en_stop)
id_stop = set(id_stop)
'bakwan' in id_stop
# Cara menggunakan stopwords
from textblob import TextBlob
T = "I am doing NLP at tau-data Indonesia,... \
adapun saya anu sedang belajar NLP di tau-data Indonesia"
T = T.lower()
id_stop.add('anu')
Tokens = TextBlob(T).words # Tokenisasi
T2 = [t for t in Tokens if t not in id_stop] # Sastrawi_StopWords_id Personal_StopWords_en Personal_StopWords_id
T2 = [t for t in T2 if t not in en_stop] # Sastrawi_StopWords_id Personal_StopWords_en Personal_StopWords_id
print(' '.join(T2))
# Catatan: Selalu lakukan Stopword filtering setelah tokenisasi (dan normalisasi).
```
<p><img alt="" src="images/2_Tokenization_Stopwords.png" style="height:400px; width:765px" /></p>
<p>[<a href="http://chdoig.github.io/acm-sigkdd-topic-modeling/#/6/2" target="_blank">image source: http://chdoig.github.io/acm-sigkdd-topic-modeling/#/6/2</a>]</p>
## Menangani Slang atau Singkatan di Data Teks
```
# Sebuah contoh sederhana
T = 'jangan ragu gan, langsung saja di order pajangannya.'
# Misal kita hendak mengganti setiap singkatan (slang) dengan bentuk penuhnya.
# Dalam hal ini kita hendak mengganti 'gan' dengan 'juragan'
H = T.replace('gan','juragan')
print(H)
# Kita tidak bisa melakukan ini
D = {'yg':'yang', 'gan':'juragan'}
D['yg']
# dengan tokenisasi
slangs = {'gan':'juragan', 'yg':'yang', 'dgn':'dengan'} #dictionary sederhana berisi daftar singkatan dan kepanjangannya
T = 'jangan ragu gan, langsung saja di order pajangan yg diatas.'
T = TextBlob(T).words
T
for i,t in enumerate(T):
if t in slangs.keys():
T[i] = slangs[t]
print(' '.join(T))
# Loading Slang dan Singkatan dari File
# Contoh memuat word fix melalui import file.
df=open('data/slang.txt',"r",encoding="utf-8", errors='replace')
slangS = df.readlines(); df.close()
slangS[:5]
slangS = [t.strip('\n').strip() for t in slangS]
print(slangS[:5])
len(slangS)
A =' apa '
A.strip()
# pisahkan berdasarkan ':'
slangS = [t.split(":") for t in slangS]
slangS = [[k.strip(), v.strip()] for k,v in slangS]
print(slangS[:3])
slangS = {k:v for k,v in slangS}
print(slangS['7an'])
# Test it!
tweet = 'I luv u say. serius gan!, tapi ndak tau kalau sesok.'
T = TextBlob(tweet).words
for i,t in enumerate(T):
if t in slangS.keys():
T[i] = slangS[t]
print(' '.join(T))
```
## Machine Language Detection and Translation
<p><img alt="" src="images/Machine_Translation_Models.png" /></p>
image Sources:
* https://www.freecodecamp.org/news/a-history-of-machine-translation-from-the-cold-war-to-deep-learning-f1d335ce8b5/
* https://medium.com/analytics-vidhya/seq2seq-model-and-the-exposure-bias-problem-962bb5607097
```
#Language Detection (TextBlob)
"""
from textblob import TextBlob
T = "Aku ingin mengerti NLP dalam bahasa Inggris"
U = "jarene iki boso jowo"
print(TextBlob(T).detect_language())
print(TextBlob(U).detect_language())
"""
# Machine Translation
import requests
def translate(txt_='', from_='en', to_='id'):
headers = {"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"}
url = 'http://translate.google.com/translate_a/t'
params = {"text": txt_, "sl": from_, "tl": to_, "client": "p"}
terjemahan = requests.get(url, params=params, headers=headers).content
return terjemahan.decode('utf8').replace('"','').replace("'","").strip()
txt = "mendung tanpo udan"
f = 'jv'
t = 'id'
translate(txt_=txt, from_=f, to_=t)
```
## Encoding-Decoding:
<ul>
<li>Hal berikutnya yang perlu diperhatikan dalam memproses data teks adalah encoding-decoding.</li>
<li>Contoh Encoding: ASCII, utf, latin, dsb.</li>
<li>saya membahas lebih jauh tetang encoding disini: <br />
<a href="https://tau-data.id/memahami-string-python/" target="_blank">https://tau-data.id/memahami-string-python/</a></li>
<li>Berikut adalah sebuah contoh sederhana tantangan proses encoding-decoding ketika kita hendak memproses data yang berasal dari internet atau media sosial.</li>
</ul>
```
# kita bisa menggunakan modul unidecode untuk mendapatkan representasi ASCII terdekat
from unidecode import unidecode
T = "ḊḕḀṙ ₲ØĐ, p̾l̾e̾a̾s̾e ḧḕḶṖ ṁḕ"
print(unidecode(T).lower())
# Bahasa Indonesia dan Inggris secara umum mampu direpresentasikan dalam encoding ASCII:
# https://en.wikipedia.org/wiki/ASCII
# Kita juga bisa membersihkan posting media sosial/website dengan entitas html menggunakan fungsi "unescape" di modul "html"
from html import unescape
print(unescape('Satu < Tiga & © adalah simbol Copyright'))
```
# Representasi Dokumen
<h1 id="Vector-Space-Model---VSM">Vector Space Model - VSM</h1>
<p><img alt="" src="images/vsm.png" style="width: 300px; height: 213px;" /></p>
<ul>
<li>Data multimedia seperti teks, gambar atau video <strong>tidak dapat</strong> <strong>secara langsung</strong> dianalisa dengan model statistik/data mining.</li>
<li>Sebuah proses awal <em>(pre-process)</em> harus dilakukan terlebih dahulu untuk merubah data-data tidak (semi) terstruktur tersebut menjadi bentuk yang dapat digunakan oleh model statistik/data mining konvensional.</li>
<li>Terdapat berbagai macam cara mengubah data-data tidak terstruktur tersebut ke dalam bentuk yang lebih sederhana, dan ini adalah suatu bidang ilmu tersendiri yang cukup dalam. Sebagai contoh saja sebuah teks biasanya dirubah dalam bentuk vektor/<em>topics</em> terlebih dahulu sebelum diolah.</li>
<li>Vektor data teks sendiri bermacam-macam jenisnya: ada yang berdasarkan eksistensi (<strong><em>binary</em></strong>), frekuensi dokumen (<strong>tf</strong>), frekuensi dan invers jumlah dokumennya dalam corpus (<strong><a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" target="_blank">tf-idf</a></strong>), <strong>tensor</strong>, dan sebagainya.</li>
<li> Proses perubahan ini sendiri biasanya tidak <em>lossless</em>, artinya terdapat cukup banyak informasi yang hilang. Maksudnya bagaimana? Sebagai contoh ketika teks direpresentasikan dalam vektor (sering disebut sebagai model <strong>bag-of-words</strong>) maka informasi urutan antar kata menghilang. </li>
</ul>
<p><img alt="" src="images/3_structureData.png" style="height:270px; width:578px" /></p>
<p><strong>Contoh bentuk umum representasi dokumen:</strong></p>
<p><img alt="" src="images/3_Bentuk umum representasi dokumen.JPG" style="height: 294px ; width: 620px" /></p>
<p>Pada Model <em>n-grams</em> kolom bisa juga berupa frase.</p>
<h2 id="Document-Term-Matrix-:-Vector-Space-Model---VSM">Document-Term Matrix : Vector Space Model - VSM</h2>
<p><img alt="" src="images/vsm_matrix.png" style="width: 500px; height: 283px;" /></p>
<p><img alt="" src="images/3_rumus tfidf.png" style="height:370px; width:367px" /></p>
<p><img alt="" src="images/3_tfidf logic.jpg" style="height:359px; width:638px" /></p>
<p><img alt="" src="images/3_variant tfidf.png" style="height:334px; width:955px" /></p>
K = |d|
<h3>Mari awali dengan me-load contoh dataset dokumen yang cukup tenar: "20 NewsGroup"</h3>
<img alt="" src="images/6_20News.jpg" style="height: 300px ; width: 533px" />
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html#sklearn.datasets.fetch_20newsgroups" target="_blank">http://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html#sklearn.datasets.fetch_20newsgroups</a></p>
<p><strong>Categories </strong>= </p>
<pre>
['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware',
'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey',
'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns',
'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']</pre>
```
# Mulai dengan loading data
from sklearn.datasets import fetch_20newsgroups
try:
f = open('data/20newsgroups.pckl', 'rb')
data = pickle.load(f)
f.close()
except:
categories = ['sci.med', 'talk.politics.misc', 'rec.autos']
data = fetch_20newsgroups(categories=categories,remove=('headers', 'footers', 'quotes'))
f = open('data/20newsgroups.pckl', 'wb')
pickle.dump(data, f)
f.close()
'Done'
# Merubah data ke bentuk yang biasa kita gunakan
D = [doc for doc in data.data]
Y = data.target
'Done'
set(Y)
D[:3]
```
## tf-idf:
<img alt="" src="images/toydata_vsm.png" />
* Menurut http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html
* default formula tf-idf yang digunakan sk-learn adalah:
* $tfidf = tf * log(\frac{N}{df+1})$ ==> Smooth IDF
* namun kita merubahnya menjadi:
* $tfidf = tf * log(\frac{N}{df})$ ==> Non Smooth IDF
* $tfidf = tf * log(\frac{N}{df+1})$ ==> linear_tf, Smooth IDF
* $tfidf = (1+log(tf)) * log(\frac{N}{df})$ ==> sublinear_tf, Non Smooth IDF
```
# Menggunakan modul SciKit untuk merubah data tidak terstruktur ke VSM
# Scikit implementation http://scikit-learn.org/stable/modules/feature_extraction.html
from sklearn.feature_extraction.text import TfidfVectorizer
# http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer
# http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer
# VSM term Frekuensi : "tf-idf"
tfidf_vectorizer = TfidfVectorizer(smooth_idf= False, sublinear_tf=True, lowercase=True, stop_words="english")
tfidf = tfidf_vectorizer.fit_transform(D)
print(tfidf.shape) # Sama
print(tfidf[0].data) # Hanya data ini yg berubah
print(tfidf[0].indices) # Letak kolomnya = tfidf
```
### Alasan melakukan filtering berdasarkan frekuensi:
* Intuitively filter noise
* Curse of Dimensionality (akan dibahas kemudian)
* Computational Complexity
* Improving accuracy
```
# Frequency Filtering di VSM
tfidf_vectorizer = TfidfVectorizer()
tfidf_1 = tfidf_vectorizer.fit_transform(D)
tfidf_vectorizer = TfidfVectorizer(max_df=0.75, min_df=5)
tfidf_2 = tfidf_vectorizer.fit_transform(D)
print(tfidf_1.shape)
print(tfidf_2.shape)
tfidf_vectorizer = TfidfVectorizer(lowercase=True, smooth_idf= True, sublinear_tf=True,
ngram_range=(1, 2), max_df=0.90, min_df=2)
tfidf_3 = tfidf_vectorizer.fit_transform(D)
print(tfidf_3.shape)
```
<h2 id="Best-Match-Formula-:-BM25">Best-Match Formula : BM25</h2>
<p><img alt="" src="images/3_bm25_simple.png" style="height: 123px; width: 300px;" /></p>
<ol>
<li>di IR nilai b dan k yang optimal adalah : <strong> <em>b</em> = 0.75 dan k = [1.2 - 2.0] </strong><br />
ref: <em>Christopher, D. M., Prabhakar, R., & Hinrich, S. C. H. Ü. T. Z. E. (2008). Introduction to information retrieval. An Introduction To Information Retrieval, 151, 177.</em></li>
<li>Tapi kalau untuk TextMining (clustering) nilai <strong>k optimal adalah 20, nilai b = sembarang (boleh = 0.75)</strong><br />
ref: <em>Whissell, J. S., & Clarke, C. L. (2011). Improving document clustering using Okapi BM25 feature weighting. Information retrieval, 14(5), 466-487.</em></li>
<li><strong>avgDL </strong>adalah rata-rata panjang dokumen di seluruh dataset dan <strong>DL </strong>adalah panjang dokumen D.<br />
hati-hati, ini berbeda dengan tf-idf MySQL diatas.</li>
</ol>
```
# Variasi pembentukan matriks VSM:
d1 = '@udin76, Minum kopi pagi-pagi sambil makan pisang goreng is the best'
d2 = 'Belajar NLP dan Text Mining ternyata seru banget sadiezz'
d3 = 'Sudah lumayan lama bingits tukang Bakso belum lewat'
d4 = 'Aduh ga banget makan Mie Ayam p4k4i kesyap, please deh'
D = [d1, d2, d3, d4]
# Jika kita menggunakan cara biasa:
tfidf_vectorizer = TfidfVectorizer()
vsm = tfidf_vectorizer.fit_transform(D)
print(tfidf_vectorizer.vocabulary_)
# N-Grams VSM
# Bermanfaat untuk menangkap frase kata, misal: "ga banget", "pisang goreng", dsb
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2))
vsm = tfidf_vectorizer.fit_transform(D)
print(tfidf_vectorizer.vocabulary_)
# Vocabulary based VSM
# Bermanfaat untuk menghasilkan hasil analisa yang "bersih"
# variasi 2
d1 = '@udin76, Minum kopi pagi-pagi sambil makan pisang goreng is the best'
d2 = 'Belajar NLP dan Text Mining ternyata seru banget sadiezz'
d3 = 'Sudah lumayan lama bingits tukang Bakso belum lewat seru'
d4 = 'Aduh ga banget makan Mie Ayam p4k4i kesyap, please deh'
D = [d1,d2,d3,d4]
Vocab = {'seru banget':0, 'seru':1, 'the best':2, 'lama':3, 'text mining':4, 'nlp':5, 'ayam':6}
tf_vectorizer = CountVectorizer(binary = False, vocabulary=Vocab)
tf = tf_vectorizer.fit_transform(D)
print(tf.toarray())
tf_vectorizer.vocabulary_
Vocab = {'seru banget':0, 'the best':1, 'lama':2, 'text mining':3, 'nlp':4, 'ayam':5}
tfidf_vectorizer = TfidfVectorizer(max_df=1.0, min_df=1, lowercase=True, vocabulary=Vocab)
vsm = tfidf_vectorizer.fit_transform(D)
print(tfidf_vectorizer.vocabulary_)
# VSM terurut sesuai definisi dan terkesan lebih "bersih"
# Perusahaan besar biasanya memiliki menggunakan teknik ini dengan vocabulary yang comprehensif
# Sangat cocok untuk Sentiment Analysis
```
# <center><strong><font color="blue"> Klasifikasi Teks dan Sentiment Analysis</font></strong></center>
```
# Mulai dengan loading data
from sklearn.datasets import fetch_20newsgroups
try:
f = open('data/20newsgroups.pckl', 'rb')
data = pickle.load(f)
f.close()
except:
categories = ['sci.med', 'talk.politics.misc', 'rec.autos']
data = fetch_20newsgroups(categories=categories,remove=('headers', 'footers', 'quotes'))
f = open('data/20newsgroups.pckl', 'wb')
pickle.dump(data, f)
f.close()
'Done'
# Merubah data ke bentuk yang biasa kita gunakan
D = [doc for doc in data.data]
Y = data.target
'Done'
set(Y)
D[0]
# Bentuk VSM-nya
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(lowercase=True, stop_words='english',smooth_idf= True, sublinear_tf=True,
ngram_range=(1, 2), max_df=0.90, min_df=2)
from sklearn.model_selection import train_test_split
seed = 99
x_train, x_test, y_train, y_test = train_test_split(D, Y, test_size=0.3, random_state=seed)
x_train = tfidf_vectorizer.fit_transform(x_train) # "Fit_Transform"
x_test = tfidf_vectorizer.transform(x_test) # Perhatikan disini hanya "Transform"
print(x_train.shape, x_test.shape) # Jumlah kolom Sama ==> ini penting
# Jangan lupa langkah penting ini! ...
# Kenapa ada yang kosong?... coba fikirkan ...
def hapusKosong(X,Y):
Y = Y[X.getnnz(1)>0] # delete label dokumen yang memiliki row =0 di tfidf-nya
X = X[X.getnnz(1)>0] # Remove Zero Rows
return X, Y
x_train, y_train = hapusKosong(x_train, y_train)
x_test, y_test = hapusKosong(x_test, y_test)
print(x_train.shape, x_test.shape)
# Kita gunakan metric yang umum
from sklearn.metrics import accuracy_score
# Naive Bayes: http://scikit-learn.org/stable/modules/naive_bayes.html
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
nbc = gnb.fit(x_train.toarray(), y_train) # Kelemahan Implementasinya disini
y_nbc = nbc.predict(x_test.toarray())
accuracy_score(y_test, y_nbc)
# Hati-hati Sparse ==> Dense bisa memenuhi memory untuk data relatif cukup besar
# Akurasi cukup baik
# Decision Tree: http://scikit-learn.org/stable/modules/tree.html
from sklearn import tree
DT = tree.DecisionTreeClassifier()
DT = DT.fit(x_train, y_train)
y_DT = DT.predict(x_test)
accuracy_score(y_test, y_DT)
# Akurasi relatif rendah ==> Mengapa?
# Mari coba perbaiki dengan Random Forest
# http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html
from sklearn.ensemble import RandomForestClassifier
RandomForest = RandomForestClassifier()
RandomForest.fit(x_train, y_train)
y_RF = RandomForest.predict(x_test)
accuracy_score(y_test, y_RF)
# Sedikit membaik (expected)
# SVM: http://scikit-learn.org/stable/modules/svm.html
from sklearn import svm
dSVM = svm.SVC(decision_function_shape='ovo') # oneversus one SVM
dSVM.fit(x_train, y_train)
y_SVM = dSVM.predict(x_test)
accuracy_score(y_test, y_SVM)
# Mengapa akurasinya rendah? Mengejutkan?
# Neural Network: http://scikit-learn.org/stable/modules/neural_networks_supervised.html
from sklearn.neural_network import MLPClassifier
NN = MLPClassifier(hidden_layer_sizes=(30, 40))
NN.fit(x_train, y_train)
y_NN = NN.predict(x_test)
accuracy_score(y_test, y_NN)
# Cukup Baik, coba rubah jumlah layer dan Neuron
```
## Tunggu dulu ... yang kita lakukan belum cukup valid/objektif ... Mengapa?
<h1>Cross Validation</h1>
<h1><img alt="" src="images/6_Cross_validation.png" style="height:274px; width:485px" /></h1>
```
# Cross validation
# http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html
from sklearn.model_selection import cross_val_score
import time
# perhatikan sekarang kita menggunakan seluruh data
# Bisa juga CV di training data ==> train, Test, Val splittting system
X = tfidf_vectorizer.fit_transform(D) # "Fit_Transform"
svm_ = svm.SVC(kernel='linear', decision_function_shape='ovo')
mulai = time.time()
scores_svm = cross_val_score(svm_, X, Y, cv=10, n_jobs=-2)
waktu = time.time() - mulai
# Interval Akurasi 95 CI
print("Accuracy SVM: %0.2f (+/- %0.2f), Waktu = %0.3f detik" % (scores_svm.mean(), scores_svm.std() * 2, waktu))
# Bandingkan dengan Neural Network
nn_ = MLPClassifier(hidden_layer_sizes=(30, 40))
mulai = time.time()
scores_nn = cross_val_score(nn_, X, Y, cv=10, n_jobs=-2)
waktu = time.time() - mulai
# Interval Akurasi 95 CI
print("Accuracy ANN: %0.2f (+/- %0.2f), Waktu = %0.3f detik" % (scores_nn.mean(), scores_nn.std() * 2, waktu))
# Kita bisa juga mengeluarkan metric evaluasi lainnya
scores = cross_val_score(svm_, X, Y, cv=10, scoring='f1_macro')
print("F1-Score: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
# scoring pilih dari sini: http://scikit-learn.org/stable/modules/model_evaluation.html
%matplotlib inline
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt; plt.style.use('classic')
import numpy as np, pandas as pd
df = pd.DataFrame({'SVM':scores_svm,'ANN':scores_nn})
sns.boxplot(data=df)
plt.show()
```
<img alt="" src="images/9_Sentiment_Analysis_Meme.jpg" />
<p><strong>Apakah sentiment analysis?</strong></p>
<p>Sentiment Analysis adalah suatu proses komputasi untuk menentukan apakah suatu penrnyataan bermakna positive, negative, atau netral.</p>
<p>Terkadang disebut juga sebagai <strong>opinion mining.</strong></p>
<p><strong>Contoh aplikasi Sentiment Analysis</strong></p>
<ul>
<li><strong>Business: tanggapan konsumen atas suatu produk</strong>.</li>
<li><strong>Politics: </strong>Sentimen masyarakat sebagai strategi pemenangan pemilu/pilkada.</li>
</ul>
<img alt="" src="images/9_SA_techniques.jpg" />
```
from textblob import TextBlob
# Lexicon Based berdasarkan
# pattern = https://www.clips.uantwerpen.be/pages/pattern-en#sentiment
Sentence = "Bakpia is good"
testimonial = TextBlob(Sentence)
print(testimonial.sentiment)
print('Polarity=Sentimen =', testimonial.sentiment.polarity)
```
<p>Sentiment menghasilkan Tuple berpasangan (<strong>Polaritas</strong>, <strong>Subjectivitas</strong>). </p>
<p>Polaritas memiliki nilai [-1, 1] ==> negative~positive Sentimen</p>
<p>Subjectivity memiliki nilai antara 0 sampai 1, dimana 0 paling objective dan 1 paling subjective.</p>
## Bagaimana Dengan Bahasa Indonesia?
<p>[A simple trick]</p>
```
kalimat = 'Saya benci Bakpia'
K = TextBlob(kalimat).translate(to='en')
print(type(K), K)
print(K.sentiment)
print('Polarity=Sentimen =', K.sentiment.polarity)
def SenSubModMood_ID(kalimat):
K = translate(txt_=kalimat, from_='id', to_='en') # TextBlob(kalimat).translate(to='en')
pol,sub = K.sentiment
if pol>0:
pol='positive'
elif pol<0:
pol='negative'
else:
pol = 'netral'
if sub>0.5:
sub = 'Subjektif'
else:
sub = "Objektif"
return pol, sub
kalimat = 'makan bakpia pakai kecap enak'
SenSubModMood_ID(kalimat)
from textblob.sentiments import NaiveBayesAnalyzer
# Warning, mungkin lambat karena membentuk model classifier* terlebih dahulu.
# *Berdasarkan NLTK corpus ==> Language dependent
Sentence = "Textblob is amazingly simple to use"
blob = TextBlob(Sentence, analyzer=NaiveBayesAnalyzer())
blob.sentiment
# Good Explanation: https://medium.com/nlpython/sentiment-analysis-analysis-ee5da4448e37
# Output probabilitas prediksinya
```
## Bagaimana dengan Sentiment Analysis menggunakan NBC untuk Bahasa indonesia?
```
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
def word_feats(words):
return dict([(word, True) for word in words])
def bentukClassifier(wPos, wNeg): # ,Nt
positive_features = [(word_feats(pos), 'pos') for pos in wPos]
negative_features = [(word_feats(neg), 'neg') for neg in wNeg]
#neutral_features = [(word_feats(neu), 'neu') for neu in Nt]
train_set = negative_features + positive_features# + neutral_features
return NaiveBayesClassifier.train(train_set)
def prediksiSentiment(kalimat, wPos, wNeg, negasi):
pos, neg = 0.0, 0.0
posWords, negWords = [], []
K = tau.cleanText(kalimat)
for w in wPos:
if w in K:
for ww in negasi:
kebalikan = False
inverted = ww+' '+w
if inverted in K:
negWords.append(inverted)
kebalikan = True
break
if not kebalikan:
posWords.append(w)
for w in wNeg:
if w in K:
for ww in negasi:
kebalikan = False
inverted = ww+' '+w
if inverted in K:
posWords.append(inverted)
kebalikan = True
break
if not kebalikan:
negWords.append(w)
nPos, nNeg = len(posWords), len(negWords)
sum_ = nPos + nNeg
if sum_ == 0 or nPos==nNeg:
return 'netral', 0.0
else:
nPos, nNeg = nPos/sum_, nNeg/sum_
if nPos>nNeg and nPos>0.01:
return 'positif', nPos
elif nNeg>nPos and nNeg<-0.01:
return 'negatif', nNeg
else:
return 'netral', (nPos + nNeg)/2
wPos = ('keren', 'suka', 'cinta', 'bagus', 'mantap', 'sadis', 'top', 'enak', 'sedap')
wNeg = ('jelek', 'benci','buruk', 'najis')
wordS = (wPos, wNeg)
negasi = ['ga', 'tidak']
sentence = "makan pempek minumnya teh panas, biasa aja :)"
prediksiSentiment(sentence, wPos, wNeg, negasi)
sentence = "makan gorengan sambil minum kopi, enak tenan"
prediksiSentiment(sentence, wPos, wNeg, negasi)
```
## Bagaimana jika mau melakukannya dengan model klasifikasi (supervised learning) lain seperti modul sebelumnya?
(e.g. SVM, NN, DT, k-NN, etc)
```
# text Classification : independent variable
d1 = 'Minum kopi pagi-pagi sambil makan pisang goreng is the best'
d2 = 'Belajar NLP dan Text Mining ternyata seru banget'
d3 = 'Palembang agak mendung hari ini'
d4 = 'Sudah lumayan lama tukang Bakso belum lewat'
d5 = 'Aduh ga banget makan Mie Ayam pakai kecap, please deh'
d6 = 'Benci banget kalau melihat orang buang sampah sembarangan di jalan'
d7 = 'Kalau liat orang ga taat aturan rasanya ingin ngegampar aja'
d8 = 'Nikmatnya meniti jalan jalan penuh romansa di tengah kota bernuansa pendidikan'
d9 = 'kemajuan bangsa ini ada pada kegigihan masyarakat dalam belajar dan bekerja'
D = [d1,d2,d3,d4,d5,d6,d7,d8,d9]
'Done!'
# dependent variable, misal 0=positif, 1=netral, 2=negatif
Class = [0,0,1,1,2,2,2,1,0]
dic = {0:'positif', 1:'netral', 2:'negatif'}
print([dic[c] for c in Class])
# Bentuk VSM-nya seperti kemarin (skip preprocessing)
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(ngram_range=(1, 2))
vsm = vectorizer.fit_transform(D)
vsm = vsm[vsm.getnnz(1)>0][:,vsm.getnnz(0)>0] # Remove zero rows and columns
print(vsm.shape)
str(vectorizer.vocabulary_)[:200]
# Lakukan klasifikasi (misal dengan SVM)
dSVM = svm.SVC(kernel='linear')
sen = dSVM.fit(vsm, Class).predict(vsm)
print(accuracy_score(Class, sen))
# Memakai seluruh training data karena sampel yang sangat kecil
```
# <center><strong><font color="blue">Topic Modelling</font></strong></center>
## <font color="blue">Outline Topic Modelling :</font>
* Importing Data
* Pendahuluan Topic Modelling
* Soft Clustering (Topic Modelling): LDA
* Visualisasi dan Interpretasi
<h3>Ketika mengolah dokumen (file dalam bentuk teks), harapan kita seperti ini:</h3>
<img alt="" src="images/4_harapan_LSA.png" style="height:99px; width:198px" />
<h3>Namun kita sudah bahas kemarin kenyataannya seperti ini:</h3>
<p><img alt="" src="images/4_kenyataan_LSA.png" style="height:183px; width:182px" /></p>
<h2 id="Topic-Modelling-1-:-Latent-Dirichlet-Allocation">Topic Modelling 1 : Latent Dirichlet Allocation</h2>
<p><img alt="" src="images/4_Document_to_Topics.png" style="height: 300px ; width: 582px" /></p>
<p><strong><big>Tapi bukan seperti klasifikasi dan bukan berarti kata-kata Sport, Technology, dan Entertainment dominan di kategori-kategori tersebut. Topic modelling lebih ke soft-clustering, dimana suatu dokumen dimasukkan ke dalam beberapa cluster (topic) sekaligus. Adapun nama "topic/cluster"-nya di interpretasi dari kata-kata yang ada didalamnya.</big></strong></p>
<p><img alt="" src="images/4_LDA vs LDA.JPG" style="height:400px; width:606px" /></p>
[<a href="http://chdoig.github.io/pytexas2015-topic-modeling/" target="_blank">Sumber gambar ini dan beberapa gambar selanjutnya</a>]</p>
<p><img alt="" src="images/4_definisi topic model.JPG" style="height:350px; width:809px" />
<p><img alt="" src="images/4_inti_LDA.JPG" style="height:500px; width:785px" /></p>
Penjelasan intuitif yang baik: https://medium.com/@lettier/how-does-lda-work-ill-explain-using-emoji-108abf40fa7d
# Add LDA Matrix Decomposition
<h3>Evaluasi LDA?</h3>
<p><img alt="" src="images/4_Evaluasi_LDA.jpg" style="height:400px; width:888px" /></p>
[Cara lain: http://mimno.infosci.cornell.edu/slides/details.pdf]
<p><img alt="" src="images/4_LDA Pipeline.JPG" style="height:300px; width:663px" /></p>
* Modifikasi dapat dilakukan dengan "pos tags"
```
# Kita mulai dengan membuat VSM-nya
# kita gunakan perintah yang ada di Segmen sebelumnya
from sklearn.feature_extraction.text import CountVectorizer
tf_vectorizer = CountVectorizer()
data = D.copy()
tf = tf_vectorizer.fit_transform(D)
tf_terms = tf_vectorizer.get_feature_names()
# Mengapa tf bukan tfidf?
# Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent dirichlet allocation. Journal of machine Learning research, 3(Jan), 993-1022.
# Bisa di tamahkan dengan Frequency filtering "Max_df" dan "Min_df"
tf.shape
# Dilanjutkan dengan membentuk model LDA-nya
from sklearn.decomposition import LatentDirichletAllocation as LDA
n_topics = 3 # Misal tidak di optimalkan terlebih dahulu
lda = LDA(n_components=n_topics, learning_method='batch', random_state=0).fit(tf)
lda
# Melihat Topik-topiknya
vsm_topics = lda.transform(tf)
print(vsm_topics.shape)
vsm_topics
# Ukuran kolom = #Topics ==> Dimension Reduction
# Mengapa tidak dibagi Train & Test???
# "Seandainya" diasumsikan 1 dokumen hanya 1 topic dengan nilai skor topic terbesar
doc_topic = [a.argmax()+1 for a in tqdm(vsm_topics)] # topic of docs
doc_topic[:10]
# mari kita plot
plot = sns.countplot(doc_topic)
# Mari kita coba maknai masing-masing topic ini
Top_Words = 25
print('Printing top {0} Topics, with top {1} Words:'.format(n_topics, Top_Words))
tau.print_Topics(lda, tf_terms, n_topics, Top_Words)
# %matplotlib inline
# Mari kita Plot, supaya lebih jelas
# Catatan, bergantung dari laptop yang digunakan, image terkadang cukup lama untuk muncul.
import pyLDAvis, pyLDAvis.sklearn; pyLDAvis.enable_notebook()
pyLDAvis.sklearn.prepare(lda, tf, tf_vectorizer)
```
# Bagaimana jika kita ingin menggunakan semi-supervised (guided) LDA?
https://medium.freecodecamp.org/how-we-changed-unsupervised-lda-to-semi-supervised-guidedlda-e36a95f3a164
# Bagaimana melakukan Post-Tag sebelum Topic Modelling?
```
from spacy.lang.id import Indonesian
from nltk.tag import CRFTagger
nlp_id = Indonesian() # Language Model
ct = CRFTagger()
ct.set_model_file('data/all_indo_man_tag_corpus_model.crf.tagger')
def NLPfilter(t, filters):
tokens = nlp_id(t)
tokens = [str(k) for k in tokens if len(k)>2]
hasil = ct.tag_sents([tokens])
return [k[0] for k in hasil[0] if k[1] in filters]
filters = set(['NN', 'NNP', 'NNS', 'NNPS', 'JJ'])
for i, d in tqdm(enumerate(data)):
data[i] = NLPfilter(d,filters)
' '.join(data[0])
print(data[:3])
```
# Referensi Pilihan:
* perhitungan Manual Topic Modelling LDA: http://brooksandrew.github.io/simpleblog/articles/latent-dirichlet-allocation-under-the-hood/
* http://mimno.infosci.cornell.edu/slides/details.pdf
* https://datascienceplus.com/evaluation-of-topic-modeling-topic-coherence/
* http://www.umiacs.umd.edu/~jbg/docs/nips2009-rtl.pdf
* http://radimrehurek.com/topic_modeling_tutorial/2%20-%20Topic%20Modeling.html
* Penjelasan intuitif yang baik: https://medium.com/@lettier/how-does-lda-work-ill-explain-using-emoji-108abf40fa7d
* inconjunction dengan interactive program berikut: https://lettier.com/projects/lda-topic-modeling/
# <center><font color="blue"> End of Module.
<hr />
| github_jupyter |
```
from __future__ import print_function
import os
import sys
import pandas as pd
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
os.chdir('D:\Practical Time Series')
data = pd.read_csv('datasets/WDI_csv/WDIData.csv')
print('Column names:', data.columns)
print('No. of rows, columns:', data.shape)
nb_indicators = data['Indicator Name'].unique().shape[0]
print('Unique number of indicators:', nb_indicators)
nb_countries = data['Country Code'].unique().shape[0]
print('Unique number of countries:', nb_countries)
central_govt_debt = data.loc[data['Indicator Name']=='Central government debt, total (% of GDP)']
military_exp = data.loc[data['Indicator Name']=='Military expenditure (% of GDP)']
print('Shape of central_govt_debt:', central_govt_debt.shape)
print('Shape of military_exp:', military_exp.shape)
central_govt_debt['2010'].describe()
military_exp['2010'].describe()
central_govt_debt.index = central_govt_debt['Country Code']
military_exp.index = military_exp['Country Code']
central_govt_debt_2010 = central_govt_debt['2010'].loc[~pd.isnull(central_govt_debt['2010'])]
military_exp_2010 = military_exp['2010'].loc[~pd.isnull(military_exp['2010'])]
data_to_plot = pd.concat((central_govt_debt_2010, military_exp_2010), axis=1)
data_to_plot.columns = ['central_govt_debt', 'military_exp']
data_to_plot.head(10)
data_to_plot = data_to_plot.loc[(~pd.isnull(data_to_plot.central_govt_debt)) & (~pd.isnull(data_to_plot.military_exp)), :]
data_to_plot.head()
plt.figure(figsize=(5.5, 5.5))
g = sns.distplot(np.array(data_to_plot.military_exp), norm_hist=False)
g.set_title('Military expenditure (% of GDP) of 85 countries in 2010')
plt.savefig('plots/ch1/B07887_01_01.png', format='png', dpi=300)
plt.figure(figsize=(5.5, 5.5))
g = sns.kdeplot(data_to_plot.military_exp, data2=data_to_plot.central_govt_debt)
g.set_title('Military expenditures & Debt of central governments in 2010')
plt.savefig('plots/ch1/B07887_01_02.png', format='png', dpi=300)
central_govt_debt_us = central_govt_debt.loc[central_govt_debt['Country Code']=='USA', :].T
military_exp_us = military_exp.loc[military_exp['Country Code']=='USA', :].T
data_us = pd.concat((military_exp_us, central_govt_debt_us), axis=1)
index0 = np.where(data_us.index=='1960')[0][0]
index1 = np.where(data_us.index=='2010')[0][0]
data_us = data_us.iloc[index0:index1+1,:]
data_us.columns = ['Federal Military Expenditure', 'Debt of Federal Government']
data_us.head(20)
#There are null rows for several years possibly due to unavailability of data for these years
data_us.dropna(inplace=True)
print('Shape of data_us:', data_us.shape)
#First 20 rows of data_us after dropping rows with missing values
data_us.head(20)
# Two subplots, the axes array is 1-d
f, axarr = plt.subplots(2, sharex=True)
f.set_size_inches(5.5, 5.5)
axarr[0].set_title('Federal Military Expenditure during 1988-2010 (% of GDP)')
data_us['Federal Military Expenditure'].plot(linestyle='-', marker='*', color='b', ax=axarr[0])
axarr[1].set_title('Debt of Federal Government during 1988-2010 (% of GDP)')
data_us['Debt of Federal Government'].plot(linestyle='-', marker='*', color='r', ax=axarr[1])
plt.savefig('plots/ch1/B07887_01_03.png', format='png', dpi=300)
chn = data.ix[(data['Indicator Name']=='Military expenditure (% of GDP)')&\
(data['Country Code']=='CHN'),index0:index1+1
]
chn = pd.Series(data=chn.values[0], index=chn.columns)
chn.dropna(inplace=True)
usa = data.ix[(data['Indicator Name']=='Military expenditure (% of GDP)')&\
(data['Country Code']=='USA'),index0:index1+1
]
usa = pd.Series(data=usa.values[0], index=usa.columns)
usa.dropna(inplace=True)
ind = data.ix[(data['Indicator Name']=='Military expenditure (% of GDP)')&\
(data['Country Code']=='IND'),index0:index1+1
]
ind = pd.Series(data=ind.values[0], index=ind.columns)
ind.dropna(inplace=True)
gbr = data.ix[(data['Indicator Name']=='Military expenditure (% of GDP)')&\
(data['Country Code']=='GBR'),index0:index1+1
]
gbr = pd.Series(data=gbr.values[0], index=gbr.columns)
gbr.dropna(inplace=True)
plt.figure(figsize=(5.5, 5.5))
usa.plot(linestyle='-', marker='*', color='b')
chn.plot(linestyle='-', marker='*', color='r')
gbr.plot(linestyle='-', marker='*', color='g')
ind.plot(linestyle='-', marker='*', color='y')
plt.legend(['USA','CHINA','UK','INDIA','RUSSIA'], loc=1)
plt.title('Miltitary expenditure of 5 countries over 10 years')
plt.ylabel('Military expenditure (% of GDP)')
plt.xlabel('Years')
plt.savefig('plots/ch1/B07887_01_04.png', format='png', dpi=300)
```
| github_jupyter |
# CRDS reference rules
This notebook explores the CRDS .rmap rules files.
## Prerequisites
To follow along with the examples in this notebook, you will need:
- Packages from the requirements.txt included in this notebook's directory:
```
$ pip install -r requirements.txt
```
## Setup
We can connect to the JWST ops server in this notebook, since we won't be attempting to submit changes to the system.
```
import os
os.environ["CRDS_SERVER_URL"] = "https://jwst-crds.stsci.edu"
os.environ["CRDS_PATH"] = os.path.join(os.environ["HOME"], "crds-tutorial-cache")
import crds # Always delay import until environment variables are set.
```
## The .rmap language
We've encountered .rmap rules files in previous notebooks, but now we'll delve into them in more detail. An .rmap is written in a little language all its own -- a subset of Python where certain classes are assumed to be imported before the .rmap "script" is interpreted. An .rmap defines two required and one optional top-level variable. Let's discuss each variable one at a time, starting with `header`.
### header
The required `header` variable contains metadata for the .rmap itself. We can use the CRDS client to pull up a real example of an .rmap and examine its header. Let's grab the latest (at time of writing) `nircam` `dark` .rmap:
```
# Make sure mappings have been cached locally:
crds.client.api.dump_mappings("jwst_0641.pmap")
# Get the path to the .rmap in the local cache:
path = crds.locate_mapping("jwst_nircam_dark_0021.rmap")
# Read the .rmap content and print:
with open(path) as f:
nircam_dark_rmap = f.read()
print(nircam_dark_rmap)
```
Certain header keys are required in every .rmap, while others enable optional features. The required keys:
#### derived_from
The `derived_from` key documents the "heritage" of the .rmap file. For brand-new .rmaps, the value will be a descriptive string like "Created by hand on 2020-09-15". For an .rmap that is an update to a previously existing set of rules, the `derived_from` value will be the original filename. In our example, the key is `jwst_nircam_dark_0018.rmap`, showing that our .rmap is an update to a previous version.
The `derived_from` value is automatically maintained by CRDS when an .rmap update is generated by the system in response to a reference file submission. When an .rmap is updated by hand, `derived_from` must be updated manually.
`derived_from` is not used when evaluating the rules, but it is important for understanding how a set of rules came to be.
#### filekind
This is simply the reference file type, in this case, `DARK`. The type string is not case sensitive, but by convention .rmaps are written with `filekind` in uppercase.
#### instrument
The instrument whose reference files the .rmap describes. We're looking at a `nircam` .rmap, so the value is `NIRCAM`.
#### mapping
This key identifies the fact that these are reference rules, as opposed to instrument (.imap) or top-level context (.pmap) rules. We're looking at an .rmap, so this value is `REFERENCE`.
#### name
The name of this file, which also serves as its unique identifier in CRDS. Given such a filename, CRDS knows how to build the full path to the file in the CRDS cache directory structure.
The `name` value is automatically maintained by CRDS when an .rmap update is generated by the system, and when CRDS is asked to assign a name to a manual update.
#### observatory
The observatory whose reference files the .rmap describes. We're looking at a JWST .rmap, so the value is `JWST`.
#### parkey
A tuple of tuples that describes selector criteria for each tier of the selector tree. `parkey` informs CRDS as to which dataset metadata fields are needed to evaluate the .rmap's rules. Typically the outer tuple will be of length 1 (for non-time-dependent matching) or length 2 (for time-dependent matching), but other configurations are possible. In our example .rmap, `parkey` describes two selector tiers:
```
'parkey' : (('META.EXPOSURE.TYPE', 'META.INSTRUMENT.DETECTOR', 'META.SUBARRAY.NAME'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')),
```
The first nested tuple shows that exposure type, detector, and subarray name are needed to evaluate the first selector tier. The second nested tuple shows that observation date and time are needed to evaluate the second selector tier.
The meaning of parkey will become more clear in the section on selectors below.
#### sha1sum
The SHA-1 checksum of this .rmap file. This is a checksum of every line of the .rmap except the `sha1sum` line (you'd be hard-pressed to compute a checksum that includes itself!). This key is automatically maintained by CRDS for both auto-generated and hand-crafted .rmaps, but you'll see a warning on submission of the checksum doesn't match your manual .rmap.
In the exercises at the end of this notebook, we pass a flag to CRDS instructing it to ignore checksum mismatches, so you won't need to update this value.
#### Optional keys
Optional header features are outside the scope of this notebook, but you can learn about them by reading the [CRDS User Manual](https://jwst-crds-bit.stsci.edu/static/users_guide/rmap_syntax.html). The `substitutions` key in our example .rmap allows CRDS to treat the string `GENERIC` like the special wildcard value `N/A` when found in the dataset's `META.SUBARRAY.NAME` field.
#### Note on custom keys
The header also permits arbitrary additional keys, so you may find .rmaps (particularly older specimens) that include keys that you don't recognize and aren't documented in the CRDS User Manual. Some of them are custom metadata that the original .rmap author thought might be useful, others refer to header features that have since been removed. They will not impact the evaluation of the .rmap's rules.
### comment
The optional `comment` variable is just that: a freeform string that can be used for documentation purposes.
### selector
The required `selector` variable contains the actual reference file selection rules that are the .rmap's reason for being. Here is encoded the logic of the file selection process for every file of a particular instrument's reference file type. No two instruments are handled by the same .rmap, and no instrument + reference type combination spans multiple .rmaps.
The selector is arranged in a tree structure, which takes the form of composed Python objects. Objects at a given tier of the tree receive input as described by the corresponding tuple in the header `parkey`. The 1st tier of the tree pairs with the 1st inner tuple, and so on.
Selector objects are initialized with a dict, where the expected key type depends on selector type. The values are string filenames, the special value `'N/A'`, or additional selectors. Many selector types are available, but the most commonly used are `{}`, `Match`, and `UseAfter`. None of these need be imported in the .rmap "script"; they can be assumed to always be available.
#### {} selector
The `{}` selector performs simple exact matches on a single dataset metadata value. For example, with `parkey` value `(('META.INSTRUMENT.DETECTOR',),)`, the following selector chooses a different file for each of two detectors:
```
selector = {
'NCRA1': 'the_file_for_ncra1.asdf',
'NCRA2': 'the_file_for_ncra2.asdf',
}
```
The `{}` selector is commonly seen in .pmap and .imap files, but less so in .rmap files, where the more advanced features of the `Match` selector tend to be necessary.
#### Match selector
The `Match` selector has many advantages over the simpler `{}`: it can match on multiple dataset metadata fields at once, offers wildcard, regular expression, and logical-or matches, chooses from among multiple matching rules using a system of weights, and more.
Instances of the `Match` selector are initialized with a dict, where the keys are tuples containing 1..N dataset metadata values (or patterns, or wildcards). For example, with `parkey` value `(('META.INSTRUMENT.DETECTOR', 'META.EXPOSURE.TYPE'),)`, the following selector chooses different files for various combinations of detector and exposure type:
```
selector = Match({
('NCRA1', 'NRC_CORON'): 'file_0001.asdf',
('NCRA1', 'NRC_FLAT'): 'file_0002.asdf',
('NCRA2', 'NRC_CORON'): 'file_0003.asdf',
('NCRA2', 'NRC_FLAT'): 'file_0004.asdf',
})
```
The majority of .rmaps will use the `Match` selector, some in a single tier configurations, but most in two tiers with a nested `UseAfter` selector within each `Match` rule.
#### UseAfter selector
The `UseAfter` selector implements matching on the dataset's observation timestamp, when reference files are only appropriate to "use" with observations taken "after" a certain date and time. Instances of the `UseAfter` selector are initialized with a dict, where the keys are timestamps in the format `YYYY-MM-DD hh:mm:ss`. The selector matches the the latest timestamp that is still on or before the observation timestamp.
For example, with `parkey` value `(('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME'),)` the following selector chooses different files depending on the observation timestamp:
```
selector = UseAfter({
'2020-01-01 00:00:00': '2020_file.asdf',
'2021-01-01 00:00:00': '2021_file.asdf',
'2022-01-01 00:00:00': '2022_file.asdf',
})
```
A dataset with observation timestamp `2021-01-01 00:00:00` would select `2021_file.asdf`, as would a dataset with timestamp `2021-12-31 23:59:59`. A dataset with timestamp `2019-12-31 23:59:59` wouldn't select anything, and any timestamp on or after `2022-01-01 00:00:00` (including timestamps in the year 9000) would select `2022_file.asdf`.
#### Dissecting the example selector
Now to return to our `nircam` `dark` .rmap. Let's print it out again, since at this point it has floated away up the page:
```
print(nircam_dark_rmap)
```
Here we have a two-tiered selector. The first tier is a `Match` selector on three dataset metadata fields, as we can see in the header `parkey`: `META.EXPOSURE.TYPE`, `META.INSTRUMENT.DETECTOR`, and `META.SUBARRAY.NAME`. The second tier is a `UseAfter` selector on the observation date and time fields. Because `UseAfter` is the second tier, the `Match` values are mostly `UseAfter` instances.
The first entry right away uses four `Match` features that aren't available in a simple `{}` selector. For one thing, it's matching three metadata fields at once. Then there's the special value `N/A`, which is a wildcard that matches any exposure type, but with less weight than other matches (so it will tend to be selected only if a more specific match isn't available). The special value `ANY` is also a wildcard, so it matches any detector, but it is assigned full weight. The `SUB8FP1A|SUB8FP1B` uses the logical-or operator `|` so either of the two subarrays will match. The value of this match rule, `'N/A'`, indicates that no reference file should be returned in this case.
In English, this rule might be described like this: for any exposure type and detector that was used in conjunction with subarrays SUB8FP1A or SUB8FP1B, return no reference file. However, another match rule may override this rule for specific exposure types.
The second entry also starts with a weak wildcard match on exposure type, but continues with specific matches on the `NRCA1` detector and the `FULL` subarray. It then proceeds to the `UseAfter` selector, and selects the `jwst_nircam_dark_0040.fits` file if the observation timestamp is 20th century or later. It's common practice to choose an absurdly early `UseAfter` date to effectively cover all time.
In English, the second rule might be described like this: for any exposure type with the `NCRA1` detector and the `FULL` subarray, select the `jwst_nircam_dark_0040.fits` reference file for observations taken at (effectively) any time.
In the next section, we'll try our hand at writing some .rmap rules.
## Reference rules olympics
Congratulations, you've been chosen to represent your scrum team in the .rmap olympics! For each of the following challenges, edit the `RMAP` variable according to the instructions. Test your changes by executing the "Test your solution" code cell.
### Challenge 1
To celebrate your humble notebook author's birthday, we're going to change the NIRCam `photom` reference file to a special edition just for that day. Modify the following .rmap to select `jwst_nircam_photom_birthday.fits` for the duration of 11/20/2020, but only for the `NRC_IMAGE` exposure type.
```
RMAP = """
header = {
'classes' : ('Match', 'UseAfter'),
'derived_from' : 'jwst_nircam_photom_0009.rmap',
'filekind' : 'PHOTOM',
'instrument' : 'NIRCAM',
'mapping' : 'REFERENCE',
'name' : 'jwst_nircam_photom_0010.rmap',
'observatory' : 'JWST',
'parkey' : (('META.INSTRUMENT.DETECTOR', 'META.EXPOSURE.TYPE'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')),
'sha1sum' : '32715a282c1417c74b06eaac369d1c1bb99ba248',
}
selector = Match({
('NRCA1', 'N/A') : UseAfter({
'1900-01-01 00:00:00' : 'jwst_nircam_photom_0031.fits',
'2014-01-01 00:00:00' : 'jwst_nircam_photom_0048.fits',
}),
('NRCA1', 'NRC_CORON|NRC_FLAT|NRC_FOCUS|NRC_IMAGE|NRC_TACONFIRM|NRC_TACQ|NRC_TSIMAGE') : UseAfter({
'2014-01-01 00:00:00' : 'jwst_nircam_photom_0074.fits',
}),
})
"""
```
#### Test your solution
```
rmap = crds.core.rmap.ReferenceMapping.from_string(RMAP, ignore_checksum=True)
def assert_best_ref(exposure_type, date, filename):
result = rmap.get_best_ref(
{
"META.INSTRUMENT.DETECTOR": "NRCA1",
"META.EXPOSURE.TYPE": exposure_type,
"META.OBSERVATION.DATE": date,
"META.OBSERVATION.TIME": "00:00:00",
}
)
if result != filename:
message = f"Test failed for META.EXPOSURE.TYPE={exposure_type}, META.OBSERVATION.DATE={date}. Expected {filename}, got {result}"
raise AssertionError(message)
assert_best_ref("SOME EXPOSURE TYPE", "1980-01-01", "jwst_nircam_photom_0031.fits")
assert_best_ref("SOME EXPOSURE TYPE", "2014-01-01", "jwst_nircam_photom_0048.fits")
assert_best_ref("SOME EXPOSURE TYPE", "2020-11-20", "jwst_nircam_photom_0048.fits")
for exposure_type in ("NRC_CORON", "NRC_FLAT", "NRC_FOCUS", "NRC_IMAGE", "NRC_TACONFIRM", "NRC_TACQ", "NRC_TSIMAGE"):
assert_best_ref(exposure_type, "2014-01-01", "jwst_nircam_photom_0074.fits")
assert_best_ref(exposure_type, "2020-11-21", "jwst_nircam_photom_0074.fits")
for exposure_type in ("NRC_CORON", "NRC_FLAT", "NRC_FOCUS", "NRC_TACONFIRM", "NRC_TACQ", "NRC_TSIMAGE"):
assert_best_ref(exposure_type, "2020-11-20", "jwst_nircam_photom_0074.fits")
assert_best_ref("NRC_IMAGE", "2020-11-20", "jwst_nircam_photom_birthday.fits")
print("Success!")
```
### Challenge 2
Oh no, MIRI was struck by rogue fireworks and the previously stable flat field correction completely changed! Add time-dependence to the following .rmap. For each match case, use the existing reference file up to 10pm UTC on 7/4/2024, but switch to the following files (identified by band) at that time:
`LONG`: jwst_miri_flat_0600.fits
`MEDIUM`: jwst_miri_flat_0601.fits
`SHORT`: jwst_miri_flat_0602.fits
```
RMAP = """
header = {
'classes' : ('Match',),
'derived_from' : 'jwst_miri_flat_0045.rmap',
'filekind' : 'FLAT',
'instrument' : 'MIRI',
'mapping' : 'REFERENCE',
'name' : 'jwst_miri_flat_0046.rmap',
'observatory' : 'JWST',
'parkey' : (('META.INSTRUMENT.DETECTOR', 'META.INSTRUMENT.FILTER', 'META.INSTRUMENT.BAND', 'META.EXPOSURE.READPATT', 'META.SUBARRAY.NAME'),),
'sha1sum' : '1b42da81d62fb32d927911f3dcae05a980bcf939',
}
selector = Match({
('MIRIFULONG', 'N/A', 'LONG', 'N/A', 'FULL') : 'jwst_miri_flat_0541.fits',
('MIRIFULONG', 'N/A', 'MEDIUM', 'N/A', 'FULL') : 'jwst_miri_flat_0539.fits',
('MIRIFULONG', 'N/A', 'SHORT', 'N/A', 'FULL') : 'jwst_miri_flat_0542.fits',
})
"""
```
#### Test your solution
```
rmap = crds.core.rmap.ReferenceMapping.from_string(RMAP, ignore_checksum=True)
def assert_best_ref(band, date, time, filename):
result = rmap.get_best_ref(
{
"META.INSTRUMENT.DETECTOR": "MIRIFULONG",
"META.INSTRUMENT.BAND": band,
"META.SUBARRAY.NAME": "FULL",
"META.OBSERVATION.DATE": date,
"META.OBSERVATION.TIME": time,
}
)
if result != filename:
message = f"Test failed for META.EXPOSURE.BAND={band}, META.OBSERVATION.DATE={date}, META.OBSERVATION.TIME={time}. Expected {filename}, got {result}"
raise AssertionError(message)
assert_best_ref("LONG", "2023-01-01", "00:00:00", "jwst_miri_flat_0541.fits")
assert_best_ref("LONG", "2024-07-04", "21:59:59", "jwst_miri_flat_0541.fits")
assert_best_ref("LONG", "2024-07-04", "22:00:00", "jwst_miri_flat_0600.fits")
assert_best_ref("LONG", "2025-01-01", "00:00:00", "jwst_miri_flat_0600.fits")
assert_best_ref("MEDIUM", "2023-01-01", "00:00:00", "jwst_miri_flat_0539.fits")
assert_best_ref("MEDIUM", "2024-07-04", "21:59:59", "jwst_miri_flat_0539.fits")
assert_best_ref("MEDIUM", "2024-07-04", "22:00:00", "jwst_miri_flat_0601.fits")
assert_best_ref("MEDIUM", "2025-01-01", "00:00:00", "jwst_miri_flat_0601.fits")
assert_best_ref("SHORT", "2023-01-01", "00:00:00", "jwst_miri_flat_0542.fits")
assert_best_ref("SHORT", "2024-07-04", "21:59:59", "jwst_miri_flat_0542.fits")
assert_best_ref("SHORT", "2024-07-04", "22:00:00", "jwst_miri_flat_0602.fits")
assert_best_ref("SHORT", "2025-01-01", "00:00:00", "jwst_miri_flat_0602.fits")
print("Success!")
```
### Challenge 3
Construct a selector for the `nirspec` `disperser` reference type with the following rules:
- If the exposure type is `NRS_DARK`, return reference file not applicable. This rule overrides any subsequent rule.
- If the grating is `G140H` and the exposure type one of (`NRS_AUTOWAVE`, `NRS_AUTOFLAT`, or `NRS_TACQ`), return `jwst_nirspec_disperser_0001.asdf`.
- If the grating is `G140H` and the exposure type not already covered by a previous rule, return `jwst_nirspec_disperser_0002.asdf`.
- If the grating is `MIRROR`, return `jwst_nirspec_disperser_0003.asdf` regardless of exposure type (except `NRS_DARK`).
The selector should be time-dependent, but this initial set of files can all share a useafter timestamp of `2020-01-01 00:00:00`.
```
RMAP = """
header = {
'classes' : ('Match', 'UseAfter'),
'derived_from' : 'jwst_nirspec_disperser_0019.rmap',
'filekind' : 'DISPERSER',
'instrument' : 'NIRSPEC',
'mapping' : 'REFERENCE',
'name' : 'jwst_nirspec_disperser_0019.rmap',
'observatory' : 'JWST',
'parkey' : (('META.INSTRUMENT.GRATING', 'META.EXPOSURE.TYPE'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')),
'sha1sum' : 'ad74383edba73deabd88922565b5f8da7237d779',
}
selector = Match({
# ???
})
"""
```
#### Test your solution
```
rmap = crds.core.rmap.ReferenceMapping.from_string(RMAP, ignore_checksum=True)
def assert_best_ref(grating, exposure_type, filename):
result = rmap.get_best_ref(
{
"META.INSTRUMENT.GRATING": grating,
"META.EXPOSURE.TYPE": exposure_type,
"META.OBSERVATION.DATE": "2020-01-01",
"META.OBSERVATION.TIME": "00:00:00",
}
)
if result != filename:
message = f"Test failed for META.INSTRUMENT.GRATING={grating}, META.EXPOSURE.TYPE={exposure_type}. Expected {filename}, got {result}"
raise AssertionError(message)
for grating in ["G140H", "MIRROR", "PRISM"]:
assert_best_ref(grating, "NRS_DARK", "NOT FOUND n/a")
for exposure_type in ["NRS_AUTOWAVE", "NRS_AUTOFLAT", "NRS_TACQ"]:
assert_best_ref("G140H", exposure_type, "jwst_nirspec_disperser_0001.asdf")
import random
import string
random_exposure_type = "NRS_" + "".join([random.choice(string.ascii_uppercase) for _ in range(8)])
assert_best_ref("G140H", random_exposure_type, "jwst_nirspec_disperser_0002.asdf")
for exposure_type in ["NRS_AUTOWAVE", "NRS_AUTOFLAT", "NRS_TACQ", random_exposure_type]:
assert_best_ref("MIRROR", exposure_type, "jwst_nirspec_disperser_0003.asdf")
assert_best_ref("PRISM", exposure_type, "NOT FOUND No match found.")
print("Success!")
```
### Challenge 4
Construct a selector for the `nirspec` `dflat` reference type with the following rules:
- For the `NRS1` detector and any exposure type that begins with `NRS_` select the `jwst_nirspec_dflat_0001.fits` reference file. Other exposure types should select `jwst_nirspec_dflat_0002.fits`.
- For the `NRS2` detector and the following exposure types: `NRS_MSATA`, `NRS_WATA`, `NRS_CONFIRM`, select `jwst_nirspec_dflat_0003.fits`. For `NRS_FOCUS`, select `jwst_nirspec_dflat_0004.fits`. Other exposure types should select `jwst_nirspec_dflat_0005.fits`.
The selector should be time-dependent, but this initial set of files can all share a useafter timestamp of `2020-01-01 00:00:00`.
Hint: you will need to use a `Match` feature that hasn't been discussed in this notebook. Consult the [CRDS User Manual](https://jwst-crds-bit.stsci.edu/static/users_guide/rmap_syntax.html) for assistance.
```
RMAP = """
header = {
'classes' : ('Match', 'UseAfter'),
'derived_from' : 'jwst_nirspec_dflat_0005.rmap',
'filekind' : 'DFLAT',
'instrument' : 'NIRSPEC',
'mapping' : 'REFERENCE',
'name' : 'jwst_nirspec_dflat_0005.rmap',
'observatory' : 'JWST',
'parkey' : (('META.INSTRUMENT.DETECTOR', 'META.EXPOSURE.TYPE'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')),
'sha1sum' : '3ee07dcd1fe41ad6d5e4e1b4dbcf3eaa4369659e',
}
selector = Match({
# ???
})
"""
```
#### Test your solution
```
rmap = crds.core.rmap.ReferenceMapping.from_string(RMAP, ignore_checksum=True)
def assert_best_ref(detector, exposure_type, filename):
result = rmap.get_best_ref(
{
"META.INSTRUMENT.DETECTOR": detector,
"META.EXPOSURE.TYPE": exposure_type,
"META.OBSERVATION.DATE": "2020-01-01",
"META.OBSERVATION.TIME": "00:00:00",
}
)
if result != filename:
message = f"Test failed for META.INSTRUMENT.DETECTOR={detector}, META.EXPOSURE.TYPE={exposure_type}. Expected {filename}, got {result}"
raise AssertionError(message)
import random
import string
random_nrs_exposure_type = "NRS_" + "".join([random.choice(string.ascii_uppercase) for _ in range(random.randint(4, 30))])
random_other_exposure_type = "".join([random.choice(string.ascii_uppercase) for _ in range(random.randint(4, 30))])
for exposure_type in ["NRS_MSATA", "NRS_WATA", "NRS_CONFIRM", random_nrs_exposure_type]:
assert_best_ref("NRS1", exposure_type, "jwst_nirspec_dflat_0001.fits")
assert_best_ref("NRS1", random_other_exposure_type, "jwst_nirspec_dflat_0002.fits")
for exposure_type in ["NRS_MSATA", "NRS_WATA", "NRS_CONFIRM"]:
assert_best_ref("NRS2", exposure_type, "jwst_nirspec_dflat_0003.fits")
assert_best_ref("NRS2", "NRS_FOCUS", "jwst_nirspec_dflat_0004.fits")
for exposure_type in [random_nrs_exposure_type, random_other_exposure_type]:
assert_best_ref("NRS2", exposure_type, "jwst_nirspec_dflat_0005.fits")
print("Success!")
```
### Challenge 5
You're throwing a series of dinner parties! You've stored your favorite recipes in individual ASDF files and need an .rmap that will select them based on metadata from your guest lists. A guest list has the following metadata available:
**META.PARTY.GUEST_COUNT**: A positive integer.
**META.PARTY.DIET**: One of `VEGAN`, `VEGETARIAN`, or `OMNIVORE`.
**META.PARTY.ALLERGEN**: A string identifier for a single allergen. The full set of allergens is unknown, but you're confident that your recipe metadata is complete.
**META.PARTY.DATE**: The date of the party.
**META.PARTY.TIME**: The time of the party.
Here are your recipes:
**mac_and_cheese.asdf**
```
Servings: 100
Allergens: WHEAT, DAIRY
Incompatible diets: VEGAN
Seasonal availability: (unrestricted)
```
**mac_and_cheese_with_asparagus.asdf**
```
Servings: 100
Allergens: WHEAT, DAIRY
Incompatible diets: VEGAN
Seasonal availability: February 1st, 2022 until June 1st, 2022
```
**stir_fry_with_beef.asdf**
```
Servings: 4
Allergens: (none)
Incompatible diets: VEGAN, VEGETARIAN
Seasonal availability: (unrestricted)
```
**oatmeal.asdf**
```
Servings: (unlimited)
Allergens: (none)
Incompatible diets: (none)
Seasonal availability: (unrestricted)
```
**oatmeal_with_apples.asdf**
```
Servings: (unlimited)
Allergens: (none)
Incompatible diets: (none)
Seasonal availability: August 1st, 2022 until November 1st, 2022
```
Serving oatmeal should be avoided whenever possible. Prioritize seasonal vegetables. In anticipation of continued SARS-CoV-2 restrictions, the parties are planned for the year 2022.
```
RMAP = """
header = {
# ???
}
selector = Match({
# ???
})
"""
```
#### Test your solution
```
rmap = crds.core.rmap.ReferenceMapping.from_string(RMAP, ignore_checksum=True)
def assert_best_ref(guest_count, diet, allergen, date, filename):
result = rmap.get_best_ref(
{
"META.PARTY.GUEST_COUNT": str(guest_count),
"META.PARTY.DIET": diet,
"META.PARTY.ALLERGEN": allergen,
"META.PARTY.DATE": date,
"META.PARTY.TIME": "00:00:00",
}
)
if result != filename:
message = f"Test failed for META.PARTY.GUEST_COUNT={guest_count}, META.PARTY.DIET={diet}, META.PARTY.ALLERGEN={allergen}, META.PARTY.DATE={date}. Expected {filename}, got {result}"
raise AssertionError(message)
for guest_count in [101, 1000, 10000]:
assert_best_ref(guest_count, "OMNIVORE", "N/A", "2022-07-01", "oatmeal.asdf")
assert_best_ref(guest_count, "OMNIVORE", "N/A", "2022-08-15", "oatmeal_with_apples.asdf")
assert_best_ref(guest_count, "OMNIVORE", "N/A", "2022-11-20", "oatmeal.asdf")
for guest_count in range(5, 100):
assert_best_ref(guest_count, "OMNIVORE", "N/A", "2022-01-05", "mac_and_cheese.asdf")
assert_best_ref(guest_count, "OMNIVORE", "N/A", "2022-03-08", "mac_and_cheese_with_asparagus.asdf")
assert_best_ref(guest_count, "VEGAN", "N/A", "2022-09-20", "oatmeal_with_apples.asdf")
assert_best_ref(guest_count, "OMNIVORE", "WHEAT", "2022-09-20", "oatmeal_with_apples.asdf")
assert_best_ref(guest_count, "OMNIVORE", "DAIRY", "2022-09-20", "oatmeal_with_apples.asdf")
assert_best_ref(guest_count, "OMNIVORE", "KANGAROO", "2022-01-05", "mac_and_cheese.asdf")
assert_best_ref(guest_count, "OMNIVORE", "KANGAROO", "2022-03-08", "mac_and_cheese_with_asparagus.asdf")
for guest_count in range(1, 5):
assert_best_ref(guest_count, "OMNIVORE", "WHEAT", "2022-05-01", "stir_fry_with_beef.asdf")
assert_best_ref(guest_count, "OMNIVORE", "DAIRY", "2022-05-01", "stir_fry_with_beef.asdf")
assert_best_ref(guest_count, "VEGETARIAN", "WHEAT", "2022-05-01", "oatmeal.asdf")
assert_best_ref(guest_count, "VEGAN", "WHEAT", "2022-05-01", "oatmeal.asdf")
print("Success!")
```
## Further reading
The CRDS User Manual includes [detailed documentation](https://jwst-crds-bit.stsci.edu/static/users_guide/rmap_syntax.html) on the subject of CRDS rules files.
| github_jupyter |
This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# Solution Notebook
## Problem: Implement a queue using two stacks.
* [Constraints](#Constraints)
* [Test Cases](#Test-Cases)
* [Algorithm](#Algorithm)
* [Code](#Code)
* [Unit Test](#Unit-Test)
## Constraints
* Do we expect the methods to be enqueue and dequeue?
* Yes
* Can we assume we already have a stack class that can be used for this problem?
* Yes
* Can we push a None value to the Stack?
* No
* Can we assume this fits memory?
* Yes
## Test Cases
* Enqueue and dequeue on empty stack
* Enqueue and dequeue on non-empty stack
* Multiple enqueue in a row
* Multiple dequeue in a row
* Enqueue after a dequeue
* Dequeue after an enqueue
## Algorithm
We'll use two stacks (left and right) to implement the queue. The left stack will be used for enqueue and the right stack will be used for dequeue.
To prevent multiple dequeue calls from needlessly shifting elements around between the stacks, we'll shift elements in a lazy manner.
### Enqueue
* If right stack is not empty
* Shift the elements of the right stack to the left stack
* Push the data to the left stack
Complexity:
* Time: O(n)
* Space: O(n)
### Dequeue
* If the left stack is not empty
* Shift the elements of the left stack to the right stack
* Pop from the right stack and return the data
Complexity:
* Time: O(n)
* Space: O(n)
### Shift Stacks
* While the source stack has elements:
* Pop from the source stack and push the data to the destination stack
Complexity:
* Time: O(n)
* Space: O(1)
## Code
```
%run ../stack/stack.py
class QueueFromStacks(object):
def __init__(self):
self.left_stack = Stack()
self.right_stack = Stack()
def shift_stacks(self, source, destination):
while source.peek() is not None:
destination.push(source.pop())
def enqueue(self, data):
self.shift_stacks(self.right_stack, self.left_stack)
self.left_stack.push(data)
def dequeue(self):
self.shift_stacks(self.left_stack, self.right_stack)
return self.right_stack.pop()
```
## Unit Test
```
%%writefile test_queue_from_stacks.py
from nose.tools import assert_equal
class TestQueueFromStacks(object):
def test_queue_from_stacks(self):
print('Test: Dequeue on empty stack')
queue = QueueFromStacks()
assert_equal(queue.dequeue(), None)
print('Test: Enqueue on empty stack')
print('Test: Enqueue on non-empty stack')
print('Test: Multiple enqueue in a row')
num_items = 3
for i in range(0, num_items):
queue.enqueue(i)
print('Test: Dequeue on non-empty stack')
print('Test: Dequeue after an enqueue')
assert_equal(queue.dequeue(), 0)
print('Test: Multiple dequeue in a row')
assert_equal(queue.dequeue(), 1)
assert_equal(queue.dequeue(), 2)
print('Test: Enqueue after a dequeue')
queue.enqueue(5)
assert_equal(queue.dequeue(), 5)
print('Success: test_queue_from_stacks')
def main():
test = TestQueueFromStacks()
test.test_queue_from_stacks()
if __name__ == '__main__':
main()
%run -i test_queue_from_stacks.py
```
| github_jupyter |
# Split datasets into train, validation, and test
This module can use for processing split datasets. You need modify the ratio of train, validation, and test. And you can modify output directory you want and input directory you have.
```
# -*- coding: utf-8 -*-
""" Split datasets into train, validation, and test
This module can use for processing split datasets. You need modify the ratio of
train, validation, and test datasetes. And you can modify output directory you
want and input directory you have.
################################################################################
# Author: Weikun Han <weikunhan@gmail.com>
# Crate Date: 03/6/2018
# Update:
# Reference: https://github.com/jhetherly/EnglishSpeechUpsampler
################################################################################
"""
import os
import csv
import numpy as np
def write_csv(filename, pairs):
"""The function to wirte
Args:
param1 (str): filename
param2 (list): pairs
"""
with open(filename, 'w') as csvfile:
writer = csv.writer(csvfile)
for n in pairs:
writer.writerow(n)
if __name__ == '__main__':
# Please modify input path to locate you file
DATASETS_ROOT_DIR = './datasets'
OUTPUT_DIR = os.path.join(DATASETS_ROOT_DIR, 'final_dataset')
# Define ratio for train, validation, and test datasetes
train_fraction = 0.6
validation_fraction = 0.2
test_fraction = 0.2
# Reset random generator
np.random.seed(0)
# Check location to save datasets
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
print('Will send .csv dataset to {}'.format(OUTPUT_DIR))
# Create list to store each original and noise file name pair
original_noise_pairs = []
input_original_path = os.path.join(DATASETS_ROOT_DIR, 'TEDLIUM_5S')
input_noise_path = os.path.join(DATASETS_ROOT_DIR,
'TEDLIUM_noise_sample_5S')
for filename in os.listdir(input_original_path):
# Link same filename in noise path
filename_component = filename.split('_')
filename_noise = (filename_component[0] +
'_' +
filename_component[1] +
'_' +
'noise_sample' +
'_' +
filename_component[2])
input_original_filename = os.path.join(input_original_path,
filename)
input_noise_filename = os.path.join(input_noise_path, filename_noise)
if not os.path.isfile(input_original_filename):
continue
original_noise_pairs.append(
[input_original_filename, input_noise_filename])
# Shuffle the datasets
np.random.shuffle(original_noise_pairs)
datasets_size = len(original_noise_pairs)
# Create indexs
validation_start_index = 0
validation_end_index = (validation_start_index +
int(datasets_size * validation_fraction))
test_start_index = validation_end_index
test_end_index = (test_start_index +
int(datasets_size * test_fraction))
train_start_index = test_end_index
# Save pairs into .csv
validation_original_noise_pairs = original_noise_pairs[
validation_start_index:validation_end_index]
write_csv(os.path.join(OUTPUT_DIR, 'validation_files.csv'),
validation_original_noise_pairs)
test_original_noise_pairs = original_noise_pairs[
test_start_index : test_end_index]
write_csv(os.path.join(OUTPUT_DIR, 'test_files.csv'),
test_original_noise_pairs)
train_original_noise_pairs = original_noise_pairs[
train_start_index :]
write_csv(os.path.join(OUTPUT_DIR, 'train_files.csv'),
original_noise_pairs)
```
| github_jupyter |
```
#hide
#skip
! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab
# default_exp layers
# default_cls_lvl 3
#export
from fastai.imports import *
from fastai.torch_imports import *
from fastai.torch_core import *
from torch.nn.utils import weight_norm, spectral_norm
#hide
from nbdev.showdoc import *
```
# Layers
> Custom fastai layers and basic functions to grab them.
## Basic manipulations and resize
```
#export
def module(*flds, **defaults):
"Decorator to create an `nn.Module` using `f` as `forward` method"
pa = [inspect.Parameter(o, inspect.Parameter.POSITIONAL_OR_KEYWORD) for o in flds]
pb = [inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD, default=v)
for k,v in defaults.items()]
params = pa+pb
all_flds = [*flds,*defaults.keys()]
def _f(f):
class c(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
for i,o in enumerate(args): kwargs[all_flds[i]] = o
kwargs = merge(defaults,kwargs)
for k,v in kwargs.items(): setattr(self,k,v)
__repr__ = basic_repr(all_flds)
forward = f
c.__signature__ = inspect.Signature(params)
c.__name__ = c.__qualname__ = f.__name__
c.__doc__ = f.__doc__
return c
return _f
#export
@module()
def Identity(self, x):
"Do nothing at all"
return x
test_eq(Identity()(1), 1)
# export
@module('func')
def Lambda(self, x):
"An easy way to create a pytorch layer for a simple `func`"
return self.func(x)
def _add2(x): return x+2
tst = Lambda(_add2)
x = torch.randn(10,20)
test_eq(tst(x), x+2)
tst2 = pickle.loads(pickle.dumps(tst))
test_eq(tst2(x), x+2)
tst
# export
class PartialLambda(Lambda):
"Layer that applies `partial(func, **kwargs)`"
def __init__(self, func, **kwargs):
super().__init__(partial(func, **kwargs))
self.repr = f'{func.__name__}, {kwargs}'
def forward(self, x): return self.func(x)
def __repr__(self): return f'{self.__class__.__name__}({self.repr})'
def test_func(a,b=2): return a+b
tst = PartialLambda(test_func, b=5)
test_eq(tst(x), x+5)
# export
@module(full=False)
def Flatten(self, x):
"Flatten `x` to a single dimension, e.g. at end of a model. `full` for rank-1 tensor"
return TensorBase(x.view(-1) if self.full else x.view(x.size(0), -1))
tst = Flatten()
x = torch.randn(10,5,4)
test_eq(tst(x).shape, [10,20])
tst = Flatten(full=True)
test_eq(tst(x).shape, [200])
# export
class View(Module):
"Reshape `x` to `size`"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view(self.size)
tst = View(10,5,4)
test_eq(tst(x).shape, [10,5,4])
# export
class ResizeBatch(Module):
"Reshape `x` to `size`, keeping batch dim the same size"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view((x.size(0),) + self.size)
tst = ResizeBatch(5,4)
test_eq(tst(x).shape, [10,5,4])
# export
@module()
def Debugger(self,x):
"A module to debug inside a model."
set_trace()
return x
# export
def sigmoid_range(x, low, high):
"Sigmoid function with range `(low, high)`"
return torch.sigmoid(x) * (high - low) + low
test = tensor([-10.,0.,10.])
assert torch.allclose(sigmoid_range(test, -1, 2), tensor([-1.,0.5, 2.]), atol=1e-4, rtol=1e-4)
assert torch.allclose(sigmoid_range(test, -5, -1), tensor([-5.,-3.,-1.]), atol=1e-4, rtol=1e-4)
assert torch.allclose(sigmoid_range(test, 2, 4), tensor([2., 3., 4.]), atol=1e-4, rtol=1e-4)
# export
@module('low','high')
def SigmoidRange(self, x):
"Sigmoid module with range `(low, high)`"
return sigmoid_range(x, self.low, self.high)
tst = SigmoidRange(-1, 2)
assert torch.allclose(tst(test), tensor([-1.,0.5, 2.]), atol=1e-4, rtol=1e-4)
```
## Pooling layers
```
# export
class AdaptiveConcatPool1d(Module):
"Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`"
def __init__(self, size=None):
self.size = size or 1
self.ap = nn.AdaptiveAvgPool1d(self.size)
self.mp = nn.AdaptiveMaxPool1d(self.size)
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
# export
class AdaptiveConcatPool2d(Module):
"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`"
def __init__(self, size=None):
self.size = size or 1
self.ap = nn.AdaptiveAvgPool2d(self.size)
self.mp = nn.AdaptiveMaxPool2d(self.size)
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
```
If the input is `bs x nf x h x h`, the output will be `bs x 2*nf x 1 x 1` if no size is passed or `bs x 2*nf x size x size`
```
tst = AdaptiveConcatPool2d()
x = torch.randn(10,5,4,4)
test_eq(tst(x).shape, [10,10,1,1])
max1 = torch.max(x, dim=2, keepdim=True)[0]
maxp = torch.max(max1, dim=3, keepdim=True)[0]
test_eq(tst(x)[:,:5], maxp)
test_eq(tst(x)[:,5:], x.mean(dim=[2,3], keepdim=True))
tst = AdaptiveConcatPool2d(2)
test_eq(tst(x).shape, [10,10,2,2])
# export
class PoolType: Avg,Max,Cat = 'Avg','Max','Cat'
#export
def adaptive_pool(pool_type):
return nn.AdaptiveAvgPool2d if pool_type=='Avg' else nn.AdaptiveMaxPool2d if pool_type=='Max' else AdaptiveConcatPool2d
# export
class PoolFlatten(nn.Sequential):
"Combine `nn.AdaptiveAvgPool2d` and `Flatten`."
def __init__(self, pool_type=PoolType.Avg): super().__init__(adaptive_pool(pool_type)(1), Flatten())
tst = PoolFlatten()
test_eq(tst(x).shape, [10,5])
test_eq(tst(x), x.mean(dim=[2,3]))
```
## BatchNorm layers
```
# export
NormType = Enum('NormType', 'Batch BatchZero Weight Spectral Instance InstanceZero')
#export
def _get_norm(prefix, nf, ndim=2, zero=False, **kwargs):
"Norm layer with `nf` features and `ndim` initialized depending on `norm_type`."
assert 1 <= ndim <= 3
bn = getattr(nn, f"{prefix}{ndim}d")(nf, **kwargs)
if bn.affine:
bn.bias.data.fill_(1e-3)
bn.weight.data.fill_(0. if zero else 1.)
return bn
#export
@delegates(nn.BatchNorm2d)
def BatchNorm(nf, ndim=2, norm_type=NormType.Batch, **kwargs):
"BatchNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."
return _get_norm('BatchNorm', nf, ndim, zero=norm_type==NormType.BatchZero, **kwargs)
#export
@delegates(nn.InstanceNorm2d)
def InstanceNorm(nf, ndim=2, norm_type=NormType.Instance, affine=True, **kwargs):
"InstanceNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."
return _get_norm('InstanceNorm', nf, ndim, zero=norm_type==NormType.InstanceZero, affine=affine, **kwargs)
```
`kwargs` are passed to `nn.BatchNorm` and can be `eps`, `momentum`, `affine` and `track_running_stats`.
```
tst = BatchNorm(15)
assert isinstance(tst, nn.BatchNorm2d)
test_eq(tst.weight, torch.ones(15))
tst = BatchNorm(15, norm_type=NormType.BatchZero)
test_eq(tst.weight, torch.zeros(15))
tst = BatchNorm(15, ndim=1)
assert isinstance(tst, nn.BatchNorm1d)
tst = BatchNorm(15, ndim=3)
assert isinstance(tst, nn.BatchNorm3d)
tst = InstanceNorm(15)
assert isinstance(tst, nn.InstanceNorm2d)
test_eq(tst.weight, torch.ones(15))
tst = InstanceNorm(15, norm_type=NormType.InstanceZero)
test_eq(tst.weight, torch.zeros(15))
tst = InstanceNorm(15, ndim=1)
assert isinstance(tst, nn.InstanceNorm1d)
tst = InstanceNorm(15, ndim=3)
assert isinstance(tst, nn.InstanceNorm3d)
```
If `affine` is false the weight should be `None`
```
test_eq(BatchNorm(15, affine=False).weight, None)
test_eq(InstanceNorm(15, affine=False).weight, None)
# export
class BatchNorm1dFlat(nn.BatchNorm1d):
"`nn.BatchNorm1d`, but first flattens leading dimensions"
def forward(self, x):
if x.dim()==2: return super().forward(x)
*f,l = x.shape
x = x.contiguous().view(-1,l)
return super().forward(x).view(*f,l)
tst = BatchNorm1dFlat(15)
x = torch.randn(32, 64, 15)
y = tst(x)
mean = x.mean(dim=[0,1])
test_close(tst.running_mean, 0*0.9 + mean*0.1)
var = (x-mean).pow(2).mean(dim=[0,1])
test_close(tst.running_var, 1*0.9 + var*0.1, eps=1e-4)
test_close(y, (x-mean)/torch.sqrt(var+1e-5) * tst.weight + tst.bias, eps=1e-4)
# export
class LinBnDrop(nn.Sequential):
"Module grouping `BatchNorm1d`, `Dropout` and `Linear` layers"
def __init__(self, n_in, n_out, bn=True, p=0., act=None, lin_first=False):
layers = [BatchNorm(n_out if lin_first else n_in, ndim=1)] if bn else []
if p != 0: layers.append(nn.Dropout(p))
lin = [nn.Linear(n_in, n_out, bias=not bn)]
if act is not None: lin.append(act)
layers = lin+layers if lin_first else layers+lin
super().__init__(*layers)
```
The `BatchNorm` layer is skipped if `bn=False`, as is the dropout if `p=0.`. Optionally, you can add an activation for after the linear layer with `act`.
```
tst = LinBnDrop(10, 20)
mods = list(tst.children())
test_eq(len(mods), 2)
assert isinstance(mods[0], nn.BatchNorm1d)
assert isinstance(mods[1], nn.Linear)
tst = LinBnDrop(10, 20, p=0.1)
mods = list(tst.children())
test_eq(len(mods), 3)
assert isinstance(mods[0], nn.BatchNorm1d)
assert isinstance(mods[1], nn.Dropout)
assert isinstance(mods[2], nn.Linear)
tst = LinBnDrop(10, 20, act=nn.ReLU(), lin_first=True)
mods = list(tst.children())
test_eq(len(mods), 3)
assert isinstance(mods[0], nn.Linear)
assert isinstance(mods[1], nn.ReLU)
assert isinstance(mods[2], nn.BatchNorm1d)
tst = LinBnDrop(10, 20, bn=False)
mods = list(tst.children())
test_eq(len(mods), 1)
assert isinstance(mods[0], nn.Linear)
```
## Inits
```
#export
def sigmoid(input, eps=1e-7):
"Same as `torch.sigmoid`, plus clamping to `(eps,1-eps)"
return input.sigmoid().clamp(eps,1-eps)
#export
def sigmoid_(input, eps=1e-7):
"Same as `torch.sigmoid_`, plus clamping to `(eps,1-eps)"
return input.sigmoid_().clamp_(eps,1-eps)
#export
from torch.nn.init import kaiming_uniform_,uniform_,xavier_uniform_,normal_
#export
def vleaky_relu(input, inplace=True):
"`F.leaky_relu` with 0.3 slope"
return F.leaky_relu(input, negative_slope=0.3, inplace=inplace)
#export
for o in F.relu,nn.ReLU,F.relu6,nn.ReLU6,F.leaky_relu,nn.LeakyReLU:
o.__default_init__ = kaiming_uniform_
#export
for o in F.sigmoid,nn.Sigmoid,F.tanh,nn.Tanh,sigmoid,sigmoid_:
o.__default_init__ = xavier_uniform_
#export
def init_default(m, func=nn.init.kaiming_normal_):
"Initialize `m` weights with `func` and set `bias` to 0."
if func and hasattr(m, 'weight'): func(m.weight)
with torch.no_grad():
if getattr(m, 'bias', None) is not None: m.bias.fill_(0.)
return m
#export
def init_linear(m, act_func=None, init='auto', bias_std=0.01):
if getattr(m,'bias',None) is not None and bias_std is not None:
if bias_std != 0: normal_(m.bias, 0, bias_std)
else: m.bias.data.zero_()
if init=='auto':
if act_func in (F.relu_,F.leaky_relu_): init = kaiming_uniform_
else: init = getattr(act_func.__class__, '__default_init__', None)
if init is None: init = getattr(act_func, '__default_init__', None)
if init is not None: init(m.weight)
```
## Convolutions
```
#export
def _conv_func(ndim=2, transpose=False):
"Return the proper conv `ndim` function, potentially `transposed`."
assert 1 <= ndim <=3
return getattr(nn, f'Conv{"Transpose" if transpose else ""}{ndim}d')
#hide
test_eq(_conv_func(ndim=1),torch.nn.modules.conv.Conv1d)
test_eq(_conv_func(ndim=2),torch.nn.modules.conv.Conv2d)
test_eq(_conv_func(ndim=3),torch.nn.modules.conv.Conv3d)
test_eq(_conv_func(ndim=1, transpose=True),torch.nn.modules.conv.ConvTranspose1d)
test_eq(_conv_func(ndim=2, transpose=True),torch.nn.modules.conv.ConvTranspose2d)
test_eq(_conv_func(ndim=3, transpose=True),torch.nn.modules.conv.ConvTranspose3d)
# export
defaults.activation=nn.ReLU
# export
class ConvLayer(nn.Sequential):
"Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and `norm_type` layers."
@delegates(nn.Conv2d)
def __init__(self, ni, nf, ks=3, stride=1, padding=None, bias=None, ndim=2, norm_type=NormType.Batch, bn_1st=True,
act_cls=defaults.activation, transpose=False, init='auto', xtra=None, bias_std=0.01, **kwargs):
if padding is None: padding = ((ks-1)//2 if not transpose else 0)
bn = norm_type in (NormType.Batch, NormType.BatchZero)
inn = norm_type in (NormType.Instance, NormType.InstanceZero)
if bias is None: bias = not (bn or inn)
conv_func = _conv_func(ndim, transpose=transpose)
conv = conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding, **kwargs)
act = None if act_cls is None else act_cls()
init_linear(conv, act, init=init, bias_std=bias_std)
if norm_type==NormType.Weight: conv = weight_norm(conv)
elif norm_type==NormType.Spectral: conv = spectral_norm(conv)
layers = [conv]
act_bn = []
if act is not None: act_bn.append(act)
if bn: act_bn.append(BatchNorm(nf, norm_type=norm_type, ndim=ndim))
if inn: act_bn.append(InstanceNorm(nf, norm_type=norm_type, ndim=ndim))
if bn_1st: act_bn.reverse()
layers += act_bn
if xtra: layers.append(xtra)
super().__init__(*layers)
```
The convolution uses `ks` (kernel size) `stride`, `padding` and `bias`. `padding` will default to the appropriate value (`(ks-1)//2` if it's not a transposed conv) and `bias` will default to `True` the `norm_type` is `Spectral` or `Weight`, `False` if it's `Batch` or `BatchZero`. Note that if you don't want any normalization, you should pass `norm_type=None`.
This defines a conv layer with `ndim` (1,2 or 3) that will be a ConvTranspose if `transpose=True`. `act_cls` is the class of the activation function to use (instantiated inside). Pass `act=None` if you don't want an activation function. If you quickly want to change your default activation, you can change the value of `defaults.activation`.
`init` is used to initialize the weights (the bias are initialized to 0) and `xtra` is an optional layer to add at the end.
```
tst = ConvLayer(16, 32)
mods = list(tst.children())
test_eq(len(mods), 3)
test_eq(mods[1].weight, torch.ones(32))
test_eq(mods[0].padding, (1,1))
x = torch.randn(64, 16, 8, 8)#.cuda()
#Padding is selected to make the shape the same if stride=1
test_eq(tst(x).shape, [64,32,8,8])
#Padding is selected to make the shape half if stride=2
tst = ConvLayer(16, 32, stride=2)
test_eq(tst(x).shape, [64,32,4,4])
#But you can always pass your own padding if you want
tst = ConvLayer(16, 32, padding=0)
test_eq(tst(x).shape, [64,32,6,6])
#No bias by default for Batch NormType
assert mods[0].bias is None
#But can be overridden with `bias=True`
tst = ConvLayer(16, 32, bias=True)
assert first(tst.children()).bias is not None
#For no norm, or spectral/weight, bias is True by default
for t in [None, NormType.Spectral, NormType.Weight]:
tst = ConvLayer(16, 32, norm_type=t)
assert first(tst.children()).bias is not None
#Various n_dim/tranpose
tst = ConvLayer(16, 32, ndim=3)
assert isinstance(list(tst.children())[0], nn.Conv3d)
tst = ConvLayer(16, 32, ndim=1, transpose=True)
assert isinstance(list(tst.children())[0], nn.ConvTranspose1d)
#No activation/leaky
tst = ConvLayer(16, 32, ndim=3, act_cls=None)
mods = list(tst.children())
test_eq(len(mods), 2)
tst = ConvLayer(16, 32, ndim=3, act_cls=partial(nn.LeakyReLU, negative_slope=0.1))
mods = list(tst.children())
test_eq(len(mods), 3)
assert isinstance(mods[2], nn.LeakyReLU)
# #export
# def linear(in_features, out_features, bias=True, act_cls=None, init='auto'):
# "Linear layer followed by optional activation, with optional auto-init"
# res = nn.Linear(in_features, out_features, bias=bias)
# if act_cls: act_cls = act_cls()
# init_linear(res, act_cls, init=init)
# if act_cls: res = nn.Sequential(res, act_cls)
# return res
# #export
# @delegates(ConvLayer)
# def conv1d(ni, nf, ks, stride=1, ndim=1, norm_type=None, **kwargs):
# "Convolutional layer followed by optional activation, with optional auto-init"
# return ConvLayer(ni, nf, ks, stride=stride, ndim=ndim, norm_type=norm_type, **kwargs)
# #export
# @delegates(ConvLayer)
# def conv2d(ni, nf, ks, stride=1, ndim=2, norm_type=None, **kwargs):
# "Convolutional layer followed by optional activation, with optional auto-init"
# return ConvLayer(ni, nf, ks, stride=stride, ndim=ndim, norm_type=norm_type, **kwargs)
# #export
# @delegates(ConvLayer)
# def conv3d(ni, nf, ks, stride=1, ndim=3, norm_type=None, **kwargs):
# "Convolutional layer followed by optional activation, with optional auto-init"
# return ConvLayer(ni, nf, ks, stride=stride, ndim=ndim, norm_type=norm_type, **kwargs)
#export
def AdaptiveAvgPool(sz=1, ndim=2):
"nn.AdaptiveAvgPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"AdaptiveAvgPool{ndim}d")(sz)
#export
def MaxPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
"nn.MaxPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"MaxPool{ndim}d")(ks, stride=stride, padding=padding)
#export
def AvgPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
"nn.AvgPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"AvgPool{ndim}d")(ks, stride=stride, padding=padding, ceil_mode=ceil_mode)
```
## Embeddings
```
# export
def trunc_normal_(x, mean=0., std=1.):
"Truncated normal initialization (approximation)"
# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12
return x.normal_().fmod_(2).mul_(std).add_(mean)
# export
class Embedding(nn.Embedding):
"Embedding layer with truncated normal initialization"
def __init__(self, ni, nf, std=0.01):
super().__init__(ni, nf)
trunc_normal_(self.weight.data, std=std)
```
Truncated normal initialization bounds the distribution to avoid large value. For a given standard deviation `std`, the bounds are roughly `-2*std`, `2*std`.
```
std = 0.02
tst = Embedding(10, 30, std)
assert tst.weight.min() > -2*std
assert tst.weight.max() < 2*std
test_close(tst.weight.mean(), 0, 1e-2)
test_close(tst.weight.std(), std, 0.1)
```
## Self attention
```
# export
class SelfAttention(Module):
"Self attention layer for `n_channels`."
def __init__(self, n_channels):
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels)]
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return ConvLayer(n_in, n_out, ks=1, ndim=1, norm_type=NormType.Spectral, act_cls=None, bias=False)
def forward(self, x):
#Notation from the paper.
size = x.size()
x = x.view(*size[:2],-1)
f,g,h = self.query(x),self.key(x),self.value(x)
beta = F.softmax(torch.bmm(f.transpose(1,2), g), dim=1)
o = self.gamma * torch.bmm(h, beta) + x
return o.view(*size).contiguous()
```
Self-attention layer as introduced in [Self-Attention Generative Adversarial Networks](https://arxiv.org/abs/1805.08318).
Initially, no change is done to the input. This is controlled by a trainable parameter named `gamma` as we return `x + gamma * out`.
```
tst = SelfAttention(16)
x = torch.randn(32, 16, 8, 8)
test_eq(tst(x),x)
```
Then during training `gamma` will probably change since it's a trainable parameter. Let's see what's happening when it gets a nonzero value.
```
tst.gamma.data.fill_(1.)
y = tst(x)
test_eq(y.shape, [32,16,8,8])
```
The attention mechanism requires three matrix multiplications (here represented by 1x1 convs). The multiplications are done on the channel level (the second dimension in our tensor) and we flatten the feature map (which is 8x8 here). As in the paper, we note `f`, `g` and `h` the results of those multiplications.
```
q,k,v = tst.query[0].weight.data,tst.key[0].weight.data,tst.value[0].weight.data
test_eq([q.shape, k.shape, v.shape], [[2, 16, 1], [2, 16, 1], [16, 16, 1]])
f,g,h = map(lambda m: x.view(32, 16, 64).transpose(1,2) @ m.squeeze().t(), [q,k,v])
test_eq([f.shape, g.shape, h.shape], [[32,64,2], [32,64,2], [32,64,16]])
```
The key part of the attention layer is to compute attention weights for each of our location in the feature map (here 8x8 = 64). Those are positive numbers that sum to 1 and tell the model to pay attention to this or that part of the picture. We make the product of `f` and the transpose of `g` (to get something of size bs by 64 by 64) then apply a softmax on the first dimension (to get the positive numbers that sum up to 1). The result can then be multiplied with `h` transposed to get an output of size bs by channels by 64, which we can then be viewed as an output the same size as the original input.
The final result is then `x + gamma * out` as we saw before.
```
beta = F.softmax(torch.bmm(f, g.transpose(1,2)), dim=1)
test_eq(beta.shape, [32, 64, 64])
out = torch.bmm(h.transpose(1,2), beta)
test_eq(out.shape, [32, 16, 64])
test_close(y, x + out.view(32, 16, 8, 8), eps=1e-4)
# export
class PooledSelfAttention2d(Module):
"Pooled self attention layer for 2d."
def __init__(self, n_channels):
self.n_channels = n_channels
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels//2)]
self.out = self._conv(n_channels//2, n_channels)
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return ConvLayer(n_in, n_out, ks=1, norm_type=NormType.Spectral, act_cls=None, bias=False)
def forward(self, x):
n_ftrs = x.shape[2]*x.shape[3]
f = self.query(x).view(-1, self.n_channels//8, n_ftrs)
g = F.max_pool2d(self.key(x), [2,2]).view(-1, self.n_channels//8, n_ftrs//4)
h = F.max_pool2d(self.value(x), [2,2]).view(-1, self.n_channels//2, n_ftrs//4)
beta = F.softmax(torch.bmm(f.transpose(1, 2), g), -1)
o = self.out(torch.bmm(h, beta.transpose(1,2)).view(-1, self.n_channels//2, x.shape[2], x.shape[3]))
return self.gamma * o + x
```
Self-attention layer used in the [Big GAN paper](https://arxiv.org/abs/1809.11096).
It uses the same attention as in `SelfAttention` but adds a max pooling of stride 2 before computing the matrices `g` and `h`: the attention is ported on one of the 2x2 max-pooled window, not the whole feature map. There is also a final matrix product added at the end to the output, before retuning `gamma * out + x`.
```
#export
def _conv1d_spect(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)
nn.init.kaiming_normal_(conv.weight)
if bias: conv.bias.data.zero_()
return spectral_norm(conv)
#export
class SimpleSelfAttention(Module):
def __init__(self, n_in:int, ks=1, sym=False):
self.sym,self.n_in = sym,n_in
self.conv = _conv1d_spect(n_in, n_in, ks, padding=ks//2, bias=False)
self.gamma = nn.Parameter(tensor([0.]))
def forward(self,x):
if self.sym:
c = self.conv.weight.view(self.n_in,self.n_in)
c = (c + c.t())/2
self.conv.weight = c.view(self.n_in,self.n_in,1)
size = x.size()
x = x.view(*size[:2],-1)
convx = self.conv(x)
xxT = torch.bmm(x,x.permute(0,2,1).contiguous())
o = torch.bmm(xxT, convx)
o = self.gamma * o + x
return o.view(*size).contiguous()
```
## PixelShuffle
PixelShuffle introduced in [this article](https://arxiv.org/pdf/1609.05158.pdf) to avoid checkerboard artifacts when upsampling images. If we want an output with `ch_out` filters, we use a convolution with `ch_out * (r**2)` filters, where `r` is the upsampling factor. Then we reorganize those filters like in the picture below:
<img src="images/pixelshuffle.png" alt="Pixelshuffle" width="800" />
```
# export
def icnr_init(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function"
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(x.new_zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
return k.contiguous().view([nf,ni,h,w]).transpose(0, 1)
```
ICNR init was introduced in [this article](https://arxiv.org/abs/1707.02937). It suggests to initialize the convolution that will be used in PixelShuffle so that each of the `r**2` channels get the same weight (so that in the picture above, the 9 colors in a 3 by 3 window are initially the same).
> Note: This is done on the first dimension because PyTorch stores the weights of a convolutional layer in this format: `ch_out x ch_in x ks x ks`.
```
tst = torch.randn(16*4, 32, 1, 1)
tst = icnr_init(tst)
for i in range(0,16*4,4):
test_eq(tst[i],tst[i+1])
test_eq(tst[i],tst[i+2])
test_eq(tst[i],tst[i+3])
# export
class PixelShuffle_ICNR(nn.Sequential):
"Upsample by `scale` from `ni` filters to `nf` (default `ni`), using `nn.PixelShuffle`."
def __init__(self, ni, nf=None, scale=2, blur=False, norm_type=NormType.Weight, act_cls=defaults.activation):
super().__init__()
nf = ifnone(nf, ni)
layers = [ConvLayer(ni, nf*(scale**2), ks=1, norm_type=norm_type, act_cls=act_cls, bias_std=0),
nn.PixelShuffle(scale)]
if norm_type == NormType.Weight:
layers[0][0].weight_v.data.copy_(icnr_init(layers[0][0].weight_v.data))
layers[0][0].weight_g.data.copy_(((layers[0][0].weight_v.data**2).sum(dim=[1,2,3])**0.5)[:,None,None,None])
else:
layers[0][0].weight.data.copy_(icnr_init(layers[0][0].weight.data))
if blur: layers += [nn.ReplicationPad2d((1,0,1,0)), nn.AvgPool2d(2, stride=1)]
super().__init__(*layers)
```
The convolutional layer is initialized with `icnr_init` and passed `act_cls` and `norm_type` (the default of weight normalization seemed to be what's best for super-resolution problems, in our experiments).
The `blur` option comes from [Super-Resolution using Convolutional Neural Networks without Any Checkerboard Artifacts](https://arxiv.org/abs/1806.02658) where the authors add a little bit of blur to completely get rid of checkerboard artifacts.
```
psfl = PixelShuffle_ICNR(16)
x = torch.randn(64, 16, 8, 8)
y = psfl(x)
test_eq(y.shape, [64, 16, 16, 16])
#ICNR init makes every 2x2 window (stride 2) have the same elements
for i in range(0,16,2):
for j in range(0,16,2):
test_eq(y[:,:,i,j],y[:,:,i+1,j])
test_eq(y[:,:,i,j],y[:,:,i ,j+1])
test_eq(y[:,:,i,j],y[:,:,i+1,j+1])
psfl = PixelShuffle_ICNR(16, norm_type=None)
x = torch.randn(64, 16, 8, 8)
y = psfl(x)
test_eq(y.shape, [64, 16, 16, 16])
#ICNR init makes every 2x2 window (stride 2) have the same elements
for i in range(0,16,2):
for j in range(0,16,2):
test_eq(y[:,:,i,j],y[:,:,i+1,j])
test_eq(y[:,:,i,j],y[:,:,i ,j+1])
test_eq(y[:,:,i,j],y[:,:,i+1,j+1])
psfl = PixelShuffle_ICNR(16, norm_type=NormType.Spectral)
x = torch.randn(64, 16, 8, 8)
y = psfl(x)
test_eq(y.shape, [64, 16, 16, 16])
#ICNR init makes every 2x2 window (stride 2) have the same elements
for i in range(0,16,2):
for j in range(0,16,2):
test_eq(y[:,:,i,j],y[:,:,i+1,j])
test_eq(y[:,:,i,j],y[:,:,i ,j+1])
test_eq(y[:,:,i,j],y[:,:,i+1,j+1])
```
## Sequential extensions
```
#export
def sequential(*args):
"Create an `nn.Sequential`, wrapping items with `Lambda` if needed"
if len(args) != 1 or not isinstance(args[0], OrderedDict):
args = list(args)
for i,o in enumerate(args):
if not isinstance(o,nn.Module): args[i] = Lambda(o)
return nn.Sequential(*args)
# export
class SequentialEx(Module):
"Like `nn.Sequential`, but with ModuleList semantics, and can access module input"
def __init__(self, *layers): self.layers = nn.ModuleList(layers)
def forward(self, x):
res = x
for l in self.layers:
res.orig = x
nres = l(res)
# We have to remove res.orig to avoid hanging refs and therefore memory leaks
res.orig, nres.orig = None, None
res = nres
return res
def __getitem__(self,i): return self.layers[i]
def append(self,l): return self.layers.append(l)
def extend(self,l): return self.layers.extend(l)
def insert(self,i,l): return self.layers.insert(i,l)
```
This is useful to write layers that require to remember the input (like a resnet block) in a sequential way.
```
# export
class MergeLayer(Module):
"Merge a shortcut with the result of the module by adding them or concatenating them if `dense=True`."
def __init__(self, dense:bool=False): self.dense=dense
def forward(self, x): return torch.cat([x,x.orig], dim=1) if self.dense else (x+x.orig)
res_block = SequentialEx(ConvLayer(16, 16), ConvLayer(16,16))
res_block.append(MergeLayer()) # just to test append - normally it would be in init params
x = torch.randn(32, 16, 8, 8)
y = res_block(x)
test_eq(y.shape, [32, 16, 8, 8])
test_eq(y, x + res_block[1](res_block[0](x)))
x = TensorBase(torch.randn(32, 16, 8, 8))
y = res_block(x)
test_is(y.orig, None)
```
## Concat
Equivalent to keras.layers.Concatenate, it will concat the outputs of a ModuleList over a given dimension (default the filter dimension)
```
#export
class Cat(nn.ModuleList):
"Concatenate layers outputs over a given dim"
def __init__(self, layers, dim=1):
self.dim=dim
super().__init__(layers)
def forward(self, x): return torch.cat([l(x) for l in self], dim=self.dim)
layers = [ConvLayer(2,4), ConvLayer(2,4), ConvLayer(2,4)]
x = torch.rand(1,2,8,8)
cat = Cat(layers)
test_eq(cat(x).shape, [1,12,8,8])
test_eq(cat(x), torch.cat([l(x) for l in layers], dim=1))
```
## Ready-to-go models
```
# export
class SimpleCNN(nn.Sequential):
"Create a simple CNN with `filters`."
def __init__(self, filters, kernel_szs=None, strides=None, bn=True):
nl = len(filters)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
strides = ifnone(strides , [2]*nl)
layers = [ConvLayer(filters[i], filters[i+1], kernel_szs[i], stride=strides[i],
norm_type=(NormType.Batch if bn and i<nl-1 else None)) for i in range(nl)]
layers.append(PoolFlatten())
super().__init__(*layers)
```
The model is a succession of convolutional layers from `(filters[0],filters[1])` to `(filters[n-2],filters[n-1])` (if `n` is the length of the `filters` list) followed by a `PoolFlatten`. `kernel_szs` and `strides` defaults to a list of 3s and a list of 2s. If `bn=True` the convolutional layers are successions of conv-relu-batchnorm, otherwise conv-relu.
```
tst = SimpleCNN([8,16,32])
mods = list(tst.children())
test_eq(len(mods), 3)
test_eq([[m[0].in_channels, m[0].out_channels] for m in mods[:2]], [[8,16], [16,32]])
```
Test kernel sizes
```
tst = SimpleCNN([8,16,32], kernel_szs=[1,3])
mods = list(tst.children())
test_eq([m[0].kernel_size for m in mods[:2]], [(1,1), (3,3)])
```
Test strides
```
tst = SimpleCNN([8,16,32], strides=[1,2])
mods = list(tst.children())
test_eq([m[0].stride for m in mods[:2]], [(1,1),(2,2)])
#export
class ProdLayer(Module):
"Merge a shortcut with the result of the module by multiplying them."
def forward(self, x): return x * x.orig
#export
inplace_relu = partial(nn.ReLU, inplace=True)
#export
def SEModule(ch, reduction, act_cls=defaults.activation):
nf = math.ceil(ch//reduction/8)*8
return SequentialEx(nn.AdaptiveAvgPool2d(1),
ConvLayer(ch, nf, ks=1, norm_type=None, act_cls=act_cls),
ConvLayer(nf, ch, ks=1, norm_type=None, act_cls=nn.Sigmoid),
ProdLayer())
#export
class ResBlock(Module):
"Resnet block from `ni` to `nh` with `stride`"
@delegates(ConvLayer.__init__)
def __init__(self, expansion, ni, nf, stride=1, groups=1, reduction=None, nh1=None, nh2=None, dw=False, g2=1,
sa=False, sym=False, norm_type=NormType.Batch, act_cls=defaults.activation, ndim=2, ks=3,
pool=AvgPool, pool_first=True, **kwargs):
norm2 = (NormType.BatchZero if norm_type==NormType.Batch else
NormType.InstanceZero if norm_type==NormType.Instance else norm_type)
if nh2 is None: nh2 = nf
if nh1 is None: nh1 = nh2
nf,ni = nf*expansion,ni*expansion
k0 = dict(norm_type=norm_type, act_cls=act_cls, ndim=ndim, **kwargs)
k1 = dict(norm_type=norm2, act_cls=None, ndim=ndim, **kwargs)
convpath = [ConvLayer(ni, nh2, ks, stride=stride, groups=ni if dw else groups, **k0),
ConvLayer(nh2, nf, ks, groups=g2, **k1)
] if expansion == 1 else [
ConvLayer(ni, nh1, 1, **k0),
ConvLayer(nh1, nh2, ks, stride=stride, groups=nh1 if dw else groups, **k0),
ConvLayer(nh2, nf, 1, groups=g2, **k1)]
if reduction: convpath.append(SEModule(nf, reduction=reduction, act_cls=act_cls))
if sa: convpath.append(SimpleSelfAttention(nf,ks=1,sym=sym))
self.convpath = nn.Sequential(*convpath)
idpath = []
if ni!=nf: idpath.append(ConvLayer(ni, nf, 1, act_cls=None, ndim=ndim, **kwargs))
if stride!=1: idpath.insert((1,0)[pool_first], pool(stride, ndim=ndim, ceil_mode=True))
self.idpath = nn.Sequential(*idpath)
self.act = defaults.activation(inplace=True) if act_cls is defaults.activation else act_cls()
def forward(self, x): return self.act(self.convpath(x) + self.idpath(x))
```
This is a resnet block (normal or bottleneck depending on `expansion`, 1 for the normal block and 4 for the traditional bottleneck) that implements the tweaks from [Bag of Tricks for Image Classification with Convolutional Neural Networks](https://arxiv.org/abs/1812.01187). In particular, the last batchnorm layer (if that is the selected `norm_type`) is initialized with a weight (or gamma) of zero to facilitate the flow from the beginning to the end of the network. It also implements optional [Squeeze and Excitation](https://arxiv.org/abs/1709.01507) and grouped convs for [ResNeXT](https://arxiv.org/abs/1611.05431) and similar models (use `dw=True` for depthwise convs).
The `kwargs` are passed to `ConvLayer` along with `norm_type`.
```
#export
def SEBlock(expansion, ni, nf, groups=1, reduction=16, stride=1, **kwargs):
return ResBlock(expansion, ni, nf, stride=stride, groups=groups, reduction=reduction, nh1=nf*2, nh2=nf*expansion, **kwargs)
#export
def SEResNeXtBlock(expansion, ni, nf, groups=32, reduction=16, stride=1, base_width=4, **kwargs):
w = math.floor(nf * (base_width / 64)) * groups
return ResBlock(expansion, ni, nf, stride=stride, groups=groups, reduction=reduction, nh2=w, **kwargs)
#export
def SeparableBlock(expansion, ni, nf, reduction=16, stride=1, base_width=4, **kwargs):
return ResBlock(expansion, ni, nf, stride=stride, reduction=reduction, nh2=nf*2, dw=True, **kwargs)
```
## Swish and Mish
```
#export
from torch.jit import script
#export
@script
def _swish_jit_fwd(x): return x.mul(torch.sigmoid(x))
@script
def _swish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
return grad_output * (x_sigmoid * (1 + x * (1 - x_sigmoid)))
class _SwishJitAutoFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _swish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _swish_jit_bwd(x, grad_output)
#export
def swish(x, inplace=False): return _SwishJitAutoFn.apply(x)
#export
class Swish(Module):
def forward(self, x): return _SwishJitAutoFn.apply(x)
#export
@script
def _mish_jit_fwd(x): return x.mul(torch.tanh(F.softplus(x)))
@script
def _mish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
x_tanh_sp = F.softplus(x).tanh()
return grad_output.mul(x_tanh_sp + x * x_sigmoid * (1 - x_tanh_sp * x_tanh_sp))
class MishJitAutoFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _mish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _mish_jit_bwd(x, grad_output)
#export
def mish(x): return MishJitAutoFn.apply(x)
#export
class Mish(Module):
def forward(self, x): return MishJitAutoFn.apply(x)
#export
for o in swish,Swish,mish,Mish: o.__default_init__ = kaiming_uniform_
```
## Helper functions for submodules
It's easy to get the list of all parameters of a given model. For when you want all submodules (like linear/conv layers) without forgetting lone parameters, the following class wraps those in fake modules.
```
# export
class ParameterModule(Module):
"Register a lone parameter `p` in a module."
def __init__(self, p): self.val = p
def forward(self, x): return x
# export
def children_and_parameters(m):
"Return the children of `m` and its direct parameters not registered in modules."
children = list(m.children())
children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[])
for p in m.parameters():
if id(p) not in children_p: children.append(ParameterModule(p))
return children
class TstModule(Module):
def __init__(self): self.a,self.lin = nn.Parameter(torch.randn(1)),nn.Linear(5,10)
tst = TstModule()
children = children_and_parameters(tst)
test_eq(len(children), 2)
test_eq(children[0], tst.lin)
assert isinstance(children[1], ParameterModule)
test_eq(children[1].val, tst.a)
#export
def has_children(m):
try: next(m.children())
except StopIteration: return False
return True
class A(Module): pass
assert not has_children(A())
assert has_children(TstModule())
# export
def flatten_model(m):
"Return the list of all submodules and parameters of `m`"
return sum(map(flatten_model,children_and_parameters(m)),[]) if has_children(m) else [m]
tst = nn.Sequential(TstModule(), TstModule())
children = flatten_model(tst)
test_eq(len(children), 4)
assert isinstance(children[1], ParameterModule)
assert isinstance(children[3], ParameterModule)
#export
class NoneReduce():
"A context manager to evaluate `loss_func` with none reduce."
def __init__(self, loss_func): self.loss_func,self.old_red = loss_func,None
def __enter__(self):
if hasattr(self.loss_func, 'reduction'):
self.old_red = self.loss_func.reduction
self.loss_func.reduction = 'none'
return self.loss_func
else: return partial(self.loss_func, reduction='none')
def __exit__(self, type, value, traceback):
if self.old_red is not None: self.loss_func.reduction = self.old_red
x,y = torch.randn(5),torch.randn(5)
loss_fn = nn.MSELoss()
with NoneReduce(loss_fn) as loss_func:
loss = loss_func(x,y)
test_eq(loss.shape, [5])
test_eq(loss_fn.reduction, 'mean')
loss_fn = F.mse_loss
with NoneReduce(loss_fn) as loss_func:
loss = loss_func(x,y)
test_eq(loss.shape, [5])
test_eq(loss_fn, F.mse_loss)
#export
def in_channels(m):
"Return the shape of the first weight layer in `m`."
for l in flatten_model(m):
if getattr(l, 'weight', None) is not None and l.weight.ndim==4:
return l.weight.shape[1]
raise Exception('No weight layer')
test_eq(in_channels(nn.Sequential(nn.Conv2d(5,4,3), nn.Conv2d(4,3,3))), 5)
test_eq(in_channels(nn.Sequential(nn.AvgPool2d(4), nn.Conv2d(4,3,3))), 4)
test_eq(in_channels(nn.Sequential(BatchNorm(4), nn.Conv2d(4,3,3))), 4)
test_eq(in_channels(nn.Sequential(InstanceNorm(4), nn.Conv2d(4,3,3))), 4)
test_eq(in_channels(nn.Sequential(InstanceNorm(4, affine=False), nn.Conv2d(4,3,3))), 4)
test_fail(lambda : in_channels(nn.Sequential(nn.AvgPool2d(4))))
```
## Export -
```
#hide
from nbdev.export import *
notebook2script()
```
| github_jupyter |
## Underfitting vs. Overfitting
The exercise below is to illustrate the problems of underfitting and overfitting and how we can use linear regression with polynomial features to approximate nonlinear functions.
The plot shows the function that we want to approximate, which is a part of the cosine function. In addition, the samples from the real function and the approximations of different models are displayed.
**Determine three degrees** which lead to **underfitting**, **correctly fitted** and **overfitted** models to the given data.
**Hint 1**: Is a linear function (polynomial with degree 1) sufficient to fit the training samples?
**Hint 2**: Does a polynomial of degree 3 approximate the true function correctly? Can you think of a better one?
**Hint 3**: Which degrees higher than 3 would best show an overfitted model to the training data? i.e. learns the noise of the training data.
We evaluate quantitatively **overfitting** / **underfitting** by using cross-validation. We calculate the mean squared error (MSE) on the validation set, the higher, the less likely the model generalizes correctly from the training data.
```
# fill in 3 values, first to show underfitting, second to show correctly fitted, third to show overfitting
degrees = [?, ?, ?]
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
%matplotlib inline
def true_fun(X):
return np.cos(1.5 * np.pi * X)
np.random.seed(0)
n_samples = 30
X = np.sort(np.random.rand(n_samples))
y = true_fun(X) + np.random.randn(n_samples) * 0.1
plt.figure(figsize=(14, 5))
for i in range(len(degrees)):
ax = plt.subplot(1, len(degrees), i + 1)
plt.setp(ax, xticks=(), yticks=())
polynomial_features = PolynomialFeatures(degree=degrees[i],
include_bias=False)
linear_regression = LinearRegression()
pipeline = Pipeline([("polynomial_features", polynomial_features),
("linear_regression", linear_regression)])
pipeline.fit(X[:, np.newaxis], y)
# Evaluate the models using crossvalidation
scores = cross_val_score(pipeline, X[:, np.newaxis], y,
scoring="neg_mean_squared_error", cv=10)
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((0, 1))
plt.ylim((-2, 2))
plt.legend(loc="best")
plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
degrees[i], -scores.mean(), scores.std()))
plt.show()
```
For more additional ways, look at plotting [validation curve](http://scikit-learn.org/stable/auto_examples/model_selection/plot_validation_curve.html#sphx-glr-auto-examples-model-selection-plot-validation-curve-py) & [learning curve](http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py).
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import signal
from scipy.optimize import minimize_scalar, minimize
from scipy.interpolate import interp1d
from time import time
import seaborn as sns
import cvxpy as cxv
sns.set_style('darkgrid')
sns.set_context('notebook')
import sys
sys.path.append('..')
from osd import Problem
from osd.components import GaussNoise, SmoothFirstDifference, SparseFirstDiffConvex, Boolean, MarkovChain
from osd.utilities import progress
import cvxpy as cvx
from admm_helpers import markov_process_simulator, run_admm
```
# Convex example, $K=3$
```
def proj_l2_d0(data, theta=1, c=1):
"""Sum of squares"""
x = data
y = cvx.Variable(len(x))
cost = cvx.sum_squares(x - y)
objective = cvx.Minimize(cost)
constraints = [theta * cvx.sum_squares(y) <= c]
problem = cvx.Problem(objective, constraints)
problem.solve(solver='MOSEK')
return y.value
def proj_l1_d0(data, theta=1, c=1):
"""Sum of squares"""
x = data
y = cvx.Variable(len(x))
cost = cvx.sum_squares(x - y)
objective = cvx.Minimize(cost)
constraints = [theta * cvx.sum(cvx.abs(y)) <= c]
problem = cvx.Problem(objective, constraints)
problem.solve(solver='MOSEK')
return y.value
def proj_l1_d1(data, theta=1, c=1):
"""Sum of absolute value of first difference"""
x = data
y = cvx.Variable(len(x))
cost = cvx.sum_squares(x - y)
objective = cvx.Minimize(cost)
constraints = [theta * cvx.sum(cvx.abs(cvx.diff(y, k=1))) <= c]
problem = cvx.Problem(objective, constraints)
problem.solve(solver='MOSEK')
return y.value
def proj_l1_d2(data, theta=1, c=1):
"""Sum of absolute value of second difference"""
x = data
y = cvx.Variable(len(x))
cost = cvx.sum_squares(x - y)
objective = cvx.Minimize(cost)
constraints = [theta * cvx.sum(cvx.abs(cvx.diff(y, k=2))) <= c]
problem = cvx.Problem(objective, constraints)
problem.solve(solver='MOSEK')
return y.value
def proj_l2_d2(data, theta=1, c=1):
"""Sum of squares of second difference"""
x = data
y = cvx.Variable(len(x))
cost = cvx.sum_squares(x - y)
objective = cvx.Minimize(cost)
constraints = [theta * cvx.sum_squares(cvx.diff(y, k=2)) <= c]
problem = cvx.Problem(objective, constraints)
problem.solve(solver='MOSEK')
return y.value
def proj_l2_d1(data, theta=1, c=1):
"""Sum of squares of first difference"""
x = data
y = cvx.Variable(len(x))
cost = cvx.sum_squares(x - y)
objective = cvx.Minimize(cost)
constraints = [theta * cvx.sum_squares(cvx.diff(y, k=1)) <= c]
problem = cvx.Problem(objective, constraints)
problem.solve(solver='MOSEK')
return y.value
def make_data(length, points=None, shifts=None):
if points is None:
points = [0, int(length * 0.2), int(length * 0.55), int(length * 0.85), length]
if shifts is None:
shifts = [0, .5, -0.75, .2]
cp = np.zeros(length)
for ix, shft in enumerate(shifts):
a = points[ix]
b = points[ix + 1]
cp[a:b] = shft
return cp
np.random.seed(4)
T = 200
X_real = np.zeros((3, T))
X_real[0] = 0.15 * np.random.randn(T)
X_real[1] = 5 * proj_l2_d1(np.random.randn(T), theta=3e2)
X_real[1] -= np.average(X_real[1])
X_real[2] = markov_process_simulator([[0.9, 0.1], [0.1, 0.9]], T=T, plot=False)
y = np.sum(X_real, axis=0)
np.random.seed(25)
remove_ix = np.random.choice(np.arange(len(y)), int(len(y) * 0.2), replace=False)
remove_ix.sort()
use_ix = np.ones_like(y, dtype=bool)
use_ix[remove_ix] = False
fig, ax = plt.subplots(nrows=3, sharex=True, figsize=(14, 7))
ax[0].set_title('Smooth component')
ax[0].plot(X_real[1])
ax[1].set_title('boolean component')
ax[1].plot(X_real[2])
ax[2].set_title('Observed signal')
ax[2].plot(np.arange(T)[use_ix], y[use_ix], linewidth=1, marker='.')
ax[2].plot(np.arange(T)[~use_ix], y[~use_ix], linewidth=1, marker='x', color='red', ls='none', label='missing data')
ax[2].legend()
# ax[2].plot(signal1 + signal2, label='true signal minus noise', ls='--')
plt.tight_layout()
plt.show()
K = X_real.shape[0]
fig, ax = plt.subplots(nrows=K+1, sharex=True, figsize=(5.5,2.9))
for k in range(K+1):
if k <= K-1:
ax[k].plot(X_real[k], linewidth=0.75)
ax[k].set_title('component {}'.format(k+1))
else:
ax[k].plot(np.arange(T)[use_ix], y[use_ix], linewidth=1, marker='.', ms=2)
ax[k].plot(np.arange(T)[~use_ix], y[~use_ix], linewidth=1, marker='x', ms=3,
color='red', ls='none', label='missing data', alpha=0.6)
ax[k].set_title('observed, $y$')
ax[k].legend(loc=(1.01, 0.2))
ax[1].set_ylim(-1.25, 1.25)
ax[3].set_ylim(-2, 2)
plt.tight_layout(pad=0.05)
# fig.savefig('/Users/bennetmeyers/Documents/Boyd-work/OSD-presentations/April2021/figs/example-components.pgf')
plt.show()
lambda2 = 1.27e+01
lambda3 = 6.5e-01
# lambda2 = 1e1
# lambda3 = 5e3
c1 = GaussNoise()
c2 = SmoothFirstDifference(theta=lambda2)
p = 0.25
c3 = MarkovChain([[1-p, p], [p, 1-p]], theta=lambda3)
components = [c1, c2, c3]
problem = Problem(y, components)
problem.decompose(admm=True, rho=1, num_iter=100, use_set=use_ix)
sos = np.sum(np.power((y - np.sum(problem.estimates, axis=0))[~use_ix], 2))
sae = np.sum(np.abs((y - np.sum(problem.estimates, axis=0))[~use_ix]))
print('sos: {:.2f}, sae: {:.2f}'.format(sos, sae))
plt.plot(problem.admm_result['obj_vals'])
plt.axvline(problem.admm_result['it'], color='red', ls='--')
plt.yscale('log')
# ylim = (-0.65, 1.2)
plt.plot((y - np.sum(problem.estimates, axis=0)))
plt.plot(np.arange(len(y))[~use_ix], (y - np.sum(problem.estimates, axis=0))[~use_ix], color='red', marker='.', ls='none')
plt.title('holdout errors')
# plt.ylim(*ylim)
# import matplotlib
# sns.set_context('paper')
# matplotlib.use("pgf")
# matplotlib.rcParams.update({
# "pgf.texsystem": "pdflatex",
# 'font.family': 'serif',
# 'text.usetex': True,
# 'pgf.rcfonts': False,
# })
K = len(components)
fs = np.array([5.5,2.9])
fig, ax = plt.subplots(nrows=K, sharex=True, figsize=2*fs)
for k in range(K):
if k > 0:
true = X_real[k]
est = problem.estimates[k]
ax[k].plot(true, label='true', linewidth=0.75, alpha=0.5)
ax[k].plot(est, label='estimated', linewidth=0.75, alpha=0.5)
ax[k].set_title('Component {}'.format(k+1))
else:
ax[k].plot(
np.arange(T)[use_ix],
np.sum(X_real, axis=0)[use_ix],
label='observed', linewidth=0.5, marker='.', color='green', ms=1, alpha=0.5
)
ax[k].plot(
np.arange(T)[~use_ix],
np.sum(X_real, axis=0)[~use_ix],
label='missing', marker='x', color='red', ls='none', alpha=0.5
)
ax[k].plot(np.sum(X_real[1:], axis=0), label='true', linewidth=0.75, alpha=0.5)
ax[k].plot(np.sum(problem.estimates[1:], axis=0), label='estimated', linewidth=0.75, alpha=0.5)
ax[k].set_title('Composed Signal')
ax[k].legend(loc=[1.01, 0.1])
plt.tight_layout(pad=0.05)
# fig.savefig('/Users/bennetmeyers/Documents/Boyd-work/OSD-presentations/April2021/figs/simple-example.pgf')
~np.all(np.isclose(np.diff(problem.estimates[-1]), 0))
K = len(components)
fig, ax = plt.subplots(nrows=K+1, sharex=True, figsize=(5.5,2.9))
for k in range(K+1):
if k <= K-1:
ax[k].plot(X_real[k], linewidth=0.75, label='true', alpha=0.75)
ax[k].plot(problem.estimates[k], label='estimate', linewidth=0.75, alpha=0.75)
ax[k].set_title('component {}'.format(k+1))
ax[k].legend(loc=[1.01, 0.2])
else:
ax[k].plot(
np.arange(T)[use_ix],
np.sum(X_real, axis=0)[use_ix],
label='observed', linewidth=0.5, marker='.', color='green', ms=1.5, alpha=0.5
)
ax[k].plot(
np.arange(T)[~use_ix],
np.sum(X_real, axis=0)[~use_ix],
label='missing', marker='x', color='red', ls='none', alpha=0.5, ms=3
)
ax[k].plot(np.sum(X_real[1:], axis=0), label='true', linewidth=0.75, alpha=0.75)
ax[k].plot(problem.estimates[1] + problem.estimates[2], label='estimate',
linewidth=0.75, alpha=0.75)
ax[k].set_title('composed signal')
ax[k].legend(loc=[1.01, 0.0])
plt.tight_layout(pad=0.05)
# fig.savefig('/Users/bennetmeyers/Documents/Boyd-work/OSD-presentations/April2021/figs/simple-example-bad.pgf')
```
Using a single test set (20% reserved), wide search, fine grid. Set to run before went to bed
```
# l2s = np.logspace(-0.5,3.5,60)
# l3s = np.logspace(-1.5,1.5,60)
# errors = np.zeros((len(l3s), len(l2s)))
# count_switches = np.zeros((len(l3s), len(l2s)))
# smoothness = np.zeros((len(l3s), len(l2s)))
# counter = 0
# for j, l2 in enumerate(l2s):
# for i, l3 in enumerate(l3s):
# progress(counter, errors.size)
# c1 = GaussNoise()
# c2 = SmoothFirstDifference(theta=l2)
# p = 0.25
# c3 = MarkovChain([[1-p, p], [p, 1-p]], theta=l3)
# components = [c1, c2, c3]
# problem = Problem(y, components)
# problem.decompose(admm=True, rho=1, num_iter=100, use_set=use_ix, verbose=False)
# error = np.sum(np.power((y - np.sum(problem.estimates, axis=0))[~use_ix], 2))
# errors[i, j] = error
# smoothness[i, j] = np.sum(np.power(np.diff(problem.estimates[1]), 2))
# count_switches[i, j] = np.sum(~np.isclose(np.diff(problem.estimates[-1]), 0))
# counter += 1
# progress(counter, errors.size)
# run1 = {
# 'l2': np.copy(l2s),
# 'l3': np.copy(l3s),
# 'error': np.copy(errors),
# 'smoothness': np.copy(smoothness),
# 'switches': np.copy(count_switches)
# }
# with open('validation_run_1.pkl', 'wb') as f:
# pickle.dump(run1, f)
with open('validation_run_1.pkl', 'rb') as f:
run1 = pickle.load(f)
f2 = interp1d(run1['l2'], np.arange(len(run1['l2'])))
f3 = interp1d(run1['l3'], np.arange(len(run1['l3'])))
xticks = [f2(i).item() for i in np.logspace(0, 3, 4)]
yticks = [f3(i).item() for i in np.logspace(-1, 1, 3)]
xticklabels = ['$10^{'+'{}'.format(i)+'}$' for i in range(len(xticks))]
yticklabels = ['$10^{'+'{}'.format(i - 1)+'}$' for i in range(len(yticks))]
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1)
cp = ax.imshow(run1['error'], cmap='plasma')
plt.colorbar(cp)
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('sos error');
plt.figure()
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1)
cp = ax.imshow(np.log10(run1['smoothness']), cmap='plasma')
plt.colorbar(cp)
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('log of smoothness penalty in 2nd component');
plt.figure()
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1)
cp = ax.imshow(run1['switches'], cmap='plasma')
plt.colorbar(cp)
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('count of switches in 3rd component');
```
Tighten upper and lower bounds a bit, and use Stephens bootstrap resampling strategy. Caution, this takes all afternoon to execute.
```
# from sklearn.model_selection import KFold
# l2s = np.logspace(0,3,20)
# l3s = np.logspace(-1,0.5,20)
# num_splits = 20
# hold = 0.2
# splits = []
# for s in range(num_splits):
# remove_ix = np.random.choice(np.arange(len(y)), int(len(y) * hold), replace=False)
# remove_ix.sort()
# use_ix = np.ones_like(y, dtype=bool)
# use_ix[remove_ix] = False
# splits.append(use_ix)
# l2_errors = np.zeros((len(l3s), len(l2s)))
# l1_errors = np.zeros((len(l3s), len(l2s)))
# count_switches = np.zeros((len(l3s), len(l2s)))
# smoothness = np.zeros((len(l3s), len(l2s)))
# counter = 0
# for j, l2 in enumerate(l2s):
# for i, l3 in enumerate(l3s):
# progress(counter, errors.size)
# c1 = GaussNoise()
# c2 = SmoothFirstDifference(theta=l2)
# p = 0.25
# c3 = MarkovChain([[1-p, p], [p, 1-p]], theta=l3)
# components = [c1, c2, c3]
# problem = Problem(y, components)
# sos = 0
# sae = 0
# smth = 0
# count_sw = 0
# for uix in splits:
# problem.decompose(admm=True, rho=1, num_iter=100, use_set=uix, verbose=False)
# # print(np.sum(np.power((y - np.sum(problem.estimates, axis=0))[test_ix], 2)))
# sos += np.sum(np.power((y - np.sum(problem.estimates, axis=0))[~uix], 2))
# sae += np.sum(np.abs((y - np.sum(problem.estimates, axis=0))[~uix]))
# smth =+ np.sum(np.power(np.diff(problem.estimates[1]), 2))
# count_sw +=np.sum(~np.isclose(np.diff(problem.estimates[-1]), 0))
# l2_errors[i, j] = sos / (num_splits * np.sum(~uix))
# l1_errors[i, j] = sae / (num_splits * np.sum(~uix))
# smoothness[i, j] = smth / (num_splits)
# count_switches[i, j] = count_sw / (num_splits)
# counter += 1
# progress(counter, errors.size)
# run2 = {
# 'l2': np.copy(l2s),
# 'l3': np.copy(l3s),
# 'sos': np.copy(l2_errors),
# 'sae': np.copy(l1_errors),
# 'smoothness': np.copy(smoothness),
# 'switches': np.copy(count_switches)
# }
# with open('validation_run_2.pkl', 'wb') as f:
# pickle.dump(run2, f)
with open('validation_run_2.pkl', 'rb') as f:
run2 = pickle.load(f)
f2 = interp1d(run2['l2'], np.arange(len(run2['l2'])))
f3 = interp1d(run2['l3'], np.arange(len(run2['l3'])))
xticks = [f2(i).item() for i in np.logspace(0, 3, 4)]
yticks = [f3(i).item() for i in np.logspace(-1, 0, 2)]
xticklabels = ['$10^{'+'{}'.format(i)+'}$' for i in range(len(xticks))]
yticklabels = ['$10^{'+'{}'.format(i - 1)+'}$' for i in range(len(yticks))]
i = 10
j = 7
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1, figsize=(8,6))
cp = ax.imshow(run2['sos'], cmap='plasma')
plt.colorbar(cp)
ax.scatter(f2(run2['l2'][j]), f3(run2['l3'][i]), color='red')
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('sos error');
plt.figure()
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1, figsize=(8,6))
cp = ax.imshow(run2['sae'], cmap='plasma')
plt.colorbar(cp)
ax.scatter(f2(run2['l2'][j]), f3(run2['l3'][i]), color='red')
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('sae error');
plt.figure()
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1, figsize=(8,6))
cp = ax.imshow(np.log10(run2['smoothness']), cmap='plasma')
plt.colorbar(cp)
ax.scatter(f2(run2['l2'][j]), f3(run2['l3'][i]), color='red')
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('log of smoothness penalty in 2nd component');
plt.figure()
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1, figsize=(8,6))
cp = ax.imshow(run2['switches'], cmap='plasma')
plt.colorbar(cp)
ax.scatter(f2(run2['l2'][j]), f3(run2['l3'][i]), color='red')
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('count of switches in 3rd component');
msk = X >= 5
i_best = np.argmin(run2['sae'][msk])
print(
X[msk][i_best],
Y[msk][i_best],
run2['sae'][msk][i_best]
)
slct = run2['sae'] <= 0.25
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1, figsize=(8,6))
cp = ax.imshow(run2['sae'], cmap='plasma')
plt.colorbar(cp)
ax.scatter(f2(X[msk][i_best]), f3(Y[msk][i_best]), color='red')
ax.scatter(f2(X[msk][i_best]), f3(Y[msk][i_best]*0.5), color='pink')
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('sae error');
plt.figure()
with sns.axes_style('white'):
fig,ax=plt.subplots(1,1, figsize=(8,6))
cp = ax.imshow(slct, cmap='plasma')
plt.colorbar(cp)
ax.scatter(f2(X[msk][i_best]), f3(Y[msk][i_best]), color='red')
ax.scatter(f2(X[msk][i_best]), f3(Y[msk][i_best]*0.5), color='pink')
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.set_xticklabels(xticklabels)
ax.set_yticklabels(yticklabels)
ax.invert_yaxis()
plt.xlabel('$\lambda_2$')
plt.ylabel('$\lambda_3$')
plt.title('sae error');
plt.figure()
i = 10
j = 7
X, Y = np.meshgrid(run2['l2'], run2['l3'])
plt.plot(X[i], run2['sae'][i])
plt.xscale('log')
plt.xlabel('$\lambda_2$')
plt.title('error for $\lambda_3={:.2e}$'.format(run2['l3'][i]))
plt.axvline(run2['l2'][j], color='red', ls='--')
plt.figure()
plt.plot(Y[:, j], run2['sae'][:, j])
plt.xscale('log')
plt.xlabel('$\lambda_3$')
plt.axvline(run2['l3'][i], color='red', ls='--')
plt.title('error for $\lambda_2={:.2e}$'.format(run2['l2'][j]))
lambda2 = X[msk][i_best]
lambda3 = Y[msk][i_best] * .5
c1 = GaussNoise()
c2 = SmoothFirstDifference(theta=lambda2)
p = 0.25
c3 = MarkovChain([[1-p, p], [p, 1-p]], theta=lambda3)
components = [c1, c2, c3]
problem = Problem(y, components)
problem.decompose(admm=True, rho=1, num_iter=100)#, use_set=use_ix)
sos = np.sum(np.power((y - np.sum(problem.estimates, axis=0))[~use_ix], 2))
sae = np.sum(np.abs((y - np.sum(problem.estimates, axis=0))[~use_ix]))
print('sos: {:.2f}, sae: {:.2f}'.format(sos, sae))
K = len(components)
fs = np.array([5.5,2.9])
fig, ax = plt.subplots(nrows=K, sharex=True, figsize=2*fs)
for k in range(K):
if k > 0:
true = X_real[k]
est = problem.estimates[k]
ax[k].plot(true, label='true', linewidth=0.75, alpha=0.5)
ax[k].plot(est, label='estimated', linewidth=0.75, alpha=0.5)
ax[k].set_title('Component {}'.format(k+1))
else:
ax[k].plot(
np.arange(T)[use_ix],
np.sum(X_real, axis=0)[use_ix],
label='observed', linewidth=0.5, marker='.', color='green', ms=1, alpha=0.5
)
ax[k].plot(
np.arange(T)[~use_ix],
np.sum(X_real, axis=0)[~use_ix],
label='missing', marker='x', color='red', ls='none', alpha=0.5
)
ax[k].plot(np.sum(X_real[1:], axis=0), label='true', linewidth=0.75, alpha=0.5)
ax[k].plot(np.sum(problem.estimates[1:], axis=0), label='estimated', linewidth=0.75, alpha=0.5)
ax[k].set_title('Composed Signal')
ax[k].legend(loc=[1.01, 0.1])
plt.tight_layout(pad=0.05)
# fig.savefig('/Users/bennetmeyers/Documents/Boyd-work/OSD-presentations/April2021/figs/simple-example.pgf')
```
Okay, narrow the search space even more, and don't go overkill on the number of bootstraps :/
this is "run 4". "run 3" is in the other notebook and has a higher switching rate
```
l2s = np.logspace(np.log10(7), 2, 10)
l3s = np.logspace(np.log10(0.2), np.log10(2), 10)
num_splits = 10
hold = 0.1
splits = []
for s in range(num_splits):
remove_ix = np.random.choice(np.arange(len(y)), int(len(y) * hold), replace=False)
remove_ix.sort()
use_ix = np.ones_like(y, dtype=bool)
use_ix[remove_ix] = False
splits.append(use_ix)
l2_errors = np.zeros((len(l3s), len(l2s)))
l1_errors = np.zeros((len(l3s), len(l2s)))
count_switches = np.zeros((len(l3s), len(l2s)))
smoothness = np.zeros((len(l3s), len(l2s)))
counter = 0
for j, l2 in enumerate(l2s):
for i, l3 in enumerate(l3s):
progress(counter, errors.size)
c1 = GaussNoise()
c2 = SmoothFirstDifference(theta=l2)
p = 0.25
c3 = MarkovChain([[1-p, p], [p, 1-p]], theta=l3)
components = [c1, c2, c3]
problem = Problem(y, components)
sos = 0
sae = 0
smth = 0
count_sw = 0
for uix in splits:
problem.decompose(admm=True, rho=1, num_iter=100, use_set=uix, verbose=False)
# print(np.sum(np.power((y - np.sum(problem.estimates, axis=0))[test_ix], 2)))
sos += np.sum(np.power((y - np.sum(problem.estimates, axis=0))[~uix], 2))
sae += np.sum(np.abs((y - np.sum(problem.estimates, axis=0))[~uix]))
smth =+ np.sum(np.power(np.diff(problem.estimates[1]), 2))
count_sw +=np.sum(~np.isclose(np.diff(problem.estimates[-1]), 0))
l2_errors[i, j] = sos / (num_splits * np.sum(~uix))
l1_errors[i, j] = sae / (num_splits * np.sum(~uix))
smoothness[i, j] = smth / (num_splits)
count_switches[i, j] = count_sw / (num_splits)
counter += 1
progress(counter, errors.size)
run4 = {
'l2': np.copy(l2s),
'l3': np.copy(l3s),
'sos': np.copy(l2_errors),
'sae': np.copy(l1_errors),
'smoothness': np.copy(smoothness),
'switches': np.copy(count_switches)
}
with open('validation_run_3.pkl', 'wb') as f:
pickle.dump(run4, f)
```
| github_jupyter |
## Shor's factoring algorithm
This exercise is based on the [ProjectQ](http://projectq.ch/) example. You can get the original uncommented code at [ProjectQ repository](https://github.com/ProjectQ-Framework/ProjectQ/blob/develop/examples/shor.py)
This algorithm is based on the paper [Parker S. and Planio M.B,Efficient factorization with a single pure qubit and logN mixed qubits](https://arxiv.org/abs/quant-ph/0001066v3)
Shor's quantum algorithm is a semiclassical algorithm where one of the steps, looking for the period od a function, is executed on a QPU because it has a better scalability with the number of bits of the number to factor. In the future, when the Quantum Computers can execute large programs, it can beat the most used asymmetric cryptographic algorithm: RSA. This algorithm is based on the assumption that it is very hard to compute the factors of a large number. Shor's algorithm and the experimental proof of the possibility of implementing it in QPUs (for factoring only very small numbers: [15](https://arxiv.org/abs/quant-ph/0112176) and [21](https://arxiv.org/abs/1111.4147)) started the Post-Quantum era, where new cryptographic algorithms are needed.
There are several versions of the algorithm, with different requirements in the number of qubits.
First, load the Python modules you will need to execute the code. There are some libraries that will compute the classical part, as **gcd** which calculates the Greatest Commun Divisor of two integers.
This case use [mathematical quantum maths libraries](http://projectq.readthedocs.io/en/latest/projectq.libs.math.html) and a lot of rules to decompose the [quamtum program in basic gates ](http://projectq.readthedocs.io/en/latest/projectq.setups.decompositions.html)
**NOTE**:To see an example of the Shor's algorithm, use <a href="/files/quirk.html#circuit={%22cols%22:[[1,1,1,1,1,1,1,1,1,1,%22~input%22,1,1,1,%22~guess%22],[1,1,1,1,1,1,1,1,1,1,{%22id%22:%22setR%22,%22arg%22:55},1,1,1,{%22id%22:%22setB%22,%22arg%22:26}],[],[%22H%22,%22H%22,%22H%22,%22H%22,%22H%22,%22H%22,%22H%22,%22H%22,%22H%22,%22H%22,%22X%22],[%22inputA10%22,1,1,1,1,1,1,1,1,1,%22*BToAmodR6%22],[%22QFT%E2%80%A010%22],[1,1,1,1,%22~out%22],[%22Chance10%22]],%22gates%22:[{%22id%22:%22~guess%22,%22name%22:%22guess:%22,%22matrix%22:%22{{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}%22},{%22id%22:%22~input%22,%22name%22:%22input:%22,%22matrix%22:%22{{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}%22},{%22id%22:%22~out%22,%22name%22:%22out:%22,%22matrix%22:%22{{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}%22}]}">Quirk</a>
```
from __future__ import print_function
import math
import random
import sys
from fractions import Fraction
try:
from math import gcd
except ImportError:
from fractions import gcd
from builtins import input
import projectq.libs.math
import projectq.setups.decompositions
from projectq.backends import Simulator, ResourceCounter
from projectq.cengines import (MainEngine,
AutoReplacer,
LocalOptimizer,
TagRemover,
InstructionFilter,
DecompositionRuleSet)
from projectq.libs.math import (AddConstant,
AddConstantModN,
MultiplyByConstantModN)
from projectq.meta import Control
from projectq.ops import (X,
Measure,
H,
R,
QFT,
Swap,
get_inverse,
BasicMathGate,
All)
# Filter function, which defines the gate set for the first optimization
# (don't decompose QFTs and iQFTs to make cancellation easier)
def high_level_gates(eng, cmd):
g = cmd.gate
if g == QFT or get_inverse(g) == QFT or g == Swap:
return True
if isinstance(g, BasicMathGate):
return False
if isinstance(g, AddConstant):
return True
elif isinstance(g, AddConstantModN):
return True
return False
return eng.next_engine.is_available(cmd)
```
Create the Engine. This time, several optimizations will be included. The program will also count the needed resources using the Engine ResourceCounter.
```
# build compilation engine list
resource_counter = ResourceCounter()
rule_set = DecompositionRuleSet(modules=[projectq.libs.math,
projectq.setups.decompositions])
compilerengines = [AutoReplacer(rule_set),
InstructionFilter(high_level_gates),
TagRemover(),
LocalOptimizer(3),
AutoReplacer(rule_set),
TagRemover(),
LocalOptimizer(3),
resource_counter]
# make the compiler and run the circuit on the simulator backend
eng = MainEngine(Simulator(), compilerengines)
```
Choose the integer to factor. Execute the next cell and answer the question. Select a small number as 15 or 21 and odd, or you can wait a long time! or the solution is trivial.
```
# print welcome message and ask the user for the number to factor
N=2
while gcd(2,N)==2:
print("\n\t\033[37mprojectq\033[0m\n\t--------\n\tImplementation of Shor"
"\'s algorithm.", end="")
N = int(input('\n\tNumber to factor: '))
if gcd(2,N)==2:
print("\n\n%d is EVEN. Please, select another integer"%N)
print("\n\tFactoring N = {}: \033[0m".format(N), end="")
```
Ramdomly, the algorithm selects one initial factor and tests if it is a factor.
```
# choose a base at random:
random.seed(1)
a = int(random.random()*N)
if not gcd(a, N) == 1:
print("\n\n\t\033[92mOoops, we were lucky: Chose non relative prime"
" by accident :)")
print("\tFactor: {}\033[0m".format(gcd(a, N)))
print("\tInitial guess: {}\033[0m".format(a))
```
Now, this is the Quantum part: find the period of a function. The origial idea is due to Simon who sent it to a conference where Shor was a reviewer. Lucky person, because he knew that finding a period of a function was the weak point of the factorisation. And now, he could do it!.
First of all, we need to calculate the number of qubits **n** that are needed. Afterwards, we allocate a Quantum register with this number of qubits.
```
n = int(math.ceil(math.log(N, 2)))
x = eng.allocate_qureg(n)
measurements = [0] * (2 * n) # will hold the 2n measurement results
print("Algorithm will use %d qubits to produce %d measurements"%(n+1,2*n))
```
We have to allocate one additional qubit. This is the only one that have to be measured!.
```
ctrl_qubit = eng.allocate_qubit()
```
Ok. Now this is the trick: The quantum algorithm. Because ProjectQ has some quantum routines implemented as Multiplication, it is really easy to program it. This loop implements this circuit:
<img src="Images/short.jpg"/>
Where:
1. $U_a|x>=|ax\space mod\space N>$. This function has eigenvalues of shape $e^\frac{i2\pi k}{r}$ with $k=0...r-1$ and eigenvestors $|\chi_k>$. This phase can be estimated using a phase estimation algorithm.
2. Each $R'_j(\phi'_j)$ is a phase shift gate with an angle $$\phi'_j={-2\pi \sum_{k=2}^{j}\frac{m_{j-k}}{2^k}}$$
The register is initialized to $|0\rangle^{\otimes n-1} \otimes |1\rangle$. This state is the superposition of all the eigenvectors of unitary operator, $|\chi_k>$. So
$$|1> = \sum_{k=0}^{r-1}|\chi_k>$$
In summary, really this is an interative way of making a phase estimation subroutine. The idea is to find the period of the function $f(x)=ax(mod N)$. ProjectQ has the function MultiplyByConstantModN which makes such unitary transformation.
```
X | x[0]
for k in range(2 * n):
current_a = pow(a, 1 << (2 * n - 1 - k), N)
H | ctrl_qubit
with Control(eng, ctrl_qubit):
MultiplyByConstantModN(current_a, N) | x
for i in range(k):
if measurements[i]:
R(-math.pi/(1 << (k - i))) | ctrl_qubit
H | ctrl_qubit
# and measure
Measure | ctrl_qubit
eng.flush()
measurements[k] = int(ctrl_qubit)
if measurements[k]:
X | ctrl_qubit
print("\033[95m{}\033[0m".format(measurements[k]), end="")
sys.stdout.flush()
All(Measure) | x
```
Now, we conver the results to the final period. It is done in two steps:
1. From the measurements, recover the phase, which must have the shape $2\pi k/r$
2. Convert the phase on a fraction of integers using classical methods: the <a href="https://en.wikipedia.org/wiki/Continued_fraction">Continued Fraction Expansion</a>
3. Take $r$ as the denominator of the fraction
```
y = sum([(measurements[2 * n - 1 - i]*1. / (1 << (i + 1)))
for i in range(2 * n)])
print("Result of period finding subroutine:",y)
f=Fraction(y).limit_denominator(N-1)
print("Fraction =",f)
r = f.denominator
print("r=",r)
```
And we try to find the factors. Becareful, the algorithm can fail to find a factor.
1. calculate b=$a^r \space mod \space N$
2. calculate the first factor as $f_1=gcd(b+1,N)$
3. calculate the second prime as $f_2=gcd(b-1,N)$
4. Check if $N=f_1*f_2$
```
# try to determine the factors
if r % 2 != 0:
r *= 2
apowrhalf = pow(a, r >> 1, N)
f1 = gcd(apowrhalf + 1, N)
f2 = gcd(apowrhalf - 1, N)
if ((not f1 * f2 == N) and f1 * f2 > 1 and
int(1. * N / (f1 * f2)) * f1 * f2 == N):
f1, f2 = f1*f2, int(N/(f1*f2))
if f1 * f2 == N and f1 > 1 and f2 > 1:
print("\n\n\t\033[92mFactors found :-) : {} * {} = {}\033[0m"
.format(f1, f2, N))
else:
print("\n\n\t\033[91mBad luck: Found {} and {}\033[0m".format(f1,
f2))
```
And we print the final resources we have used.
```
print(resource_counter) # print resource usage
```
| github_jupyter |
IMPORTS
```
#Import the libraries
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
df = pd.read_csv('train_csv.csv')
df.reset_index(drop=True, inplace=True)
df.shape
df.head()
#Visualize the features
plt.figure(figsize=(16,8))
plt.title('FEATURE')
plt.scatter(df['time'], df['feature'])
plt.plot(df['time'], df['feature'])
plt.xlabel('Date',fontsize=18)
plt.ylabel('features',fontsize=18)
plt.show()
```
Feature Engineering
```
#Create a new dataframe with only the 'feature' column
data = df.filter(['feature'])
#Converting the dataframe to a numpy array
dataset = data.values
#Get /Compute the number of rows to train the model on
training_data_len = math.ceil( len(dataset) *.8)
training_data_len
#Scale the all of the data to be values between 0 and 1
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
len(scaled_data)
```
Train and Test Split
```
#Create the scaled training data set
train_data = scaled_data[0:training_data_len , : ]
len(train_data)
#Split the data into x_train and y_train data sets
x_train=[]
y_train = []
for i in range(5, len(train_data)):
x_train.append(train_data[i-5:i,0])
y_train.append(train_data[i,0])
#Convert x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
#Reshape the data into the shape accepted by the LSTM
x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))
```
Build the Architecture
```
#Build the LSTM network model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True,input_shape=(x_train.shape[1],1)))
model.add(LSTM(units=50, return_sequences=False))
model.add(Dense(units=25))
model.add(Dense(units=1))
#Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# from keras.layers import Dropout
# # Initialising the RNN
# model = Sequential()
# model.add(LSTM(units = 50, return_sequences = True, input_shape = (x_train.shape[1], 1)))
# #model.add(Dropout(0.2))
# # Adding a second LSTM layer and some Dropout regularisation
# model.add(LSTM(units = 50, return_sequences = False))
# #model.add(Dropout(0.2))
# # Adding a third LSTM layer and some Dropout regularisation
# # model.add(LSTM(units = 50, return_sequences = True))
# # model.add(Dropout(0.2))
# # Adding a fourth LSTM layer and some Dropout regularisation
# model.add(LSTM(units = 50))
# #model.add(Dropout(0.2))
# # Adding the output layer
# # For Full connection layer we use dense
# # As the output is 1D so we use unit=1
# model.add(Dense(units = 25))
# # Compiling the RNN
# # For optimizer we can go through keras optimizers Docomentation
# # As it is regression problem so we use mean squared error
# model.compile(optimizer = 'adam', loss = 'mean_squared_error')
```
Train The Model
```
#Train the model
model.fit(x_train, y_train, batch_size=50, epochs=100)
```
Testing Dataset
```
#Test data set
test_data = scaled_data[training_data_len - 5: , : ]
len(test_data)
#Create the x_test and y_test data sets
x_test = []
y_test = dataset[training_data_len : , : ] #Get all of the rows from index 1603 to the rest and all of the columns (in this case it's only column 'Close'), so 2003 - 1603 = 400 rows of data
for i in range(5,len(test_data)):
x_test.append(test_data[i-5:i,0])
# x_test
# y_test
len(x_test)
len(y_test)
#Convert x_test to a numpy array
x_test = np.array(x_test)
#Reshape the data into the shape accepted by the LSTM
x_test = np.reshape(x_test, (x_test.shape[0],x_test.shape[1],1))
```
Make Predictions
```
#Getting the models predicted price values
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)#Undo scaling
```
Calculate RMSE
```
#Calculate/Get the value of RMSE
rmse=np.sqrt(np.mean(((predictions- y_test)**2)))
rmse
```
Visualizations of Results
```
#Plot/Create the data for the graph
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions
#Visualize the data
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('feature', fontsize=18)
plt.plot(train['feature'])
plt.plot(valid[['feature', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')
plt.show()
#Show the valid and predicted prices
valid
```
Make Future Predictions
```
df1 = pd.read_csv('train_csv.csv')
df2 = pd.read_csv('test_csv.csv')
valid_csv = pd.concat([df1, df2])
valid_csv.tail
valid_csv.to_csv('valid_csv.csv')
#Get the quote
feature_quote = pd.read_csv('valid_csv.csv')
#Create a new dataframe
new_df = feature_quote.filter(['feature'])
#Get teh last 60 day closing price
last_1_days = new_df[114:119].values
#Scale the data to be values between 0 and 1
last_1_days_scaled = scaler.transform(last_1_days)
#Create an empty list
X_test = []
#Append teh past 1 days
X_test.append(last_1_days_scaled)
#Convert the X_test data set to a numpy array
X_test = np.array(X_test)
#Reshape the data
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
#Get the predicted scaled price
pred_price = model.predict(X_test)
#undo the scaling
pred_price = scaler.inverse_transform(pred_price)
print(pred_price)
```
| github_jupyter |
```
import tensorflow as tf
import numpy as np
import mvc_env
p = 4; initialization_stddev=1e-3; n_mlp_layers = 1; T = 2; n_nodes = 5
x = tf.placeholder(dtype=tf.float32, shape=[None, n_nodes])
adj = tf.placeholder(tf.float32, [None, n_nodes, n_nodes])
w = tf.placeholder(tf.float32, [None, n_nodes, n_nodes])
with tf.variable_scope('Q_func', reuse=False):
with tf.variable_scope('thetas'):
theta1 = tf.Variable(tf.random_normal([p], stddev=initialization_stddev), name='theta1')
theta2 = tf.Variable(tf.random_normal([p, p], stddev=initialization_stddev), name='theta2')
theta3 = tf.Variable(tf.random_normal([p, p], stddev=initialization_stddev), name='theta3')
theta4 = tf.Variable(tf.random_normal([p], stddev=initialization_stddev), name='theta4')
theta5 = tf.Variable(tf.random_normal([2 * p], stddev=initialization_stddev), name='theta5')
theta6 = tf.Variable(tf.random_normal([p, p], stddev=initialization_stddev), name='theta6')
theta7 = tf.Variable(tf.random_normal([p, p], stddev=initialization_stddev), name='theta7')
with tf.variable_scope('MLP', reuse=False):
Ws_MLP = []; bs_MLP = []
for i in range(n_mlp_layers):
Ws_MLP.append(tf.Variable(tf.random_normal([p, p], stddev=initialization_stddev),
name='W_MLP_' + str(i)))
bs_MLP.append(tf.Variable(tf.random_normal([p], stddev=initialization_stddev),
name='b_MLP_' + str(i)))
# Define the mus
# Initial mu
# Loop over t
for t in range(T):
# First part of mu
mu_part1 = tf.einsum('iv,k->ivk', x, theta1)
# Second part of mu
if t != 0:
mu_part2 = tf.einsum('kl,ivk->ivl', theta2, tf.einsum('ivu,iuk->ivk', adj, mu))
# Add some non linear transformations of the pooled neighbors' embeddings
with tf.variable_scope('MLP', reuse=False):
for i in range(n_mlp_layers):
mu_part2 = tf.nn.relu(tf.einsum('kl,ivk->ivl', Ws_MLP[i],
tf.nn.relu(mu_part2)) + bs_MLP[i])
# Third part of mu
mu_part3_0 = tf.einsum('ikvu->ikv', tf.nn.relu(tf.einsum('k,ivu->ikvu', theta4, w)))
mu_part3_1 = tf.einsum('kl,ilv->ivk', theta3, mu_part3_0)
# All all of the parts of mu and apply ReLui
if t != 0:
mu = tf.nn.relu(tf.add(mu_part1 + mu_part2, mu_part3_1, name='mu_' + str(t)))
else:
mu = tf.nn.relu(tf.add(mu_part1, mu_part3_1, name='mu_' + str(t)))
# Define the Qs
Q_part1 = tf.einsum('kl,ivk->ivl', theta6, tf.einsum('ivu,iuk->ivk', adj, mu))
Q_part2 = tf.einsum('kl,ivk->ivl', theta7, mu)
out = tf.identity(tf.einsum('k,ivk->iv', theta5,
tf.nn.relu(tf.concat([Q_part1, Q_part2], axis=2))),
name='Q')
env = mvc_env.MVC_env(5); env.reset()
sess = tf.InteractiveSession(); tf.global_variables_initializer().run()
sess.run(mu, feed_dict={x: np.array([1, 0, 0, 0, 0])[None],
adj: env.adjacency_matrix[None],
w: env.weight_matrix[None]})
a = sess.run(theta3)
sess.run(theta4)
sess.run(tf.einsum('ikvu->ikv', tf.nn.relu(tf.einsum('k,ivu->ikvu', theta4, w))),
feed_dict={w: env.weight_matrix[None]})
sess.run(tf.nn.relu(tf.einsum('k,ivu->ikv', theta4, w)),
feed_dict={w: env.weight_matrix[None]})
```
| github_jupyter |
# This Data Mining Workflow uses both Pipefitter and SWAT
## Set up the Jupyter Notebook for Analysis
```
# Import necessary packages and modules
import swat, collections
import pandas as pd
import matplotlib.pyplot as plt
from pipefitter.pipeline import Pipeline
from pipefitter.transformer import Imputer
from pipefitter.estimator import DecisionTree, DecisionForest, GBTree, NeuralNetwork
%matplotlib inline
# Set the connection by specifying the hostname, port, username, and password
conn = swat.CAS(host, port, username, password)
# Data set shortcut
indata = 'hmeq'
# Create a CAS library called DMLib pointing to the defined server-side directory
DMLib = conn.addCaslib('DMlib', datasource = 'path', path = '/viyafiles')
# Do a server-side data load into CAS memory
castbl = conn.loadTable(indata + '.sas7bdat', casOut = indata)['casTable']
castbl.replace = True
```
## Get the first few rows
```
# Assign the variable name df to the new CASTable object
df = conn.CASTable(indata)
# Perform the head method to return the first 5 rows
df.head()
```
## Feature engineering
```
# Create new columns to help with analysis
df['MORTPAID'] = df['VALUE'] - df['MORTDUE']
df.head()
```
## Investigate the data
### Variable types
```
# Get the variable types
df.dtypes
```
### Summary statistics
```
# Get summary statistics using the describe method, then switch rows and columns
summary = df.describe(include = 'all').transpose()
summary
```
### Numeric variable distribution
```
# Get the distribution of all numeric variables
df.hist(figsize = (15, 10));
```
### Investigate missingness
```
# Create percent missing column for plotting
summary['pctmiss'] = (len(castbl) - summary['count'])/len(castbl)
# Make a bar graph using pandas/matplotlib functionality
summary.query('pctmiss > 0')['pctmiss'].plot('bar', title = 'Pct Missing Values', figsize = (10, 6), color = 'c');
```
## Split the data into training and validation before imputing
```
# Load the sampling actionset
conn.loadactionset('sampling')
# Do a simple random sample with a 70/30 split
df.srs(samppct = 70, partind = True, output = dict(casout = castbl, copyvars = 'all'))
# Verify that the partition worked using the groupby method
castbl.groupby('_PartInd_')['_PartInd_'].count()/len(castbl)
```
## Impute missing values using pipefitter pipelines
```
# Will end up imputing the median value for numeric variables, most common value for nominal
imp_castbl = Pipeline([Imputer(Imputer.MEDIAN), Imputer(Imputer.MODE)]).transform(castbl)
# I want my imputed dataset name to have the imp_ prefix
imp_castbl.partition(casout = dict(name = 'imp_' + indata, replace = True))
# Remove the unnecessary impute staging tables
[conn.droptable(s) for s in conn.tableinfo()['TableInfo']['Name'] if 'IMPUTE' in s]
# Make sure everything worked properly for the new imputed dataset
conn.fetch('imp_' + indata, to = 5)
```
### Do a quick check on the available datasets
```
conn.tableinfo()
```
## Prepare for modeling - shortcuts to make life easier
```
# Create CASTable objects for training and validation for models that can handle missing values
train = conn.CASTable(indata, where = '_partind_ = 1')
valid = conn.CASTable(indata, where = '_partind_ = 0')
# Create CASTable objects for training and validation for models that cannot handle missing values
imp_train = conn.CASTable('imp_' + indata, where = '_partind_ = 1')
imp_valid = conn.CASTable('imp_' + indata, where = '_partind_ = 0')
# Key word argument shortcuts for model building (common imputs)
params = dict(
target = castbl.columns[0],
inputs = castbl.columns[1:-1].tolist(),
nominals = [castbl.columns[0]] + castbl.columninfo()['ColumnInfo'].query('Type == "varchar"')['Column'].tolist()
)
```
# Model Fitting & Scoring using Pipefitter
## Decision Tree
```
# Train decision tree on training dataset
dt = DecisionTree(**params).fit(train)
# Score decision tree on validation dataset
dt_score = dt.score(valid)
dt_score
```
## Random Forest
```
# Train random forest on training dataset
rf = DecisionForest(**params).fit(train)
# Score decision tree on validation dataset
rf_score = rf.score(valid)
rf_score
```
## Gradient Boosting
```
# Train gradient boosting on training dataset
gbt = GBTree(**params).fit(train)
# Score gradient boosting on validation dataset
gbt_score = gbt.score(valid)
gbt_score
```
## Neural Network
```
# Train neural network on training dataset
nn = NeuralNetwork(**params).fit(imp_train)
# Score neural network on validation dataset
nn_score = nn.score(imp_valid, event = 0)
nn_score
```
# Model Assessment
## Compare model misclassification side-by-side
```
# Aggregate the misclassification metrics from previous output
Models = ['Decision Tree', 'Random Forest', 'Gradient Boosting', 'Neural Network']
Misclassification = [dt_score[-1], rf_score[-1], gbt_score[-1], nn_score[-1]]
mcr = pd.DataFrame({'Misclassification Rate': Misclassification}, Models).sort_values('Misclassification Rate')
print('\n', mcr)
# Which model is the champion?
print('\n', 'The', mcr.index[0], 'model is the champion!')
```
# Optional: obtain more model assessment metrics
## Check available tables
There should be the prepared datasets and saved models
```
# What are the in-memory tables?
conn.tableinfo()
```
### Assessment dictionary shortcuts
```
# Give model tables appropriate shortcuts in a dictionary
saved = {}
saved['dt'] = next((s for s in conn.tableinfo()['TableInfo']['Name'] if 'MODELTREE' in s), None)
saved['rf'] = next((s for s in conn.tableinfo()['TableInfo']['Name'] if 'MODELFOREST' in s), None)
saved['gbt'] = next((s for s in conn.tableinfo()['TableInfo']['Name'] if 'MODELGBT' in s), None)
saved['nn'] = next((s for s in conn.tableinfo()['TableInfo']['Name'] if 'NNMODEL' in s), None)
# Models to be assessed
models = collections.OrderedDict()
models['dt'] = 'Decision Tree'
models['rf'] = 'Random Forest'
models['gbt'] = 'Gradient Boosting'
models['nn'] = 'Neural Network'
```
## Score the models built using Pipefitter
```
# Define function that will score the models based on the model prefix
def score_model(model):
return dict(
table = valid,
modelTable = saved[model],
assessonerow = True,
copyvars = [castbl.columns[0], castbl.columns[-1]],
casOut = dict(name = model + '_scored', replace = True)
)
### Decision Tree
conn.dtreeScore(**score_model('dt'))
### Random Forest
conn.forestScore(**score_model('rf'))
### Gradient Boosting
conn.gbtreeScore(**score_model('gbt'))
### Neural Network
conn.annScore(**score_model('nn'))
# See the available tables now
conn.tableinfo()
```
## Assess the models using the scored datasets
```
# Model assessment function
def assess_model(model):
return conn.assess(
table = dict(name = model + '_scored', where = '_partind_ = 0'),
inputs = '_' + model + '_p_ 1',
response = castbl.columns[0],
event = '1'
)
# Loop through the models and append to the roc_df dataframe
roc_df = pd.DataFrame()
for i in range(len(models)):
tmp = assess_model(list(models)[i])
tmp.ROCInfo['Model'] = list(models.values())[i]
roc_df = pd.concat([roc_df, tmp.ROCInfo])
```
## Additional Assessment
### Confusion Matrix
```
# Display stacked confusion matrix
print('\n', 'Confusion Matrix Information'.center(38, ' '))
roc_df[round(roc_df['CutOff'], 2) == 0.5][['Model', 'TP', 'FP', 'FN', 'TN']].reset_index(drop = True)
```
### ROC Curve
```
# Plot ROC curve
plt.figure(figsize = (7, 6))
for key, grp in roc_df.groupby(['Model']):
plt.plot(grp['FPR'], grp['Sensitivity'], label = key + ' (C = %0.2f)' % grp['C'].mean())
plt.plot([0,1], [0,1], 'k--')
plt.xlabel('False Postivie Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc = 'lower right')
plt.title('ROC Curve (using validation data)');
```
## End the session
```
# End the session
conn.endsession()
```
| github_jupyter |
```
#hide
#skip
! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab
#export
from fastai.basics import *
from fastai.text.core import *
from fastai.text.data import *
from fastai.text.models.core import *
from fastai.text.models.awdlstm import *
from fastai.callback.rnn import *
from fastai.callback.progress import *
#hide
from nbdev.showdoc import *
#default_exp text.learner
```
# Learner for the text application
> All the functions necessary to build `Learner` suitable for transfer learning in NLP
The most important functions of this module are `language_model_learner` and `text_classifier_learner`. They will help you define a `Learner` using a pretrained model. See the [text tutorial](http://docs.fast.ai/tutorial.text) for exmaples of use.
## Loading a pretrained model
In text, to load a pretrained model, we need to adapt the embeddings of the vocabulary used for the pre-training to the vocabulary of our current corpus.
```
#export
def match_embeds(old_wgts, old_vocab, new_vocab):
"Convert the embedding in `old_wgts` to go from `old_vocab` to `new_vocab`."
bias, wgts = old_wgts.get('1.decoder.bias', None), old_wgts['0.encoder.weight']
wgts_m = wgts.mean(0)
new_wgts = wgts.new_zeros((len(new_vocab),wgts.size(1)))
if bias is not None:
bias_m = bias.mean(0)
new_bias = bias.new_zeros((len(new_vocab),))
old_o2i = old_vocab.o2i if hasattr(old_vocab, 'o2i') else {w:i for i,w in enumerate(old_vocab)}
for i,w in enumerate(new_vocab):
idx = old_o2i.get(w, -1)
new_wgts[i] = wgts[idx] if idx>=0 else wgts_m
if bias is not None: new_bias[i] = bias[idx] if idx>=0 else bias_m
old_wgts['0.encoder.weight'] = new_wgts
if '0.encoder_dp.emb.weight' in old_wgts: old_wgts['0.encoder_dp.emb.weight'] = new_wgts.clone()
old_wgts['1.decoder.weight'] = new_wgts.clone()
if bias is not None: old_wgts['1.decoder.bias'] = new_bias
return old_wgts
```
For words in `new_vocab` that don't have a corresponding match in `old_vocab`, we use the mean of all pretrained embeddings.
```
wgts = {'0.encoder.weight': torch.randn(5,3)}
new_wgts = match_embeds(wgts.copy(), ['a', 'b', 'c'], ['a', 'c', 'd', 'b'])
old,new = wgts['0.encoder.weight'],new_wgts['0.encoder.weight']
test_eq(new[0], old[0])
test_eq(new[1], old[2])
test_eq(new[2], old.mean(0))
test_eq(new[3], old[1])
#hide
#With bias
wgts = {'0.encoder.weight': torch.randn(5,3), '1.decoder.bias': torch.randn(5)}
new_wgts = match_embeds(wgts.copy(), ['a', 'b', 'c'], ['a', 'c', 'd', 'b'])
old_w,new_w = wgts['0.encoder.weight'],new_wgts['0.encoder.weight']
old_b,new_b = wgts['1.decoder.bias'], new_wgts['1.decoder.bias']
test_eq(new_w[0], old_w[0])
test_eq(new_w[1], old_w[2])
test_eq(new_w[2], old_w.mean(0))
test_eq(new_w[3], old_w[1])
test_eq(new_b[0], old_b[0])
test_eq(new_b[1], old_b[2])
test_eq(new_b[2], old_b.mean(0))
test_eq(new_b[3], old_b[1])
#export
def _get_text_vocab(dls):
vocab = dls.vocab
if isinstance(vocab, L): vocab = vocab[0]
return vocab
#export
def load_ignore_keys(model, wgts):
"Load `wgts` in `model` ignoring the names of the keys, just taking parameters in order"
sd = model.state_dict()
for k1,k2 in zip(sd.keys(), wgts.keys()): sd[k1].data = wgts[k2].data.clone()
return model.load_state_dict(sd)
#export
def _rm_module(n):
t = n.split('.')
for i in range(len(t)-1, -1, -1):
if t[i] == 'module':
t.pop(i)
break
return '.'.join(t)
#export
#For previous versions compatibility, remove for release
def clean_raw_keys(wgts):
keys = list(wgts.keys())
for k in keys:
t = k.split('.module')
if f'{_rm_module(k)}_raw' in keys: del wgts[k]
return wgts
#export
#For previous versions compatibility, remove for release
def load_model_text(file, model, opt, with_opt=None, device=None, strict=True):
"Load `model` from `file` along with `opt` (if available, and if `with_opt`)"
distrib_barrier()
if isinstance(device, int): device = torch.device('cuda', device)
elif device is None: device = 'cpu'
state = torch.load(file, map_location=device)
hasopt = set(state)=={'model', 'opt'}
model_state = state['model'] if hasopt else state
get_model(model).load_state_dict(clean_raw_keys(model_state), strict=strict)
if hasopt and ifnone(with_opt,True):
try: opt.load_state_dict(state['opt'])
except:
if with_opt: warn("Could not load the optimizer state.")
elif with_opt: warn("Saved filed doesn't contain an optimizer state.")
#export
@log_args(but_as=Learner.__init__)
@delegates(Learner.__init__)
class TextLearner(Learner):
"Basic class for a `Learner` in NLP."
def __init__(self, dls, model, alpha=2., beta=1., moms=(0.8,0.7,0.8), **kwargs):
super().__init__(dls, model, moms=moms, **kwargs)
self.add_cbs([ModelResetter(), RNNRegularizer(alpha=alpha, beta=beta)])
def save_encoder(self, file):
"Save the encoder to `file` in the model directory"
if rank_distrib(): return # don't save if child proc
encoder = get_model(self.model)[0]
if hasattr(encoder, 'module'): encoder = encoder.module
torch.save(encoder.state_dict(), join_path_file(file, self.path/self.model_dir, ext='.pth'))
def load_encoder(self, file, device=None):
"Load the encoder `file` from the model directory, optionally ensuring it's on `device`"
encoder = get_model(self.model)[0]
if device is None: device = self.dls.device
if hasattr(encoder, 'module'): encoder = encoder.module
distrib_barrier()
wgts = torch.load(join_path_file(file,self.path/self.model_dir, ext='.pth'), map_location=device)
encoder.load_state_dict(clean_raw_keys(wgts))
self.freeze()
return self
def load_pretrained(self, wgts_fname, vocab_fname, model=None):
"Load a pretrained model and adapt it to the data vocabulary."
old_vocab = load_pickle(vocab_fname)
new_vocab = _get_text_vocab(self.dls)
distrib_barrier()
wgts = torch.load(wgts_fname, map_location = lambda storage,loc: storage)
if 'model' in wgts: wgts = wgts['model'] #Just in case the pretrained model was saved with an optimizer
wgts = match_embeds(wgts, old_vocab, new_vocab)
load_ignore_keys(self.model if model is None else model, clean_raw_keys(wgts))
self.freeze()
return self
#For previous versions compatibility. Remove at release
@delegates(load_model_text)
def load(self, file, with_opt=None, device=None, **kwargs):
if device is None: device = self.dls.device
if self.opt is None: self.create_opt()
file = join_path_file(file, self.path/self.model_dir, ext='.pth')
load_model_text(file, self.model, self.opt, device=device, **kwargs)
return self
```
Adds a `ModelResetter` and an `RNNRegularizer` with `alpha` and `beta` to the callbacks, the rest is the same as `Learner` init.
This `Learner` adds functionality to the base class:
```
show_doc(TextLearner.load_pretrained)
```
`wgts_fname` should point to the weights of the pretrained model and `vocab_fname` to the vocabulary used to pretrain it.
```
show_doc(TextLearner.save_encoder)
```
The model directory is `Learner.path/Learner.model_dir`.
```
show_doc(TextLearner.load_encoder)
```
## Language modeling predictions
For language modeling, the predict method is quite different form the other applications, which is why it needs its own subclass.
```
#export
def decode_spec_tokens(tokens):
"Decode the special tokens in `tokens`"
new_toks,rule,arg = [],None,None
for t in tokens:
if t in [TK_MAJ, TK_UP, TK_REP, TK_WREP]: rule = t
elif rule is None: new_toks.append(t)
elif rule == TK_MAJ:
new_toks.append(t[:1].upper() + t[1:].lower())
rule = None
elif rule == TK_UP:
new_toks.append(t.upper())
rule = None
elif arg is None:
try: arg = int(t)
except: rule = None
else:
if rule == TK_REP: new_toks.append(t * arg)
else: new_toks += [t] * arg
return new_toks
test_eq(decode_spec_tokens(['xxmaj', 'text']), ['Text'])
test_eq(decode_spec_tokens(['xxup', 'text']), ['TEXT'])
test_eq(decode_spec_tokens(['xxrep', '3', 'a']), ['aaa'])
test_eq(decode_spec_tokens(['xxwrep', '3', 'word']), ['word', 'word', 'word'])
#export
@log_args(but_as=TextLearner.__init__)
class LMLearner(TextLearner):
"Add functionality to `TextLearner` when dealing with a language model"
def predict(self, text, n_words=1, no_unk=True, temperature=1., min_p=None, no_bar=False,
decoder=decode_spec_tokens, only_last_word=False):
"Return `text` and the `n_words` that come after"
self.model.reset()
idxs = idxs_all = self.dls.test_dl([text]).items[0].to(self.dls.device)
if no_unk: unk_idx = self.dls.vocab.index(UNK)
for _ in (range(n_words) if no_bar else progress_bar(range(n_words), leave=False)):
with self.no_bar(): preds,_ = self.get_preds(dl=[(idxs[None],)])
res = preds[0][-1]
if no_unk: res[unk_idx] = 0.
if min_p is not None:
if (res >= min_p).float().sum() == 0:
warn(f"There is no item with probability >= {min_p}, try a lower value.")
else: res[res < min_p] = 0.
if temperature != 1.: res.pow_(1 / temperature)
idx = torch.multinomial(res, 1).item()
idxs = idxs_all = torch.cat([idxs_all, idxs.new([idx])])
if only_last_word: idxs = idxs[-1][None]
num = self.dls.train_ds.numericalize
tokens = [num.vocab[i] for i in idxs_all if num.vocab[i] not in [BOS, PAD]]
sep = self.dls.train_ds.tokenizer.sep
return sep.join(decoder(tokens))
@delegates(Learner.get_preds)
def get_preds(self, concat_dim=1, **kwargs): return super().get_preds(concat_dim=1, **kwargs)
show_doc(LMLearner, title_level=3)
show_doc(LMLearner.predict)
```
The words are picked randomly among the predictions, depending on the probability of each index. `no_unk` means we never pick the `UNK` token, `temperature` is applied to the predictions, if `min_p` is passed, we don't consider the indices with a probability lower than it. Set `no_bar` to `True` if you don't want any progress bar, and you can pass a long a custom `decoder` to process the predicted tokens.
## `Learner` convenience functions
```
#export
from fastai.text.models.core import _model_meta
#export
def _get_text_vocab(dls):
vocab = dls.vocab
if isinstance(vocab, L): vocab = vocab[0]
return vocab
#export
@log_args(to_return=True, but_as=Learner.__init__)
@delegates(Learner.__init__)
def language_model_learner(dls, arch, config=None, drop_mult=1., backwards=False, pretrained=True, pretrained_fnames=None, **kwargs):
"Create a `Learner` with a language model from `dls` and `arch`."
vocab = _get_text_vocab(dls)
model = get_language_model(arch, len(vocab), config=config, drop_mult=drop_mult)
meta = _model_meta[arch]
learn = LMLearner(dls, model, loss_func=CrossEntropyLossFlat(), splitter=meta['split_lm'], **kwargs)
url = 'url_bwd' if backwards else 'url'
if pretrained or pretrained_fnames:
if pretrained_fnames is not None:
fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])]
else:
if url not in meta:
warn("There are no pretrained weights for that architecture yet!")
return learn
model_path = untar_data(meta[url] , c_key='model')
try: fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']]
except IndexError: print(f'The model in {model_path} is incomplete, download again'); raise
learn = learn.load_pretrained(*fnames)
return learn
```
You can use the `config` to customize the architecture used (change the values from `awd_lstm_lm_config` for this), `pretrained` will use fastai's pretrained model for this `arch` (if available) or you can pass specific `pretrained_fnames` containing your own pretrained model and the corresponding vocabulary. All other arguments are passed to `Learner`.
```
path = untar_data(URLs.IMDB_SAMPLE)
df = pd.read_csv(path/'texts.csv')
dls = TextDataLoaders.from_df(df, path=path, text_col='text', is_lm=True, valid_col='is_valid')
learn = language_model_learner(dls, AWD_LSTM)
```
You can then use the `.predict` method to generate new text.
```
learn.predict('This movie is about', n_words=20)
```
By default the entire sentence is feed again to the model after each predicted word, this little trick shows an improvement on the quality of the generated text. If you want to feed only the last word, specify argument `only_last_word`.
```
learn.predict('This movie is about', n_words=20, only_last_word=True)
#export
@log_args(to_return=True, but_as=Learner.__init__)
@delegates(Learner.__init__)
def text_classifier_learner(dls, arch, seq_len=72, config=None, backwards=False, pretrained=True, drop_mult=0.5, n_out=None,
lin_ftrs=None, ps=None, max_len=72*20, y_range=None, **kwargs):
"Create a `Learner` with a text classifier from `dls` and `arch`."
vocab = _get_text_vocab(dls)
if n_out is None: n_out = get_c(dls)
assert n_out, "`n_out` is not defined, and could not be inferred from data, set `dls.c` or pass `n_out`"
model = get_text_classifier(arch, len(vocab), n_out, seq_len=seq_len, config=config, y_range=y_range,
drop_mult=drop_mult, lin_ftrs=lin_ftrs, ps=ps, max_len=max_len)
meta = _model_meta[arch]
learn = TextLearner(dls, model, splitter=meta['split_clas'], **kwargs)
url = 'url_bwd' if backwards else 'url'
if pretrained:
if url not in meta:
warn("There are no pretrained weights for that architecture yet!")
return learn
model_path = untar_data(meta[url], c_key='model')
try: fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']]
except IndexError: print(f'The model in {model_path} is incomplete, download again'); raise
learn = learn.load_pretrained(*fnames, model=learn.model[0])
learn.freeze()
return learn
```
You can use the `config` to customize the architecture used (change the values from `awd_lstm_clas_config` for this), `pretrained` will use fastai's pretrained model for this `arch` (if available). `drop_mult` is a global multiplier applied to control all dropouts. `n_out` is usually inferred from the `dls` but you may pass it.
The model uses a `SentenceEncoder`, which means the texts are passed `seq_len` tokens at a time, and will only compute the gradients on the last `max_len` steps. `lin_ftrs` and `ps` are passed to `get_text_classifier`.
All other arguments are passed to `Learner`.
```
path = untar_data(URLs.IMDB_SAMPLE)
df = pd.read_csv(path/'texts.csv')
dls = TextDataLoaders.from_df(df, path=path, text_col='text', label_col='label', valid_col='is_valid')
learn = text_classifier_learner(dls, AWD_LSTM)
```
## Show methods -
```
#export
@typedispatch
def show_results(x: LMTensorText, y, samples, outs, ctxs=None, max_n=10, **kwargs):
if ctxs is None: ctxs = get_empty_df(min(len(samples), max_n))
for i,l in enumerate(['input', 'target']):
ctxs = [b.show(ctx=c, label=l, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs,range(max_n))]
ctxs = [b.show(ctx=c, label='pred', **kwargs) for b,c,_ in zip(outs.itemgot(0),ctxs,range(max_n))]
display_df(pd.DataFrame(ctxs))
return ctxs
#export
@typedispatch
def show_results(x: TensorText, y, samples, outs, ctxs=None, max_n=10, trunc_at=150, **kwargs):
if ctxs is None: ctxs = get_empty_df(min(len(samples), max_n))
samples = L((s[0].truncate(trunc_at),*s[1:]) for s in samples)
ctxs = show_results[object](x, y, samples, outs, ctxs=ctxs, max_n=max_n, **kwargs)
display_df(pd.DataFrame(ctxs))
return ctxs
#export
@typedispatch
def plot_top_losses(x: TensorText, y:TensorCategory, samples, outs, raws, losses, trunc_at=150, **kwargs):
rows = get_empty_df(len(samples))
samples = L((s[0].truncate(trunc_at),*s[1:]) for s in samples)
for i,l in enumerate(['input', 'target']):
rows = [b.show(ctx=c, label=l, **kwargs) for b,c in zip(samples.itemgot(i),rows)]
outs = L(o + (TitledFloat(r.max().item()), TitledFloat(l.item())) for o,r,l in zip(outs, raws, losses))
for i,l in enumerate(['predicted', 'probability', 'loss']):
rows = [b.show(ctx=c, label=l, **kwargs) for b,c in zip(outs.itemgot(i),rows)]
display_df(pd.DataFrame(rows))
```
## Export -
```
#hide
from nbdev.export import notebook2script
notebook2script()
```
| github_jupyter |
```
%matplotlib inline
```
Net file
========
This is the Net file for the clique problem: state and output transition function definition
```
import tensorflow as tf
import numpy as np
def weight_variable(shape, nm):
'''function to initialize weights'''
initial = tf.truncated_normal(shape, stddev=0.1)
tf.summary.histogram(nm, initial, collections=['always'])
return tf.Variable(initial, name=nm)
class Net:
'''class to define state and output network'''
def __init__(self, input_dim, state_dim, output_dim):
'''initialize weight and parameter'''
self.EPSILON = 0.00000001
self.input_dim = input_dim
self.state_dim = state_dim
self.output_dim = output_dim
self.state_input = self.input_dim - 1 + state_dim
#### TO BE SET FOR A SPECIFIC PROBLEM
self.state_l1 = 15
self.state_l2 = self.state_dim
self.output_l1 = 10
self.output_l2 = self.output_dim
# list of weights
self.weights = {'State_L1': weight_variable([self.state_input, self.state_l1], "WEIGHT_STATE_L1"),
'State_L2': weight_variable([ self.state_l1, self.state_l2], "WEIGHT_STATE_L1"),
'Output_L1':weight_variable([self.state_l2,self.output_l1], "WEIGHT_OUTPUT_L1"),
'Output_L2': weight_variable([self.output_l1, self.output_l2], "WEIGHT_OUTPUT_L2")
}
# list of biases
self.biases = {'State_L1': weight_variable([self.state_l1],"BIAS_STATE_L1"),
'State_L2': weight_variable([self.state_l2], "BIAS_STATE_L2"),
'Output_L1':weight_variable([self.output_l1],"BIAS_OUTPUT_L1"),
'Output_L2': weight_variable([ self.output_l2], "BIAS_OUTPUT_L2")
}
def netSt(self, inp):
with tf.variable_scope('State_net'):
# method to define the architecture of the state network
layer1 = tf.nn.tanh(tf.add(tf.matmul(inp,self.weights["State_L1"]),self.biases["State_L1"]))
layer2 = tf.nn.tanh(tf.add(tf.matmul(layer1, self.weights["State_L2"]), self.biases["State_L2"]))
return layer2
def netOut(self, inp):
# method to define the architecture of the output network
with tf.variable_scope('Out_net'):
layer1 = tf.nn.tanh(tf.add(tf.matmul(inp, self.weights["Output_L1"]), self.biases["Output_L1"]))
layer2 = tf.nn.softmax(tf.add(tf.matmul(layer1, self.weights["Output_L2"]), self.biases["Output_L2"]))
return layer2
def Loss(self, output, target, output_weight=None):
# method to define the loss function
#lo=tf.losses.softmax_cross_entropy(target,output)
output = tf.maximum(output, self.EPSILON, name="Avoiding_explosions") # to avoid explosions
xent = -tf.reduce_sum(target * tf.log(output), 1)
lo = tf.reduce_mean(xent)
return lo
def Metric(self, target, output, output_weight=None):
# method to define the evaluation metric
correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(target, 1))
metric = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return metric
```
| github_jupyter |
# Turn water observations into waterbody polygons <img align="right" src="../../Supplementary_data/dea_logo.jpg">
* **Compatibility:** Notebook currently compatible with both the NCI and DEA Sandbox environments if you set your filepaths to the required datasets.
* **Products used:**
[wofs_summary](https://explorer.sandbox.dea.ga.gov.au/wofs_summary)
* **Special requirements:**
This notebook requires the [python_geohash](https://pypi.org/project/python-geohash/) library. If you are using the default dea environment, this package may not be available. You can install it locally by using `pip install --user python-geohash`.
* **Prerequisites:**
* NetCDF files with WOfS outputs that will be used to define the persistent water body polygons
* Variable name: `TileFolder`
* This folder can be either a custom extraction of datacube-stats, or you can choose to use the WOfS summary tiles for all of Australia (see [here for further information](#Tiles)).
* A coastline polygon to filter out polygons generated from ocean pixels.
* Variable name: `LandSeaMaskFile`
* Here we have generated a hightide coastline using the [Intertidal Extents Model (ITEM) v2](http://pid.geoscience.gov.au/dataset/ga/113842) dataset. See [here for more details](#coastline)
* **Optional prerequisites:**
* River line dataset for filtering out polygons comprised of river segments.
* Variable name: `MajorRiversDataset`
* The option to filter out major rivers is provided, and so this dataset is optional if `FilterOutRivers = False`.
* Here we use the [Bureau of Meteorology's Geofabric v 3.0.5 Beta (Suface Hydrology Network)](ftp://ftp.bom.gov.au/anon/home/geofabric/), filtered to only keep features tagged as `major rivers`.
* There are some identified issues with this data layer that make the filtering using this data inconsistent (see [the discussion here](#rivers))
* We therefore turn this off during the production of the water bodies shapefile.
* Urban high rise polygon dataset
* Variable name: `UrbanMaskFile`, but this is optional and can be skipped by setting `UrbanMask = False`.
* WOfS has a known limitation, where deep shadows thrown by tall CBD buildings are misclassified as water. This results in 'waterbodies' around these misclassified shadows in capital cities. If you are not using WOfS for your analysis, you may choose to set `UrbanMask = False`.
## Background
On average, the Australian Government invests around half a billion dollars a year in monitoring, protecting and enhancing Australia's land, coasts and oceans. DEA provides near real-time satellite information which can be used by government to better target these investments.
Water is among one the most precious natural resources and is essential for the survival of life on Earth. Within Australia, the scarcity of water is both an economic and social issue. Water is required not only for consumption but for industries and environmental ecosystems to function and flourish.
With the demand for water increasing, there is a need to better understand our water availability to ensure we are managing our water resources effectively and efficiently.
Digital Earth Australia (DEA)'s [Water Observations from Space (WOfS) dataset](https://www.sciencedirect.com/science/article/pii/S0034425715301929), provides a water classified image of Australia approximately every 16 days. These individual water observations have been combined into a [WOfS summary product](https://explorer.sandbox.dea.ga.gov.au/wofs_summary), which calculates the frequency of wet observations (compared against all clear observations of that pixel), over the full 30 year satellite archive.
The WOfS summary product provides valuable insights into the persistence of water across the Australian landscape on a pixel by pixel basis. While knowing the wet history of a single pixel within a waterbody is useful, it is more useful to be able to map the whole waterbody as a single object.
This notebook demonstrates a workflow for mapping waterbodies across Australia as polygon objects. This workflow has been used to produce **DEA Waterbodies**.
## Description
This code follows the following workflow:
* Load the required python packages
* Load the required functions
* Set your chosen analysis parameters
* minimum number of valid observations
* wetness threshold/s
* min/max waterbody size
* optional flag to filter out waterbodies that intersect with major rivers
* if you set this flag you will need to provide a dataset to do the filtering
* set the analysis region
* set the input files for the analysis
* read in a land/sea mask
* read in an urban mask
* Generate a list of netCDF files within a specified folder location
* Opens each netCDF file and:
* Keep only pixels observed at least x times
* Keep only pixels identified as wet at least x% of the time
* Here the code can take in two wetness thresholds, to produce two initial temporary polygon files.
* Convert the raster data into polygons
* Append the polygon set to a temporary shapefile
* Remove artificial polygon borders created at tile boundaries by merging polygons that intersect across Albers Tile boundaries
* Filter the combined polygon dataset (note that this step happens after the merging of Albers tile boundary polygons to ensure that artifacts are not created by part of a polygon being filtered out, while the remainder of the polygon that sits on a separate tile is treated differently).
* Filter the polygons based on size
* Remove polygons that intersect with Australia's coastline
* Remove erroneous 'water' polygons within high-rise CBD areas
* Combine the two generated wetness thresholds (optional)
* Optional filtering for proximity to major rivers (as identified by the Geofabric dataset)
* Save out the final polygon set to a shapefile
## Getting started
To run this analysis, work through this notebook starting with the "Load packages" cell.
### Load packages
Import Python packages that are used for the analysis.
```
import rasterio.features
from shapely.geometry import Polygon, shape, mapping
from shapely.ops import unary_union
import geopandas as gp
import fiona
from fiona.crs import from_epsg
import xarray as xr
import pandas as pd
import glob
import os.path
import math
import geohash as gh
import re
```
### Set up the functions for this script
```
def Generate_list_of_albers_tiles(TileFolder="TileFolder", CustomData=True):
"""
Generate a list of Albers tiles to loop through for the water body analysis. This
function assumes that the list of tiles will be generated from a custom
datacube-stats run, and the file names will have the format
*/wofs_summary_8_-37_{date}.nc
The tile number is expected in the 2nd and 3rd last positions when the string has been
broken using `_`. If this is not the case, then this code will not work, and will throw an error.
Parameters
----------
TileFolder : str
This is the path to the folder of netCDF files for analysis. If this is not provided, or an
incorrect path name is provided, the code will exit with an error.
CustomData : boolean
This is passed in from elsewhere in the notebook. If this is not entered, the default parameter is True.
Returns
-------
CustomRegionAlbersTiles: list
List of Albers tiles across the analysis region.
E.g. ['8_-32', '9_-32', '10_-32', '8_-33', '9_-33']
"""
if os.path.exists(TileFolder) == False:
print(
"** ERROR ** \n"
"You need to specify a folder of files for running a custom region")
return
# Grab a list of all of the netCDF files in the tile folder
TileFiles = glob.glob(f"{TileFolder}*.nc")
CustomRegionAlbersTiles = set()
for filePath in TileFiles:
AlbersTiles = re.split("[_\.]", filePath)
if CustomData:
# Test that the albers tile numbers are actually where we expect them to be in the file name
try:
int(AlbersTiles[-4])
int(AlbersTiles[-3])
except ValueError:
print(
"** ERROR ** \n"
'The netCDF files are expected to have the file format "*/wofs_summary_8_-37_{date}.nc",\n'
"with the Albers tile numbers in the 2nd and 3rd last positions when separated on `_`. \n"
"Please fix the file names, or alter the `Generate_list_of_albers_tiles` function."
)
return
# Now that we're happy that the file is reading the correct Albers tiles
ThisTile = f"{AlbersTiles[-3]}_{AlbersTiles[-2]}"
else:
# Test that the albers tile numbers are actually where we expect them to be in the file name
try:
int(AlbersTiles[-3])
int(AlbersTiles[-2])
except ValueError:
print(
"** ERROR ** \n"
'The netCDF files are expected to have the file format "*/wofs_filtered_summary_8_-37.nc",\n'
"with the Albers tile numbers in the 2nd and 3rd last positions when separated on `_` and `.`. \n"
"Please fix the file names, or alter the `Generate_list_of_albers_tiles` function."
)
return
# Now that we're happy that the file is reading the correct Albers tiles
ThisTile = f"{AlbersTiles[-3]}_{AlbersTiles[-2]}"
CustomRegionAlbersTiles.add(ThisTile)
CustomRegionAlbersTiles = list(CustomRegionAlbersTiles)
return CustomRegionAlbersTiles
def Generate_list_of_tile_datasets(ListofAlbersTiles,
Year,
TileFolder="TileFolder",
CustomData=True):
"""
Generate a list of Albers tiles datasets to loop through for the water body analysis. Here, the
ListofAlbersTiles is used to generate a list of NetCDF files where the Albers coordinates have
been substituted into the naming file format.
Parameters
----------
CustomRegionAlbersTiles: list
List of albers tiles to loop through
E.g. ['8_-32', '9_-32', '10_-32', '8_-33', '9_-33']
Year: int
Year for the analysis. This will correspond to the netCDF files for analysis.
TileFolder : str
This is the path to the folder of netCDF files for analysis. If this is not provided, or an
incorrect path name is provided, the code will exit with an error.
CustomData : boolean
This is passed from elsewhere in the notebook. If this parameter is not entered, the default value
is True.
Returns
-------
Alltilespaths: list
List of file paths to files to be analysed.
"""
if os.path.exists(TileFolder) == False:
print(
"** ERROR ** \n"
"You need to specify a folder of files for running a custom region")
raise
Alltilespaths = []
if CustomData:
for tile in ListofAlbersTiles:
Tiles = glob.glob(f"{TileFolder}*_{tile}_{Year}0101.nc")
Alltilespaths.append(
Tiles[0]) # Assumes only one file will be returned
else:
for tile in ListofAlbersTiles:
# Use glob to check that the file actually exists in the format we expect
Tiles = glob.glob(f"{TileFolder}wofs_filtered_summary_{tile}.nc")
# Check that assumption by seeing if the returned list is empty
if not Tiles:
Tiles = glob.glob(f"{TileFolder}WOFS_3577_{tile}_summary.nc")
# Check that we actually have something now
if not Tiles:
print(
"** ERROR ** \n"
"An assumption in the file naming conventions has gone wrong somewhere.\n"
"We assume two file naming formats here: {TileFolder}wofs_filtered_summary_{tile}.nc, \n"
"and {TileFolder}WOFS_3577_{tile}_summary.nc. The files you have directed to don't meet \n"
"either assumption. Please fix the file names, or alter the `Generate_list_of_albers_tiles` function."
)
Alltilespaths.append(
Tiles[0]) # Assumes only one file will be returned
return Alltilespaths
def Filter_shapefile_by_intersection(gpdData,
gpdFilter,
filtertype="intersects",
invertMask=True,
returnInverse=False):
"""
Filter out polygons that intersect with another polygon shapefile.
Parameters
----------
gpdData: geopandas dataframe
Polygon data that you wish to filter
gpdFilter: geopandas dataframe
Dataset you are using as a filter
Optional
--------
filtertype: default = 'intersects'
Options = ['intersects', 'contains', 'within']
invertMask: boolean
Default = 'True'. This determines whether you want areas that DO ( = 'False') or DON'T ( = 'True')
intersect with the filter shapefile.
returnInnverse: boolean
Default = 'False'. If true, then return both parts of the intersection - those that intersect AND
those that don't as two dataframes.
Returns
-------
gpdDataFiltered: geopandas dataframe
Filtered polygon set, with polygons that intersect with gpdFilter removed.
IntersectIndex: list of indices of gpdData that intersect with gpdFilter
Optional
--------
if 'returnInverse = True'
gpdDataFiltered, gpdDataInverse: two geopandas dataframes
Filtered polygon set, with polygons that DON'T intersect with gpdFilter removed.
"""
# Check that the coordinate reference systems of both dataframes are the same
# assert gpdData.crs == gpdFilter.crs, 'Make sure the the coordinate reference systems of the two provided dataframes are the same'
Intersections = gp.sjoin(gpdFilter, gpdData, how="inner", op=filtertype)
# Find the index of all the polygons that intersect with the filter
IntersectIndex = sorted(set(Intersections["index_right"]))
# Grab only the polygons NOT in the IntersectIndex
# i.e. that don't intersect with a river
if invertMask:
gpdDataFiltered = gpdData.loc[~gpdData.index.isin(IntersectIndex)]
else:
gpdDataFiltered = gpdData.loc[gpdData.index.isin(IntersectIndex)]
if returnInverse:
# We need to use the indices from IntersectIndex to find the inverse dataset, so we
# will just swap the '~'.
if invertMask:
gpdDataInverse = gpdData.loc[gpdData.index.isin(IntersectIndex)]
else:
gpdDataInverse = gpdData.loc[~gpdData.index.isin(IntersectIndex)]
return gpdDataFiltered, IntersectIndex, gpdDataInverse
else:
return gpdDataFiltered, IntersectIndex
```
## Analysis parameters
The following section walks you through the analysis parameters you will need to set for this workflow. Each section describes the parameter, how it is used, and what value was used for the DEA Waterbodies product.
<a id='wetnessThreshold'></a>
### How frequently wet does a pixel need to be to be included?
The value/s set here will be the minimum frequency (as a decimal between 0 and 1) that you want water to be detected across all analysis years before it is included.
E.g. If this was set to 0.10, any pixels that are wet *at least* 10% of the time across all valid observations will be included. If you don't want to use this filter, set this value to 0.
Following the exploration of an appropriate wetness threshold for DEA Waterbodies ([see here](DEAWaterbodiesSupplement/DEAWaterbodiesThresholdSensitivityAnalysis.ipynb)), we choose to set two thresholds here. The code is set up to loop through both wetness thresholds, and to write out two temporary shapefiles. These two shapefiles with two separate thresholds are then used together to combine polygons from both thresholds later on in the workflow.
Polygons identified by the secondary threshold that intersect with the polygons generated by the primary threshold will be extracted, and included in the final polygon dataset. This means that the **location** of polygons is set by the primary threshold, but the **shape** of these polygons is set by the secondary threshold.
Threshold values need to be provided as a list of either one or two floating point numbers. If one number is provided, then this will be used to generate the initial polygon dataset. If two thresholds are entered, the **first number becomes the secondary threshold, and the second number becomes the primary threshold**. If more than two numbers are entered, the code will generate an error below.
```
AtLeastThisWet = [0.05, 0.1]
```
<a id='size'></a>
### How big/small should the polygons be?
This filtering step can remove very small and/or very large waterbody polygons. The size listed here is in m2. A single pixel in Landsat data is 25 m X 25 m = 625 m2.
**MinSize**
E.g. A minimum size of 6250 means that polygons need to be at least 10 pixels to be included. If you don't want to use this filter, set this value to 0.
**MaxSize**
E.g. A maximum size of 1 000 000 means that you only want to consider polygons less than 1 km2. If you don't want to use this filter, set this number to `math.inf`.
*NOTE: if you are doing this analysis for all of Australia, very large polygons will be generated offshore, in the steps prior to filtering by the Australian coastline. For this reason, we have used a `MaxSize` = Area of Kati Thanda-Lake Eyre. This will remove the huge ocean polygons, but keep large inland waterbodies that we want to map.*
```
MinSize = 3125 # 5 pixels
MaxSize = 5000000000 # approx area of Lake Eyre
```
<a id='valid'></a>
### Filter results based on number of valid observations
The total number of valid WOfS observations for each pixel varies depending on the frequency of clouds and cloud shadow, the proximity to high slope and terrain shadow, and the seasonal change in solar angle.
The `count_clear` parameter within the [`wofs_summary`](https://explorer.sandbox.dea.ga.gov.au/wofs_summary) data provides a count of the number of valid observations each pixel recorded over the analysis period. We can use this parameter to mask out pixels that were infrequently observed.
If this mask is not applied, pixels that were observed only once could be included if that observation was wet (i.e. a single wet observation means the calculation of the frequency statistic would be (1 wet observation) / (1 total observation) = 100% frequency of wet observations).
Here we set the minimum number of observations to be 128 (roughly 4 per year over our 32 year analysis). Note that this parameter does not specify the timing of these observations, but rather just the **total number of valid observations** (observed at any time of the year, in any year).
```
MinimumValidObs = 128
```
<a id='rivers'></a>
### Do you want to filter out polygons that intersect with major rivers?
The [Bureau of Meteorology's Geofabric v 3.0.5 Beta (Suface Hydrology Network)](ftp://ftp.bom.gov.au/anon/home/geofabric/) can be used to filter out polygons that intersect with major rivers. This is done to remove river segments from the polygon dataset. The `SH_Network AHGFNetworkStream any` layer within the `SH_Network_GDB_V2_1_1.zip` geodatabase can be used. You may chose to filter the rivers dataset to only keep rivers tagged as `major`, as the full rivers dataset contains a lot of higher order streams and can remove smaller waterbodies situated on upland streams.
If you have an alternative dataset you wish to use inplace of the Bureau of Meteorology Geofabric, you can set the filepath to this file in the `MajorRiversDataset` variable. Any alternative dataset needs to be a vector dataset, and [able to be read in by the fiona python library](https://fiona.readthedocs.io/en/latest/fiona.html#fiona.open).
Note that we reproject this dataset to `epsg 3577`, [Australian Albers coordinate reference system](https://spatialreference.org/ref/epsg/3577/) to match the coordinate reference system of the WOfS data we use. If this is not correct for your analysis, you can change this in the cell below. A list of epsg code [can be found here](https://spatialreference.org/ref/epsg/).
If you don't want to filter out polygons that intersect with rivers, set this parameter to `False`.
**Note that for the Water Body Polygon dataset, we set this filter to False (`FilterOutRivers = False`)**
#### Note when using the Geofabric to filter out rivers
The option to filter out rivers was switched off for the production of DEA Waterbodies.
Note that the Geofabric continues the streamline through on-river dams, which means these polygons are filtered out. This may not be the desired result.

```
FilterOutRivers = False
# Where is this file located?
MajorRiversDataset = '/g/data/r78/cek156/ShapeFiles/Geofabric_v2_1_1/SH_Network_GDB_V2_1_1_Major_Filtered.shp'
# Read in the major rivers dataset (if you are using it)
if FilterOutRivers:
MajorRivers = gp.GeoDataFrame.from_file(MajorRiversDataset)
MajorRivers = MajorRivers.to_crs({'init': 'epsg:3577'})
```
<a id='Tiles'></a>
### Set up the input datasets for the analysis
This section of code allows you to choose whether to use the WOfS summary data, or your own custom analysis.
There are a number of options available to you here:
* All of Australia WOfS analysis
* Set `AllofAustraliaAllTime = True`
* Set `CustomData = False`
* Set `AutoGenerateTileList = False`
* Some of Australia WOfS analysis
* Set `AllofAustraliaAllTime = False`
* Set `CustomData = False`
* Set `AutoGenerateTileList = False`
* You will then need to input a list of Albers Equal Area tiles over which you would like to perform your analysis in the `ListofAlbersTiles` variable.
* Custom analysis for any spatial extent
* Set `AllofAustraliaAllTime = False`
* Set `CustomData = True`
* Provide a path to where the files are sitting. *Note that this code assumes the files are netCDF.*
* Set `AutoGenerateTileList = True/False`
* If you want to analyse all of the tiles in the custom folder, set this to `True`.
* If you want to analyse a subset of the tiles in the custom folder, set this to `False`, and provide a list of tiles to the `ListofAlbersTiles` variable.
**All of Australia analysis**
If you would like to perform the analysis for all of Australia, using the published WOfS all time summaries, set `AllofAustraliaAllTime = True`.
The WOfS all time summaries NetCDF files used are located in `/g/data/fk4/datacube/002/WOfS/WOfS_Stats_25_2_1/netcdf/`. These files contain the following three variables: `count_wet`, `count_clear` and `frequency`.
**Custom Data option**
This code is set up to allow you to input your own set of custom data statistics. You can generate your own custom statistics using the [datacube-stats](https://github.com/opendatacube/datacube-stats) code repository.
For example, you may wish to calculate WOfS summary statistics over a specified period, rather than over the full 1987 to 2018 period provided in the WOfS summary product. Datacube-stats allows you to specify the parameters for generating statistical summaries. You will need to ensure the output format is set to netCDF to make it compatible with the code here.
If `CustomData = True`, you will need to specify the location of the data you would like to use for this analysis, setting `TileFolder` below, under the `if CustomData` code section below.
If `CustomData = False`, the code will automatically look at the published WOfS all time summaries.
**Autogeneration of tile list**
`AutoGenerateTileList` will only be used if `AllOfAustraliaAllTime = False`. We only want to generate a list of tiles to iterate through if it will be a subset of all of the available data.
If you would like to automatically generate a list of tiles using the outputs of an analysis (e.g. if you have run a custom `datacube-stats` analysis over just NSW), set `AutoGenerateTileList = True` and update the location of the output file directory. This will generate a tile list consisting of every available tile within that folder.
Note that this option currently assumes a filename format. If you experience an error when running this step, you may need to modify the `Generate_list_of_albers_tiles` function loaded above.
If you would like to manually feed in a list of albers tiles (i.e. run a subset of the tiles available within a chosen folder), set `AutoGenerateTileList = False`, and feed in a list of tiles in the format:
```
ListofAlbersTiles = ['7_-34', '10_-40', '16_-34']
```
For testing and debugging, set `CustomData = True` and `AutoGenerateTileList = False`, then enter a list of tiles to run using the `ListofAlbersTiles` described above.
```
AllOfAustraliaAllTime = False
CustomData = False
AutoGenerateTileList = False
if CustomData:
# Path to the files you would like to use for the analysis
TileFolder = '/g/data/r78/cek156/datacube_stats/WOFSDamsAllTimeNSWMDB/'
else:
# Default path to the WOfS summary product
TileFolder = '/g/data/fk4/datacube/002/WOfS/WOfS_Stats_25_2_1/netcdf/'
# We only want to generate the tile list if we are not doing all of Australia.
if not AllOfAustraliaAllTime:
if AutoGenerateTileList:
ListofAlbersTiles = Generate_list_of_albers_tiles(
TileFolder, CustomData)
else:
# Provide you own list of tiles to be run
ListofAlbersTiles = [
'8_-32', '19_-40', '10_-30', '14_-31', '13_-31', '18_-38', '19_-33',
'9_-31', '20_-34', '6_-39', '17_-31', '12_-40', '13_-39', '10_-38',
'6_-41', '16_-32', '9_-40', '10_-31', '16_-37', '10_-39', '16_-35',
'7_-38', '10_-37', '17_-39', '9_-34', '19_-35', '15_-33', '15_-30',
'11_-32', '20_-39', '17_-30', '13_-40', '7_-41', '17_-29', '12_-33',
'15_-28', '16_-40', '6_-35', '17_-40', '13_-38', '17_-42', '14_-39',
'13_-29', '17_-37', '16_-38', '9_-32', '16_-34', '9_-41', '11_-31',
'7_-36', '16_-39', '18_-30', '9_-37', '20_-37', '13_-32', '7_-40',
'18_-41', '20_-32', '8_-41', '14_-28', '18_-39', '14_-43', '12_-39',
'20_-36', '8_-34', '17_-41', '12_-41', '18_-31', '11_-38', '18_-34',
'14_-35', '12_-42', '19_-39', '12_-34', '10_-42', '11_-35',
'17_-35', '15_-41', '18_-33', '6_-37', '13_-41', '10_-40', '14_-33',
'13_-37', '8_-36', '6_-36', '16_-43', '18_-36', '14_-40', '15_-43',
'12_-30', '5_-39', '8_-39', '18_-35', '15_-39', '15_-29', '7_-34',
'11_-34', '14_-41', '15_-42', '16_-29', '16_-28', '14_-37', '8_-33',
'6_-38', '19_-38', '13_-33', '16_-36', '15_-37', '12_-38', '7_-35',
'18_-40', '12_-31', '16_-41', '14_-38', '19_-37', '10_-34',
'14_-32', '12_-32', '14_-42', '15_-35', '16_-31', '19_-36', '7_-37',
'11_-41', '14_-36', '13_-35', '16_-42', '13_-36', '6_-40', '17_-36',
'10_-41', '18_-37', '14_-29', '14_-30', '20_-38', '17_-38',
'12_-36', '10_-35', '9_-42', '21_-33', '12_-37', '17_-32', '15_-31',
'10_-36', '15_-36', '19_-34', '17_-34', '12_-35', '20_-40',
'20_-33', '19_-31', '20_-35', '16_-30', '18_-32', '12_-29',
'11_-30', '15_-32', '16_-33', '8_-37', '10_-33', '13_-34', '11_-33',
'13_-30', '11_-36', '8_-40', '11_-40', '10_-32', '9_-38', '11_-42',
'11_-39', '15_-34', '21_-34', '13_-42', '9_-35', '8_-42', '17_-33',
'8_-38', '13_-28', '15_-38', '9_-36', '8_-35', '11_-37', '14_-34',
'15_-40', '9_-33', '19_-32', '9_-39', '7_-39'
]
```
<a id='coastline'></a>
### Read in a land/sea mask
A high tide coastline for Australia is used to mask out ocean polygons. You can choose which land/sea mask you would like to use, depending on how much coastal water you would like in the final product.
We use a coastline generated using the [Intertidal Extents Model (ITEM) v2](http://pid.geoscience.gov.au/dataset/ga/113842) dataset. This particular coastline creates a mask by identifying any water pixels that are continuously connected to the ocean, or an estuary. Any polygons that intersect with this mask are filtered out. I.e. if a polygon identified within our workflow overlaps with this coastal mask by even a single pixel, it will be discarded. We chose this very severe ocean mask as the aim of DEA Waterbodies is not to map coastal waterbodies, but just inland ones. For a detailed description of how this coastline was created, see [this notebook](DEAWaterbodiesSupplement/CreateAustralianCoastlineUsingITEM.ipynb).
Note that the mask we use here sets `ocean = 1, land = NaN`. If your mask has `land = 1` instead, you can either invert it, or change the code in the [`Filter merged polygons by:`](#Filtering) code section below.
```
# Path to the coastal mask you would like to use.
LandSeaMaskFile = '/g/data/r78/cek156/ShapeFiles/ITEMv2Coastline/ITEM_Ocean_Polygon.shp'
Coastline = gp.read_file(LandSeaMaskFile)
Coastline = Coastline.to_crs({'init': 'epsg:3577'})
```
<a id='Urban'></a>
### Read in a mask for high-rise CBDs
WOfS has a known limitation, where deep shadows thrown by tall CBD buildings are misclassified as water. This results in 'waterbodies' around these misclassified shadows in capital cities.
To address this problem, we use the [Australian Bureau of Statistics Statistical Area 3 shapefile (2016)](http://www.abs.gov.au/AUSSTATS/abs@.nsf/DetailsPage/1270.0.55.001July%202016?OpenDocument#Data) to define a spatial footprint for Australia's CBD areas.
We use the following polygons as our CBD filter:
|SA3_CODE1|SA3_NAME16|
|---------|----------|
|11703 |Sydney Inner City|
|20604 |Melbourne City|
|30501 |Brisbane Inner|
|30901 |Broadbeach - Burleigh|
|30910 |Surfers Paradise|
|40101 |Adelaide City|
|50302 |Perth City|
If you are not using WOfS for your analysis, you may choose to set `UrbanMask = False`.
```
UrbanMask = True
if UrbanMask:
UrbanMaskFile = '/g/data/r78/cek156/ShapeFiles/ABS_1270055001_sa3_2016_aust_shape/HighRiseCBD_ABS_sa3.shp'
CBDs = gp.read_file(UrbanMaskFile)
CBDs = CBDs.to_crs({'init': 'epsg:3577'})
```
## Generate the first temporary polygon dataset
This code section:
1. Checks that the `AtLeastThisWet` threshold has been correctly entered above
2. Sets up a `for` loop that allows the user to input multiple temporal datasets (see below)
3. Generates a list of netCDF files to loop through
4. Sets up a `for` loop for that list of files. Here we have separate data for each Landsat tile, so this loop loops through the list of tile files
5. Opens the netCDF `frequency` data and removes the `time` dimension (which in this case is only of size 1)
6. Opens the netCDF `count_clear` data and removes the `time` dimension (which in this case is only of size 1)
7. Removes any pixels not observed at least [`MinimumValidObs` times](#valid)
8. Sets up a `for` loop for the entered [`AtLeastThisWet` thresholds](#wetnessThreshold)
9. Masks out any data that does not meet the wetness threshold
10. Converts the data to a Boolean array, with included pixels == 1
11. Converts the raster array to a polygon dataset
12. Cleans up the polygon dataset
13. Resets the `geometry` to a shapely geometry
14. Merges any overlapping polygons
15. Convert the output of the merging back into a geopandas dataframe
16. Calculates the area of each polygon
17. Saves the results to a shapefile
Within this section you need to set up:
- **WaterBodiesShp:** The name and filepath of the intermediate output polygon set
- **WOFSshpMerged:** The filepath for the location of temp files during the code run
- **WOFSshpFiltered:** The name and filepath of the outputs following the [filtering steps](#Filtering)
- **FinalName:** The name and file path of the final, completed waterbodies shapefile
- **years to analyse:** `for year in range(x,y)` - note that the last year is NOT included in the analysis. This for loop is set up to allow you to loop through multiple datasets to create multiple polygon outputs. If you only have one input dataset, set this to `range(<year of the analysis>, <year of the analysis + 1>)`
```
## Set up some file names for the inputs and outputs
# The name and filepath of the intermediate output polygon set
WaterBodiesShp = f'/g/data/r78/cek156/dea-notebooks/DEAWaterbodies/AusAllTime01-005HybridWaterbodies/Temp'
# The name and filepath of the temp, filtered output polygon set
WOFSshpMerged = f'/g/data/r78/cek156/dea-notebooks/DEAWaterbodies/AusAllTime01-005HybridWaterbodies/'
WOFSshpFiltered = '/g/data/r78/cek156/dea-notebooks/DEAWaterbodies/AusAllTime01-005HybridWaterbodies/AusWaterBodiesFiltered.shp'
# Final shapefile name
FinalName = '/g/data/r78/cek156/dea-notebooks/DEAWaterbodies/AusAllTime01-005HybridWaterbodies/AusWaterBodies.shp'
# First, test whether the wetness threshold has been correctly set
if len(AtLeastThisWet) == 2:
print(
f'We will be running a hybrid wetness threshold. Please ensure that the major threshold is \n'
f'listed second, with the supplementary threshold entered first.'
f'**You have set {AtLeastThisWet[-1]} as the primary threshold,** \n'
f'**with {AtLeastThisWet[0]} set as the supplementary threshold.**')
elif len(AtLeastThisWet) == 1:
print(
f'You have not set up the hybrid threshold option. If you meant to use this option, please \n'
f'set this option by including two wetness thresholds in the `AtLeastThisWet` variable above. \n'
f'The wetness threshold we will use is {AtLeastThisWet}.')
else:
raise ValueError(
f'There is something wrong with your entered wetness threshold. Please enter a list \n'
f'of either one or two numbers. You have entered {AtLeastThisWet}. \n'
f'See above for more information')
# Now perform the analysis to generate the first iteration of polygons
for year in range(1980, 1981):
### Get the list of netcdf file names to loop through
if AllOfAustraliaAllTime:
# Grab everything from the published WOfS all time summaries
Alltiles = glob.glob(f'{TileFolder}*.nc')
else:
Alltiles = Generate_list_of_tile_datasets(ListofAlbersTiles, year,
TileFolder, CustomData)
for WOFSfile in Alltiles:
try:
# Read in the data
# Note that the netCDF files we are using here contain a variable called 'frequency',
# which is what we are using to define our water polygons.
# If you use a different netCDF input source, you may need to change this variable name here
WOFSnetCDFData = xr.open_rasterio(f'NETCDF:{WOFSfile}:frequency')
# Remove the superfluous time dimension
WOFSnetCDFData = WOFSnetCDFData.squeeze()
# Open the clear count variable to generate the minimum observation mask
# If you use a different netCDF input source, you may need to change this variable name here
WOFSvalidcount = xr.open_rasterio(f'NETCDF:{WOFSfile}:count_clear')
WOFSvalidcount = WOFSvalidcount.squeeze()
# Filter our WOfS classified data layer to remove noise
# Remove any pixels not abserved at least MinimumValidObs times
WOFSValidFiltered = WOFSvalidcount >= MinimumValidObs
for Thresholds in AtLeastThisWet:
# Remove any pixels that are wet < AtLeastThisWet% of the time
WOFSfiltered = WOFSnetCDFData > Thresholds
# Now find pixels that meet both the MinimumValidObs and AtLeastThisWet criteria
# Change all zeros to NaN to create a nan/1 mask layer
# Pixels == 1 now represent our water bodies
WOFSfiltered = WOFSfiltered.where((WOFSfiltered != 0) &
(WOFSValidFiltered != 0))
# Convert the raster to polygons
# We use a mask of '1' to only generate polygons around values of '1' (not NaNs)
WOFSpolygons = rasterio.features.shapes(
WOFSfiltered.data.astype('float32'),
mask=WOFSfiltered.data.astype('float32') == 1,
transform=WOFSnetCDFData.transform)
# The rasterio.features.shapes returns a tuple. We only want to keep the geometry portion,
# not the value of each polygon (which here is just 1 for everything)
WOFSbreaktuple = (a for a, b in WOFSpolygons)
# Put our polygons into a geopandas geodataframe
PolygonGP = gp.GeoDataFrame(list(WOFSbreaktuple))
# Grab the geometries and convert into a shapely geometry
# so we can quickly calcuate the area of each polygon
PolygonGP['geometry'] = None
for ix, poly in PolygonGP.iterrows():
poly['geometry'] = shape(poly)
# Set the geometry of the dataframe to be the shapely geometry we just created
PolygonGP = PolygonGP.set_geometry('geometry')
# We need to add the crs back onto the dataframe
PolygonGP.crs = {'init': 'epsg:3577'}
# Combine any overlapping polygons
MergedPolygonsGeoms = unary_union(PolygonGP['geometry'])
# Turn the combined multipolygon back into a geodataframe
MergedPolygonsGPD = gp.GeoDataFrame(
[poly for poly in MergedPolygonsGeoms])
# Rename the geometry column
MergedPolygonsGPD.columns = ['geometry']
# We need to add the crs back onto the dataframe
MergedPolygonsGPD.crs = {'init': 'epsg:3577'}
# Calculate the area of each polygon again now that overlapping polygons
# have been merged
MergedPolygonsGPD['area'] = MergedPolygonsGPD['geometry'].area
# Save the polygons to a shapefile
schema = {
'geometry': 'Polygon',
'properties': {
'area': 'float'
}
}
# Generate our dynamic filename
FileName = f'{WaterBodiesShp}_{Thresholds}.shp'
# Append the file name to the list so we can call it later on
if os.path.isfile(FileName):
with fiona.open(FileName,
"a",
crs=from_epsg(3577),
driver='ESRI Shapefile',
schema=schema) as output:
for ix, poly in MergedPolygonsGPD.iterrows():
output.write(({
'properties': {
'area': poly['area']
},
'geometry': mapping(shape(poly['geometry']))
}))
else:
with fiona.open(FileName,
"w",
crs=from_epsg(3577),
driver='ESRI Shapefile',
schema=schema) as output:
for ix, poly in MergedPolygonsGPD.iterrows():
output.write(({
'properties': {
'area': poly['area']
},
'geometry': mapping(shape(poly['geometry']))
}))
except:
print(
f'{WOFSfile} did not run. \n'
f'This is probably because there are no waterbodies present in this tile.'
)
```
<a id='MergeTiles'></a>
## Merge polygons that have an edge at a tile boundary
Now that we have all of the polygons across our whole region of interest, we need to check for artifacts in the data caused by tile boundaries.
We have created a shapefile that consists of the albers tile boundaries, plus a 1 pixel (25 m) buffer. This shapefile will help us to find any polygons that have a boundary at the edge of an albers tile. We can then find where polygons touch across this boundary, and join them up.
Within this section you need to set up:
- **AlbersBuffer:** The file location of a shapefile that is a 1 pixel buffer around the Albers tile boundaries
*NOTE: for the Australia-wide analysis, the number and size of polygons means that this cell cannot be run in this notebook. Instead, we ran this cell on raijin*
```
#!/bin/bash
#PBS -P r78
#PBS -q hugemem
#PBS -l walltime=96:00:00
#PBS -l mem=500GB
#PBS -l jobfs=200GB
#PBS -l ncpus=7
#PBS -l wd
#PBS -lother=gdata1a
module use /g/data/v10/public/modules/modulefiles/
module load dea
PYTHONPATH=$PYTHONPATH:/g/data/r78/cek156/dea-notebooks
```
```
AlbersBuffer = gp.read_file('/g/data/r78/cek156/ShapeFiles/AlbersBuffer25m.shp')
for Threshold in AtLeastThisWet:
print(f'Working on {Threshold} shapefile')
# We are using the more severe wetness threshold as the main polygon dataset.
# Note that this assumes that the thresholds have been correctly entered into the 'AtLeastThisWet'
# variable, with the higher threshold listed second.
WaterPolygons = gp.read_file(f'{WaterBodiesShp}_{Threshold}.shp')
# Find where the albers polygon overlaps with our dam polygons
BoundaryMergedDams, IntersectIndexes, NotBoundaryDams = Filter_shapefile_by_intersection(
WaterPolygons, AlbersBuffer, invertMask=False, returnInverse=True)
# Now combine overlapping polygons in `BoundaryDams`
UnionBoundaryDams = BoundaryMergedDams.unary_union
# `Explode` the multipolygon back out into individual polygons
UnionGDF = gp.GeoDataFrame(crs=WaterPolygons.crs,
geometry=[UnionBoundaryDams])
MergedDams = UnionGDF.explode()
# Then combine our new merged polygons with the `NotBoundaryDams`
# Combine New merged polygons with the remaining polygons that are not near the tile boundary
AllTogether = gp.GeoDataFrame(
pd.concat([NotBoundaryDams, MergedDams], ignore_index=True,
sort=True)).set_geometry('geometry')
# Calculate the area of each polygon
AllTogether['area'] = AllTogether.area
# Check for nans
AllTogether.dropna(inplace=True)
schema = {'geometry': 'Polygon', 'properties': {'area': 'float'}}
print(f'Writing out {Threshold} shapefile')
with fiona.open(f'{WOFSshpMerged}Union_{Threshold}.shp',
"w",
crs=from_epsg(3577),
driver='ESRI Shapefile',
schema=schema) as output:
for ix, poly in AllTogether.iterrows():
output.write(({
'properties': {
'area': poly['area']
},
'geometry': mapping(shape(poly['geometry']))
}))
```
<a id='Filtering'></a>
## Filter the merged polygons by:
- **Area:**
Based on the `MinSize` and `MaxSize` parameters set [here](#size).
- **Coastline:**
Using the `Coastline` dataset loaded [here](#coastline).
- **CBD location (optional):**
Using the `CBDs` dataset loaded [here](#Urban).
- **Wetness thresholds:**
Here we apply the hybrid threshold described [here](#wetness)
- **Intersection with rivers (optional):**
Using the `MajorRivers` dataset loaded [here](#rivers)
*NOTE: for the Australia-wide analysis, the number and size of polygons means that this cell cannot be run in this notebook. Instead, we ran this cell on raijin*
```
#!/bin/bash
#PBS -P r78
#PBS -q hugemem
#PBS -l walltime=96:00:00
#PBS -l mem=500GB
#PBS -l jobfs=200GB
#PBS -l ncpus=7
#PBS -l wd
#PBS -lother=gdata1a
module use /g/data/v10/public/modules/modulefiles/
module load dea
PYTHONPATH=$PYTHONPATH:/g/data/r78/cek156/dea-notebooks
```
```
try:
AllTogether = gp.read_file(f'{WOFSshpMerged}Temp_{AtLeastThisWet[1]}.shp')
except IndexError:
AllTogether = gp.read_file(f'{WOFSshpMerged}Temp_{AtLeastThisWet[0]}.shp')
AllTogether['area'] = pd.to_numeric(AllTogether.area)
# Filter out any polygons smaller than MinSize, and greater than MaxSize
WaterBodiesBig = AllTogether.loc[((AllTogether['area'] > MinSize) &
(AllTogether['area'] <= MaxSize))]
# Filter out any ocean in the pixel
WaterBodiesLand, IntersectIndexes = Filter_shapefile_by_intersection(
WaterBodiesBig, Coastline, invertMask=True)
# WOfS has a known bug where deep shadows from high-rise CBD buildings are misclassified
# as water. We will use the ABS sa3 dataset to filter out Brisbane, Gold Coast, Sydney,
# Melbourne, Adelaide and Perth CBDs.
# If you have chosen to set UrbanMask = False, this step will be skipped.
if UrbanMask:
NotCities, IntersectIndexes = Filter_shapefile_by_intersection(
WaterBodiesLand, CBDs)
else:
print(
'You have chosen not to filter out waterbodies within CBDs. If you meant to use this option, please \n'
'set `UrbanMask = True` variable above, and set the path to your urban filter shapefile'
)
NotCities = WaterBodiesLand
# Check for hybrid wetness thresholds
if len(AtLeastThisWet) == 2:
# Note that this assumes that the thresholds have been correctly entered into the 'AtLeastThisWet'
# variable, with the supplementary threshold listed first.
LowerThreshold = gp.read_file(
f'{WOFSshpMerged}Union_{AtLeastThisWet[0]}.shp')
LowerThreshold['area'] = pd.to_numeric(LowerThreshold.area)
# Filter out those pesky huge polygons
LowerThreshold = LowerThreshold.loc[(LowerThreshold['area'] <= MaxSize)]
# Find where the albers polygon overlaps with our dam polygons
BoundaryMergedDams, IntersectIndexes = Filter_shapefile_by_intersection(
LowerThreshold, NotCities)
# Pull out the polygons from the supplementary shapefile that intersect with the primary shapefile
LowerThresholdToUse = LowerThreshold.loc[LowerThreshold.index.isin(
IntersectIndexes)]
# Concat the two polygon sets together
CombinedPolygons = gp.GeoDataFrame(
pd.concat([LowerThresholdToUse, NotCities], ignore_index=True))
# Merge overlapping polygons
CombinedPolygonsUnion = CombinedPolygons.unary_union
# `Explode` the multipolygon back out into individual polygons
UnionGDF = gp.GeoDataFrame(crs=LowerThreshold.crs,
geometry=[CombinedPolygonsUnion])
HybridDams = UnionGDF.explode()
else:
print(
'You have not set up the hybrid threshold option. If you meant to use this option, please \n'
'set this option by including two wetness thresholds in the `AtLeastThisWet` variable above'
)
HybridDams = NotCities
# Here is where we do the river filtering (if FilterOutRivers == True)
if FilterOutRivers:
WaterBodiesBigRiverFiltered, IntersectIndexes = Filter_shapefile_by_intersection(
HybridDams, MajorRivers)
else:
# If river filtering is turned off, then we just keep all the same polygons
WaterBodiesBigRiverFiltered = HybridDams
# We need to add the crs back onto the dataframe
WaterBodiesBigRiverFiltered.crs = {'init': 'epsg:3577'}
# Calculate the area and perimeter of each polygon again now that overlapping polygons
# have been merged
WaterBodiesBigRiverFiltered['area'] = WaterBodiesBigRiverFiltered[
'geometry'].area
WaterBodiesBigRiverFiltered['perimeter'] = WaterBodiesBigRiverFiltered[
'geometry'].length
# Calculate the Polsby-Popper value (see below), and write out too
WaterBodiesBigRiverFiltered['PPtest'] = (
(WaterBodiesBigRiverFiltered['area'] * 4 * math.pi) /
(WaterBodiesBigRiverFiltered['perimeter']**2))
# Save the polygons to a shapefile
schema = {
'geometry': 'Polygon',
'properties': {
'area': 'float',
'perimeter': 'float',
'PPtest': 'float'
}
}
with fiona.open(WOFSshpFiltered,
"w",
crs=from_epsg(3577),
driver='ESRI Shapefile',
schema=schema) as output:
for ix, poly in WaterBodiesBigRiverFiltered.iterrows():
output.write(({
'properties': {
'area': poly['area'],
'perimeter': poly['perimeter'],
'PPtest': poly['PPtest']
},
'geometry': mapping(shape(poly['geometry']))
}))
```
### Dividing up very large polygons
The size of polygons is determined by the contiguity of waterbody pixels through the landscape. This can result in very large polygons, e.g. where rivers are wide and unobscured by trees, or where waterbodies are connected to rivers or neighbouring waterbodies. The image below shows this for the Menindee Lakes, NSW. The relatively flat terrain in this part of Australia means that the 0.05 wetness threshold results in the connection of a large stretch of river and the individual lakes into a single large polygon that spans 154 km. This polygon is too large to provide useful insights into the changing water surface area of the Menindee Lakes, and needs to be broken into smaller, more useful polygons.

We do this by applying the [Polsby-Popper test (1991)](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2936284). The Polsby-Popper test is an assessment of the 'compactness' of a polygon. This method was originally developed to test the shape of congressional and state legislative districts, to prevent gerrymandering.
The Polsby-Popper test examines the ratio between the area of a polygon, and the area of a circle equal to the perimeter of that polygon. The result falls between 0 and 1, with values closer to 1 being assessed as more compact.
\begin{align*}
PPtest = \frac{polygon\ area * 4\pi}{polygon\ perimeter^2}
\end{align*}
The Menindee Lakes polygon above has a PPtest value $\approx$ 0.00.
We selected all polygons with a `PPtest` value <=0.005. This resulted in a subset of 186 polygons.

The 186 polygons were buffered with a -50 meter (2 pixel) buffer to separate the polygons where they are connected bu two pixels or less. This allows us to split up these very large polygons by using natural thinning points. The resulting negatively buffered polygons was run through the `multipart to singlepart` tool in QGIS, to give the now separated polygons unique IDs.
These polygons were then buffered with a +50 meter buffer to return the polygons to approximately their original size. These final polygons were used to separate the 186 original polygons identified above.
The process for dividing up the identified very large polygons varied depending on the polygon in question. Where large waterbodies (like the Menindee Lakes) were connected, the buffered polygons were used to determine the cut points in the original polygons. Where additional breaks were required, the [Bureau of Meteorology's Geofabric v 3.0.5 Beta (Suface Hydrology Network)](ftp://ftp.bom.gov.au/anon/home/geofabric/) `waterbodies` dataset was used as an additional source of information for breaking up connected segments.
The buffering method didn't work on large segments of river, which became a series of disconnected pieces when negatively and positively buffered. Instead, we used a combination of tributaries and man-made features such as bridges and weirs to segment these river sections.
## Final checks and recalculation of attributes
```
WaterBodiesBigRiverFiltered = gp.read_file(WOFSshpFiltered)
# Recalculate the area and perimeter of each polygon again following the manual checking
# step performed above
WaterBodiesBigRiverFiltered['area'] = WaterBodiesBigRiverFiltered[
'geometry'].area
WaterBodiesBigRiverFiltered['perimeter'] = WaterBodiesBigRiverFiltered[
'geometry'].length
# Remove the PPtest column, since we don't really want this as an attribute of the final shapefile
WaterBodiesBigRiverFiltered.drop(labels='PPtest', axis=1, inplace=True)
# Reapply the size filtering, just to check that all of the split and filtered waterbodies are
# still in the size range we want
DoubleCheckArea = WaterBodiesBigRiverFiltered.loc[(
(WaterBodiesBigRiverFiltered['area'] > MinSize) &
(WaterBodiesBigRiverFiltered['area'] <= MaxSize))]
```
### Generate a unique ID for each polygon
A unique identifier is required for every polygon to allow it to be referenced. The naming convention for generating unique IDs here is the [geohash](geohash.org).
A Geohash is a geocoding system used to generate short unique identifiers based on latitude/longitude coordinates. It is a short combination of letters and numbers, with the length of the string a function of the precision of the location. The methods for generating a geohash are outlined [here - yes, the official documentation is a wikipedia article](https://en.wikipedia.org/wiki/Geohash).
Here we use the python package `python-geohash` to generate a geohash unique identifier for each polygon. We use `precision = 9` geohash characters, which represents an on the ground accuracy of <20 metres. This ensures that the precision is high enough to differentiate between waterbodies located next to each other.
```
# We need to convert from Albers coordinates to lat/lon, in order to generate the geohash
GetUniqueID = DoubleCheckArea.to_crs(epsg=4326)
# Generate a geohash for the centroid of each polygon
GetUniqueID['UID'] = GetUniqueID.apply(lambda x: gh.encode(
x.geometry.centroid.y, x.geometry.centroid.x, precision=9),
axis=1)
# Check that our unique ID is in fact unique
assert GetUniqueID['UID'].is_unique
# Make an arbitrary numerical ID for each polygon. We will first sort the dataframe by geohash
# so that polygons close to each other are numbered similarly
SortedData = GetUniqueID.sort_values(by=['UID']).reset_index()
SortedData['WB_ID'] = SortedData.index
# The step above creates an 'index' column, which we don't actually want, so drop it.
SortedData.drop(labels='index', axis=1, inplace=True)
```
### Write out the final results to a shapefile
```
BackToAlbers = SortedData.to_crs(epsg=3577)
BackToAlbers.to_file(FinalName, driver='ESRI Shapefile')
```
## Some extra curation
Following the development of timeseries for each individual polygon, it was determined that a number of polygons do not produce complete timeseries.
### Splitting polygons that cross swath boundaries
Three large polygons were identified that straddle Landsat swath boundaries. This is problematic, as the whole polygon will never be observed on a single day, which trips the requirement for at least 90% of a polygon to be observed in order for an observation to be valid.
There are two options for dealing with this issue:
- Splitting the polygons using the swath boundaries, so that each half of the polygon will be observed in a single day. This will retain information as to the exact timing of observations.
- Creating time averaged timeseries, which would group observations into monthly blocks and provide a value for each month. This would provide information for the whole polygon, but would lose the specific timing information.
We chose to go with the first option to keep the high fidelity timing information for each polygon. Three polygons were split using the swath boundaries as a guide. The split polygons were given a new `WB_ID`, and a new geohash was calculated for each new polygon.
```
WaterBodiesSplit = gp.read_file(
'/g/data/r78/cek156/dea-notebooks/DEAWaterbodies/AusAllTime01-005HybridWaterbodies/AusWaterBodiesSplitEliminate.shp'
)
# We need to convert from Albers coordinates to lat/lon, in order to generate the geohash
GetUniqueID = WaterBodiesSplit.to_crs(epsg=4326)
# Only recalculate the geohash for the polygons that have changed:
ChangedWB_ID = [145126, 66034, 146567, 295902, 295903, 295904, 295905]
for ix, rowz in GetUniqueID.iterrows():
if rowz['WB_ID'] in ChangedWB_ID:
# Generate a geohash for the centroid of each polygon
GetUniqueID.loc[ix, 'WB_ID'] = gh.encode(
GetUniqueID.iloc[ix].geometry.centroid.y,
GetUniqueID.iloc[ix].geometry.centroid.x,
precision=9)
print('Changing geohash')
# Check that our unique ID is in fact unique
assert GetUniqueID['UID'].is_unique
```
### Save the final version of the polygons!
```
BackToAlbers = GetUniqueID.to_crs(epsg=3577)
BackToAlbers.to_file(
'/g/data/r78/cek156/dea-notebooks/DEAWaterbodies/AusAllTime01-005HybridWaterbodies/AusWaterBodiesFINAL.shp',
driver='ESRI Shapefile')
```
***
## Additional information
**License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).
Digital Earth Australia data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license.
**Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)).
If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/GeoscienceAustralia/dea-notebooks).
**Last modified:** December 2019. Peer Code Quality Check Performed, March 2019
**Compatible datacube version:** A full list of python packages used to produce DEA Waterbodies is available [here](TurnWaterObservationsIntoWaterbodyPolygons.txt).
## Tags
| 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.
```
# Multi-worker Training with Estimator
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/beta/tutorials/distribute/multi_worker_with_estimator"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/distribute/multi_worker_with_estimator.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/distribute/multi_worker_with_estimator.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/r2/tutorials/distribute/multi_worker_with_estimator.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Overview
This tutorial demonstrates how `tf.distribute.Strategy` can be used for distributed multi-worker training with `tf.estimator`. If you write your code using `tf.estimator`, and you're interested in scaling beyond a single machine with high performance, this tutorial is for you.
Before getting started, please read the [`tf.distribute.Strategy` guide](../../guide/distribute_strategy.ipynb). The [multi-GPU training tutorial](./keras.ipynb) is also relevant, because this tutorial uses the same model.
## Setup
First, setup TensorFlow and the necessary imports.
```
from __future__ import absolute_import, division, print_function, unicode_literals
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow_datasets as tfds
import tensorflow as tf
tfds.disable_progress_bar()
import os, json
```
## Input function
This tutorial uses the MNIST dataset from [TensorFlow Datasets](https://www.tensorflow.org/datasets). The code here is similar to the [multi-GPU training tutorial](./keras.ipynb) with one key difference: when using Estimator for multi-worker training, it is necessary to shard the dataset by the number of workers to ensure model convergence. The input data is sharded by worker index, so that each worker processes `1/num_workers` distinct portions of the dataset.
```
BUFFER_SIZE = 10000
BATCH_SIZE = 64
def input_fn(mode, input_context=None):
datasets, info = tfds.load(name='mnist',
with_info=True,
as_supervised=True)
mnist_dataset = (datasets['train'] if mode == tf.estimator.ModeKeys.TRAIN else
datasets['test'])
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label
if input_context:
mnist_dataset = mnist_dataset.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
return mnist_dataset.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
```
Another reasonable approach to achieve convergence would be to shuffle the dataset with distinct seeds at each worker.
## Multi-worker configuration
One of the key differences in this tutorial (compared to the [multi-GPU training tutorial](./keras.ipynb)) is the multi-worker setup. The `TF_CONFIG` environment variable is the standard way to specify the cluster configuration to each worker that is part of the cluster.
There are two components of `TF_CONFIG`: `cluster` and `task`. `cluster` provides information about the entire cluster, namely the workers and parameter servers in the cluster. `task` provides information about the current task. In this example, the task `type` is `worker` and the task `index` is `0`.
For illustration purposes, this tutorial shows how to set a `TF_CONFIG` with 2 workers on `localhost`. In practice, you would create multiple workers on an external IP address and port, and set `TF_CONFIG` on each worker appropriately, i.e. modify the task `index`.
Warning: *Do not execute the following code in Colab.* TensorFlow's runtime will attempt to create a gRPC server at the specified IP address and port, which will likely fail.
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"]
},
'task': {'type': 'worker', 'index': 0}
})
```
## Define the model
Write the layers, the optimizer, and the loss function for training. This tutorial defines the model with Keras layers, similar to the [multi-GPU training tutorial](./keras.ipynb).
```
LEARNING_RATE = 1e-4
def model_fn(features, labels, mode):
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
logits = model(features, training=False)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {'logits': logits}
return tf.estimator.EstimatorSpec(labels=labels, predictions=predictions)
optimizer = tf.compat.v1.train.GradientDescentOptimizer(
learning_rate=LEARNING_RATE)
loss = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(labels, logits)
loss = tf.reduce_sum(loss) * (1. / BATCH_SIZE)
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode, loss=loss)
return tf.estimator.EstimatorSpec(
mode=mode,
loss=loss,
train_op=optimizer.minimize(
loss, tf.compat.v1.train.get_or_create_global_step()))
```
Note: Although the learning rate is fixed in this example, in general it may be necessary to adjust the learning rate based on the global batch size.
## MultiWorkerMirroredStrategy
To train the model, use an instance of `tf.distribute.experimental.MultiWorkerMirroredStrategy`. `MultiWorkerMirroredStrategy` creates copies of all variables in the model's layers on each device across all workers. It uses `CollectiveOps`, a TensorFlow op for collective communication, to aggregate gradients and keep the variables in sync. The [`tf.distribute.Strategy` guide](../../guide/distribute_strategy.ipynb) has more details about this strategy.
```
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
```
## Train and evaluate the model
Next, specify the distribution strategy in the `RunConfig` for the estimator, and train and evaluate by invoking `tf.estimator.train_and_evaluate`. This tutorial distributes only the training by specifying the strategy via `train_distribute`. It is also possible to distribute the evaluation via `eval_distribute`.
```
config = tf.estimator.RunConfig(train_distribute=strategy)
classifier = tf.estimator.Estimator(
model_fn=model_fn, model_dir='/tmp/multiworker', config=config)
tf.estimator.train_and_evaluate(
classifier,
train_spec=tf.estimator.TrainSpec(input_fn=input_fn),
eval_spec=tf.estimator.EvalSpec(input_fn=input_fn)
)
```
## Optimize training performance
You now have a model and a multi-worker capable Estimator powered by `tf.distribute.Strategy`. You can try the following techniques to optimize performance of multi-worker training:
* *Increase the batch size:* The batch size specified here is per-GPU. In general, the largest batch size that fits the GPU memory is advisable.
* *Cast variables:* Cast the variables to `tf.float` if possible. The official ResNet model includes [an example](https://github.com/tensorflow/models/blob/8367cf6dabe11adf7628541706b660821f397dce/official/resnet/resnet_model.py#L466) of how this can be done.
* *Use collective communication:* `MultiWorkerMirroredStrategy` provides multiple [collective communication implementations](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/distribute/cross_device_ops.py).
* `RING` implements ring-based collectives using gRPC as the cross-host communication layer.
* `NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives.
* `AUTO` defers the choice to the runtime.
The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. To override the automatic choice, specify a valid value to the `communication` parameter of `MultiWorkerMirroredStrategy`'s constructor, e.g. `communication=tf.distribute.experimental.CollectiveCommunication.NCCL`.
## Other code examples
1. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kubernetes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.
2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.
| github_jupyter |
```
from collections import defaultdict, OrderedDict
import warnings
import gffutils
import pybedtools
import pandas as pd
import copy
import os
import re
from gffutils.pybedtools_integration import tsses
from copy import deepcopy
from collections import OrderedDict, Callable
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
class DefaultOrderedDict(OrderedDict):
# Source: http://stackoverflow.com/a/6190500/562769
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not isinstance(default_factory, Callable)):
raise TypeError('first argument must be callable')
OrderedDict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,
OrderedDict.__repr__(self))
#gtf = '/home/cmb-panasas2/skchoudh/genomes/drosophila_melanogaster_BDGP6/annotation/Drosophila_melanogaster.BDGP6.91.gtf'
#gtf_db = '/home/cmb-panasas2/skchoudh/genomes/drosophila_melanogaster_BDGP6/annotation/Drosophila_melanogaster.BDGP6.91.gtf.db'
#prefix = '/home/cmb-panasas2/skchoudh/github_projects/riboraptor/riboraptor/annotation/BDGP6/v91'
#chrsizes = '/home/cmb-panasas2/skchoudh/genomes/drosophila_melanogaster_BDGP6/fasta/Drosophila_melanogaster.BDGP6.dna.toplevel.sizes'
#mkdir_p(prefix)
gtf = '/home/cmb-panasas2/skchoudh/genomes/TAIR10/annotation/Arabidopsis_thaliana.TAIR10.44.gtf'
gtf_db = '/home/cmb-panasas2/skchoudh/genomes/TAIR10/annotation/Arabidopsis_thaliana.TAIR10.44.gtf.db'
prefix = '/home/cmb-panasas2/skchoudh/github_projects/riboraptor/riboraptor/annotation/TAIR10/v44'
chrsizes = '/home/cmb-panasas2/skchoudh/genomes/TAIR10/fasta/Arabidopsis_thaliana.TAIR10.dna.toplevel.sizes'
mkdir_p(prefix)
def create_gene_dict(db):
'''
Store each feature line db.all_features() as a dict of dicts
'''
gene_dict = DefaultOrderedDict(lambda: DefaultOrderedDict(lambda: DefaultOrderedDict(list)))
for line_no, feature in enumerate(db.all_features()):
gene_ids = feature.attributes['gene_id']
feature_type = feature.featuretype
if feature_type == 'gene':
if len(gene_ids)!=1:
logging.warning('Found multiple gene_ids on line {} in gtf'.format(line_no))
break
else:
gene_id = gene_ids[0]
gene_dict[gene_id]['gene'] = feature
else:
transcript_ids = feature.attributes['transcript_id']
for gene_id in gene_ids:
for transcript_id in transcript_ids:
gene_dict[gene_id][transcript_id][feature_type].append(feature)
return gene_dict
db = gffutils.create_db(gtf, dbfn=gtf_db, merge_strategy='merge', force=True, disable_infer_transcripts=True, disable_infer_genes=True)
#db = gffutils.FeatureDB(gtf_db, keep_order=True)
#gene_dict = create_gene_dict(db)
db = gffutils.FeatureDB(gtf_db, keep_order=True)
gene_dict = create_gene_dict(db)
for x in db.featuretypes():
print(x)
def get_gene_list(gene_dict):
return list(set(gene_dict.keys()))
def get_UTR_regions(gene_dict, gene_id, transcript, cds):
if len(cds)==0:
return [], []
utr5_regions = []
utr3_regions = []
utrs = gene_dict[gene_id][transcript]['UTR']
first_cds = cds[0]
last_cds = cds[-1]
for utr in utrs:
## Push all cds at once
## Sort later to remove duplicates
strand = utr.strand
if strand == '+':
if utr.stop < first_cds.start:
utr.feature_type = 'five_prime_UTR'
utr5_regions.append(utr)
elif utr.start > last_cds.stop:
utr.feature_type = 'three_prime_UTR'
utr3_regions.append(utr)
else:
raise RuntimeError('Error with cds')
elif strand == '-':
if utr.stop < first_cds.start:
utr.feature_type = 'three_prime_UTR'
utr3_regions.append(utr)
elif utr.start > last_cds.stop:
utr.feature_type = 'five_prime_UTR'
utr5_regions.append(utr)
else:
raise RuntimeError('Error with cds')
return utr5_regions, utr3_regions
def create_bed(regions, bedtype='0'):
'''Create bed from list of regions
bedtype: 0 or 1
0-Based or 1-based coordinate of the BED
'''
bedstr = ''
for region in regions:
assert len(region.attributes['gene_id']) == 1
## GTF start is 1-based, so shift by one while writing
## to 0-based BED format
if bedtype == '0':
start = region.start - 1
else:
start = region.start
bedstr += '{}\t{}\t{}\t{}\t{}\t{}\n'.format(region.chrom,
start,
region.stop,
re.sub('\.\d+', '', region.attributes['gene_id'][0]),
'.',
region.strand)
return bedstr
def rename_regions(regions, gene_id):
regions = list(regions)
if len(regions) == 0:
return []
for region in regions:
region.attributes['gene_id'] = gene_id
return regions
def merge_regions(db, regions):
if len(regions) == 0:
return []
merged = db.merge(sorted(list(regions), key=lambda x: x.start))
return merged
def merge_regions_nostrand(db, regions):
if len(regions) == 0:
return []
merged = db.merge(sorted(list(regions), key=lambda x: x.start), ignore_strand=True)
return merged
utr5_bed = ''
utr3_bed = ''
gene_bed = ''
exon_bed = ''
intron_bed = ''
start_codon_bed = ''
stop_codon_bed = ''
cds_bed = ''
gene_list = []
for gene_id in get_gene_list(gene_dict):
gene_list.append(gene_dict[gene_id]['gene'])
utr5_regions, utr3_regions = [], []
exon_regions, intron_regions = [], []
star_codon_regions, stop_codon_regions = [], []
cds_regions = []
for feature in gene_dict[gene_id].keys():
if feature == 'gene':
continue
cds = list(gene_dict[gene_id][feature]['CDS'])
exons = list(gene_dict[gene_id][feature]['exon'])
merged_exons = merge_regions(db, exons)
introns = db.interfeatures(merged_exons)
#utr5_region, utr3_region = get_UTR_regions(gene_dict, gene_id, feature, cds)
utr5_region = list(gene_dict[gene_id][feature]['five_prime_utr'])
utr3_region = list(gene_dict[gene_id][feature]['three_prime_utr'])
utr5_regions += utr5_region
utr3_regions += utr3_region
exon_regions += exons
intron_regions += introns
cds_regions += cds
merged_utr5 = merge_regions(db, utr5_regions)
renamed_utr5 = rename_regions(merged_utr5, gene_id)
merged_utr3 = merge_regions(db, utr3_regions)
renamed_utr3 = rename_regions(merged_utr3, gene_id)
merged_exons = merge_regions(db, exon_regions)
renamed_exons = rename_regions(merged_exons, gene_id)
merged_introns = merge_regions(db, intron_regions)
renamed_introns = rename_regions(merged_introns, gene_id)
merged_cds = merge_regions(db, cds_regions)
renamed_cds = rename_regions(merged_cds, gene_id)
utr3_bed += create_bed(renamed_utr3)
utr5_bed += create_bed(renamed_utr5)
exon_bed += create_bed(renamed_exons)
intron_bed += create_bed(renamed_introns)
cds_bed += create_bed(renamed_cds)
gene_bed = create_bed(gene_list)
gene_bedtool = pybedtools.BedTool(gene_bed, from_string=True)
utr5_bedtool = pybedtools.BedTool(utr5_bed, from_string=True)
utr3_bedtool = pybedtools.BedTool(utr3_bed, from_string=True)
exon_bedtool = pybedtools.BedTool(exon_bed, from_string=True)
intron_bedtool = pybedtools.BedTool(intron_bed, from_string=True)
cds_bedtool = pybedtools.BedTool(cds_bed, from_string=True)
utr5_cds_subtracted = utr5_bedtool.subtract(cds_bedtool)
utr3_cds_subtracted = utr3_bedtool.subtract(cds_bedtool)
utr5_cds_subtracted.remove_invalid().sort().saveas(os.path.join(prefix, 'utr5.bed.gz'))
utr3_cds_subtracted.remove_invalid().sort().saveas(os.path.join(prefix, 'utr3.bed.gz'))
gene_bedtool.remove_invalid().sort().saveas(os.path.join(prefix, 'gene.bed.gz'))
exon_bedtool.remove_invalid().sort().saveas(os.path.join(prefix, 'exon.bed.gz'))
intron_bedtool.remove_invalid().sort().saveas(os.path.join(prefix, 'intron.bed.gz'))
cds_bedtool.remove_invalid().sort().saveas(os.path.join(prefix, 'cds.bed.gz'))
for gene_id in get_gene_list(gene_dict):
start_codons = []
stop_codons = []
for start_codon in db.children(gene_id, featuretype='start_codon'):
## 1 -based stop
## 0-based start handled while converting to bed
start_codon.stop = start_codon.start
start_codons.append(start_codon)
for stop_codon in db.children(gene_id, featuretype='stop_codon'):
stop_codon.start = stop_codon.stop
stop_codon.stop = stop_codon.stop+1
stop_codons.append(stop_codon)
merged_start_codons = merge_regions(db, start_codons)
renamed_start_codons = rename_regions(merged_start_codons, gene_id)
merged_stop_codons = merge_regions(db, stop_codons)
renamed_stop_codons = rename_regions(merged_stop_codons, gene_id)
start_codon_bed += create_bed(renamed_start_codons)
stop_codon_bed += create_bed(renamed_stop_codons)
start_codon_bedtool = pybedtools.BedTool(start_codon_bed, from_string=True)
stop_codon_bedtool = pybedtools.BedTool(stop_codon_bed, from_string=True)
start_codon_bedtool.remove_invalid().sort().saveas(os.path.join(prefix, 'start_codon.bed.gz'))
stop_codon_bedtool.remove_invalid().sort().saveas(os.path.join(prefix, 'stop_codon.bed.gz'))
```
| github_jupyter |
This note book is mainly about making predictions given the pre-trained models
## Define model class
```
import copy
import torch
from torch import nn
import os
import numpy as np
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
CACHE_SIZE=100
LR = 0.001
BATCH_SIZE=32
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(
in_channels=1,
out_channels=8,
kernel_size=(30,3),
stride=1,
padding=0,
),
nn.ReLU(),
)
self.conv2 = nn.Sequential(
nn.Conv2d(
in_channels=8,
out_channels=16,
kernel_size=(30,1),
stride=1,
padding=2),
nn.ReLU(),
)
self.out = nn.Sequential(
nn.Linear(3680,100),
)
def forward(self, x):
x = self.conv1(x.unsqueeze(1))
x = self.conv2(x)
x = x.view(x.size(0), -1) # flatten the output of conv2 to (batch_size, 32 *#
output = self.out(x)
return output
model = CNN()
```
## Load the model and initiate the object
```
model.load_state_dict(torch.load('cnn1/CNN.pth',map_location='cpu'))
model.eval()
```
## Necessary functions (mostly borrowed from Shabhaz with customization fitting for Conv NN)
```
def lruPredict(C,LRUQ,Y_OPT):
global lruCorrect, lruIncorrect
Y_current = []
KV = defaultdict(int)
for i in range(len(LRUQ)):
KV[LRUQ[i]] = len(LRUQ) - i
KV_sorted = Counter(KV)
evict_dict = dict(KV_sorted.most_common(eviction))
for e in C:
if e in evict_dict:
Y_current.append(1)
else:
Y_current.append(0)
for i in range(len(Y_current)):
if Y_current[i] is Y_OPT[i]:
lruCorrect+=1
else:
lruIncorrect+=1
return Y_current
# returns sequence of blocks in prioirty order
def Y_getBlockSeq(Y_pred_prob):
x = []
for i in range(len(Y_pred_prob)):
x.append(Y_pred_prob[i][0])
x = np.array(x)
idx = np.argsort(x)
idx = idx[:eviction]
return idx
def Y_getMinPredict(Y_pred_prob):
x = []
for i in range(len(Y_pred_prob)):
x.append(Y_pred_prob[i][0])
x = np.array(x)
idx = np.argpartition(x, eviction)
Y_pred = np.zeros(len(Y_pred_prob), dtype=int)
for i in range(eviction):
Y_pred[idx[i]] = 1
assert(Counter(Y_pred)[1] == eviction)
return Y_pred
def lfuPredict(C,LFUDict,Y_OPT):
global lfuCorrect, lfuIncorrect
Y_current = []
KV = defaultdict()
for e in C:
KV[e] = LFUDict[e]
KV_sorted = Counter(KV)
evict_dict = dict(KV_sorted.most_common(eviction))
for e in C:
if e in evict_dict:
Y_current.append(1)
else:
Y_current.append(0)
for i in range(len(Y_current)):
if Y_current[i] is Y_OPT[i]:
lfuCorrect+=1
else:
lfuIncorrect+=1
return Y_current
# return "eviction" blocks that are being accessed furthest
# from the cache that was sent to us.
def getY(C,D):
assert(len(C) == len(D))
Y_current = []
KV_sorted = Counter(D)
evict_dict = dict(KV_sorted.most_common(eviction))
assert(len(evict_dict) == eviction)
all_vals = evict_dict.values()
for e in C:
if e in evict_dict.values():
Y_current.append(1)
else:
Y_current.append(0)
#print (Y_current.count(1))
assert(Y_current.count(1) == eviction)
assert((set(all_vals)).issubset(set(C)))
return Y_current
def getLFURow(LFUDict, C):
x_lfurow = []
for e in C:
x_lfurow.append(LFUDict[e])
norm = x_lfurow / np.linalg.norm(x_lfurow)
return norm
def getLRURow(LRUQ, C):
x_lrurow = []
KV = defaultdict(int)
for i in range(len(LRUQ)):
KV[LRUQ[i]] = i
for e in C:
x_lrurow.append(KV[e])
norm = x_lrurow / np.linalg.norm(x_lrurow)
return norm
def normalize(feature, blocks):
x_feature = []
for i in range(len(blocks)):
x_feature.append(feature[blocks[i]])
return x_feature / np.linalg.norm(x_feature)
def getX(LRUQ, LFUDict, C):
#def getX(LRUQ, LFUDict, C, CacheTS, CachePID):
X_lfurow = getLFURow(LFUDict, C)
X_lrurow = getLRURow(LRUQ, C)
X_bno = C / np.linalg.norm(C)
# X_ts = normalize(CacheTS, C)
# X_pid = normalize(CachePID, C)
return (np.column_stack((X_lfurow, X_lrurow, X_bno)))
def populateData(LFUDict, LRUQ, C, D):
#def populateData(LFUDict, LRUQ, C, D, CacheTS, CachePID):
global X,Y
C = list(C)
Y_current = getY(C, D)
#X_current = getX(LRUQ, LFUDict, C, CacheTS, CachePID)
X_current = getX(LRUQ, LFUDict, C)
Y = np.append(Y, Y_current)
X = np.concatenate((X,X_current))
assert(Y_current.count(1) == eviction)
return Y_current
def hitRate(blocktrace, frame, model):
LFUDict = defaultdict(int)
LRUQ = []
# CacheTS = defaultdict(int)
# CachePID = defaultdict(int)
hit, miss = 0, 0
C = []
evictCacheIndex = np.array([])
#count=0
#seq_number = 0
for seq_number, block in enumerate(tqdm(blocktrace, desc="OPT")):
#print(len(evictCacheIndex))
LFUDict[block] +=1
#CacheTS[blocktrace[seq_number]] = timestamp[seq_number]
#CachePID[blocktrace[seq_number]] = pid[seq_number]
if block in C:
hit+=1
# if C.index(block) in evictCacheIndex:
# np.delete(evictCacheIndex, C.index(block))
LRUQ.remove(block)
LRUQ.append(block)
else:
evictPos = -1
miss+=1
if len(C) == frame:
if len(evictCacheIndex) == 0: # call eviction candidates
#X_test = getX(LRUQ, LFUDict, C)
#X_test = getX(LRUQ, LFUDict, C, CacheTS, CachePID)
blockNo = C / np.linalg.norm(C)
recency_ = np.array([LRUQ.index(i) for i in C])
recency_ = recency_ / np.linalg.norm(recency_)
frequency_ = np.array([LFUDict[i] for i in C])
frequency_ = frequency_ / np.linalg.norm(frequency_)
# stack = np.column_stack((blockNo, recency_, frequency_)).reshape(1,frame*3)
stack = np.column_stack((blockNo, recency_, frequency_))
#X_current = model.predict(stack)[0]
evictCacheIndex = np.argsort(Y_pred_prob)[0].detach().numpy())[::-1][:eviction]
# index of cache blocks that should be removed
#return Y_pred_prob, evictCacheIndex
# evict from cache
evictPos = evictCacheIndex[0]
evictBlock = C[evictPos]
LRUQ.remove(evictBlock)
#del CacheTS [evictBlock]
#del CachePID [evictBlock]
if evictPos is -1:
C.append(block)
else:
C[evictPos] = block
evictCacheIndex = np.delete(evictCacheIndex, 0)
LRUQ.append(block)
#CacheTS [blocktrace[seq_number]] = timestamp[seq_number]
#CachePID [blocktrace[seq_number]] = pid[seq_number]
#seq_number += 1
hitrate = hit / (hit + miss)
print(hitrate)
return hitrate
```
## Load test data for predictions
```
import sys
import random
import numpy as np
import pandas as pd
from tqdm import tqdm_notebook as tqdm
from collections import Counter, deque, defaultdict
from sklearn import preprocessing
from sklearn.preprocessing import normalize
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.neural_network import MLPClassifier
test = "../../data/cheetah.cs.fiu.edu-110108-113008.4.blkparse"
df = pd.read_csv(test, sep=' ',header = None)
df.columns = ['timestamp','pid','pname','blockNo', \
'blockSize', 'readOrWrite', 'bdMajor', 'bdMinor', 'hash']
testBlockTrace = df['blockNo'].tolist()
testBlockTrace = testBlockTrace[:int(len(testBlockTrace)*0.1)]
len(testBlockTrace)
sampling_freq = CACHE_SIZE # number of samples skipped
eviction = int(0.7 * CACHE_SIZE)
```
## Predict
```
CNNHitrate = hitRate(testBlockTrace, CACHE_SIZE, model)
```
| github_jupyter |
# 2017 interleaved A/B test of machine learned ranking
Prior to 2016, our search engine used term frequency—inverse document frequency ([tf—idf](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)) for ranking documents (e.g. articles and other pages on English Wikipedia). After successful A/B testing, we switched to [BM25 scoring algorithm](https://en.wikipedia.org/wiki/Okapi_BM25) which was used production on almost all languages – except a few space-less languages. After that we focused our efforts on information retrieval using [machine-learned ranking](https://en.wikipedia.org/wiki/Learning_to_rank) (MLR). In MLR, a model is trained to predict a document’s relevance from various document-level and query-level features which represent the document.
[MjoLniR](https://gerrit.wikimedia.org/g/search/MjoLniR) – our Python and Spark-based library for handling the backend data processing for Machine Learned Ranking at Wikimedia – uses a click-based [Dynamic Bayesian Network](https://en.wikipedia.org/wiki/Dynamic_Bayesian_network) (Chapelle and Zhang 2009) (implemented via [ClickModels](https://github.com/varepsilon/clickmodels) Python library) to create relevance labels for training data fed into XGBoost.
## Data
This example uses archived data from the 2017 test of our machine-learned ranking functions. The data was collected using the [SearchSatisfaction instrument](https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/WikimediaEvents/+/c7b48d995dbbbe6767b3d3ef452b5aea68ce7a60/modules/ext.wikimediaEvents/searchSatisfaction.js) ([schema](https://gerrit.wikimedia.org/r/plugins/gitiles/schemas/event/secondary/+/30087c7f6910f7ca917ede504f2c8498edb29216/jsonschema/analytics/legacy/searchsatisfaction/current.yaml)). Sessions with 50 or more searches were excluded from the analysis, due to them potentially being automated/bots.
```
from interleaved import Experiment
import pandas as pd
ltr_test = pd.read_csv('learning_to_rank_2017.csv')
ltr_test = ltr_test.groupby(ltr_test.group_id)
test_1 = ltr_test.get_group("ltr-i-1024")
test_2 = ltr_test.get_group("ltr-i-20")
test_3 = ltr_test.get_group("ltr-i-20-1024")
```
## BM-25 vs MLR-20
The "MLR-20" model used a rescore window of 20. This means that each shard (of which English Wikipedia has 7) applies the model to the top 20 results. Those 140 results are then collected and sorted to produce the top 20 shown to the user.
```
experiment_1 = Experiment(
queries = test_1['search_id'].to_numpy(),
clicks = test_1['team'].to_numpy()
)
experiment_1.bootstrap(seed=20)
print(experiment_1.summary(rescale=True, ranker_labels=['BM-25', 'MLR-20']))
```
## BM-25 vs MLR-1024
The "MLR-1024" model used a rescore window of 1024. This means that each of the seven shards applies the model to the top 1024 results. Those 7168 results are then collected and sorted to produce the final top 20 (or top 15) shown to the users, since almost no users look at results beyond the first page.
```
experiment_2 = Experiment(
queries = test_2['search_id'].to_numpy(),
clicks = test_2['team'].to_numpy()
)
experiment_2.bootstrap(seed=1024)
print(experiment_2.summary(rescale=True, ranker_labels=['BM-25', 'MLR-1024']))
```
## MLR-20 vs MLR-1024
```
experiment_3 = Experiment(
queries = test_3['search_id'].to_numpy(),
clicks = test_3['team'].to_numpy()
)
experiment_3.bootstrap(seed=1004)
print(experiment_3.summary(rescale=True, ranker_labels=['MLR-20', 'MLR-1024']))
```
------------
## References
Chapelle, O., & Zhang, Y. (2009). *A dynamic bayesian network click model for web search ranking*. New York, New York, USA: ACM.
Chapelle, O., Joachims, T., Radlinski, F., & Yue, Y. (2012). Large-scale validation and analysis of interleaved search evaluation. *ACM Trans. Inf. Syst.*, **30**(1), 6:1–6:41. doi:10.1145/2094072.2094078
| github_jupyter |
<div class="alert alert-block alert-info">
<b>How to run this notebook?</b><br />
<ol>
<li>Install the DockStream environment: conda env create -f environment.yml in the DockStream directory</li>
<li>Activate the environment: conda activate DockStreamCommunity</li>
<li>Execute jupyter: jupyter notebook</li>
<li> Copy the link to a browser</li>
<li> Update variables <b>dockstream_path</b> and <b>dockstream_env</b> (the path to the environment DockStream) in the
first code block below</li>
</ol>
</div>
<div class="alert alert-block alert-warning">
<b>Caution:</b>
Make sure, you have the AutoDock Vina binary available somewhere.
</div>
# `AutoDock Vina` backend demo
This notebook will demonstrate how to **(a)** set up a `AutoDock Vina` backend run with `DockStream`, including the most important settings and **(b)** how to set up a `REINVENT` run with `AutoDock` docking enabled as one of the scoring function components.
**Steps:**
* a: Set up `DockStream` run
1. Prepare the receptor
2. Prepare the input: SMILES and configuration file (JSON format)
3. Execute the docking and parse the results
* b: Set up `REINVENT` run with a `DockStream` component
1. Prepare the receptor (see *a.1*)
2. Prepare the input (see *a.2*)
3. Prepare the `REINVENT` configuration (JSON format)
4. Execute `REINVENT`
The following imports / loadings are only necessary when executing this notebook. If you want to use `DockStream` directly from the command-line, it is enough to execute the following with the appropriate configurations:
```
conda activate DockStream
python /path/to/DockStream/target_preparator.py -conf target_prep.json
python /path/to/DockStream/docker.py -conf docking.json
```
```
import os
import json
import tempfile
# update these paths to reflect your system's configuration
dockstream_path = os.path.expanduser("~/Desktop/ProjectData/DockStream")
dockstream_env = os.path.expanduser("~/miniconda3/envs/DockStream")
vina_binary_location = os.path.expanduser("~/Desktop/ProjectData/foreign/AutoDockVina/autodock_vina_1_1_2_linux_x86/bin")
# no changes are necessary beyond this point
# ---------
# get the notebook's root path
try: ipynb_path
except NameError: ipynb_path = os.getcwd()
# generate the paths to the entry points
target_preparator = dockstream_path + "/target_preparator.py"
docker = dockstream_path + "/docker.py"
# generate a folder to store the results
output_dir = os.path.expanduser("~/Desktop/AutoDock_Vina_demo")
try:
os.mkdir(output_dir)
except FileExistsError:
pass
# generate the paths to the files shipped with this implementation
apo_1UYD_path = ipynb_path + "/../data/1UYD/1UYD_apo.pdb"
reference_ligand_path = ipynb_path + "/../data/1UYD/PU8.pdb"
smiles_path = ipynb_path + "/../data/1UYD/ligands_smiles.txt"
# generate output paths for the configuration file, the "fixed" PDB file and the "Gold" receptor
target_prep_path = output_dir + "/ADV_target_prep.json"
fixed_pdb_path = output_dir + "/ADV_fixed_target.pdb"
adv_receptor_path = output_dir + "/ADV_receptor.pdbqt"
log_file_target_prep = output_dir + "/ADV_target_prep.log"
log_file_docking = output_dir + "/ADV_docking.log"
# generate output paths for the configuration file, embedded ligands, the docked ligands and the scores
docking_path = output_dir + "/ADV_docking.json"
ligands_conformers_path = output_dir + "/ADV_embedded_ligands.sdf"
ligands_docked_path = output_dir + "/ADV_ligands_docked.sdf"
ligands_scores_path = output_dir + "/ADV_scores.csv"
```
## Target preparation
`AutoDock Vina` uses the `PDBQT` format for both the receptors and the (individual ligands). First, we will generate the receptor into which we want to dock the molecules. This is a semi-automated process and while `DockStream` has an entry point to help you setting this up, it might be wise to think about the details of this process beforehand, including:
* Is my target structure complete (e.g. has it missing loops in the area of interest)?
* Do I have a reference ligand in a complex (holo) structure or do I need to define the binding cleft (cavity) in a different manner?
* Do I want to keep the crystal water molecules, potential co-factors and such or not?
This step has to be done once per project and target. Typically, we start from a PDB file with a holo-structure, that is, a protein with its ligand. Using a holo-structure as input is convenient for two reasons:
1. The cavity can be specified as being a certain area around the ligand in the protein (assuming the binding mode does not change too much).
2. One can align other ligands (often a series with considerable similarity is used in docking studies) to the "reference ligand", potentially improving the performance.

For this notebook, it is assumed that you are able to
1. download `1UYD` and
2. split it into `1UYD_apo.pdb` and `reference_ligand.pdb` (name is `PU8` in the file), respectively.
We will now set up the JSON instruction file for the target preparator that will help us build a receptor suitable for `AutoDock Vina` docking later. We will also include a small section (internally using [PDBFixer](https://github.com/openmm/pdbfixer)) that will take care of minor problems of the input structure, such as missing hetero atoms - but of course you can address these things with a program of your choice as well. We will write the JSON to the output folder in order to load it with the `target_preparator.py` entry point of `DockStream`.
Note, that we can use the (optional) `extract_box` block in the configuration to specify the cavity's box (the area where the algorithm will strive to optimize the poses). For this we simply specify a reference ligand and the algorithm will extract the center-of-geometry and the minimum and maximum values for all three axes. This information is printed to the log file and can be used to specify the cavity in the docking step.
```
# specify the target preparation JSON file as a dictionary and write it out
tp_dict = {
"target_preparation":
{
"header": { # general settings
"logging": { # logging settings (e.g. which file to write to)
"logfile": log_file_target_prep
}
},
"input_path": apo_1UYD_path, # this should be an absolute path
"fixer": { # based on "PDBFixer"; tries to fix common problems with PDB files
"enabled": True,
"standardize": True, # enables standardization of residues
"remove_heterogens": True, # remove hetero-entries
"fix_missing_heavy_atoms": True, # if possible, fix missing heavy atoms
"fix_missing_hydrogens": True, # add hydrogens, which are usually not present in PDB files
"fix_missing_loops": False, # add missing loops; CAUTION: the result is usually not sufficient
"add_water_box": False, # if you want to put the receptor into a box of water molecules
"fixed_pdb_path": fixed_pdb_path # if specified and not "None", the fixed PDB file will be stored here
},
"runs": [ # "runs" holds a list of backend runs; at least one is required
{
"backend": "AutoDockVina", # one of the backends supported ("AutoDockVina", "OpenEye", ...)
"output": {
"receptor_path": adv_receptor_path # the generated receptor file will be saved to this location
},
"parameters": {
"pH": 7.4, # sets the protonation states (NOT used in Vina)
"extract_box": { # in order to extract the coordinates of the pocket (see text)
"reference_ligand_path": reference_ligand_path, # path to the reference ligand
"reference_ligand_format": "PDB" # format of the reference ligand
}
}}]}}
with open(target_prep_path, 'w') as f:
json.dump(tp_dict, f, indent=" ")
# execute this in a command-line environment after replacing the parameters
!{dockstream_env}/bin/python {target_preparator} -conf {target_prep_path}
!head -n 25 {adv_receptor_path}
```
This is it, now we have **(a)** fixed some minor issues with the input structure and **(b)** generated a reference ligand-based receptor and stored it in a binary file. For inspection later, we will write out the "fixed" PDB structure (parameter `fixed_pdb_path` in the `fixer` block above).
## Docking
In this section we consider a case where we have just prepared the receptor and want to dock a bunch of ligands (molecules, compounds) into the binding cleft. Often, we only have the structure of the molecules in the form of `SMILES`, rather than a 3D structure so the first step will be to generate these conformers before proceeding. In `DockStream` you can embed your ligands with a variety of programs including `Corina`, `RDKit`, `OMEGA` and `LigPrep` and use them freely with any backend. Here, we will use `Corina` for the conformer embedding.
But first, we will have a look at the ligands:
```
# load the smiles (just for illustrative purposes)
# here, 15 moleucles will be used
with open(smiles_path, 'r') as f:
smiles = [smile.strip() for smile in f.readlines()]
print(smiles)
```
While the embedding and docking tasks in `DockStream` are both specified in the same configuration file, they are handled independently. This means it is perfectly fine to either load conformers (from an `SDF` file) directly or to use a call of `docker.py` merely to generate conformers without doing the docking afterwards.
`DockStream` uses the notion of (embedding) "pool"s, of which multiple can be specified and accessed via identifiers. Note, that while the way conformers are generated is highly backend specific, `DockStream` allows you to use the results interchangably. This allows to (a) re-use embedded molecules for multiple docking runs (e.g. different scoring functions), without the necessity to embed them more than once and (b) to combine embeddings and docking backends freely.
One important feature is that you can also specify an `align` block for the pools, which will try to align the conformers produced to the reference ligand's coordinates. Alignment is especially useful if your molecules have a large common sub-structure, as it will potentially enhance the results. **Warning:** At the moment, this feature is a bit unstable at times (potentially crashes, if no overlap of a ligand with the reference ligand can be found).
As mentioned at the target preparation stage, we need to specify the cavity (binding cleft) or search space for `AutoDock Vina`. As we have extracted the "box" (see print-out of the logging file below) using a reference ligand, this helps us deciding on the dimensions of the search space:
```
!cat {log_file_target_prep}
```
The three `mean` values will serve as the center of the search space and from the minimum and maximum values in all three dimensions, we decide to use 15 (for `x`) and 10 (for `y` and `z`, respectively). As larger ligands could be used, we will give the algorithm some leeway in each dimension.
```
# specify the embedding and docking JSON file as a dictionary and write it out
ed_dict = {
"docking": {
"header": { # general settings
"logging": { # logging settings (e.g. which file to write to)
"logfile": log_file_docking
}
},
"ligand_preparation": { # the ligand preparation part, defines how to build the pool
"embedding_pools": [
{
"pool_id": "Corina_pool", # here, we only have one pool
"type": "Corina",
"parameters": {
"prefix_execution": "module load corina" # only required, if a module needs to be loaded to execute "Corina"
},
"input": {
"standardize_smiles": False,
"type": "smi",
"input_path": smiles_path
},
"output": { # the conformers can be written to a file, but "output" is
# not required as the ligands are forwarded internally
"conformer_path": ligands_conformers_path,
"format": "sdf"
}
}
]
},
"docking_runs": [
{
"backend": "AutoDockVina",
"run_id": "AutoDockVina",
"input_pools": ["Corina_pool"],
"parameters": {
"binary_location": vina_binary_location, # absolute path to the folder, where the "vina" binary
# can be found
"parallelization": {
"number_cores": 4
},
"seed": 42, # use this "seed" to generate reproducible results; if
# varied, slightly different results will be produced
"receptor_pdbqt_path": [adv_receptor_path], # paths to the receptor files
"number_poses": 2, # number of poses to be generated
"search_space": { # search space (cavity definition); see text
"--center_x": 3.3,
"--center_y": 11.5,
"--center_z": 24.8,
"--size_x": 15,
"--size_y": 10,
"--size_z": 10
}
},
"output": {
"poses": { "poses_path": ligands_docked_path },
"scores": { "scores_path": ligands_scores_path }
}}]}}
with open(docking_path, 'w') as f:
json.dump(ed_dict, f, indent=2)
# print out path to generated JSON
print(docking_path)
# execute this in a command-line environment after replacing the parameters
!{dockstream_env}/bin/python {docker} -conf {docking_path} -print_scores
```
Note, that the scores are usually only outputted to a `CSV` file specified by the `scores` block, but that since we have used parameter `-print_scores` they will also be printed to `stdout` (line-by-line).
These scores are associated with docking poses (see picture below for a couple of ligands overlaid in the binding pocket).

## Using `DockStream` as a scoring component in `REINVENT`
The *de novo* design platform `REINVENT` holds a recently added `DockStream` scoring function component (also check out our collection of notebooks in the [ReinventCommunity](https://github.com/MolecularAI/ReinventCommunity) repository). This means, provided that all necessary input files and configurations are available, you may run `REINVENT` and incorporate docking scores into the score of the compounds generated. Together with `FastROCS`, this represents the first step to integrate physico-chemical 3D information.
While the docking scores are a very crude proxy for the actual binding affinity (at best), it does prove useful as a *geometric filter* (removing ligands that obviously do not fit the binding cavity). Furthermore, a severe limitation of knowledge-based predictions e.g. in activity models is the domain applicability. Docking, as a chemical space agnostic component, can enhance the ability of the agent for scaffold-hopping, i.e. to explore novel sub-areas in the chemical space.
### The `REINVENT` configuration JSON
While every docking backend has its own configuration (see section above), calling `DockStream`'s `docker.py` entry point ensures that they all follow the same external API. Thus the component that needs to be added to `REINVENT`'s JSON configuration (to the `scoring_function`->`parameters` list) looks as follows for `AutoDock Vina`:
```
{
"component_type": "dockstream",
"name": "dockstream",
"weight": 1,
"specific_parameters": {
"transformation": {
"transformation_type": "reverse_sigmoid",
"low": -12,
"high": -8,
"k": 0.25
},
"configuration_path": "<absolute_path_to_DockStream_configuration>/docking.json",
"docker_script_path": "<absolute_path_to_DockStream_source>/docker.py",
"environment_path": "<absolute_path_to_miniconda_installation>/envs/DockStream/bin/python"
}
}
```
You will need to update `configuration_path`, `docker_script_path` and the link to the environment, `environment_path` to match your system's configuration. It might be, that the latter two are already set to meaningful defaults, but your `DockStream` configuration JSON file will be specific for each run.
#### How to find an appropriate transformation?
We use a *reverse sigmoid* score transformation to bring the numeric, continuous value that was outputted by `DockStream` and fed back to `REINVENT` into a 0 to 1 regime. The parameters `low`, `high` and `k` are critical: their exact value naturally depends on the backend used, but also on the scoring function (make sure, "more negative is better" - otherwise you are looking for a *sigmoid* transformation) and potentially also the project used. The values reported here can be used as rule-of-thumb for an `AutoDock Vina` run. Below is a code snippet, that helps to find the appropriate parameters (excerpt of the `ReinventCommunity` notebook `Score_Transformations`).
```
# load the dependencies and classes used
%run code/score_transformation.py
# set plotting parameters
small = 12
med = 16
large = 22
params = {"axes.titlesize": large,
"legend.fontsize": med,
"figure.figsize": (16, 10),
"axes.labelsize": med,
"axes.titlesize": med,
"xtick.labelsize": med,
"ytick.labelsize": med,
"figure.titlesize": large}
plt.rcParams.update(params)
plt.style.use("seaborn-whitegrid")
sns.set_style("white")
%matplotlib inline
# set up Enums and factory
tt_enum = TransformationTypeEnum()
csp_enum = ComponentSpecificParametersEnum()
factory = TransformationFactory()
# sigmoid transformation
# ---------
values_list = np.arange(-14, -7, 0.25).tolist()
specific_parameters = {csp_enum.TRANSFORMATION: True,
csp_enum.LOW: -12,
csp_enum.HIGH: -8,
csp_enum.K: 0.25,
csp_enum.TRANSFORMATION_TYPE: tt_enum.REVERSE_SIGMOID}
transform_function = factory.get_transformation_function(specific_parameters)
transformed_scores = transform_function(predictions=values_list,
parameters=specific_parameters)
# render the curve
render_curve(title=" Reverse Sigmoid Transformation", x=values_list, y=transformed_scores)
```
### How to specify the `DockStream` configuration file?
In principle, all options that are supported in a "normal" `DockStream` run (see above) are supported for usage with `REINVENT` as well, with a few notable exceptions. First, as we report only one value per ligand (and a "consensus score" is not yet supported), you should only use **one** embedding / pool and **one** backend (as in the example above). Second, the prospective ligands are not supplied via a file but from `stdin`, thus we will need to change the `input` part of the pool definition. Also, we might not want to write-out all conformers, so we will remove the `output` block entirely. The updated section then looks as follows:
```
{
"pool_id": "Corina_pool",
"type": "Corina",
"parameters": {
"removeHs": False
},
"input": {
"standardize_smiles": False
}
}
```
Finally, we will update the docking run as well. Typically, we want to see the docked poses per epoch and maybe also the scores and the SMILES in a well-tabulated format. Thus, we might retain the `output` block here, but as every epoch generates each of the files, it would overwrite it by default. If parameter `overwrite` is set to `False`, each consecutive write-out will be appended by a number, e.g. first epoch *poses.sdf* and *scores.csv*, second epoch *0001_poses.sdf* and *0001_scores.csv*, third epoch *0002_poses.sdf* and *0002_scores.csv* and so on.
```
{
"backend": "AutoDockVina",
"run_id": "AutoDockVina",
"input_pools": ["Corina_pool"],
...
"output": {
"poses": { "poses_path": ligands_docked_path, "overwrite": False },
"scores": { "scores_path": ligands_scores_path, "overwrite": False }
}
}
```
| github_jupyter |
# Deep autoencoders for recommendations
In this notebook, we'll apply a more advanced algorithm to the same dataset as before, taking a different approach. We'll use a deep autoencoder network, which attempts to reconstruct its input and with that gives us ratings for unseen user / movie pairs.

```
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import models
tf.random.set_seed(42)
# Clean up the logdir if it exists
import shutil
shutil.rmtree('logs', ignore_errors=True)
# Load TensorBoard extension for notebooks
%load_ext tensorboard
movielens_ratings_file = 'https://github.com/janhartman/recsystf/raw/master/datasets/movielens_ratings.csv'
df = pd.read_csv(movielens_ratings_file)
user_ids = df['userId'].unique()
user_encoding = {x: i for i, x in enumerate(user_ids)} # {user_id: index}
movie_ids = df['movieId'].unique()
movie_encoding = {x: i for i, x in enumerate(movie_ids)}
df['user'] = df['userId'].map(user_encoding) # Map from IDs to indices
df['movie'] = df['movieId'].map(movie_encoding)
n_users = len(user_ids)
n_movies = len(movie_ids)
```
We're going to use the same dataset as before, but our preprocessing will be a bit different due to the difference in our model. Our autoencoder will take a vector of all ratings for a movie and attempt to reconstruct it. However, our input vector will have a lot of zeroes due to the sparsity of our data. We'll modify our loss so our model won't predict zeroes for those combinations - it will actually predict unseen ratings.
To facilitate this, we'll use the sparse tensor that TF supports. Note: to make training easier, we'll transform it to dense form, which would not work in larger datasets - we would have to preprocess the data in a different way or stream it into the model.
#### Sparse representation and autoencoder reconstruction

```
# Create a sparse tensor: at each user, movie location, we have a value, the rest is 0
sparse_x = tf.sparse.SparseTensor(indices=df[['movie', 'user']].values, values=df['rating'], dense_shape=(n_movies, n_users))
# Transform it to dense form and to float32 (good enough precision)
dense_x = tf.cast(tf.sparse.to_dense(tf.sparse.reorder(sparse_x)), tf.float32)
# Shuffle the data
x = tf.random.shuffle(dense_x, seed=42)
```
Now, let's create the model. We'll have to specify the input shape. Because we have 9724 movies and only 610 users, we'll prefer to predict ratings for movies instead of users - this way, our dataset is larger.
```
class Encoder(layers.Layer):
def __init__(self, **kwargs):
super(Encoder, self).__init__(**kwargs)
self.dense1 = layers.Dense(28, activation='selu', kernel_initializer='glorot_uniform')
self.dense2 = layers.Dense(56, activation='selu', kernel_initializer='glorot_uniform')
self.dense3 = layers.Dense(56, activation='selu', kernel_initializer='glorot_uniform')
self.dropout = layers.Dropout(0.3)
def call(self, x):
d1 = self.dense1(x)
d2 = self.dense2(d1)
d3 = self.dense3(d2)
return self.dropout(d3)
class Decoder(layers.Layer):
def __init__(self, n, **kwargs):
super(Decoder, self).__init__(**kwargs)
self.dense1 = layers.Dense(56, activation='selu', kernel_initializer='glorot_uniform')
self.dense2 = layers.Dense(28, activation='selu', kernel_initializer='glorot_uniform')
self.dense3 = layers.Dense(n, activation='selu', kernel_initializer='glorot_uniform')
def call(self, x):
d1 = self.dense1(x)
d2 = self.dense2(d1)
return self.dense3(d2)
n = n_users
inputs = layers.Input(shape=(n,))
encoder = Encoder()
decoder = Decoder(n)
enc1 = encoder(inputs)
dec1 = decoder(enc1)
enc2 = encoder(dec1)
dec2 = decoder(enc2)
model = models.Model(inputs=inputs, outputs=dec2, name='DeepAutoencoder')
model.summary()
```
Because our inputs are sparse, we'll need to create a modified mean squared error function. We have to look at which ratings are zero in the ground truth and remove them from our loss calculation (if we didn't, our model would quickly learn to predict zeros almost everywhere).
We'll use masking - first get a boolean mask of non-zero values and then extract them from the result.
```
def masked_mse(y_true, y_pred):
mask = tf.not_equal(y_true, 0)
se = tf.boolean_mask(tf.square(y_true - y_pred), mask)
return tf.reduce_mean(se)
model.compile(
loss=masked_mse,
optimizer=keras.optimizers.Adam()
)
```
The model training will be similar as before - we'll use early stopping and TensorBoard. Our batch size will be smaller due to the lower number of examples. Note that we are passing the same array for both $x$ and $y$, because the autoencoder reconstructs its input.
```
callbacks = [
keras.callbacks.EarlyStopping(
monitor='val_loss',
min_delta=1e-2,
patience=5,
verbose=1,
),
keras.callbacks.TensorBoard(log_dir='logs')
]
model.fit(
x,
x,
batch_size=16,
epochs=100,
validation_split=0.1,
callbacks=callbacks
)
```
Let's visualize our loss and the model itself with TensorBoard.
```
%tensorboard --logdir logs
```
That's it! We've seen how to use TensorFlow to implement recommender systems in a few different ways. I hope this short introduction has been informative and has prepared you to use TF on new problems. Thank you for your attention!
| github_jupyter |
```
from IPython.display import Markdown as md
### change to reflect your notebook
_nb_loc = "06_preprocessing/06h_tftransform.ipynb"
_nb_title = "Avoid training-serving skew using TensorFlow Transform"
### no need to change any of this
_nb_safeloc = _nb_loc.replace('/', '%2F')
md("""
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://console.cloud.google.com/ai-platform/notebooks/deploy-notebook?name={1}&url=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fpractical-ml-vision-book%2Fblob%2Fmaster%2F{2}&download_url=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fpractical-ml-vision-book%2Fraw%2Fmaster%2F{2}">
<img src="https://raw.githubusercontent.com/GoogleCloudPlatform/practical-ml-vision-book/master/logo-cloud.png"/> Run in AI Platform Notebook</a>
</td>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/GoogleCloudPlatform/practical-ml-vision-book/blob/master/{0}">
<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/GoogleCloudPlatform/practical-ml-vision-book/blob/master/{0}">
<img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://raw.githubusercontent.com/GoogleCloudPlatform/practical-ml-vision-book/master/{0}">
<img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
""".format(_nb_loc, _nb_title, _nb_safeloc))
```
# Avoid training-serving skew using TensorFlow Transform
In this notebook, we show how to use tf.transform to carry out preprocessing efficiently,
but save the preprocessing operations so that they are automatically applied during inference.
## Enable GPU and set up helper functions
This notebook and pretty much every other notebook in this repository
will run faster if you are using a GPU.
On Colab:
- Navigate to Edit→Notebook Settings
- Select GPU from the Hardware Accelerator drop-down
On Cloud AI Platform Notebooks:
- Navigate to https://console.cloud.google.com/ai-platform/notebooks
- Create an instance with a GPU or select your instance and add a GPU
Next, we'll confirm that we can connect to the GPU with tensorflow:
```
import tensorflow as tf
print(tf.version.VERSION)
device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
raise SystemError('GPU device not found')
print('Found GPU at: {}'.format(device_name))
```
## Run Beam pipeline locally
```
!cat run_dataflow.sh
!./run_dataflow.sh > /dev/null 2>&1
!ls -l flower_tftransform/
```
## Display preprocessing data
Note that the files contain already preprocessed (scaled, resized images),
so we can simply read the data and display it.
```
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
IMG_HEIGHT = 448
IMG_WIDTH = 448
IMG_CHANNELS = 3
CLASS_NAMES = 'daisy dandelion roses sunflowers tulips'.split()
ds = tf.data.experimental.make_batched_features_dataset(
'./flower_tftransform/train-00000-of-00016.gz',
batch_size=5,
features = {
'image': tf.io.FixedLenFeature([IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS], tf.float32),
'label': tf.io.FixedLenFeature([], tf.string),
'label_int': tf.io.FixedLenFeature([], tf.int64)
},
reader=lambda filenames: tf.data.TFRecordDataset(filenames, compression_type='GZIP')
)
for feats in ds.take(1):
print(feats['image'].shape)
f, ax = plt.subplots(1, 5, figsize=(15,15))
for feats in ds.take(1):
for idx in range(5): # batchsize
ax[idx].imshow((feats['image'][idx].numpy()));
ax[idx].set_title(feats['label'][idx].numpy())
ax[idx].axis('off')
```
## Train the model
```
# Helper functions
def training_plot(metrics, history):
f, ax = plt.subplots(1, len(metrics), figsize=(5*len(metrics), 5))
for idx, metric in enumerate(metrics):
ax[idx].plot(history.history[metric], ls='dashed')
ax[idx].set_xlabel("Epochs")
ax[idx].set_ylabel(metric)
ax[idx].plot(history.history['val_' + metric]);
ax[idx].legend([metric, 'val_' + metric])
import tensorflow_hub as hub
import os
# Load compressed models from tensorflow_hub
os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'
def create_preproc_dataset(pattern, batch_size):
return tf.data.experimental.make_batched_features_dataset(
pattern,
batch_size=batch_size,
features = {
'image': tf.io.FixedLenFeature([IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS], tf.float32),
'label': tf.io.FixedLenFeature([], tf.string),
'label_int': tf.io.FixedLenFeature([], tf.int64)
},
reader=lambda filenames: tf.data.TFRecordDataset(filenames, compression_type='GZIP'),
num_epochs=1
).map(
lambda x: (x['image'], x['label_int'])
)
# parameterize to the values in the previous cell
# WARNING! training on a small subset dataset (note top_dir)
def train_and_evaluate(top_dir='./flower_tftransform',
batch_size = 32,
lrate = 0.001,
l1 = 0.,
l2 = 0.,
num_hidden = 16):
regularizer = tf.keras.regularizers.l1_l2(l1, l2)
train_dataset = create_preproc_dataset(os.path.join(top_dir, 'train-*'), batch_size)
eval_dataset = create_preproc_dataset(os.path.join(top_dir, 'valid-*'), batch_size)
layers = [
tf.keras.layers.experimental.preprocessing.CenterCrop(
height=IMG_HEIGHT//2, width=IMG_WIDTH//2,
input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS),
),
hub.KerasLayer(
"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4",
trainable=False,
name='mobilenet_embedding'),
tf.keras.layers.Dense(num_hidden,
kernel_regularizer=regularizer,
activation=tf.keras.activations.relu,
name='dense_hidden'),
tf.keras.layers.Dense(len(CLASS_NAMES),
kernel_regularizer=regularizer,
activation='softmax',
name='flower_prob')
]
model = tf.keras.Sequential(layers, name='flower_classification')
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lrate),
loss=tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=False),
metrics=['accuracy'])
print(model.summary())
history = model.fit(train_dataset, validation_data=eval_dataset, epochs=3)
training_plot(['loss', 'accuracy'], history)
return model
model = train_and_evaluate()
```
## Predictions
For serving, we will write a serving function that calls the transform model
followed by our actual model.
We will look at serving functions in Chapter 7. For now, we show how to explicitly
call the transform function followed by model.predict()
```
!saved_model_cli show --all --dir ./flower_tftransform/tft/transform_fn
# get some files to do inference on.
filenames = [
'gs://cloud-ml-data/img/flower_photos/dandelion/9818247_e2eac18894.jpg',
'gs://cloud-ml-data/img/flower_photos/dandelion/9853885425_4a82356f1d_m.jpg',
'gs://cloud-ml-data/img/flower_photos/dandelion/98992760_53ed1d26a9.jpg',
'gs://cloud-ml-data/img/flower_photos/dandelion/9939430464_5f5861ebab.jpg',
'gs://cloud-ml-data/img/flower_photos/dandelion/9965757055_ff01b5ee6f_n.jpg'
]
img_bytes = [
tf.io.read_file(filename) for filename in filenames
]
label = [
'n/a' for filename in filenames
] # not used in inference
label_int = [
-1 for filename in filenames
] # not used in inference
# by calling the preproc function, we get images of the right size & crop
preproc = tf.keras.models.load_model('./flower_tftransform/tft/transform_fn').signatures['transform_signature']
preprocessed = preproc(img_bytes=tf.convert_to_tensor(img_bytes),
label=tf.convert_to_tensor(label, dtype=tf.string),
label_int=tf.convert_to_tensor(label_int, dtype=tf.int64))
# then we call model.predict() and take the argmx of the result
pred_label_index = tf.math.argmax(model.predict(preprocessed)).numpy()
print(pred_label_index)
```
## License
Copyright 2020 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 |
# Two competing species
### Kirill Zakharov
```
import numpy as np
import matplotlib.pyplot as plt
import math
plt.style.use("ggplot")
#Runge-Kutt method
def runge_Kutt(f, g, t0, x0, y0, h, b):
t = t0
x = x0
y = y0
arrayX = np.array([])
arrayY = np.array([])
arrayT = np.array([])
while t<b:
k1 = g(t, x, y)
q1 = f(t, x, y)
k2 = g(t + h/2, x + (h*q1)/2, y + (h*k1)/2)
q2 = f(t + h/2, x + (h*q1)/2, y + (h*k1)/2)
k3 = g(t + h/2, x + (h*q2)/2, y + (h*k2)/2)
q3 = f(t + h/2, x + (h*q2)/2, y + (h*k2)/2)
k4 = g(t + h, x + h*q3, y + h*k3)
q4 = f(t + h, x + h*q3, y + h*k3)
y = y + h*(k1 + 2*k2 + 2*k3 + k4)/6
x = x + h*(q1 + 2*q2 + 2*q3 + q4)/6
arrayX = np.append(arrayX, x)
arrayT = np.append(arrayT, t)
arrayY = np.append(arrayY, y)
t += h
return arrayT, arrayX, arrayY
# a1 = 1
# a2 = 1
# b11 = 0.2
# b12 = 0.3
# b21 = 0.205
# b22 = 0.25
a1 = 1
a2 = 0.75
b11 = 1
b12 = 0.85
b21 = 0.55
b22 = 0.55
def fx(t, x, y):
return a1*x - b11*x**2 - b12*x*y
def fy(t, x, y):
return a2*y - b21*x*y - b22*y**2
def fxl(t, x, y):
return a1*math.log(x) - b11*math.log(x)**2 - b12*math.log(x)*math.log(y)
def fyl(t, x, y):
return a2*math.log(y) - b21*math.log(x)*math.log(y) - b22*math.log(y)**2
p1, p2, p3 = runge_Kutt(fxl, fyl, 0, 4, 5, 0.01, 100)
print(f"Solution: x = {p2[-1]}, y = {p3[-1]}")
```
## Visualization
```
fig, ax = plt.subplots(figsize=(11,8))
n = len(p1)
t = np.linspace(0, 100, n)
t1 = np.linspace(0, 14, 20)
plt.plot(t, p2, label="first population")
plt.plot(t, p3, label="second population")
plt.legend(prop={'size': 12})
plt.show()
fig, ax = plt.subplots(figsize=(11, 8))
for i in range(15):
p1, p2, p3 = runge_Kutt(fx, fy, 0, math.cos(i*np.pi/60), math.sin(i*np.pi/60), 0.01, 100)
plt.plot(p2, p3,c='purple')
#stationary points
plt.scatter(0, 0, c='black', label="x = 0, y = 0")
plt.scatter(a1/b11, 0, c='red', label="x = a1/b11, y = 0")
plt.scatter(0, a2/b22, c='blue', label="x = 0, y = a2/b22")
plt.scatter((b12*a2 - b22*a1)/(b21*b12 - b22*b11), (a1*b21 - a2*b11)/(b12*b21 - b22*b11), c='green')
ax.set_xlim(-0.05, a1/b11+0.05)
ax.set_ylim(-0.05, a2/b22+0.05)
plt.legend()
plt.show()
fig, ax = plt.subplots(figsize=(12,8))
X, Y = np.mgrid[0:a1/b11:16j,
0:a2/b22:16j]
U = a1*X - b11*X**2 - b12*X*Y
V = a2*Y - b21*X*Y - b22*Y**2
#vector field
ax.quiver(X, Y, U, V, color='black')
#stationary points
plt.scatter(0, 0, c='black', label="x = 0, y = 0")
plt.scatter(a1/b11, 0, c='red', label="x = a1/b11, y = 0")
plt.scatter(0, a2/b22, c='blue', label="x = 0, y = a2/b22")
plt.scatter((b12*a2 - b22*a1)/(b21*b12 - b22*b11), (a1*b21 - a2*b11)/(b12*b21 - b22*b11), c='green')
ax.set_xlim(-0.05, a1/b11+0.05)
ax.set_ylim(-0.05, a2/b22+0.05)
plt.legend()
plt.show()
```
### x1 = 0, x2 = 0
```
x1 = 0
x2 = 0
jacobi_matrix = np.array([[a1-2*b11*x1-b12*x2, -b12*x1], [-b21*x2, a2-2*b22*x2-b21*x1]])
jacobi_matrix
D0 = (jacobi_matrix.trace())**2-4*(jacobi_matrix[0][0]*jacobi_matrix[1][1]-(jacobi_matrix[0][1]*jacobi_matrix[1][0]))
D0
```
неустойчивый узел
### x1 = a1/b11, x2 = 0
```
x1 = a1/b11
x2 = 0
jacobi_matrix = np.array([[a1-2*b11*x1-b12*x2, -b12*x1], [-b21*x2, a2-2*b22*x2-b21*x1]])
jacobi_matrix
D = (jacobi_matrix.trace())**2-4*(jacobi_matrix[0][0]*jacobi_matrix[1][1]-(jacobi_matrix[0][1]*jacobi_matrix[1][0]))
D
```
устойчивый узел
### x1 = 0, x2 = a2/b22
```
x1 = 0
x2 = a2/b22
jacobi_matrix1 = np.array([[a1-2*b11*x1-b12*x2, -b12*x1], [-b21*x2, a2-2*b22*x2-b21*x1]])
jacobi_matrix1
D1 = (jacobi_matrix1.trace())**2-4*(jacobi_matrix1[0][0]*jacobi_matrix1[1][1]-(jacobi_matrix1[0][1]*jacobi_matrix1[1][0]))
D1
```
устойчивый узел
### x1 = (a2b12-a1b22)/(b12b21-b22b11), x2 = (a1b21-a2b11)/(b12b21-b22b11)
```
x1 = (a2*b12-a1*b22)/(b12*b21-b22*b11)
x2 = (a1*b21-a2*b11)/(b12*b21-b22*b11)
jacobi_matrix2 = np.array([[a1-2*b11*x1-b12*x2, -b12*x1], [-b21*x2, a2-2*b22*x2-b21*x1]])
jacobi_matrix2
D2 = (jacobi_matrix1.trace())**2-4*(jacobi_matrix1[0][0]*jacobi_matrix1[1][1]-(jacobi_matrix1[0][1]*jacobi_matrix1[1][0]))
D2
```
Седло
| github_jupyter |
# Deep learning the collisional cross sections of the peptide universe from a million experimental values
Florian Meier, Niklas D. Köhler, Andreas-David Brunner, Jean-Marc H. Wanka, Eugenia Voytik, Maximilian T. Strauss, Fabian J. Theis, Matthias Mann
Pre-print: https://doi.org/10.1101/2020.05.19.102285
Publication: pending
revised 09/2020
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.colors
from scipy import optimize
from Bio.SeqUtils.ProtParam import ProteinAnalysis
aminoacids = 'A R N D C Q E G H I L K M F P S T W Y V'.split()
# amino acid bulkiness
# Zimmerman J.M., Eliezer N., Simha R. J. Theor. Biol. 21:170-201(1968).
aa_bulkiness = {
"A": 11.500,
"R": 14.280,
"N": 12.820,
"D": 11.680,
"C": 13.460,
"Q": 14.450,
"E": 13.570,
"G": 3.400,
"H": 13.690,
"I": 21.400,
"L": 21.400,
"K": 15.710,
"M": 16.250,
"F": 19.800,
"P": 17.430,
"S": 9.470,
"T": 15.770,
"W": 21.670,
"Y": 18.030,
"V": 21.570
}
def bulkiness(sequence):
total_bulk = sum(aa_bulkiness[aa] for aa in sequence)
return total_bulk / len(sequence)
cmap = plt.get_cmap("RdYlBu")
colors = cmap(np.linspace(0, 1, num=20))
charge_col = {'2': colors[0], '3': colors[6], '4': colors[18]}
cmap2 = plt.get_cmap("YlOrRd")
cmap3 = plt.get_cmap("YlOrRd_r")
evidences = pd.read_csv('output/evidence_aligned.csv')
evidences.head()
len(evidences)
evidences['lastAA'] = evidences['Sequence'].str[-1:]
## calculate physicochemical properties
evidences['gravy'] = [ProteinAnalysis(seq).gravy() for seq in evidences['Sequence']]
evidences['bulkiness'] = [bulkiness(seq) for seq in evidences['Sequence']]
# Amino acids favoring secondary structures (Levitt, M. Biochemistry 17, 4277–4285 (1978))
evidences['helix_fraction'] = [(seq.count('A') + seq.count('L') + seq.count('M') + seq.count('H') +
seq.count('Q') + seq.count('E'))/len(seq) for seq in evidences['Sequence']]
evidences['sheet_fraction'] = [(seq.count('V') + seq.count('I') + seq.count('F') + seq.count('T') +
seq.count('Y'))/len(seq) for seq in evidences['Sequence']]
evidences['turn_fraction'] = [(seq.count('G') + seq.count('S') + seq.count('D') + seq.count('N') +
seq.count('P'))/len(seq) for seq in evidences['Sequence']]
evidences_trp = evidences.loc[evidences['lastAA'].str.contains('K|R')]
len(evidences_trp)
evidences_trp_H = evidences_trp.loc[evidences_trp['Sequence'].str.count('H') > 0]
positions = []
for sequence in evidences_trp_H['Sequence']:
pos = np.array([pos for pos, char in enumerate(sequence) if char == 'H'])
vector = pos - np.median(range(len(sequence)))
relpos = sum(vector) / len(sequence)
positions.append(relpos)
evidences_trp_H['H_pos'] = positions
len(evidences_trp_H)
# Calculate trend line functions
CCS_fit_charge2 = evidences[evidences['Charge'] == 2]
CCS_fit_charge3 = evidences[evidences['Charge'] == 3]
CCS_fit_charge4 = evidences[evidences['Charge'] == 4]
def trendline_func(x, a, b):
return a * np.power(x, b)
params_charge2, params_covariance_charge2 = optimize.curve_fit(
trendline_func, CCS_fit_charge2['m/z'], CCS_fit_charge2['CCS'])
params_charge3, params_covariance_charge3 = optimize.curve_fit(
trendline_func, CCS_fit_charge3['m/z'], CCS_fit_charge3['CCS'])
params_charge4, params_covariance_charge4 = optimize.curve_fit(
trendline_func, CCS_fit_charge4['m/z'], CCS_fit_charge4['CCS'])
print('2+')
print(params_charge2, params_covariance_charge2)
print('---')
print('3+')
print(params_charge3, params_covariance_charge3)
print('---')
print('4+')
print(params_charge4, params_covariance_charge4)
fig, axs = plt.subplots(1,3, figsize=(12, 4))
# panel a
im1 = axs[0].scatter(x = evidences['m/z'],
y = evidences['CCS'],
c = evidences['gravy'],
alpha = 0.8, s = 0.8, linewidth=0, #vmin = -1, vmax = 1,
cmap = cmap);
axs[0].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge2[0], params_charge2[1]), color = "black", ls = 'dashed', lw = .5)
axs[0].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge3[0], params_charge3[1]), color = "black", ls = 'dashed', lw = .5)
axs[0].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge4[0], params_charge4[1]), color = "black", ls = 'dashed', lw = .5)
axs[0].set_ylabel('CCS ($\AA^2$)')
axs[0].set_xlabel('$\it{m/z}$')
axs[0].text(-0.2, 1.05, "a", transform=axs[0].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im1, ax = axs[0])
cb.set_label('GRAVY score')
# panel b
im2 = axs[1].scatter(x = evidences_trp['m/z'],
y = evidences_trp['CCS'],
c = (evidences_trp['Sequence'].str.count('P') / evidences_trp['Sequence'].str.len() * 100),
alpha = 0.5, s = 0.5, linewidth=0, vmin = 0, vmax = 15,
cmap = cmap3)
axs[1].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge2[0], params_charge2[1]), color = "black", ls = 'dashed', lw = .5)
axs[1].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge3[0], params_charge3[1]), color = "black", ls = 'dashed', lw = .5)
axs[1].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge4[0], params_charge4[1]), color = "black", ls = 'dashed', lw = .5)
axs[1].set_ylabel('CCS ($\AA^2$)')
axs[1].set_xlabel('$\it{m/z}$')
axs[1].text(-0.2, 1.05, "b", transform=axs[1].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im2, ax = axs[1])
cb.set_ticks([0,5,10,15])
cb.set_ticklabels(['0', '5', '10', '$\geq$ 15'])
cb.set_label('Rel. P count (%)', labelpad = -10)
# panel c
im3 = axs[2].scatter(x = evidences_trp_H['m/z'],
y = evidences_trp_H['CCS'],
c = evidences_trp_H['H_pos'],
alpha = 0.5, s = 0.5, linewidth=0, vmin = -1, vmax = 1,
cmap = cmap)
axs[2].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge2[0], params_charge2[1]), color = "black", ls = 'dashed', lw = .5)
axs[2].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge3[0], params_charge3[1]), color = "black", ls = 'dashed', lw = .5)
axs[2].plot(np.arange(300,1800,1), trendline_func(
np.arange(300,1800,1), params_charge4[0], params_charge4[1]), color = "black", ls = 'dashed', lw = .5)
axs[2].set_ylabel('CCS ($\AA^2$)')
axs[2].set_xlabel('$\it{m/z}$')
axs[2].text(-0.2, 1.05, "c", transform=axs[2].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im3, ax = axs[2])
cb.set_ticks([-1,1])
cb.set_ticklabels(['C-term', 'N-term'])
cb.set_label('H position', labelpad = -20)
plt.tight_layout()
plt.savefig('figures/Figure3.jpg')
plt.show();
```
<b>Figure 3. A global view on peptide cross sections.</b> <b>a,</b> Mass-to-charge vs. collisional cross section distribution of all peptides in this study colored by the GRAVY hydrophobicity index (n = 559,979). </b> <b>b,</b> Subset of peptides with C-terminal arginine or lysine colored by the fraction of prolines in the linear sequence (n = 452,592). </b> <b>c,</b> Histidine-containing peptides of b colored by the relative position of histidine (n = 171,429). Trend lines (dashed) are fitted to the overall peptide distribution to visualize the correlation of ion mass and mobility in each charge state.
```
fig, axs = plt.subplots(1,3, figsize=(12, 4))
# panel a
im1 = axs[0].scatter(x = evidences_trp['m/z'],
y = evidences_trp['CCS'],
c = evidences_trp['helix_fraction'],
alpha = 0.5, s = 0.5, linewidth=0, vmin = 0, vmax = 0.5,
cmap = cmap3);
axs[0].set_ylabel('CCS ($\AA^2$)')
axs[0].set_xlabel('$\it{m/z}$')
axs[0].text(-0.2, 1.05, "a", transform=axs[0].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im1, ax = axs[0])
cb.set_ticks([0,0.1,0.2,0.3, 0.4, 0.5])
cb.set_ticklabels(['0.0', '0.1', '0.2', '0.3', '0.4', '$\geq$ 0.5'])
cb.set_label('Helix fraction')
# panel b
im2 = axs[1].scatter(x = evidences_trp['m/z'],
y = evidences_trp['CCS'],
c = evidences_trp['turn_fraction'],
alpha = 0.5, s = 0.5, linewidth=0, vmin = 0, vmax = 0.5,
cmap = cmap3)
axs[1].set_ylabel('CCS ($\AA^2$)')
axs[1].set_xlabel('$\it{m/z}$')
axs[1].text(-0.2, 1.05, "b", transform=axs[1].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im2, ax = axs[1])
cb.set_ticks([0,0.1,0.2,0.3, 0.4, 0.5])
cb.set_ticklabels(['0.0', '0.1', '0.2', '0.3', '0.4', '$\geq$ 0.5'])
cb.set_label('Turn fraction')
# panel c
im3 = axs[2].scatter(x = evidences_trp['m/z'],
y = evidences_trp['CCS'],
c = evidences_trp['sheet_fraction'],
alpha = 0.5, s = 0.5, linewidth=0, vmin = 0, vmax = 0.5,
cmap = cmap3)
axs[2].set_ylabel('CCS ($\AA^2$)')
axs[2].set_xlabel('$\it{m/z}$')
axs[2].text(-0.2, 1.05, "c", transform=axs[2].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im3, ax = axs[2])
cb.set_ticks([0,0.1,0.2,0.3, 0.4, 0.5])
cb.set_ticklabels(['0.0', '0.1', '0.2', '0.3', '0.4', '$\geq$ 0.5'])
cb.set_label('Sheet fraction')
plt.tight_layout()
plt.savefig('figures/Figure_S3.png')
plt.show();
```
<b>Supplementary Figure 5.</b> Fraction of amino acids favoring <b>a,</b> helical (A, L, M, H, Q, E), <b>b,</b> turn (V, I, F, T, Y) and <b>c,</b> sheet (G, S, D, N, P) secondary structures according to Levitt 1978.
### Comparison LysC vs. LysN
```
evidences['firstAA'] = evidences['Sequence'].str[:1]
evidences['lastAA'] = evidences['Sequence'].str[-1:]
evidence_subset_LysC = evidences[evidences['lastAA'].isin(['K'])]
evidence_subset_LysN = evidences[evidences['firstAA'].isin(['K'])]
mod_seq_lysC = []
mod_seq_lysN = []
seq_lysC = []
seq_lysN = []
internal_seq = []
CCS_lysC = []
CCS_lysN = []
deltas = []
Mass = []
mz = []
for index, row in evidence_subset_LysC.iterrows():
internal_sequence = row['Modified sequence'][1:-2]
tmp = evidence_subset_LysN.loc[evidence_subset_LysN['Modified sequence'].str[2:-1] == internal_sequence]
if(len(tmp) > 0):
for i, sequence in enumerate(tmp['Sequence']):
if ( (row['Charge'] == tmp.iloc[i]['Charge'])):
mod_seq_lysC.append(row['Modified sequence'])
mod_seq_lysN.append(tmp.iloc[i]['Modified sequence'])
seq_lysC.append(row['Sequence'])
seq_lysN.append(tmp.iloc[i]['Sequence'])
internal_seq.append(internal_sequence)
CCS_lysC.append(row['CCS'])
CCS_lysN.append(tmp.iloc[i]['CCS'])
Mass.append(row['Mass'])
mz.append(row['m/z'])
deltas.append(row['CCS'] - tmp.iloc[i]['CCS'])
lysc_lysn = pd.DataFrame()
lysc_lysn['mod_seq_lysC'] = mod_seq_lysC
lysc_lysn['mod_seq_lysN'] = mod_seq_lysN
lysc_lysn['seq_lysC'] = seq_lysC
lysc_lysn['seq_lysN'] = seq_lysN
lysc_lysn['internal_seq'] = internal_seq
lysc_lysn['CCS_lysC'] = CCS_lysC
lysc_lysn['CCS_lysN'] = CCS_lysN
lysc_lysn['deltas'] = deltas
lysc_lysn['Mass'] = Mass
lysc_lysn['mz'] = mz
lysc_lysn.to_csv('output/peptides_LysN_LysC.csv');
print(len(deltas))
lysc_lysn['charge'] = np.rint(lysc_lysn['Mass']/lysc_lysn['mz'])
# Median relative shift
((lysc_lysn['CCS_lysC']-lysc_lysn['CCS_lysN'])/lysc_lysn['CCS_lysC']*100).median()
lysc_lysn_charge2 = lysc_lysn[lysc_lysn['charge'] == 2]
lysc_lysn_charge3 = lysc_lysn[lysc_lysn['charge'] == 3]
lysc_lysn_charge4 = lysc_lysn[lysc_lysn['charge'] == 4]
len(lysc_lysn_charge2), len(lysc_lysn_charge3), len(lysc_lysn_charge4)
((lysc_lysn_charge2['CCS_lysC']-lysc_lysn_charge2['CCS_lysN'])/lysc_lysn_charge2['CCS_lysC']*100).hist(bins = 50)
plt.xlabel('CCS (LysC-LysN)/LysC (%) ')
plt.ylabel('Count');
plt.savefig("figures/Suppl_Fig_5c.jpg")
((lysc_lysn_charge3['CCS_lysC']-lysc_lysn_charge3['CCS_lysN'])/lysc_lysn_charge3['CCS_lysC']*100).hist(bins = 80)
plt.xlabel('CCS (LysC-LysN)/LysC (%) ')
plt.ylabel('Count');
plt.savefig("figures/Suppl_Fig_5d.png")
sns.kdeplot(evidence_subset_LysC.loc[evidence_subset_LysC['Charge'] == 3]['m/z'],
evidence_subset_LysC.loc[evidence_subset_LysC['Charge'] == 3]['CCS'],
cmap="Blues", shade=True, shade_lowest=False)
plt.xlabel('m/z')
plt.ylabel('CCS ($\AA^2$)')
plt.savefig("figures/Suppl_Fig_5a_charge3.png");
sns.kdeplot(evidence_subset_LysN.loc[evidence_subset_LysN['Charge'] == 3]['m/z'],
evidence_subset_LysN.loc[evidence_subset_LysN['Charge'] == 3]['CCS'],
cmap="Blues", shade=True, shade_lowest=False)
plt.xlabel('m/z')
plt.ylabel('CCS ($\AA^2$)')
plt.savefig("figures/Suppl_Fig_5b_charge3.png");
sns.kdeplot(evidence_subset_LysC.loc[evidence_subset_LysC['Charge'] == 2]['m/z'],
evidence_subset_LysC.loc[evidence_subset_LysC['Charge'] == 2]['CCS'],
cmap="Blues", shade=True, shade_lowest=False)
plt.xlabel('m/z')
plt.ylabel('CCS ($\AA^2$)')
plt.savefig("figures/Suppl_Fig_5a_charge2.png");
sns.kdeplot(evidence_subset_LysN.loc[evidence_subset_LysN['Charge'] == 2]['m/z'],
evidence_subset_LysN.loc[evidence_subset_LysN['Charge'] == 2]['CCS'],
cmap="Blues", shade=True, shade_lowest=False)
plt.xlabel('m/z')
plt.ylabel('CCS ($\AA^2$)')
plt.savefig("figures/Suppl_Fig_5b_charge2.png");
```
### Comparison bulkiness vs. hydrophobicity
```
fig, axs = plt.subplots(1,2, figsize=(12, 4))
# panel a
im1 = axs[0].scatter(x = evidences_trp['m/z'],
y = evidences_trp['CCS'],
c = evidences_trp['bulkiness'],
alpha = 1, s = 0.5, linewidth=0, vmin = 11, vmax = 19,
cmap = cmap);
axs[0].set_ylabel('CCS ($\AA^2$)')
axs[0].set_xlabel('$\it{m/z}$')
axs[0].text(-0.2, 1.05, "a", transform=axs[0].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im1, ax = axs[0])
cb.set_label('Bulkiness')
# panel b
im2 = axs[1].scatter(x = evidences_trp['m/z'],
y = evidences_trp['CCS'],
c = evidences_trp['gravy'],
alpha = 1, s = 0.5, linewidth=0, vmin = -3, vmax = 2,
cmap = cmap);
axs[1].set_ylabel('CCS ($\AA^2$)')
axs[1].set_xlabel('$\it{m/z}$')
axs[1].text(-0.2, 1.05, "b", transform=axs[1].transAxes,
fontsize=16, fontweight='bold', va='top', ha='right')
cb = fig.colorbar(im2, ax = axs[1])
cb.set_label('GRAVY score')
plt.tight_layout()
plt.savefig('figures/revision_bulk_hydrophob.png')
plt.show();
# define quantiles for deviation from trend line
CCS_fit_charge2['deltaFit'] = (CCS_fit_charge2['CCS'] - trendline_func(
CCS_fit_charge2['m/z'], params_charge2[0], params_charge2[1])) / trendline_func(
CCS_fit_charge2['m/z'], params_charge2[0], params_charge2[1])
q1 = CCS_fit_charge2['deltaFit'].quantile(0.20)
q2 = CCS_fit_charge2['deltaFit'].quantile(0.40)
q3 = CCS_fit_charge2['deltaFit'].quantile(0.60)
q4 = CCS_fit_charge2['deltaFit'].quantile(0.80)
CCS_fit_charge2.loc[CCS_fit_charge2['deltaFit'] < q1, 'quantile'] = 1
CCS_fit_charge2.loc[(CCS_fit_charge2['deltaFit'] >= q1) & (CCS_fit_charge2['deltaFit'] < q2), 'quantile'] = 2
CCS_fit_charge2.loc[(CCS_fit_charge2['deltaFit'] >= q2) & (CCS_fit_charge2['deltaFit'] < q3), 'quantile'] = 3
CCS_fit_charge2.loc[(CCS_fit_charge2['deltaFit'] >= q3) & (CCS_fit_charge2['deltaFit'] < q4), 'quantile'] = 4
CCS_fit_charge2.loc[(CCS_fit_charge2['deltaFit'] >= q4), 'quantile'] = 5
CCS_fit_charge3['deltaFit'] = (CCS_fit_charge3['CCS'] - trendline_func(
CCS_fit_charge3['m/z'], params_charge3[0], params_charge3[1])) / trendline_func(
CCS_fit_charge3['m/z'], params_charge3[0], params_charge3[1])
q1 = CCS_fit_charge3['deltaFit'].quantile(0.20)
q2 = CCS_fit_charge3['deltaFit'].quantile(0.40)
q3 = CCS_fit_charge3['deltaFit'].quantile(0.60)
q4 = CCS_fit_charge3['deltaFit'].quantile(0.80)
CCS_fit_charge3.loc[CCS_fit_charge3['deltaFit'] < q1, 'quantile'] = 1
CCS_fit_charge3.loc[(CCS_fit_charge3['deltaFit'] >= q1) & (CCS_fit_charge3['deltaFit'] < q2), 'quantile'] = 2
CCS_fit_charge3.loc[(CCS_fit_charge3['deltaFit'] >= q2) & (CCS_fit_charge3['deltaFit'] < q3), 'quantile'] = 3
CCS_fit_charge3.loc[(CCS_fit_charge3['deltaFit'] >= q3) & (CCS_fit_charge3['deltaFit'] < q4), 'quantile'] = 4
CCS_fit_charge3.loc[(CCS_fit_charge3['deltaFit'] >= q4), 'quantile'] = 5
from matplotlib.colors import ListedColormap
cmap = ListedColormap(sns.color_palette('tab10', n_colors = 5))
plt.scatter(CCS_fit_charge2['m/z'], CCS_fit_charge2['CCS'], s = .1, alpha = .1, c=CCS_fit_charge2['quantile'], cmap = cmap)
plt.ylabel('CCS ($\AA^2$)')
plt.xlabel('$\it{m/z}$')
plt.savefig('figures/Supplementary_Figure_quantiles_a.jpg');
sns.violinplot(y = 'gravy', x = 'quantile', data = CCS_fit_charge2)
plt.ylabel('GRAVY score')
plt.xlabel('Quantile')
plt.savefig('figures/Supplementary_Figure_quantiles_b.jpg')
sns.violinplot(y = 'bulkiness', x = 'quantile', data = CCS_fit_charge2)
plt.ylabel('Bulkiness')
plt.xlabel('Quantile')
plt.savefig('figures/Supplementary_Figure_quantiles_c.jpg')
plt.scatter(CCS_fit_charge3['m/z'], CCS_fit_charge3['CCS'], s = .1, alpha = .1, c=CCS_fit_charge3['quantile'], cmap = cmap)
plt.ylabel('CCS ($\AA^2$)')
plt.xlabel('$\it{m/z}$')
plt.savefig('figures/Supplementary_Figure_quantiles_d.jpg')
sns.violinplot(y = 'gravy', x = 'quantile', data = CCS_fit_charge3)
plt.ylabel('GRAVY score')
plt.xlabel('Quantile')
plt.savefig('figures/Supplementary_Figure_quantiles_e.jpg')
sns.violinplot(y = 'bulkiness', x = 'quantile', data = CCS_fit_charge3)
plt.ylabel('Bulkiness')
plt.xlabel('Quantile')
plt.savefig('figures/Supplementary_Figure_quantiles_f.jpg')
```
| github_jupyter |
## Data Science Challenge
The data given is of credit records of individuals with certain attributes. Please go through following to understand the variables involved:
1. **serial number :** unique identification key
2. **account_info :** Categorized details of existing accounts of the individuals. The balance of money in account provided is stated by this variable
3. **purpose:** This variable signifies why the loan was taken
- A40 signifies that the loan is taken to buy a new car
- A46 signifies that the loan is taken for education
- A47 signifies that the loan is taken for vacation
- A48 signifies that the loan is taken for re skilling
- A49 signifies that the loan is taken for business and establishment
- A410 signifies other purposes
4. **savings_account:** This variable signifies details of the amount present in savings account of the individual:
- A61 signifies that less than 100 units (excluding 100) of currency is present
- A62 signifies that greater than 100 units (including 100) and less than 500 (excluding 500) units of currency is present
- A63 signifies that greater than 500 (including 500) and less than 1000 (excluding 1000) units of currency is present.
- A64 signifies that greater than 1000 (including 1000) units of currency is present.
- A65 signifies that no savings account details is present on record
5. **employment_st:** Catergorical variable that signifies the employment status of everyone who has been alloted loans
- A71 signifies that the individual is unemployed
- A72 signifies that the individual has been employed for less than a year
- A73 signifies that the individual has been employed for more than a year but less than four years
- A74 signifies that the individual has been employed more than four years but less than seven years
- A75 signifies that the individual has been employed for more than seven years
6. **gurantors:** Categorical variable which signifies if any other individual is involved with an individual loan case
- A101 signifies that only a single individual is involved in the loan application
- A102 signifies that one or more co-applicant is present in the loan application
- A103 signifies that guarantor are present.
7. **resident_since:** Numerical variable that signifies for how many years the applicant has been a resident
8. **property_type:** This qualitative variable defines the property holding information of the individual
- A121 signifies that the individual holds real estate property
- A122 signifies that the individual holds a building society savings agreement or life insurance
- A123 signifies that the individual holds cars or other properties
- A124 signifies that property information is not available
9. **age:** Numerical variable that signifies age in number of years
10. **installment_type:** This variable signifies other installment types taken
- A141 signifies installment to bank
- A142 signifies installment to outlets or stores
- A143 signifies that no information is present
11. **housing_type:** This is a categorical variable that signifies which type of housing does a applicant have.
- A151 signifies that the housing is on rent
- A152 signifies that the housing is owned by the applicant
- A153 signifies that no loan amount is present on the housing and there is no expense for the housing)
12. **credits_no:** Numerical variable for number of credits taken by the person
13. **job_type:** Signifies the employment status of the person
- A171 signifies that the individual is unemployed or unskilled and is a non-resident
- A172 signifies that the individual is unskilled but is a resident
- A173 signifies that the individual is a skilled employee or official
- A174 signifies that the individual is involved in management or is self-employed or a
highly qualified employee or officer
14. **liables:** Signifies number of persons dependent on the applicant
15. **telephone:** Signifies if the individual has a telephone or not
- A191 signifies that no telephonic records are present
- A192 signifies that a telephone is registered with the customer’s name
16. **foreigner:** Signifies if the individual is a foreigner or not (considering the country of residence of the bank)
- A201 signifies that the individual is a foreigner
- A202 signifies that the individual is a resident
**Objective of the problem:** The objective of the problem is to predict the values of credit_amount variable as per serial number variable. Please view the sample submissions file for better understanding. The solution must be presented in the form of a csv with predicted values of the response variable credit_amount along with it’s corresponding serial number.
**Evaluation Metric :** Normalized root mean squared error. The score is calculated by (1-rmse/normalization factor)*100.
**Submission Limit:** . Please note that individual submission limits 15
The objective of the problem is to predict the values of credit_amount variable as per serial number variable. Please view the sample submissions file for better understanding. The solution must be presented in the form of a csv with predicted values of the response variable credit_amount along with it’s corresponding serial number.
**Evaluation Algorithm**
**Root Mean Square Error (RMSE**)
normalization_constant 100000
Datasets
Training download train.csv
Testing download test.csv
Sample Submission download sample.csv
# Importing required libraries and setup some variables
```
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
#import pylab as plt # help to plot different graphs
# Set the global default size of matplotlib figures
plt.rc('figure', figsize=(10, 5))
# Size of matplotlib figures that contain subplots
fizsize_with_subplots = (10, 10)
# Size of matplotlib histogram bins
bin_size = 10
#test.csv
#train.csv
#submission.csv
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
%matplotlib inline
# Until fuction: line seperator
def print_dashes_and_ln():
print('-'*100, '\n')
# Formatter to display all float format in 2 decimal format
#pd.options.display.float_format = '{:.2f}'.format
import warnings
warnings.filterwarnings('ignore')
```
### Reading training data with showing first 5 records
```
df_train = pd.read_csv('train.csv')
df_train_copy = df_train.copy()
df_train_copy.head()
```
### Fetching last 5 records from training data
```
df_train.tail()
```
### Checking datatypes of columns
```
df_train.dtypes
```
### Get some basic information of the DataFrame:
```
df_train.info()
```
There are some of variables which have missing values for example account_info, Saving Account. Saving Account has too many missing values, whereas we might be able to infer values for Age and Embarked.
```
#Delete serial number because that is not need for serial number and telephone
del df_train['serial number']
del df_train['telephone']
# getting total number of rows and column in the dataframe
def shape_of_dataframe(df_train):
print(f" Shape of the dataframe = {df_train.shape}"); print_dashes_and_ln();
totalrows=df_train.shape[0]
print(f" Total number of rows in the dataset = {totalrows}"); print_dashes_and_ln();
shape_of_dataframe(df_train)
```
Let's plots some basic figure to get basic idea of data.
```
plt.subplots(figsize=(12,9))
sns.distplot(df_train['credit_amount'], fit=stats.norm)
# Get the fitted parameters used by the function
(mu, sigma) = stats.norm.fit(df_train['credit_amount'])
# plot with the distribution
plt.legend(['Normal dist. ($\mu=$ {:.2f} and $\sigma=$ {:.2f} )'.format(mu, sigma)], loc='best')
plt.ylabel('Frequency')
#Probablity plot
fig = plt.figure()
stats.probplot(df_train['credit_amount'], plot=plt)
plt.show()
#we use log function which is in numpy
df_train['credit_amount'] = np.log1p(df_train['credit_amount'])
#Check again for more normal distribution
plt.subplots(figsize=(12,9))
sns.distplot(df_train['credit_amount'], fit=stats.norm)
# Get the fitted parameters used by the function
(mu, sigma) = stats.norm.fit(df_train['credit_amount'])
# plot with the distribution
plt.legend(['Normal dist. ($\mu=$ {:.2f} and $\sigma=$ {:.2f} )'.format(mu, sigma)], loc='best')
plt.ylabel('Frequency')
#Probablity plot
fig = plt.figure()
stats.probplot(df_train['credit_amount'], plot=plt)
plt.show()
```
Check the missing values
```
#Let's check if the data set has any missing values.
df_train.columns[df_train.isnull().any()]
```
Imputting missing values
```
df_train['account_info'] = df_train['account_info'].fillna('None')
df_train['Saving Account'] = df_train['Saving Account'].fillna(float(0))
```
#Let's check if the data set has any missing values.
```
df_train.columns[df_train.isnull().any()]
# Columns by Data Type
non_numeric_columns = df_train.select_dtypes(['object']).columns
numeric_columns = df_train.select_dtypes(['number']).columns
print(f" Non Numerical Columns of the dataframe = {non_numeric_columns}"); print_dashes_and_ln();
print(f" Numerical Columns of the dataframe = {numeric_columns}"); print_dashes_and_ln();
```
Now, there is no any missing values. Encoding str to int
```
cols = ('account_info', 'Loan', 'Regularity', 'Purpose', 'savings_account',
'employment_st', 'Gender', 'Status', 'gurantors', 'property_type',
'installment_type', 'housing_type', 'job_type', 'foreigner')
from sklearn.preprocessing import LabelEncoder
for c in cols:
lbl = LabelEncoder()
lbl.fit(list(df_train[c].values))
df_train[c] = lbl.transform(list(df_train[c].values))
df_train.info()
```
Change data type from float to int
```
df_train['Saving Account'] = df_train['Saving Account'].astype(int)
df_train['investment'] = df_train['investment'] * 10
df_train['investment'] = df_train['investment'].astype(int)
df_train[['credit_amount','investment']].head(50)
```
credit amount is our target value so
```
#Coralation plot
corr = df_train.corr()
plt.subplots(figsize=(20,9))
sns.heatmap(corr, annot=True)
```
Top 10% Corralation train attributes with credit amount
```
top_feature = corr.index[abs(corr['credit_amount']>0.1)]
plt.subplots(figsize=(12, 8))
top_corr = df_train[top_feature].corr()
sns.heatmap(top_corr, annot=True)
plt.show()
```
Here duration_month is highly correlated with target feature of credit amount by 64%.
So, more duration month then more credit amount.
```
def clean_data(df, drop_serial_number):
df['account_info'] = df['account_info'].fillna('None')
df['Saving Account'] = df['Saving Account'].fillna(float(0))
cols = ('account_info', 'Loan', 'Regularity', 'Purpose', 'savings_account',
'employment_st', 'Gender', 'Status', 'gurantors', 'property_type',
'installment_type', 'housing_type', 'job_type', 'foreigner')
#from sklearn.preprocessing import LabelEncoder
for c in cols:
lbl = LabelEncoder()
lbl.fit(list(df[c].values))
df[c] = lbl.transform(list(df[c].values))
df['Saving Account'] = df['Saving Account'].astype(int)
df['investment'] = df['investment'] * 10
df['investment'] = df['investment'].astype(int)
# Drop the telephone column since it won't be used as a feature.
df = df.drop(['telephone'], axis=1)
if drop_serial_number:
df = df.drop(['serial number'], axis=1)
return df
df_train = clean_data(df_train_copy,drop_serial_number=True)
df_train['credit_amount'] = np.log1p(df_train['credit_amount'])
```
### Prepraring data for prediction
```
#Take targate variable into y
y = df_train['credit_amount']
#Delete the credit_amount
del df_train['credit_amount']
#Take their values in X and y
X = df_train.values
y = y.values
# Split data into train and test formate
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
```
### Linear Regression
```
#Train the model
from sklearn import linear_model
model_linear_regression = linear_model.LinearRegression()
#Fit the model
model_linear_regression.fit(X_train, y_train)
# #Prediction
print("Predict value " + str(model_linear_regression.predict([X_test[13]])))
print("Real value " + str(y_test[13]))
#Score/Accuracy
print("Accuracy for Linear Regression--> ", model_linear_regression.score(X_test, y_test)*100)
```
### RandomForestRegression
```
#Train the model
from sklearn.ensemble import RandomForestRegressor
model_random = RandomForestRegressor(n_estimators=10)
#Fit
model_random.fit(X_train, y_train)
#Score/Accuracy
print("Accuracy for RandomForestRegression--> ", model_random.score(X_test, y_test)*100)
```
### GradientBoostingRegressor
```
#Train the model
from sklearn.ensemble import GradientBoostingRegressor
GBR = GradientBoostingRegressor(n_estimators=100, max_depth=4)
#Fit
GBR.fit(X_train, y_train)
print("Accuracy --> ", GBR.score(X_test, y_test)*100)
```
# XGBOOST ALGO: PREPARE FOR SUBMISSION
Create a DataFrame by combining the index from the test data with the output of predictions, then write the results to the output:
```
import xgboost as xgb
from sklearn.metrics import mean_squared_error
import pandas as pd
import numpy as np
df_test = pd.read_csv('test.csv')
df_test = clean_data(df_test,drop_serial_number=False)
test_data = df_test.values
data_dmatrix = xgb.DMatrix(data=df_test,label=y)
xg_reg = xgb.XGBRegressor(objective ='reg:linear', colsample_bytree = 0.2, learning_rate = 0.1,
max_depth = 5, alpha = 10, n_estimators = 10)
xg_reg.fit(X_train,y_train)
preds = model_linear_regression.predict(X_test)
#print("Accuracy --> ", xg_reg.score(X_test, y_test)*100)
#from sklearn.metrics import accuracy_score
#print ("Accuracy = %.2f" % (accuracy_score(y_test, preds)))
rmse = np.sqrt(mean_squared_error(y_test, preds))
print("RMSE: %f" % (rmse))
params = {"objective":"reg:linear",'colsample_bytree': 0.3,'learning_rate': 0.1,
'max_depth': 5, 'alpha': 10}
cv_results = xgb.cv(dtrain=data_dmatrix, params=params, nfold=3,
num_boost_round=50,early_stopping_rounds=10,metrics="rmse", as_pandas=True, seed=123)
cv_results.head()
print((cv_results["test-rmse-mean"]).tail(1))
#S.no
# Get the test data features, skipping the first column 'Serial Number'
test_x = test_data[:, 1:]
# Predict the credit amount values for the test data
test_y = model_linear_regression.predict(test_x)
#df_test = df_test.rename(columns={"S.no": "serial number"})
df_test['credit_amount'] = test_y
#df_test['credit_amount'] = np.expm1(df_test['credit_amount'])
df_test['S.no'] = df_test['serial number']
df_test['credit_amount'] = df_test['credit_amount'].astype(float)
df_test[['S.no','credit_amount']] \
.to_csv('submission.csv', index=False)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
from statsmodels.graphics.regressionplots import influence_plot
import matplotlib.pyplot as plt
toyota=pd.read_csv("ToyotaCorolla.csv")
toyota
toyota.shape
toyota.describe()
toyota.head()
toyo1= toyota.iloc[:,[2,3,6,8,12,13,15,16,17]]
toyo1
toyo1.rename(columns={"Age_08_04":"Age"},inplace=True)
toyo1.corr()
import seaborn as sns
sns.set_style(style="darkgrid")
sns.pairplot(toyo1)
import statsmodels.formula.api as smf
model1 = smf.ols('Price~Age+KM+HP+Doors+cc+Gears+Quarterly_Tax+Weight', data=toyo1).fit()
model1.summary()
model_influence = model1.get_influence()
(c, _)=model_influence.cooks_distance
c
fig = plt.subplots(figsize=(20,7))
plt.stem(np.arange(len(toyota)), np.round(c,3))
plt.xlabel('Row Index')
plt.ylabel('Cooks Distance')
plt.show()
np.argmax(c), np.max(c)
from statsmodels.graphics.regressionplots import influence_plot
influence_plot(model1)
plt.show()
k = toyo1.shape[1]
n = toyo1.shape[0]
leverage_cutoff = 3*((k+1)/n)
leverage_cutoff
toyo_new=toyo1.drop(toyo1.index[[80,960,221,601]],axis=0).reset_index()
toyo2=toyo_new.drop(['index'],axis=1)
toyo2
import statsmodels.formula.api as smf
model2=smf.ols('Price~Age+KM+HP+Doors+cc+Gears+Quarterly_Tax+Weight', data=toyo2).fit()
model2.summary()
finalmodel = smf.ols('Price~Age+KM+HP+Doors+cc+Gears+Quarterly_Tax+Weight', data=toyo2).fit()
finalmodel.summary()
finalmodel_pred = finalmodel.predict(toyo2)
plt.scatter(toyo2["Price"],finalmodel_pred,color='Green');plt.xlabel("Observed values");plt.ylabel("Predicted values")
plt.scatter(finalmodel_pred, finalmodel.resid_pearson,color='red');
plt.axhline(y=0, color='red');
plt.xlabel("Fitted values");
plt.ylabel("Residuals")
plt.hist(finalmodel.resid_pearson, color='black')
import pylab
import scipy.stats as st
st.probplot(finalmodel.resid_pearson, dist='norm', plot=pylab)
new_data=pd.DataFrame({'Age':25,'KM':40000,'HP':80,'cc':1500,'Doors':3,'Gears':5,'Quarterly_Tax':180,'Weight':1050}, index=[1])
new_data
finalmodel.predict(new_data)
pred_y=finalmodel.predict(toyo1)
pred_y
```
# Training and Testing Data
```
from sklearn.model_selection import train_test_split
train_data,test_Data= train_test_split(toyo1,test_size=0.3)
finalmodel1 = smf.ols("Price~Age+KM+HP+cc+Doors+Gears+Quarterly_Tax+Weight", data = train_data).fit()
finalmodel1.summary()
finalmodel_pred = finalmodel1.predict(train_data)
finalmodel_res = train_data["Price"]-finalmodel_pred
finalmodel_rmse = np.sqrt(np.mean(finalmodel_res*finalmodel_res))
finalmodel_testpred = finalmodel1.predict(test_Data)
finalmodel_testres= test_Data["Price"]-finalmodel_testpred
finalmodel_testrmse = np.sqrt(np.mean(finalmodel_testres*finalmodel_testres))
finalmodel_testrmse
```
| github_jupyter |
Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.
- Author: Sebastian Raschka
- GitHub Repository: https://github.com/rasbt/deeplearning-models
```
%load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p tensorflow
```
# Convolutional General Adversarial Networks with Label Smoothing
Same as [./gan-conv.ipynb](./gan-conv.ipynb) but with **label smoothing**.
Here, the label smoothing approach is to replace real image labels (1's) by 0.9, based on the idea in
- Salimans, Tim, Ian Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, and Xi Chen. "Improved techniques for training GANs." In Advances in Neural Information Processing Systems, pp. 2234-2242. 2016.
```
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import pickle as pkl
tf.test.gpu_device_name()
### Abbreviatiuons
# dis_*: discriminator network
# gen_*: generator network
########################
### Helper functions
########################
def leaky_relu(x, alpha=0.0001):
return tf.maximum(alpha * x, x)
########################
### DATASET
########################
mnist = input_data.read_data_sets('MNIST_data')
#########################
### SETTINGS
#########################
# Hyperparameters
learning_rate = 0.001
training_epochs = 50
batch_size = 64
dropout_rate = 0.5
# Architecture
dis_input_size = 784
gen_input_size = 100
# Other settings
print_interval = 200
#########################
### GRAPH DEFINITION
#########################
g = tf.Graph()
with g.as_default():
# Placeholders for settings
dropout = tf.placeholder(tf.float32, shape=None, name='dropout')
is_training = tf.placeholder(tf.bool, shape=None, name='is_training')
# Input data
dis_x = tf.placeholder(tf.float32, shape=[None, dis_input_size],
name='discriminator_inputs')
gen_x = tf.placeholder(tf.float32, [None, gen_input_size],
name='generator_inputs')
##################
# Generator Model
##################
with tf.variable_scope('generator'):
# 100 => 784 => 7x7x64
gen_fc = tf.layers.dense(inputs=gen_x, units=3136,
bias_initializer=None, # no bias required when using batch_norm
activation=None)
gen_fc = tf.layers.batch_normalization(gen_fc, training=is_training)
gen_fc = leaky_relu(gen_fc)
gen_fc = tf.reshape(gen_fc, (-1, 7, 7, 64))
# 7x7x64 => 14x14x32
deconv1 = tf.layers.conv2d_transpose(gen_fc, filters=32,
kernel_size=(3, 3), strides=(2, 2),
padding='same',
bias_initializer=None,
activation=None)
deconv1 = tf.layers.batch_normalization(deconv1, training=is_training)
deconv1 = leaky_relu(deconv1)
deconv1 = tf.layers.dropout(deconv1, rate=dropout_rate)
# 14x14x32 => 28x28x16
deconv2 = tf.layers.conv2d_transpose(deconv1, filters=16,
kernel_size=(3, 3), strides=(2, 2),
padding='same',
bias_initializer=None,
activation=None)
deconv2 = tf.layers.batch_normalization(deconv2, training=is_training)
deconv2 = leaky_relu(deconv2)
deconv2 = tf.layers.dropout(deconv2, rate=dropout_rate)
# 28x28x16 => 28x28x8
deconv3 = tf.layers.conv2d_transpose(deconv2, filters=8,
kernel_size=(3, 3), strides=(1, 1),
padding='same',
bias_initializer=None,
activation=None)
deconv3 = tf.layers.batch_normalization(deconv3, training=is_training)
deconv3 = leaky_relu(deconv3)
deconv3 = tf.layers.dropout(deconv3, rate=dropout_rate)
# 28x28x8 => 28x28x1
gen_logits = tf.layers.conv2d_transpose(deconv3, filters=1,
kernel_size=(3, 3), strides=(1, 1),
padding='same',
bias_initializer=None,
activation=None)
gen_out = tf.tanh(gen_logits, 'generator_outputs')
######################
# Discriminator Model
######################
def build_discriminator_graph(input_x, reuse=None):
with tf.variable_scope('discriminator', reuse=reuse):
# 28x28x1 => 14x14x8
conv_input = tf.reshape(input_x, (-1, 28, 28, 1))
conv1 = tf.layers.conv2d(conv_input, filters=8, kernel_size=(3, 3),
strides=(2, 2), padding='same',
bias_initializer=None,
activation=None)
conv1 = tf.layers.batch_normalization(conv1, training=is_training)
conv1 = leaky_relu(conv1)
conv1 = tf.layers.dropout(conv1, rate=dropout_rate)
# 14x14x8 => 7x7x32
conv2 = tf.layers.conv2d(conv1, filters=32, kernel_size=(3, 3),
strides=(2, 2), padding='same',
bias_initializer=None,
activation=None)
conv2 = tf.layers.batch_normalization(conv2, training=is_training)
conv2 = leaky_relu(conv2)
conv2 = tf.layers.dropout(conv2, rate=dropout_rate)
# fully connected layer
fc_input = tf.reshape(conv2, (-1, 7*7*32))
logits = tf.layers.dense(inputs=fc_input, units=1, activation=None)
out = tf.sigmoid(logits)
return logits, out
# Create a discriminator for real data and a discriminator for fake data
dis_real_logits, dis_real_out = build_discriminator_graph(dis_x, reuse=False)
dis_fake_logits, dis_fake_out = build_discriminator_graph(gen_out, reuse=True)
#####################################
# Generator and Discriminator Losses
#####################################
# Two discriminator cost components: loss on real data + loss on fake data
# Real data has class label 1, fake data has class label 0
dis_real_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=dis_real_logits,
labels=tf.ones_like(dis_real_logits) * 0.9)
dis_fake_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=dis_fake_logits,
labels=tf.zeros_like(dis_fake_logits))
dis_cost = tf.add(tf.reduce_mean(dis_fake_loss),
tf.reduce_mean(dis_real_loss),
name='discriminator_cost')
# Generator cost: difference between dis. prediction and label "1" for real images
gen_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=dis_fake_logits,
labels=tf.ones_like(dis_fake_logits) * 0.9)
gen_cost = tf.reduce_mean(gen_loss, name='generator_cost')
#########################################
# Generator and Discriminator Optimizers
#########################################
dis_optimizer = tf.train.AdamOptimizer(learning_rate)
dis_train_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='discriminator')
dis_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='discriminator')
with tf.control_dependencies(dis_update_ops): # required to upd. batch_norm params
dis_train = dis_optimizer.minimize(dis_cost, var_list=dis_train_vars,
name='train_discriminator')
gen_optimizer = tf.train.AdamOptimizer(learning_rate)
gen_train_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='generator')
gen_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='generator')
with tf.control_dependencies(gen_update_ops): # required to upd. batch_norm params
gen_train = gen_optimizer.minimize(gen_cost, var_list=gen_train_vars,
name='train_generator')
# Saver to save session for reuse
saver = tf.train.Saver()
##########################
### TRAINING & EVALUATION
##########################
with tf.Session(graph=g) as sess:
sess.run(tf.global_variables_initializer())
avg_costs = {'discriminator': [], 'generator': []}
for epoch in range(training_epochs):
dis_avg_cost, gen_avg_cost = 0., 0.
total_batch = mnist.train.num_examples // batch_size
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
batch_x = batch_x*2 - 1 # normalize
batch_randsample = np.random.uniform(-1, 1, size=(batch_size, gen_input_size))
# Train
_, dc = sess.run(['train_discriminator', 'discriminator_cost:0'],
feed_dict={'discriminator_inputs:0': batch_x,
'generator_inputs:0': batch_randsample,
'dropout:0': dropout_rate,
'is_training:0': True})
_, gc = sess.run(['train_generator', 'generator_cost:0'],
feed_dict={'generator_inputs:0': batch_randsample,
'dropout:0': dropout_rate,
'is_training:0': True})
dis_avg_cost += dc
gen_avg_cost += gc
if not i % print_interval:
print("Minibatch: %04d | Dis/Gen Cost: %.3f/%.3f" % (i + 1, dc, gc))
print("Epoch: %04d | Dis/Gen AvgCost: %.3f/%.3f" %
(epoch + 1, dis_avg_cost / total_batch, gen_avg_cost / total_batch))
avg_costs['discriminator'].append(dis_avg_cost / total_batch)
avg_costs['generator'].append(gen_avg_cost / total_batch)
saver.save(sess, save_path='./gan-conv.ckpt')
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(range(len(avg_costs['discriminator'])),
avg_costs['discriminator'], label='discriminator')
plt.plot(range(len(avg_costs['generator'])),
avg_costs['generator'], label='generator')
plt.legend()
plt.show()
####################################
### RELOAD & GENERATE SAMPLE IMAGES
####################################
n_examples = 25
with tf.Session(graph=g) as sess:
saver.restore(sess, save_path='./gan-conv.ckpt')
batch_randsample = np.random.uniform(-1, 1, size=(n_examples, gen_input_size))
new_examples = sess.run('generator/generator_outputs:0',
feed_dict={'generator_inputs:0': batch_randsample,
'dropout:0': 0.0,
'is_training:0': False})
fig, axes = plt.subplots(nrows=5, ncols=5, figsize=(8, 8),
sharey=True, sharex=True)
for image, ax in zip(new_examples, axes.flatten()):
ax.imshow(image.reshape((dis_input_size // 28, dis_input_size // 28)), cmap='binary')
plt.show()
```
| github_jupyter |
## Text Classification Model Analysis: Graph Structure
In this notebook, we analyze the model to understand the effect of graph convolution on the text classification task.
* Wha kind of graph structure is effective?
* Node representation
* Edge definition
* What kind of connection is effective?
* dependency type etc.
In This notebook, we find effective graph structure.
```
import os
import sys
import numpy as np
import pandas as pd
import spacy
import matplotlib as plt
from sklearn.metrics import classification_report
%load_ext autoreload
%autoreload 2
%matplotlib inline
def set_path():
root = os.path.join(os.path.realpath("."), "../../")
if root not in sys.path:
sys.path.append(root)
return root
ROOT_DIR = set_path()
```
## Graph Structure Experiments
Node representation
* Word embedding only
* LSTM before Graph Convolution
* LSTM after Graph Convolution
LSTM: bidirectional/LSTM
Edge kind
* Dependency
* Similarity
```
from sklearn.metrics import classification_report
from gcn.data.multi_nli_dataset import MultiNLIDataset
from gcn.classification.trainer import Trainer
from gcn.graph.dependency_graph import DependencyGraph
from gcn.graph.similarity_graph import SimilarityGraph
from gcn.graph.static_graph import StaticGraph
from gcn.classification.graph_based_classifier import GraphBasedClassifier
def experiment(graph_type, head_types=("concat",), head=1,
epochs=35, sequence_length=25, lstm=None, bidirectional=False):
dataset = MultiNLIDataset(ROOT_DIR)
if graph_type == "dependency":
graph_builder = DependencyGraph(lang="en")
elif graph_type == "similarity":
graph_builder = SimilarityGraph(lang="en")
else:
graph_builder = StaticGraph(lang="en")
trainer = Trainer(graph_builder, ROOT_DIR, log_dir="classifier_structure")
trainer.build()
vocab_size = len(trainer.preprocessor.vocabulary.get())
def preprocessor(x):
_x = trainer.preprocess(x, sequence_length)
values = (_x["text"], _x["graph"])
return values
model = GraphBasedClassifier(vocab_size, sequence_length,
head_types=head_types, heads=head,
lstm=lstm, bidirectional=bidirectional)
model.build(trainer.num_classes, preprocessor)
metrics = trainer.train(model.model, epochs=epochs, verbose=0)
result = pd.DataFrame.from_dict(metrics.history)
result.plot.line(secondary_y=["loss", "val_loss"])
test_data = dataset.test_data()
y_pred = model.predict(test_data["text"])
print(classification_report(test_data["label"], y_pred,
target_names=dataset.labels()))
return model
```
### Word Embedding Only
```
model_d = experiment("dependency", lstm=None)
model_s = experiment("similarity", lstm=None)
model_st = experiment("static", lstm=None)
```
### Multi Layer
```
model_d_ml = experiment("dependency", head_types=("concat", "average"), lstm=None)
model_s_ml = experiment("similarity", head_types=("concat", "average"), lstm=None)
model_st_ml = experiment("static", head_types=("concat", "average"), lstm=None)
```
### +LSTM
```
model_d_b = experiment("dependency", lstm="before")
model_d_a =experiment("dependency", lstm="after")
model_s_b =experiment("similarity", lstm="before")
model_s_a =experiment("similarity", lstm="after")
model_st_b =experiment("static", lstm="before")
model_st_a =experiment("static", lstm="after")
```
### Bidirectional
```
model_d_b_b = experiment("dependency", lstm="before", bidirectional=True)
model_s_b_b = experiment("similarity", lstm="before", bidirectional=True)
model_st_b_b = experiment("static", lstm="before", bidirectional=True)
```
| github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
!pip install picklable_itertools
!pip install fuel
!pip install foolbox
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import numpy as np
PROJECT_DIR = "/content/drive/My Drive/2018/Colab_Deep_Learning/one_class_neural_networks/"
import sys,os
import numpy as np
sys.path.append(PROJECT_DIR)
```
##** 0 Vs All Experiments **##
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 0
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 1 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 1
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 2 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 2
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 3 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 3
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 4 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 4
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 5 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 5
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 6 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 6
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 7 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 7
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 8 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 8
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
## ** MNIST 9 Vs All
```
## Obtaining the training and testing data
%reload_ext autoreload
%autoreload 2
from src.models.isoForest import IsoForest
import numpy as np
from src.config import Configuration as Cfg
DATASET = "mnist"
ESTIMATORS = 100
MAX_SAMPLES = 250
CONTAMINATION = 0.1
MODEL_SAVE_PATH = PROJECT_DIR + "/models/mnist/ISO_FOREST/"
REPORT_SAVE_PATH = PROJECT_DIR + "/reports/figures/mnist/ISO_FOREST/"
PRETRAINED_WT_PATH = ""
RANDOM_SEED = [42,56,81,67,33,25,90,77,15,11]
AUC = []
## Setting the required config values
Cfg.out_frac = 0.1
Cfg.ad_experiment = 1 # 1 : yes # 0 : No
Cfg.unit_norm_used = "l1"
Cfg.gcn = 1 # 1 : yes # 0 : No
Cfg.zca_whitening = 0 # 1 : yes # 0 : No
Cfg.pca = 0 # 1 for yes # 0 : No
Cfg.mnist_val_frac = 0.1
Cfg.mnist_normal = 9
Cfg.mnist_outlier = -1
for seed in RANDOM_SEED:
# plot parameters
# Cfg.xp_path = REPORT_SAVE_PATH
# dataset
Cfg.seed = seed
# initialize Isolation Forest
model = IsoForest(dataset=DATASET, n_estimators=ESTIMATORS, max_samples=MAX_SAMPLES,
contamination=CONTAMINATION)
# train IF model
model.fit()
print("===========PREDICTING WITH ISO_FOREST============================")
# predict
# model.predict(which_set='train')
auc_roc = model.predict(which_set='test')
print("========================================================================",)
print("AUROC: ",auc_roc)
AUC.append(auc_roc)
print("===========AURO Computed============================")
print("AUROC computed ", AUC)
auc_roc_mean = np.mean(np.asarray(AUC))
auc_roc_std = np.std(np.asarray(AUC))
print ("AUROC =====", auc_roc_mean ,"+/-",auc_roc_std)
print("========================================================================")
```
| github_jupyter |
## astropy.modeling solutions
### Exercise 1:
#Generate fake data
```
np.random.seed(0)
x = np.linspace(-5., 5., 200)
y = 3 * np.exp(-0.5 * (x - 1.3)**2 / 0.8**2)
y += np.random.normal(0., 0.2, x.shape)
```
- Fit the data with a Trapezoid1D model.
- Fit a Gaussian1D model to it.
- Display the results.
```
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from astropy.modeling import models, fitting
```
Create the data.
```
np.random.seed(0)
x = np.linspace(-5., 5., 200)
y = 3 * np.exp(-0.5 * (x - 1.3)**2 / 0.8**2)
y += np.random.normal(0., 0.2, x.shape)
plt.plot(x, y)
```
Let's see what the parameter names for Trapezoi1D are.
```
print(models.Trapezoid1D.param_names)
```
Create a Trapezoid1D model - the prameter values will be used as initial guesses for the fitting.
```
trapez_init = models.Trapezoid1D(amplitude=1., x_0=0., width=1., slope=0.5)
```
Fit the model to the data. The output is a new model - `trapez`.
```
fitter = fitting.LevMarLSQFitter()
trapez = fitter(trapez_init, x, y)
print(trapez.parameters)
```
In a similar way fit a Gaussian to the data.
```
gauss_init = models.Gaussian1D(amplitude=1, mean=0, stddev=1)
gauss = fitter(gauss_init, x, y)
print(gauss.parameters)
```
Diplay the results.
```
plt.figure(figsize=(9,6))
plt.plot(x, y, 'ko', label='data')
plt.plot(x, trapez(x), 'r', label='Trapezoid', lw=3)
plt.plot(x, gauss(x), 'g', label='Gaussian', lw=3)
plt.legend(loc=2)
```
Exercise 2:
- read a spectrum from a text file (data/sample.txt)
- Using the rest wavelengths as initial values, fit a gaussian to the H beta and OIII lines.
```
from astropy.io import ascii
sdss = ascii.read('data/sample_sdss.txt')
sdss.colnames
wave = sdss['lambda']
flux = sdss['flux']
#%matplotlib notebook
plt.plot(wave, flux)
```
Use the rest wavelengths as initial values for the locaiton of the lines.
```
Hbeta = 4862.721
Halpha = 6564.614
OIII_1 = 4958.911
OIII_2 = 5008.239
Na = 6549.86
Nb = 6585.27
Sa = 6718.29
Sb = 6732.68
wave = sdss['lambda']
flux = sdss['flux']
plt.figure(figsize=(8, 5))
plt.plot(wave, flux)
plt.text(4800, 70, 'Hbeta', rotation=90)
plt.text(4900, 100, 'OIII_1', rotation=90)
plt.text(4950, 200, 'OIII_2', rotation=90)
plt.text(6500, 170, 'Halpha', rotation=90)
plt.text(6700, 70, 'Sa and Sb', rotation=90)
```
Create a Polynomial model to fit the continuum.
```
mean_flux = flux.mean()
cont = np.where(flux > mean_flux, mean_flux, flux)
linfitter = fitting.LinearLSQFitter()
poly_cont = linfitter(models.Polynomial1D(1), wave, cont)
print(poly_cont)
```
Create Gaussin1D models for each of the Hbeta and OIII lines.
```
h_beta = models.Gaussian1D(amplitude=34, mean=Hbeta, stddev=5)
o3 = models.Gaussian1D(amplitude=170, mean=OIII_2, stddev=5)
o1 = models.Gaussian1D(amplitude=57, mean=OIII_1, stddev=5)
```
Create a compound model for the three lines and the continuum.
```
hbeta_combo = h_beta + o1 + o3 + poly_cont
print(hbeta_combo.param_names)
```
Tie the ratio of the intensity of the two OIII lines.
```
def tie_ampl(model):
return model.amplitude_2 / 3.1
hbeta_combo.amplitude_1.tied = tie_ampl
```
Also tie the wavelength of the Hbeta line to the OIII wavelength.
```
def tie_wave(model):
return model.mean_0 * OIII_1/Hbeta
hbeta_combo.mean_1.tied = tie_wave
```
Fit all lines simultaneously.
```
fitter = fitting.LevMarLSQFitter()
fitted_model = fitter(hbeta_combo, wave, flux)
fitted_lines = fitted_model(wave)
plt.figure(figsize=(9, 6))
plt.plot(wave, flux)
plt.plot(wave, fitted_lines, 'r')
```
| github_jupyter |
# Word Embeddings First Steps: Data Preparation
In this series of ungraded notebooks, you'll try out all the individual techniques that you learned about in the lectures. Practicing on small examples will prepare you for the graded assignment, where you will combine the techniques in more advanced ways to create word embeddings from a real-life corpus.
This notebook focuses on data preparation, which is the first step of any machine learning algorithm. It is a very important step because models are only as good as the data they are trained on and the models used require the data to have a particular structure to process it properly.
To get started, import and initialize all the libraries you will need.
```
%%capture
!pip install -Uqq emoji
import re
import nltk
import emoji
import numpy as np
from nltk.tokenize import word_tokenize
nltk.download('punkt')
print("nltk ", nltk.__version__)
print("emoji ", emoji.__version__)
def get_dict(data):
"""
Input:
K: the number of negative samples
data: the data you want to pull from
indices: a list of word indices
Output:
word_dict: a dictionary with the weighted probabilities of each word
word2Ind: returns dictionary mapping the word to its index
Ind2Word: returns dictionary mapping the index to its word
"""
words = sorted(list(set(data)))
n = len(words)
idx = 0
# return these correctly
word2Ind = {}
Ind2word = {}
for k in words:
word2Ind[k] = idx
Ind2word[idx] = k
idx += 1
return word2Ind, Ind2word
```
## Data preparation
In the data preparation phase, starting with a corpus of text, you will:
- Clean and tokenize the corpus.
- Extract the pairs of context words and center word that will make up the training data set for the CBOW model. The context words are the features that will be fed into the model, and the center words are the target values that the model will learn to predict.
- Create simple vector representations of the context words (features) and center words (targets) that can be used by the neural network of the CBOW model.
### Cleaning and tokenization
To demonstrate the cleaning and tokenization process, consider a corpus that contains emojis and various punctuation signs.
```
# Define a corpus
corpus = 'Who ❤️ "word embeddings" in 2020? I do!!! I love pre-processing 2:)!?'
```
First, replace all interrupting punctuation signs — such as commas and exclamation marks — with periods.
```
print("Corpus:\n\t", corpus, "\n")
data = re.sub(r"[,!?;-]+", ".", corpus)
print("After cleaning punctuation:\n\t", data)
```
Next, use NLTK's tokenization engine to split the corpus into individual tokens.
```
print("Initial string:\n\t", data, "\n")
tokenized = nltk.word_tokenize(data)
print("After tokenization\n\t", tokenized)
```
Finally, as you saw in the lecture, get rid of numbers and punctuation other than periods, and convert all the remaining tokens to lowercase.
```
print("Initial list of tokens:\n\t", tokenized, "\n")
clean_tokenized = [
ch.lower()
for ch in tokenized
if ch.isalpha() or ch == "." or emoji.get_emoji_regexp().search(ch)
]
print("After cleaning\n\t", clean_tokenized)
```
Note that the heart emoji is considered as a token just like any normal word.
Now let's streamline the cleaning and tokenization process by wrapping the previous steps in a function.
```
def tokenize(corpus):
data = re.sub(r"[,!?;-]+", ".", corpus)
data = nltk.word_tokenize(data)
data = [
ch.lower()
for ch in data
if ch.isalpha() or ch == "." or emoji.get_emoji_regexp().search(ch)
]
return data
```
Apply this function to the corpus that you'll be working on in the rest of this notebook: "I am happy because I am learning"
```
corpus = "I am happy because I am learning"
print(f'Corpus: {corpus}')
words = tokenize(corpus)
print(f'Words (tokens): {words}')
```
## Sliding window of words
Now that you have transformed the corpus into a list of clean tokens, you can slide a window of words across this list. For each window you can extract a center word and the context words.
The `get_windows` function in the next cell was introduced in the lecture.
```
def get_windows(words, C):
i = C
while i < len(words) - C:
center_word = words[i]
context_words = words[i - C : i] + words[i + 1 : i + 1 + C]
yield context_words, center_word
i += 1
```
The first argument of this function is a list of words (or tokens). The second argument, `C`, is the context half-size. Recall that for a given center word, the context words are made of `C` words to the left and `C` words to the right of the center word.
Here is how you can use this function to extract context words and center words from a list of tokens. These context and center words will make up the training set that you will use to train the CBOW model.
```
for x, y in get_windows(
["i", "am", "happy", "because", "i", "am", "learning"], 2
):
print(f"{x}\t{y}")
```
The first example of the training set is made of:
- the context words "i", "am", "because", "i",
- and the center word to be predicted: "happy".
**Now try it out yourself. In the next cell, you can change both the sentence and the context half-size.**
```
for x, y in get_windows(
tokenize("Now it's your turn: try with your own sentence!"), 1
):
print(f"{x}\t{y}")
```
## Transforming words into vectors for the training set
To finish preparing the training set, you need to transform the context words and center words into vectors.
### Mapping words to indices and indices to words
The center words will be represented as one-hot vectors, and the vectors that represent context words are also based on one-hot vectors.
To create one-hot word vectors, you can start by mapping each unique word to a unique integer (or index). We have provided a helper function, `get_dict`, that creates a Python dictionary that maps words to integers and back.
```
word2ind, ind2word = get_dict(words)
word2ind, ind2word
V = len(word2ind)
print("Size of vocabulary", V)
```
### Getting one-hot word vectors
Recall from the lecture that you can easily convert an integer, $n$, into a one-hot vector.
Consider the word "happy". First, retrieve its numeric index.
```
n = word2ind["happy"]
n
center_word_vector = np.zeros(V)
center_word_vector[n] = 1
center_word_vector
def word_to_one_hot_vector(word, word2ind, V):
one_hot_vector = np.zeros(V)
one_hot_vector[word2ind[word]] = 1
return one_hot_vector
word_to_one_hot_vector("happy", word2ind, V)
```
### Getting context word vectors
To create the vectors that represent context words, you will calculate the average of the one-hot vectors representing the individual words.
Let's start with a list of context words.
```
context_words = ['i', 'am', 'because', 'i']
context_words_vectors = [word_to_one_hot_vector(w, word2ind, V) for w in context_words]
context_words_vectors
```
And you can now simply get the average of these vectors using numpy's `mean` function, to get the vector representation of the context words.
```
np.mean(context_words_vectors, axis=0)
```
And you can now simply get the average of these vectors using numpy's `mean` function, to get the vector representation of the context words.
```
np.mean(context_words_vectors, axis=1)
```
Note the `axis=0` parameter that tells `mean` to calculate the average of the rows (if you had wanted the average of the columns, you would have used `axis=1`).
**Now create the `context_words_to_vector` function that takes in a list of context words, a word-to-index dictionary, and a vocabulary size, and outputs the vector representation of the context words.**
```
def context_words_to_vector(context_words, word2ind, V):
context_words_vectors = [word_to_one_hot_vector(w, word2ind, V) for w in context_words]
context_words_vectors = np.mean(context_words_vectors, axis=0)
return context_words_vectors
# Print output of 'context_words_to_vector' function for context words: 'i', 'am', 'because', 'i'
context_words_to_vector(['i', 'am', 'because', 'i'], word2ind, V)
context_words_to_vector(['am', 'happy', 'i', 'am'], word2ind, V)
```
## Building the training set
You can now combine the functions that you created in the previous sections, to build a training set for the CBOW model, starting from the following tokenized corpus.
```
words
```
To do this you need to use the sliding window function (`get_windows`) to extract the context words and center words, and you then convert these sets of words into a basic vector representation using `word_to_one_hot_vector` and `context_words_to_vector`.
```
for context_words, center_word in get_windows(words, 2):
print(
f"Context words: {context_words} -> {context_words_to_vector(context_words, word2ind, V)}"
)
print(
f"Center word: {center_word} -> {word_to_one_hot_vector(center_word, word2ind, V)}"
)
print("")
```
In this practice notebook you'll be performing a single iteration of training using a single example, but in this week's assignment you'll train the CBOW model using several iterations and batches of example.
Here is how you would use a Python generator function (remember the `yield` keyword from the lecture?) to make it easier to iterate over a set of examples.
```
def get_training_example(words, C, word2ind, V):
for context_words, center_word in get_windows(words, C):
yield context_words_to_vector(
context_words, word2ind, V
), word_to_one_hot_vector(center_word, word2ind, V)
# Print vectors associated to center and context words for corpus using the generator function
for context_words_vector, center_word_vector in get_training_example(words, 2, word2ind, V):
print(f'Context words vector: {context_words_vector}')
print(f'Center word vector: {center_word_vector}')
print()
```
| github_jupyter |
# COMP3359 Project
## Group 28: Classification of Tropical Cyclone Satellite Image by Intensity
## Demostration
This notebook serves for using a trained model to perform prediction of a tropical cyclone satellite image.
#### Requirement of the input's image
1. The size of it must be least 256px x 256px
2. It can be in RGB/Greyscale
3. It is readable by python PIL package
```
"""Install pytorch according to your CUDA version"""
# Uncomment % ... to see your CUDA version, if you are using Linux
# !/usr/local/cuda/bin/nvcc --version
# If you are using CUDA 10.0 (HKU GPU Phrase 1)
# !pip install Pillow==6.1
# !pip install torch===1.2.0 torchvision===0.4.0 -f https://download.pytorch.org/whl/torch_stable.html
# If you have CUDA 10.1 (HKU GPU Phrase 2)
# !pip install torch==1.5.0+cu101 torchvision==0.6.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html
# If you have CUDA 10.2
# !pip install pytorch torchvision
# If you don't have any supported GPU
# !pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
# Install required packages that is not included in Conda
# !pip install torchsummary efficientnet_pytorch
# If you are not using conda then install these as well
# !pip install matplotlib Pillow
# Import all required Stuff
import requests
from io import BytesIO
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from efficientnet_pytorch import EfficientNet
from torchsummary import summary
from torchvision import transforms
from PIL import Image
%matplotlib inline
# The final model of this project
class EffNet(nn.Module):
def __init__(self):
super(EffNet, self).__init__()
self.conv = EfficientNet.from_pretrained('efficientnet-b3')
self.fc = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Flatten(),
nn.Dropout(0.25),
nn.Linear(1536, 768),
nn.Dropout(0.35),
nn.ELU(inplace=True),
nn.Linear(768,6)
)
def forward(self, x):
x = self.conv.extract_features(x)
x = self.fc(x)
return x
# Check the running computer have supported GPU or not
GPU_aval = torch.cuda.is_available()
device = torch.device('cuda') if GPU_aval else torch.device('cpu')
print(device)
# Load the trained model parameters
model_path = './effnet3/model_best.pth.tar'
if GPU_aval:
state_dict = torch.load(model_path)['state_dict']
else:
state_dict = torch.load(model_path, map_location=device)['state_dict']
model = EffNet()
model.load_state_dict(state_dict)
model.to(device)
summary(model, (3, 224, 224))
def download_img(url):
response = requests.get(url)
img = Image.open(BytesIO(response.content)).convert("RGB")
return img
"""
First, we need an typhoon for testing.
As a Hong Konger, lets use the most significant typhoon in recent Hong Kong history:
Typhoon Mangkhut(山竹). We are going to use digital typhoon as data source.
Once again, Thanks Prof. Kitamoto for the amazing website and wonderful research
Here we download a image of it.
By the time of the image taken, it was just borned, so it was a class 2 typhoon
Url for reference:
Typhoon Mangkhut's detail:
http://agora.ex.nii.ac.jp/digital-typhoon/summary/wnp/s/201822.html.en
Image's detail:
http://agora.ex.nii.ac.jp/cgi-bin/dt/single2.pl?prefix=HMW818090618&id=201822&basin=wnp&lang=en
"""
# Grab one image
img = download_img('http://agora.ex.nii.ac.jp/digital-typhoon/wnp/by-name/201822/1/512x512/HMW818090618.201822.jpg')
plt.title('Typhoon Mangkhut, Class 2')
imgplot = plt.imshow(img, cmap='gray')
plt.show()
"""
Next we need to pass to a transformer to make it works well with the model
Here we use the transform that is idential to test set-up with to greyscale layer
for potential non-digital typhoon images
"""
default_transform = transforms.Compose([
transforms.Grayscale(num_output_channels=3),
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5])])
def transform_to_tensor(img, transform=default_transform):
return transform(img)
img_tensor = transform_to_tensor(img)
plt.title('Typhoon Mangkhut(Transformed), Class 2')
imgplot = plt.imshow(transforms.ToPILImage()(img_tensor), cmap='gray')
plt.show()
# Predict intensity class using the image
def predict(img_tensor, model):
img_tensor = img_tensor.view(-1, 3, 224, 224)
img_tensor = img_tensor.to(device)
model.eval()
with torch.no_grad():
output = model(img_tensor)
# Pass it to a sigmoid to get probabilities of each class
output = torch.sigmoid(output)
_, predict = torch.max(output.data, 1)
predict_val = predict.item()
conf = output[0][predict_val].item()
return predict_val + 1, conf
predict(img_tensor, model)
def get_saliency (img_tensor, model):
img_tensor = img_tensor.view(-1, 3, 224, 224)
img_tensor = img_tensor.to(device)
model.eval()
img_tensor.requires_grad_()
output = model(img_tensor)
# Pass it to a sigmoid to get probabilities of each class
output = torch.sigmoid(output)
score_max_index = output.argmax()
score_max = output[0,score_max_index]
score_max.backward()
saliency, _ = torch.max(img_tensor.grad.data.abs(),dim=1)
saliency = saliency.cpu()
plt.title('Saliency Map')
plt.imshow(saliency[0], cmap=plt.cm.hot)
plt.show()
get_saliency(img_tensor, model)
# Alternatively we can use this all in one function
def predict_img(img):
img_tensor = transform_to_tensor(img)
result, conf = predict(img_tensor, model)
print(f"The predicted class is {result} with {conf * 100:.2f}% confidence.")
get_saliency(img_tensor, model)
# Grab another image from another typhoon
img = download_img('http://agora.ex.nii.ac.jp/digital-typhoon/wnp/by-name/201910/1/512x512/HMW819080612.201910.jpg')
plt.title('Typhoon KROSA, Class 3')
imgplot = plt.imshow(img, cmap='gray')
plt.show()
```
#### Prediction function
With this function, we can easily predict a typhoon intensity just by passing an image.
Then, it will tell you the prediction result and the confidence rate.
As a bonus, it will also generate a saliency map that can tell you the model is looking at where part of the image.
```
predict_img(img)
```
| github_jupyter |
# Train object detection model with annotations and images from EXACT
## Imports
#### Import error
If import fails clone both repos and add them to sys path:
```
!pip install object-detection-fastai
```
```
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
from exact_sync.v1.api.annotations_api import AnnotationsApi
from exact_sync.v1.api.images_api import ImagesApi
from exact_sync.v1.api.image_sets_api import ImageSetsApi
from exact_sync.v1.api.annotation_types_api import AnnotationTypesApi
from exact_sync.v1.models import ImageSet, Team, Product, AnnotationType, Image, Annotation, AnnotationMediaFile
from exact_sync.v1.rest import ApiException
from exact_sync.v1.configuration import Configuration
from exact_sync.v1.api_client import ApiClient
import os
from pathlib import Path
from tqdm import tqdm
```
## Train EXACT
### Set user name, password and server address
Load from file for production
```
configuration = Configuration()
configuration.username = 'exact'
configuration.password = 'exact'
configuration.host = "http://127.0.0.1:8000"
client = ApiClient(configuration)
image_sets_api = ImageSetsApi(client)
annotations_api = AnnotationsApi(client)
annotation_types_api = AnnotationTypesApi(client)
images_api = ImagesApi(client)
target_folder = Path('examples/images/')
# Name of the data-sets to download images and annotations from
training_dataset_name = 'IconArt'
os.makedirs(str(target_folder), exist_ok=True)
image_sets = image_sets_api.list_image_sets(name__contains=training_dataset_name)
image_set = image_sets.results[0]
"Name: {} Images: {}".format(image_set.name, len(image_set.images))
```
### Download
```
annotationtypes = {}
images, lbl_bbox = [], []
for image_set in image_sets.results:
for image_id in tqdm(image_set.images[:50]):
coordinates, labels = [], []
image = images_api.retrieve_image(id=image_id)
name = image.name
image_path = target_folder/name
# if file not exists download it
if image_path.is_file() == False:
images_api.download_image(id=image_id, target_path=image_path, original_image=True)
for anno in annotations_api.list_annotations(pagination=False, async_req=True, image=image.id).results:
coordinates.append([anno.vector['y1'], anno.vector['x1'], anno.vector['y2'], anno.vector['x2']])
if anno.annotation_type not in annotationtypes:
annotationtypes[anno.annotation_type] = annotation_types_api.retrieve_annotation_type(id=anno.annotation_type)
labels.append(annotationtypes[anno.annotation_type].name)
if len(labels) > 0:
images.append(name)
lbl_bbox.append([coordinates, labels])
img2bbox = dict(zip(images, lbl_bbox))
get_y_func = lambda o:img2bbox[o.name]
print("Images: {} Annotations: {}".format(len(images), sum([len(annos[1]) for annos in lbl_bbox])))
images[0]
lbl_bbox[0]
```
### Create fastai data object
```
from object_detection_fastai.helper.object_detection_helper import *
from object_detection_fastai.loss.RetinaNetFocalLoss import RetinaNetFocalLoss
from object_detection_fastai.models.RetinaNet import RetinaNet
from object_detection_fastai.callbacks.callbacks import BBLossMetrics, BBMetrics, PascalVOCMetric
from fastai.utils.collect_env import show_install
show_install()
```
### Import or install object detection lib
#### Import error
If import fails clone both repos and add them to sys path:
```
!pip install object-detection-fastai
```
```
size = 256
bs = 4
data = (ObjectItemList.from_folder(target_folder)
#Where are the images?
.split_by_rand_pct()
#How to split in train/valid? -> randomly with the default 20% in valid
.label_from_func(get_y_func)
#How to find the labels? -> use get_y_func
.transform(get_transforms(), tfm_y=True, size=size)
#Data augmentation? -> Standard transforms with tfm_y=True
.databunch(bs=bs, collate_fn=bb_pad_collate, num_workers=0))
data.show_batch()
data.train_ds.classes
```
### Train data-set
```
anchors = create_anchors(sizes=[(32,32),(16,16),(8,8),(4,4)], ratios=[0.5, 1, 2], scales=[0.35, 0.5, 0.6, 1, 1.25, 1.6])
crit = RetinaNetFocalLoss(anchors)
encoder = create_body(models.resnet18, True, -2)
model = RetinaNet(encoder, n_classes=data.train_ds.c, n_anchors=18, sizes=[32,16,8,4], chs=128, final_bias=-4., n_conv=3)
voc = PascalVOCMetric(anchors, size, [str(i) for i in data.train_ds.y.classes[1:]])
learn = Learner(data, model, loss_func=crit, callback_fns=[BBMetrics, ShowGraph], #BBMetrics, ShowGraph
metrics=[voc]
)
learn.split([model.encoder[6], model.c5top5])
learn.freeze_to(-2)
learn.fit_one_cycle(1, 1e-4)
```
| github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Datasets/Vectors/usgs_watershed_boundary.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Vectors/usgs_watershed_boundary.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Datasets/Vectors/usgs_watershed_boundary.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Vectors/usgs_watershed_boundary.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
## Install Earth Engine API
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.
The magic command `%%capture` can be used to hide output from a specific cell.
```
# %%capture
# !pip install earthengine-api
# !pip install geehydro
```
Import libraries
```
import ee
import folium
import geehydro
```
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()`
if you are running this notebook for this first time or if you are getting an authentication error.
```
# ee.Authenticate()
ee.Initialize()
```
## Create an interactive map
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function.
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
```
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')
```
## Add Earth Engine Python script
```
dataset = ee.FeatureCollection('USGS/WBD/2017/HUC02')
styleParams = {
'fillColor': '000070',
'color': '0000be',
'width': 3.0,
}
regions = dataset.style(**styleParams)
Map.setCenter(-96.8, 40.43, 4)
Map.addLayer(regions, {}, 'USGS/WBD/2017/HUC02')
dataset = ee.FeatureCollection('USGS/WBD/2017/HUC04')
styleParams = {
'fillColor': '5885E3',
'color': '0000be',
'width': 3.0,
}
subregions = dataset.style(**styleParams)
Map.setCenter(-110.904, 36.677, 7)
Map.addLayer(subregions, {}, 'USGS/WBD/2017/HUC04')
dataset = ee.FeatureCollection('USGS/WBD/2017/HUC06')
styleParams = {
'fillColor': '588593',
'color': '587193',
'width': 3.0,
}
basins = dataset.style(**styleParams)
Map.setCenter(-96.8, 40.43, 7)
Map.addLayer(basins, {}, 'USGS/WBD/2017/HUC06')
dataset = ee.FeatureCollection('USGS/WBD/2017/HUC08')
styleParams = {
'fillColor': '2E8593',
'color': '587193',
'width': 2.0,
}
subbasins = dataset.style(**styleParams)
Map.setCenter(-96.8, 40.43, 8)
Map.addLayer(subbasins, {}, 'USGS/WBD/2017/HUC08')
dataset = ee.FeatureCollection('USGS/WBD/2017/HUC10')
styleParams = {
'fillColor': '2E85BB',
'color': '2E5D7E',
'width': 1.0,
}
watersheds = dataset.style(**styleParams)
Map.setCenter(-96.8, 40.43, 9)
Map.addLayer(watersheds, {}, 'USGS/WBD/2017/HUC10')
dataset = ee.FeatureCollection('USGS/WBD/2017/HUC12')
styleParams = {
'fillColor': '2E85BB',
'color': '2E5D7E',
'width': 0.1,
}
subwatersheds = dataset.style(**styleParams)
Map.setCenter(-96.8, 40.43, 10)
Map.addLayer(subwatersheds, {}, 'USGS/WBD/2017/HUC12')
```
## Display Earth Engine data layers
```
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
```
| github_jupyter |
<a href="https://colab.research.google.com/github/IlyaGusev/purano/blob/master/baselines.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Requirements
```
!git clone https://github.com/IlyaGusev/purano
%cd purano
!pip install -r requirements.txt
!pip install catboost
!pip install tensorflow-text tensorflow-hub
!pip install --upgrade transformers
!mkdir models/lang_detect
!mkdir models/cat_detect
!wget https://www.dropbox.com/s/hoapmnvqlknmu6v/lang_detect_v10.ftz -O models/lang_detect/lang_detect_v10.ftz
!wget https://www.dropbox.com/s/23x35wuet280eh6/ru_cat_v5.ftz -O models/cat_detect/ru_cat_v5.ftz
```
# Data loading
```
# May 25 (training)
!rm -rf data
!mkdir -p data
!cd data && wget https://data-static.usercontent.dev/DataClusteringDataset0525.tar.gz -O - | tar -xz && cd ../
# May 27 and 29 (test)
!cd data && wget https://data-static.usercontent.dev/DataClusteringDataset0527.tar.gz -O - | tar -xz && cd ../
!cd data && wget https://data-static.usercontent.dev/DataClusteringDataset0529.tar.gz -O - | tar -xz && cd ../
%%writefile configs/cleaner.jsonnet
{
"lang_detect_model_path": "models/lang_detect/lang_detect_v10.ftz",
"cat_detect_model_path": "models/cat_detect/ru_cat_v5.ftz",
"is_lower": true,
"is_russian_only": true,
"is_news_only": true
}
!rm -f 0525_parsed.db
!python3 -m purano.run_parse --inputs "data/20200525" --output-file 0525_parsed.db --fmt html --cleaner-config configs/cleaner.jsonnet
!rm -f 0527_parsed.db
!python3 -m purano.run_parse --inputs "data/20200527" --output-file 0527_parsed.db --fmt html --cleaner-config configs/cleaner.jsonnet
!rm -f 0529_parsed.db
!python3 -m purano.run_parse --inputs "data/20200529" --output-file 0529_parsed.db --fmt html --cleaner-config configs/cleaner.jsonnet
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from purano.models import Document
def parse_db(file_name):
db_engine = "sqlite:///{}".format(file_name)
engine = create_engine(db_engine)
Session = sessionmaker(bind=engine)
session = Session()
query = session.query(Document)
docs = query.all()
records = []
for doc in docs:
records.append({
"title": doc.title,
"text": doc.text,
"url": doc.url,
"host": doc.host,
"timestamp": doc.date,
"patched_title": doc.patched_title,
"patched_text": doc.patched_text
})
return records
train_records = parse_db("0525_parsed.db")
test_0527_records = parse_db("0527_parsed.db")
test_0529_records = parse_db("0529_parsed.db")
print(len(train_records))
print(len(test_0527_records))
print(len(test_0529_records))
print(train_records[0])
# Fasttext model tuned on older documents
!wget https://www.dropbox.com/s/vttjivmmxw7leea/ru_vectors_v3.bin
# Clustering training markup
!wget https://www.dropbox.com/s/8lu6dw8zcrn840j/ru_clustering_0525_urls.tsv
# Clustering test set
!wget https://www.dropbox.com/s/v2lbfft6pgzoeq3/ru_clustering_test_fixed.tsv
# Headline selection training set
!wget https://www.dropbox.com/s/jpcwryaeszqtrf9/titles_markup_0525_urls.tsv
# Headline selection test set
!wget https://www.dropbox.com/s/v3c0q6msy2pwvfm/titles_markup_test.tsv
```
# Fetching texts for pretraining
Optional section, required for TF-IDF and Text-Title models
Full list of archives: https://github.com/IlyaGusev/purano/blob/master/raw_datasets.txt
```
%%writefile raw_datasets.txt
https://data-static.usercontent.dev/DataClusteringSample0410.tar.gz
https://data-static.usercontent.dev/DataClusteringSample1117.tar.gz
%%writefile download_datasets.sh
#!/bin/bash
# Download datasets
rm -rf raw_datasets
mkdir raw_datasets
cd raw_datasets
wget -i ../raw_datasets.txt
for F in *.tar.gz; do
tar -xzf "$F"
rm -f "$F"
done
cd ../
!bash download_datasets.sh
from purano.io import read_tg_html_dir
from tqdm.notebook import tqdm
from purano.run_parse import DocumentsCleaner
cleaner = DocumentsCleaner("configs/cleaner.jsonnet")
raw_texts = []
pretrain_records = []
for i, record in tqdm(enumerate(read_tg_html_dir("raw_datasets"))):
cleaned_document = cleaner(record)
if not cleaned_document:
continue
raw_texts.append(cleaned_document["title"])
raw_texts.append(cleaned_document["text"])
pretrain_records.append(cleaned_document)
print(len(pretrain_records))
```
# Clustering
## Evaluation
```
from purano.io import read_markup_tsv
train_markup = read_markup_tsv("ru_clustering_0525_urls.tsv")
test_markup = read_markup_tsv("ru_clustering_test_fixed.tsv")
from collections import Counter
from statistics import median, mean
from sklearn.cluster import AgglomerativeClustering
from purano.clusterer.metrics import calc_metrics
def get_quality(markup, embeds, records, dist_threshold, print_result=False):
clustering_model = AgglomerativeClustering(
n_clusters=None,
distance_threshold=dist_threshold,
linkage="average",
affinity="cosine"
)
clustering_model.fit(embeds)
labels = clustering_model.labels_
idx2url = dict()
url2record = dict()
for i, record in enumerate(records):
idx2url[i] = record["url"]
url2record[record["url"]] = record
url2label = dict()
for i, label in enumerate(labels):
url2label[idx2url[i]] = label
metrics = calc_metrics(markup, url2record, url2label)[0]
if print_result:
print()
print("Accuracy: {:.1f}".format(metrics["accuracy"] * 100.0))
print("Positives Recall: {:.1f}".format(metrics["1"]["recall"] * 100.0))
print("Positives Precision: {:.1f}".format(metrics["1"]["precision"] * 100.0))
print("Positives F1: {:.1f}".format(metrics["1"]["f1-score"] * 100.0))
print("Distance: ", dist_threshold)
sizes = list(Counter(labels).values())
print("Max cluster size: ", max(sizes))
print("Median cluster size: ", median(sizes))
print("Avg cluster size: {:.2f}".format(mean(sizes)))
return
return metrics["1"]["f1-score"]
import copy
def form_submission(markup, embeds, records, dist_threshold, dataset_name):
clustering_model = AgglomerativeClustering(
n_clusters=None,
distance_threshold=dist_threshold,
linkage="average",
affinity="cosine"
)
clustering_model.fit(embeds)
labels = clustering_model.labels_
idx2url = dict()
url2record = dict()
for i, record in enumerate(records):
idx2url[i] = record["url"]
url2record[record["url"]] = record
url2label = dict()
for i, label in enumerate(labels):
url2label[idx2url[i]] = label
submission = []
for record in markup:
dataset = record["dataset"]
if dataset != dataset_name:
continue
first_url = record["first_url"]
second_url = record["second_url"]
r = copy.copy(record)
r["quality"] = "OK" if url2label[first_url] == url2label[second_url] else "BAD"
submission.append(r)
return submission
```
## FastText model
```
import fasttext
import numpy as np
from tqdm import tqdm
def ft_embed_text(text, ft_model, max_tokens_count=150):
vector_dim = ft_model.get_dimension()
tokens = text.split(" ")[:max_tokens_count]
word_embeddings = np.zeros((len(tokens), vector_dim), dtype=np.float32)
for token_num, token in enumerate(tokens):
word_embeddings[token_num, :] = ft_model.get_word_vector(token)
mean_embedding = np.mean(word_embeddings, axis=0)
max_embeddings = np.max(word_embeddings, axis=0)
return np.concatenate((mean_embedding, max_embeddings), axis=0)
def ft_records_to_embeds(records, ft_model):
ft_embeddings = np.zeros((len(records), ft_model.get_dimension() * 2), dtype=np.float32)
for i, record in enumerate(tqdm(records)):
sample = record["patched_title"] + " " + record["patched_text"]
ft_embeddings[i, :] = ft_embed_text(sample, ft_model)
return ft_embeddings
ft_model = fasttext.load_model("ru_vectors_v3.bin")
train_ft_embeddings = ft_records_to_embeds(train_records, ft_model)
test_0527_ft_embeddings = ft_records_to_embeds(test_0527_records, ft_model)
test_0529_ft_embeddings = ft_records_to_embeds(test_0529_records, ft_model)
get_quality(train_markup, train_ft_embeddings, train_records, 0.041, print_result=True)
from purano.io import write_markup_tsv
submission_0527_ft = form_submission(test_markup, test_0527_ft_embeddings, test_0527_records, 0.041, "0527")
submission_0529_ft = form_submission(test_markup, test_0529_ft_embeddings, test_0529_records, 0.041, "0529")
full_submission_ft = submission_0527_ft + submission_0529_ft
write_markup_tsv(full_submission_ft, "answer.txt", res_key="quality")
!rm -f submission_ft.zip
!zip submission_ft.zip answer.txt
!head answer.txt
```
## USE model
```
!pip install tensorflow-text tensorflow-hub
import tensorflow as tf
import tensorflow_text
import tensorflow_hub as hub
module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
use_model = hub.load(module_url)
print("module %s loaded" % module_url)
import numpy as np
import tqdm.notebook as tq
def use_get_embedding(text, model):
return model([text]).numpy()[0]
def use_records_to_embeds(records, model):
embeddings = np.zeros((len(records), 512))
for i, record in tq.tqdm(enumerate(records)):
embeddings[i] = use_get_embedding(record["title"] + " " + record["text"], model)
return embeddings
train_use_embeddings = use_records_to_embeds(train_records, use_model)
test_0527_use_embeddings = use_records_to_embeds(test_0527_records, use_model)
test_0529_use_embeddings = use_records_to_embeds(test_0529_records, use_model)
get_quality(train_markup, train_use_embeddings, train_records, 0.37, print_result=True)
from purano.io import write_markup_tsv
submission_0527_use = form_submission(test_markup, test_0527_use_embeddings, test_0527_records, 0.37, "0527")
submission_0529_use = form_submission(test_markup, test_0529_use_embeddings, test_0529_records, 0.37, "0529")
full_submission_use = submission_0527_use + submission_0529_use
write_markup_tsv(full_submission_use, "answer.txt", res_key="quality")
!rm -f submission_use.zip
!zip submission_use.zip answer.txt
```
## LSA model
```
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from purano.util import tokenize_to_lemmas
tfidf_vectorizer = TfidfVectorizer(tokenizer=tokenize_to_lemmas, max_df=0.3, min_df=5)
old_embeddings = tfidf_vectorizer.fit_transform(raw_texts[-150000:])
svd = TruncatedSVD(n_components=500, n_iter=20, random_state=42)
svd.fit(old_embeddings)
import numpy as np
def tfidf_records_to_embeds(records, vectorizer, svd):
embeddings = vectorizer.transform([r["title"] + " " + r["text"] for r in records])
embeddings = svd.transform(embeddings)
embeddings[np.logical_and(np.max(embeddings, axis=1) == 0, np.sum(embeddings, axis=1) == 0)] = np.random.rand(embeddings.shape[1])
return embeddings
train_tfidf_embeddings = tfidf_records_to_embeds(train_records, tfidf_vectorizer, svd)
test_0527_tfidf_embeddings = tfidf_records_to_embeds(test_0527_records, tfidf_vectorizer, svd)
test_0529_tfidf_embeddings = tfidf_records_to_embeds(test_0529_records, tfidf_vectorizer, svd)
get_quality(train_markup, train_tfidf_embeddings, train_records, 0.5, print_result=True)
from purano.io import write_markup_tsv
submission_0527_tfidf = form_submission(test_markup, test_0527_tfidf_embeddings, test_0527_records, 0.5, "0527")
submission_0529_tfidf = form_submission(test_markup, test_0529_tfidf_embeddings, test_0529_records, 0.5, "0529")
full_submission_tfidf = submission_0527_tfidf + submission_0529_tfidf
write_markup_tsv(full_submission_tfidf, "answer.txt", res_key="quality")
!rm -f submission_tfidf.zip
!zip submission_tfidf.zip answer.txt
```
## Text2Title siamise model over FastText
```
import numpy as np
from hnswlib import Index as HnswIndex
from purano.util import tokenize
def ft_words_to_embeddings(model, words):
vector_dim = model.get_dimension()
embeddings = np.zeros((len(words), vector_dim))
for i, w in enumerate(words):
embeddings[i] = model.get_word_vector(w)
embeddings[i] /= np.linalg.norm(embeddings[i])
return embeddings
def ft_embed_text(model, text):
words = tokenize(text)
norm_vectors = ft_words_to_embeddings(model, words)
avg_wv = np.mean(norm_vectors, axis=0)
max_wv = np.max(norm_vectors, axis=0)
min_wv = np.min(norm_vectors, axis=0)
return np.concatenate((avg_wv, max_wv, min_wv))
# Index for mining hard negatives
class FasttextHnsw:
def __init__(self, model):
self.model = model
self.vector_dim = model.get_dimension()
self.hnsw = HnswIndex(space='l2', dim=self.vector_dim * 3)
def build_hnsw(self, texts):
n = len(texts)
self.hnsw.init_index(max_elements=n, ef_construction=100, M=16)
embeddings = np.zeros((n, self.vector_dim * 3))
for i, text in enumerate(texts):
embeddings[i] = ft_embed_text(self.model, text)
self.hnsw.add_items(embeddings)
import random
import numpy as np
import torch
import fasttext
from torch.utils.data import Dataset
from tqdm.notebook import tqdm
from purano.util import tokenize
from purano.training.fasttext_hnsw import FasttextHnsw
class Text2TitleDataset(Dataset):
def __init__(self, data, ft_model, min_words=2, max_words=150):
self.ft_hnsw = FasttextHnsw(ft_model)
self.ft_hnsw.build_hnsw([r["title"] for r in data])
self.samples = []
for row in tqdm(data):
title_words = tokenize(row["title"])
text_words = tokenize(row["text"])[:max_words]
if len(text_words) < min_words or len(title_words) < min_words:
continue
title = " ".join(title_words)
text = " ".join(text_words)
text_vector = ft_embed_text(ft_model, text)
title_vector = ft_embed_text(ft_model, title)
labels = list(self.ft_hnsw.hnsw.knn_query(title_vector, k=20)[0][0])[1:]
random.shuffle(labels)
bad_indices = labels[:2] + [random.randint(0, len(data) - 1)]
bad_vectors = self.ft_hnsw.hnsw.get_items(bad_indices)
for bad_vector in bad_vectors:
bad_vector = np.array(bad_vector)
assert bad_vector.shape == title_vector.shape == text_vector.shape
assert bad_vector.dtype == title_vector.dtype == text_vector.dtype
sample = (
torch.FloatTensor(text_vector),
torch.FloatTensor(title_vector),
torch.FloatTensor(bad_vector)
)
self.samples.append(sample)
def __len__(self):
return len(self.samples)
def __getitem__(self, index):
return self.samples[index]
import torch
import torch.nn as nn
from pytorch_lightning import LightningModule
class Embedder(nn.Module):
def __init__(self, embedding_dim, hidden_dim):
super().__init__()
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self.mapping_layer = nn.Linear(embedding_dim, hidden_dim)
def forward(self, in_vectors):
projections = self.mapping_layer(in_vectors)
norm = projections.norm(p=2, dim=1, keepdim=True)
projections = projections.div(norm)
return projections
class Text2TitleModel(LightningModule):
def __init__(self, embedding_dim=384, hidden_dim=128):
super().__init__()
self.text_embedder = Embedder(embedding_dim, hidden_dim)
self.title_embedder = Embedder(embedding_dim, hidden_dim)
self.distance = nn.PairwiseDistance(p=2)
self.margin = 0.3
def forward(self, pivot_vectors, positive_vectors, negative_vectors):
pivot = self.text_embedder(pivot_vectors)
positive = self.title_embedder(positive_vectors)
negative = self.title_embedder(negative_vectors)
distances = self.distance(pivot, positive) - self.distance(pivot, negative) + self.margin
loss = torch.mean(torch.max(distances, torch.zeros_like(distances)))
return loss
def training_step(self, batch, batch_nb):
train_loss = self(*batch)
self.log("train_loss", train_loss, prog_bar=True, logger=True)
return train_loss
def validation_step(self, batch, batch_nb):
val_loss = self(*batch)
self.log("val_loss", val_loss, prog_bar=True, logger=True)
def test_step(self, batch, batch_nb):
test_loss = self(*batch)
self.log("test_loss", test_loss, prog_bar=True, logger=True)
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
return [optimizer]
import random
from torch.utils.data import DataLoader, RandomSampler
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import EarlyStopping
BATCH_SIZE = 64
NUM_WORKERS = 5
MAX_WORDS = 150
EPOCHS = 100
PATIENCE = 4
pretrain_records.sort(key=lambda x: x.get("date"))
tt_records = pretrain_records[:150000]
val_border = int(0.9 * len(tt_records))
tt_train_records = tt_records[:val_border]
tt_val_records = tt_records[val_border:]
ft_model = fasttext.load_model("ru_vectors_v3.bin")
train_data = Text2TitleDataset(tt_train_records, ft_model, max_words=MAX_WORDS)
train_sampler = RandomSampler(train_data)
train_loader = DataLoader(train_data,
sampler=train_sampler,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS
)
val_data = Text2TitleDataset(tt_val_records, ft_model, max_words=MAX_WORDS)
val_loader = DataLoader(val_data, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS)
tt_model = Text2TitleModel()
early_stop_callback = EarlyStopping(
monitor="val_loss",
min_delta=0.0,
patience=PATIENCE,
verbose=True,
mode="min"
)
trainer = Trainer(
gpus=0,
checkpoint_callback=False,
accumulate_grad_batches=1,
max_epochs=EPOCHS,
callbacks=[early_stop_callback],
val_check_interval=1.0,
progress_bar_refresh_rate=100,
deterministic=True
)
trainer.fit(tt_model, train_loader, val_loader)
from tqdm.notebook import tqdm
def tt_records_to_embeds(records, ft_model, tt_model, max_words=150):
title_embedder = tt_model.title_embedder
text_embedder = tt_model.text_embedder
embeddings = np.zeros((len(records), text_embedder.hidden_dim + title_embedder.hidden_dim))
for i, record in tqdm(enumerate(records)):
title_words = tokenize(record["title"])
if not title_words:
title_words = ["нет"]
text_words = tokenize(record["text"])[:max_words]
if not text_words:
text_words = ["нет"]
title_embedding = ft_embed_text(ft_model, " ".join(title_words))
text_embedding = ft_embed_text(ft_model, " ".join(text_words))
title_embedding = title_embedder(torch.FloatTensor(title_embedding).unsqueeze(0)).squeeze(0).detach().cpu().numpy()
text_embedding = text_embedder(torch.FloatTensor(text_embedding).unsqueeze(0)).squeeze(0).detach().cpu().numpy()
embedding = np.concatenate((title_embedding, text_embedding), axis=0)
embeddings[i] = embedding
return embeddings
train_tt_embeddings = tt_records_to_embeds(train_records, ft_model, tt_model, MAX_WORDS)
test_0527_tt_embeddings = tt_records_to_embeds(test_0527_records, ft_model, tt_model)
test_0529_tt_embeddings = tt_records_to_embeds(test_0529_records, ft_model, tt_model)
get_quality(train_markup, train_tt_embeddings, train_records, 0.38, print_result=True)
from purano.io import write_markup_tsv
submission_0527_tt = form_submission(test_markup, test_0527_tt_embeddings, test_0527_records, 0.38, "0527")
submission_0529_tt = form_submission(test_markup, test_0529_tt_embeddings, test_0529_records, 0.38, "0529")
full_submission_tt = submission_0527_tt + submission_0529_tt
write_markup_tsv(full_submission_tt, "answer.txt", res_key="quality")
!rm -f submission_tt.zip
!zip submission_tt.zip answer.txt
```
## TTGenBottleneck model
```
from tqdm.notebook import tqdm
import numpy as np
import torch
def gen_batch(records, batch_size):
batch_start = 0
while batch_start < len(records):
batch_end = batch_start + batch_size
batch = records[batch_start: batch_end]
batch_start = batch_end
yield batch
def gtbe_records_to_embeds(records, model, tokenizer, batch_size=4, max_tokens_count=196):
current_index = 0
embeddings = np.zeros((len(records), 768))
for batch in tqdm(gen_batch(records, batch_size)):
samples = [r["text"] for r in batch]
inputs = tokenizer(
samples,
add_special_tokens=True,
max_length=max_tokens_count,
padding="max_length",
truncation=True,
return_tensors='pt'
)
batch_input_ids = inputs["input_ids"].cuda()
batch_mask = inputs["attention_mask"].cuda()
assert len(batch_input_ids[0]) == len(batch_mask[0]) == max_tokens_count
with torch.no_grad():
output = model(
batch_input_ids,
attention_mask=batch_mask,
return_dict=True,
output_hidden_states=True
)
layer_embeddings = output.hidden_states[-1]
batch_embeddings = layer_embeddings.cpu().numpy()
batch_embeddings = batch_embeddings[:, 0, :]
embeddings[current_index:current_index+batch_size, :] = batch_embeddings
current_index += batch_size
return embeddings
from transformers import AutoTokenizer, AutoModel
gtbe_model = AutoModel.from_pretrained("IlyaGusev/gen_title_tg_bottleneck_encoder").cuda()
gtbe_tokenizer = AutoTokenizer.from_pretrained("IlyaGusev/gen_title_tg_bottleneck_encoder", do_lower_case=False)
train_gtbe_embeddings = gtbe_records_to_embeds(train_records, gtbe_model, gtbe_tokenizer)
get_quality(train_markup, train_gtbe_embeddings, train_records, 0.37, print_result=True)
test_0527_gtbe_embeddings = gtbe_records_to_embeds(test_0527_records, gtbe_model, gtbe_tokenizer)
test_0529_gtbe_embeddings = gtbe_records_to_embeds(test_0529_records, gtbe_model, gtbe_tokenizer)
from purano.io import write_markup_tsv
submission_gtbe_0527 = form_submission(test_markup, test_0527_gtbe_embeddings, test_0527_records, 0.37, "0527")
submission_gtbe_0529 = form_submission(test_markup, test_0529_gtbe_embeddings, test_0529_records, 0.37, "0529")
full_submission_gtbe = submission_gtbe_0527 + submission_gtbe_0529
write_markup_tsv(full_submission_gtbe, "answer.txt", res_key="quality")
!rm -f submission_gtbe.zip
!zip submission_gtbe.zip answer.txt
```
# Headline selection
```
from purano.io import read_markup_tsv
hl_train_markup = read_markup_tsv("titles_markup_0525_urls.tsv")
hl_test_markup = read_markup_tsv("titles_markup_test.tsv")
```
## USE + Catboost
```
import tensorflow as tf
import tensorflow_text
import tensorflow_hub as hub
import numpy as np
import tqdm.notebook as tq
module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
use_model = hub.load(module_url)
print("module %s loaded" % module_url)
def use_get_embedding(text, model):
return model([text]).numpy()[0]
def use_records_to_embeds(records, model):
embeddings = np.zeros((len(records), 512))
for i, record in tq.tqdm(enumerate(records)):
embeddings[i] = use_get_embedding(record["title"], model)
return embeddings
train_use_title_embeddings = use_records_to_embeds(train_records, use_model)
test_0527_use_embeddings = use_records_to_embeds(test_0527_records, use_model)
test_0529_use_embeddings = use_records_to_embeds(test_0529_records, use_model)
import random
from catboost import Pool
from collections import Counter
def get_groups(markup):
groups = list()
url2group = dict()
for r in markup:
if r["quality"] == "draw" or r["quality"] == "bad":
continue
left_url = r["left_url"]
right_url = r["right_url"]
left_group_id = url2group.get(left_url, None)
right_group_id = url2group.get(right_url, None)
if left_group_id is not None and right_group_id is None:
groups[left_group_id].add(right_url)
url2group[right_url] = left_group_id
elif right_group_id is not None and left_group_id is None:
groups[right_group_id].add(left_url)
url2group[left_url] = right_group_id
elif left_group_id is None and right_group_id is None:
groups.append({left_url, right_url})
url2group[left_url] = url2group[right_url] = len(groups) - 1
elif left_group_id != right_group_id:
for u in groups[right_group_id]:
url2group[u] = left_group_id
groups[left_group_id] = groups[left_group_id] | groups[right_group_id]
groups[right_group_id] = set()
assert right_url in groups[url2group[right_url]]
assert left_url in groups[url2group[left_url]]
assert url2group[right_url] == url2group[left_url]
groups = [group for group in groups if group]
url2group = dict()
for i, group in enumerate(groups):
for url in group:
url2group[url] = i
return groups, url2group
def get_features(markup, url2record, embeddings, url2id):
urls = set()
for r in markup:
if r["quality"] == "draw" or r["quality"] == "bad":
continue
urls.add(r["left_url"])
urls.add(r["right_url"])
features = dict()
for url in urls:
record = url2record[url]
embedding = list(embeddings[url2id[url]])
features[url] = embedding
return features
def get_pairs(markup, url2group, is_train_group):
all_pairs = list()
train_pairs = list()
val_pairs = list()
for r in markup:
if r["quality"] == "draw" or r["quality"] == "bad":
continue
left_url = r["left_url"]
right_url = r["right_url"]
group_id = url2group[left_url]
assert url2group[right_url] == group_id
is_train = is_train_group[group_id]
pairs = train_pairs if is_train else val_pairs
if r["quality"] == "left":
pairs.append((left_url, right_url))
all_pairs.append((left_url, right_url))
elif r["quality"] == "right":
pairs.append((right_url, left_url))
all_pairs.append((right_url, left_url))
return all_pairs, train_pairs, val_pairs
def convert_to_cb_pool(groups, pairs, features):
urls_set = set()
for url1, url2 in pairs:
urls_set.add(url1)
urls_set.add(url2)
urls = []
group_id = []
for i, group in enumerate(groups):
for url in group:
if url not in urls_set:
continue
group_id.append(i)
urls.append(url)
urls2id = {url: i for i, url in enumerate(urls)}
features = [features[url] for url in urls]
pairs = [(urls2id[url1], urls2id[url2]) for url1, url2 in pairs]
pool = Pool(data=features, pairs=pairs, group_id=group_id)
return pool, urls
random.seed(1338)
train_url2record = {r["url"]: r for r in train_records}
train_url2id = {r["url"]: i for i, r in enumerate(train_records)}
val_part = 0.1
train_part = 1.0 - val_part
groups, url2group = get_groups(hl_train_markup)
is_train_group = [random.random() < train_part for _ in range(len(groups))]
features = get_features(hl_train_markup, train_url2record, train_use_title_embeddings, train_url2id)
all_pairs, train_pairs, val_pairs = get_pairs(hl_train_markup, url2group, is_train_group)
train_pool, train_urls = convert_to_cb_pool(groups, train_pairs, features)
val_pool, val_urls = convert_to_cb_pool(groups, val_pairs, features)
from catboost import CatBoost
cb_model = CatBoost(params={"loss_function": "PairLogit", "task_type": "GPU"})
cb_model.fit(train_pool, eval_set=val_pool)
val_predictions = cb_model.predict(val_pool)
val_urls2id = {url: i for i, url in enumerate(val_urls)}
correct_pairs = 0
all_pairs = 0
for winner_url, loser_url in val_pairs:
all_pairs += 1
winner_id = val_urls2id[winner_url]
loser_id = val_urls2id[loser_url]
winner_pred = val_predictions[winner_id]
loser_pred = val_predictions[loser_id]
correct_pairs += 1 if winner_pred > loser_pred else 0
print(float(correct_pairs) / all_pairs)
import copy
def hl_form_submission(markup, records, embeddings, cb_model, dataset_name, draw_border=0.1):
predictions = cb_model.predict(embeddings)
url2idx = dict()
for i, record in enumerate(records):
url = record["url"]
url2idx[url] = i
submission = []
for record in markup:
if record["dataset"] != dataset_name:
continue
left_url = record["left_url"]
right_url = record["right_url"]
left_idx = url2idx[left_url]
right_idx = url2idx[right_url]
left_pred = predictions[left_idx]
right_pred = predictions[right_idx]
result = "left" if left_pred > right_pred else "right"
result = "draw" if abs(left_pred - right_pred) < draw_border else result
r = copy.copy(record)
r["quality"] = result
submission.append(r)
return submission
from purano.io import write_markup_tsv
hl_use_cb_submission_0527 = hl_form_submission(hl_test_markup, test_0527_records, test_0527_use_embeddings, cb_model, "0527")
hl_use_cb_submission_0529 = hl_form_submission(hl_test_markup, test_0529_records, test_0529_use_embeddings, cb_model, "0529")
hl_use_cb_full_submission = hl_use_cb_submission_0527 + hl_use_cb_submission_0529
write_markup_tsv(hl_use_cb_full_submission, "answer.txt", res_key="quality")
!rm -f hl_use_cb_submission.zip
!zip hl_use_cb_submission.zip answer.txt
```
# Headline generation
```
!wget https://www.dropbox.com/s/opgtoc8ucjhhyii/hg_texts.jsonl.tar.gz
!tar -xzvf hg_texts.jsonl.tar.gz
import json
hg_records = []
with open("hg_texts.jsonl", "r") as r:
for line in r:
hg_records.append(json.loads(line))
print(hg_records[0])
```
## Lead-1
```
import razdel
import random
from collections import defaultdict
id2hyps = defaultdict(list)
with open("hg_texts.jsonl", "r") as r:
for line in r:
record = json.loads(line)
sample_id = record["sample_id"]
text = record["text"]
first_sentence = list(razdel.sentenize(text))[0].text.replace(".", "")
id2hyps[sample_id].append(first_sentence)
with open("answer.txt", "w") as w:
for sample_id, hyps in id2hyps.items():
hyp = random.choice(hyps)
w.write(json.dumps({
"sample_id": sample_id,
"title": hyp
}, ensure_ascii=False) + "\n")
!zip submission_lead1.zip answer.txt
```
## Trained EncoderDecoder RuBERT
```
from transformers import AutoTokenizer, EncoderDecoderModel
model_name = "IlyaGusev/rubert_telegram_headlines"
tokenizer = AutoTokenizer.from_pretrained(model_name, do_lower_case=False, do_basic_tokenize=False, strip_accents=False)
model = EncoderDecoderModel.from_pretrained(model_name).cuda()
def predict_headline(text):
input_ids = tokenizer(
[text],
add_special_tokens=True,
max_length=256,
padding="max_length",
truncation=True,
return_tensors="pt",
)["input_ids"]
output_ids = model.generate(
input_ids=input_ids.cuda(),
max_length=64,
no_repeat_ngram_size=3,
num_beams=6,
top_p=0.95
)[0]
headline = tokenizer.decode(output_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
return headline
predict_headline(hg_records[0]["text"])
import random
from collections import defaultdict
from tqdm.notebook import tqdm
id2hyps = defaultdict(list)
random.seed(13332417)
for record in tqdm(hg_records):
text = record["text"]
sample_id = record["sample_id"]
text_id = record["text_id"]
prediction = predict_headline(text)
id2hyps[sample_id].append(prediction)
with open("answer.txt", "w") as w:
for sample_id, hyps in id2hyps.items():
hyp = random.choice(hyps)
w.write(json.dumps({
"title": hyp,
"sample_id": sample_id
}, ensure_ascii=False).strip() + "\n")
!zip submission_hg_rubert.zip answer.txt
```
| github_jupyter |
## Magics
```
%load_ext autoreload
%autoreload 2
```
## Imports
```
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, roc_auc_score, f1_score, classification_report
from aif360.datasets import AdultDataset, GermanDataset, CompasDataset, BankDataset
from aif360.metrics import BinaryLabelDatasetMetric
from aif360.metrics import ClassificationMetric
from aif360.metrics.utils import compute_boolean_conditioning_vector
from aif360.algorithms.preprocessing.optim_preproc_helpers.data_preproc_functions\
import load_preproc_data_adult, load_preproc_data_compas
from sklearn.preprocessing import scale
from sklearn.linear_model import LogisticRegression
from IPython.display import Markdown, display
%matplotlib inline
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
```
## Get Data
```
## import dataset
dataset_used = "adult" # "adult", "german", "compas"
protected_attribute_used = 1 # 1, 2
if dataset_used == "adult":
dataset_orig = AdultDataset()
# dataset_orig = load_preproc_data_adult()
if protected_attribute_used == 1:
privileged_groups = [{'sex': 1}]
unprivileged_groups = [{'sex': 0}]
else:
privileged_groups = [{'race': 1}]
unprivileged_groups = [{'race': 0}]
elif dataset_used == "german":
dataset_orig = GermanDataset()
if protected_attribute_used == 1:
privileged_groups = [{'sex': 1}]
unprivileged_groups = [{'sex': 0}]
else:
privileged_groups = [{'age': 1}]
unprivileged_groups = [{'age': 0}]
elif dataset_used == "compas":
# dataset_orig = CompasDataset()
dataset_orig = load_preproc_data_compas()
if protected_attribute_used == 1:
privileged_groups = [{'sex': 1}]
unprivileged_groups = [{'sex': 0}]
else:
privileged_groups = [{'race': 1}]
unprivileged_groups = [{'race': 0}]
dataset_orig_train, dataset_orig_vt = dataset_orig.split([0.6], shuffle=True)
dataset_orig_valid, dataset_orig_test = dataset_orig_vt.split([0.5], shuffle=True)
# print out some labels, names, etc.
display(Markdown("#### Dataset shape"))
print(dataset_orig_train.features.shape)
display(Markdown("#### Favorable and unfavorable labels"))
print(dataset_orig_train.favorable_label, dataset_orig_train.unfavorable_label)
display(Markdown("#### Protected attribute names"))
print(dataset_orig_train.protected_attribute_names)
display(Markdown("#### Privileged and unprivileged protected attribute values"))
print(dataset_orig_train.privileged_protected_attributes, dataset_orig_train.unprivileged_protected_attributes)
display(Markdown("#### Dataset feature names"))
print(dataset_orig_train.feature_names)
from sklearn.preprocessing import StandardScaler
scale_orig = StandardScaler()
X_train = torch.tensor(scale_orig.fit_transform(dataset_orig_train.features), dtype=torch.float32)
y_train = torch.tensor(dataset_orig_train.labels.ravel(), dtype=torch.float32)
X_valid = torch.tensor(scale_orig.transform(dataset_orig_valid.features), dtype=torch.float32)
y_valid = torch.tensor(dataset_orig_valid.labels.ravel(), dtype=torch.float32)
X_test = torch.tensor(scale_orig.transform(dataset_orig_test.features), dtype=torch.float32)
y_test = torch.tensor(dataset_orig_test.labels.ravel(), dtype=torch.float32)
```
## Deep Learning Model
```
class Model(nn.Module):
def __init__(self, input_size, num_deep=10, hid=32, dropout_p=0.2):
super().__init__()
self.fc0 = nn.Linear(input_size, hid)
self.bn0 = nn.BatchNorm1d(hid)
self.fcs = nn.ModuleList([nn.Linear(hid, hid) for _ in range(num_deep)])
self.bns = nn.ModuleList([nn.BatchNorm1d(hid) for _ in range(num_deep)])
self.out = nn.Linear(hid, 2)
self.dropout = nn.Dropout(dropout_p)
def forward(self, t):
t = self.bn0(self.dropout(F.relu(self.fc0(t))))
for bn, fc in zip(self.bns, self.fcs):
t = bn(self.dropout(F.relu(fc(t))))
return torch.sigmoid(self.out(t))
def trunc_forward(self, t):
t = self.bn0(self.dropout(F.relu(self.fc0(t))))
for bn, fc in zip(self.bns, self.fcs):
t = bn(self.dropout(F.relu(fc(t))))
return t
model = Model(dataset_orig_train.features.shape[1])
loss_fn = torch.nn.BCELoss()
optimizer = optim.Adam(model.parameters())
patience = (math.inf, None, 0)
patience_limit = 4
for epoch in range(201):
model.train()
batch_idxs = torch.split(torch.randperm(X_train.size(0)), 64)
train_loss = 0
for batch in batch_idxs:
X = X_train[batch,:]
y = y_train[batch]
optimizer.zero_grad()
loss = loss_fn(model(X)[:,0], y)
loss.backward()
train_loss += loss.item()
optimizer.step()
if epoch % 10 == 0:
model.eval()
with torch.no_grad():
valid_loss = loss_fn(model(X_valid)[:,0], y_valid)
if valid_loss > patience[0]:
patience = (patience[0], patience[1], patience[2]+1)
else:
patience = (valid_loss, model.state_dict(), 0)
if patience[2] > patience_limit:
print("Ending early, patience limit has been crossed without an increase in validation loss!")
model.load_state_dict(patience[1])
break
print(f'=======> Epoch: {epoch} Train loss: {train_loss / len(batch_idxs)} Valid loss: {valid_loss} Patience valid loss: {patience[0]}')
from sklearn.metrics import roc_curve, roc_auc_score, f1_score, classification_report
model.eval()
with torch.no_grad():
y_valid_hat = model(X_valid)[:,0]
fpr, tpr, thresh = roc_curve(y_valid, y_valid_hat)
roc_auc = roc_auc_score(y_valid, y_valid_hat)
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
x = np.linspace(0,1,1000)
fscore = [f1_score(y_valid, y_valid_hat > i) for i in x]
plt.plot(x, fscore)
plt.show()
best_thresh = x[np.argmax(fscore)]
print(f'Threshold to maximize f1 score is {best_thresh}')
print(classification_report(y_valid, y_valid_hat > best_thresh))
```
## Linear Model (Logistic Regression)
```
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_curve
# Logistic regression classifier and predictions for training data]
lmod = LogisticRegression()
lmod.fit(X_train, y_train)
from sklearn.metrics import roc_curve, roc_auc_score, f1_score
# Prediction probs for validation and testing data
X_valid = torch.tensor(scale_orig.transform(dataset_orig_valid.features), dtype=torch.float32)
y_valid_hat = lmod.predict_proba(X_valid)[:, 1]
y_valid = dataset_orig_valid.labels.ravel()
fpr, tpr, thresh = roc_curve(y_valid, y_valid_hat)
roc_auc = roc_auc_score(y_valid, y_valid_hat)
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
x = np.linspace(0,1,1000)
fscore = [f1_score(y_valid, y_valid_hat > i) for i in x]
plt.plot(x, fscore)
plt.show()
best_thresh = x[np.argmax(fscore)]
print(f'Threshold to maximize f1 score is {best_thresh}')
print(classification_report(y_valid, y_valid_hat > best_thresh))
```
## Random Forest
```
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier()
rf.fit(X_train, y_train)
y_valid_hat = rf.predict_proba(X_valid)[:,1]
fpr, tpr, thresh = roc_curve(y_valid, y_valid_hat)
roc_auc = roc_auc_score(y_valid, y_valid_hat)
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
x = np.linspace(0,1,1000)
fscore = [f1_score(y_valid, y_valid_hat > i) for i in x]
plt.plot(x, fscore)
plt.show()
best_thresh = x[np.argmax(fscore)]
print(f'Threshold to maximize f1 score is {best_thresh}')
print(classification_report(y_valid, y_valid_hat > best_thresh))
```
## Initial Bias
```
from collections import OrderedDict
from aif360.metrics import ClassificationMetric
def compute_metrics(dataset_true, dataset_pred,
unprivileged_groups, privileged_groups,
disp = True):
""" Compute the key metrics """
classified_metric_pred = ClassificationMetric(dataset_true,
dataset_pred,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
metrics = OrderedDict()
metrics["Balanced accuracy"] = 0.5*(classified_metric_pred.true_positive_rate()+
classified_metric_pred.true_negative_rate())
metrics["Statistical parity difference"] = classified_metric_pred.statistical_parity_difference()
metrics["Disparate impact"] = classified_metric_pred.disparate_impact()
metrics["Average odds difference"] = classified_metric_pred.average_odds_difference()
metrics["Equal opportunity difference"] = classified_metric_pred.equal_opportunity_difference()
metrics["Theil index"] = classified_metric_pred.theil_index()
if disp:
for k in metrics:
print("%s = %.4f" % (k, metrics[k]))
return metrics
model.eval()
with torch.no_grad():
dataset_orig_train_pred = dataset_orig_train.copy(deepcopy=True)
dataset_orig_train_pred.scores = model(X_train)[:,0].reshape(-1,1).numpy()
dataset_orig_valid_pred = dataset_orig_valid.copy(deepcopy=True)
dataset_orig_valid_pred.scores = model(X_valid)[:,0].reshape(-1,1).numpy()
dataset_orig_test_pred = dataset_orig_test.copy(deepcopy=True)
dataset_orig_test_pred.scores = model(X_test)[:,0].reshape(-1,1).numpy()
# Transform the validation set
model.eval()
with torch.no_grad():
dataset_transf_valid_pred = dataset_orig_valid.copy(deepcopy=True)
dataset_transf_valid_pred.labels = (model(X_valid)[:,0] > best_thresh).reshape(-1,1).numpy()
display(Markdown("#### Validation set - Initial"))
display(Markdown("##### Transformed predictions"))
metric_valid_aft = compute_metrics(dataset_orig_valid, dataset_transf_valid_pred, unprivileged_groups, privileged_groups)
display(Markdown("##### Classification Report"))
print(classification_report(y_valid, dataset_transf_valid_pred.labels))
```
## Reject Option Classification
```
allowed_metrics = ["Statistical parity difference", "Average odds difference", "Equal opportunity difference"]
from aif360.algorithms.postprocessing.reject_option_classification import RejectOptionClassification
ROC = RejectOptionClassification(unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups,
low_class_thresh=0.01, high_class_thresh=0.99,
num_class_thresh=100, num_ROC_margin=50,
metric_name="Statistical parity difference",
metric_ub=0.05, metric_lb=-0.05)
ROC = ROC.fit(dataset_orig_valid, dataset_orig_valid_pred)
roc_thresh = ROC.classification_threshold
print("Optimal classification threshold (with fairness constraints) = %.4f" % roc_thresh)
print("Optimal ROC margin = %.4f" % ROC.ROC_margin)
# Transform the validation set
dataset_transf_valid_pred = ROC.predict(dataset_orig_valid_pred)
display(Markdown("#### Validation set - With ROC fairness"))
display(Markdown("##### Transformed predictions"))
metric_valid_aft = compute_metrics(dataset_orig_valid, dataset_transf_valid_pred, unprivileged_groups, privileged_groups)
display(Markdown("##### Classification Report"))
print(classification_report(y_valid, dataset_transf_valid_pred.labels))
```
## Calibrated Equalized Odds
```
# Odds equalizing post-processing algorithm
from aif360.algorithms.postprocessing.calibrated_eq_odds_postprocessing import CalibratedEqOddsPostprocessing
from tqdm import tqdm
# cost constraint of fnr will optimize generalized false negative rates, that of
# fpr will optimize generalized false positive rates, and weighted will optimize
# a weighted combination of both
cost_constraint = "fnr" # "fnr", "fpr", "weighted"
randseed=101
# Learn parameters to equalize odds and apply to create a new dataset
cpp = CalibratedEqOddsPostprocessing(privileged_groups = privileged_groups,
unprivileged_groups = unprivileged_groups,
cost_constraint=cost_constraint,
seed=randseed)
cpp = cpp.fit(dataset_orig_valid, dataset_orig_valid_pred)
dataset_transf_valid_pred = cpp.predict(dataset_orig_valid_pred)
display(Markdown("#### Validation sets - With CalibEqOdds fairness"))
display(Markdown("##### Transformed prediction"))
metric_valid_aft = compute_metrics(dataset_orig_valid, dataset_transf_valid_pred, unprivileged_groups, privileged_groups)
display(Markdown("##### Classification Report"))
print(classification_report(y_valid, dataset_transf_valid_pred.labels))
```
## Random
```
# from aif360.algorithms.postprocessing.reject_option_classification import RejectOptionClassification
# ROC = RejectOptionClassification(unprivileged_groups=unprivileged_groups,
# privileged_groups=privileged_groups,
# low_class_thresh=0.01, high_class_thresh=0.99,
# num_class_thresh=100, num_ROC_margin=50,
# metric_name="Statistical parity difference",
# metric_ub=0.05, metric_lb=-0.05)
results = []
for _ in range(50):
rand_model = Model(X_train.size(1))
rand_model.load_state_dict(model.state_dict())
for param in rand_model.parameters():
param.data = param.data * (torch.randn_like(param) + 1)
rand_model.eval()
with torch.no_grad():
dataset_orig_valid_pred = dataset_orig_valid.copy(deepcopy=True)
dataset_orig_valid_pred.scores = rand_model(X_valid)[:,0].reshape(-1,1).numpy()
roc_auc = roc_auc_score(dataset_orig_valid.labels, dataset_orig_valid_pred.scores)
threshs = np.linspace(0,1,101)
fscores = []
for thresh in threshs:
fscores.append(f1_score(dataset_orig_valid.labels, dataset_orig_valid_pred.scores > thresh))
best_rand_thresh = threshs[np.argmax(fscores)]
dataset_orig_valid_pred.labels = dataset_orig_valid_pred.scores > best_rand_thresh
# ROC = ROC.fit(dataset_orig_valid, dataset_orig_valid_pred)
# dataset_transf_valid_pred = ROC.predict(dataset_orig_valid_pred)
classified_metric_pred = ClassificationMetric(dataset_orig_valid, dataset_orig_valid_pred, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups)
spd = classified_metric_pred.statistical_parity_difference()
results.append([roc_auc, spd])
sorted(results)
```
## Critic
```
class Critic(nn.Module):
def __init__(self, sizein, num_deep=3, hid=32):
super().__init__()
self.fc0 = nn.Linear(sizein, hid)
self.fcs = nn.ModuleList([nn.Linear(hid, hid) for _ in range(num_deep)])
self.dropout = nn.Dropout(0.2)
self.out = nn.Linear(hid, 1)
def forward(self, t):
t = t.reshape(1,-1)
t = self.fc0(t)
for fc in self.fcs:
t = F.relu(fc(t))
t = self.dropout(t)
return self.out(t)
truncmodel = Model(X_train.size(1))
truncmodel.load_state_dict(model.state_dict())
critic = Critic(1024)
trunc_optimizer = optim.Adam(truncmodel.parameters())
critic_optimizer = optim.Adam(critic.parameters())
critic_loss_fn = torch.nn.MSELoss()
for epoch in range(51):
for param in critic.parameters():
param.requires_grad = True
for param in truncmodel.parameters():
param.requires_grad = False
truncmodel.eval()
critic.train()
for step in range(201):
critic_optimizer.zero_grad()
indices = torch.randint(0, X_valid.size(0), (32,))
cy_valid = y_valid[indices]
cX_valid = X_valid[indices]
with torch.no_grad():
dataset_orig_valid_pred = dataset_orig_valid.copy(deepcopy=True)
dataset_orig_valid_pred.scores = truncmodel(cX_valid)[:,0].reshape(-1,1).numpy()
classified_metric_pred = ClassificationMetric(dataset_orig_valid, dataset_orig_valid_pred, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups)
spd = classified_metric_pred.statistical_parity_difference()
res = critic(truncmodel.trunc_forward(cX_valid))
loss = critic_loss_fn(torch.tensor(spd), res[0])
loss.backward()
train_loss = loss.item()
critic_optimizer.step()
if step % 100 == 0:
print(f'=======> Epoch: {(epoch, step)} Critic loss: {train_loss}')
for param in critic.parameters():
param.requires_grad = False
for param in truncmodel.parameters():
param.requires_grad = True
truncmodel.train()
critic.eval()
for step in range(101):
trunc_optimizer.zero_grad()
indices = torch.randint(0, X_valid.size(0), (32,))
cy_valid = y_valid[indices]
cX_valid = X_valid[indices]
bias = abs(critic(truncmodel.trunc_forward(cX_valid)))
loss = critic_loss_fn(cy_valid, truncmodel(cX_valid)[:,0])
loss = loss + 2*bias
loss.backward()
train_loss = loss.item()
trunc_optimizer.step()
if step % 100 == 0:
print(f'=======> Epoch: {(epoch, step)} Actor loss: {train_loss}')
with torch.no_grad():
dataset_orig_valid_pred = dataset_orig_valid.copy(deepcopy=True)
dataset_orig_valid_pred.scores = truncmodel(X_valid)[:,0].reshape(-1,1).numpy()
roc_auc = roc_auc_score(dataset_orig_valid.labels, dataset_orig_valid_pred.scores)
threshs = np.linspace(0,1,1001)
fscores = []
for thresh in threshs:
fscores.append(f1_score(dataset_orig_valid.labels, dataset_orig_valid_pred.scores > thresh))
best_rand_thresh = threshs[np.argmax(fscores)]
dataset_orig_valid_pred.labels = dataset_orig_valid_pred.scores > best_rand_thresh
display(Markdown("#### Validation sets - With Critic fairness"))
display(Markdown("##### Transformed prediction"))
metric_valid_aft = compute_metrics(dataset_orig_valid, dataset_orig_valid_pred, unprivileged_groups, privileged_groups)
display(Markdown("##### Classification Report"))
print(classification_report(y_valid, dataset_transf_valid_pred.labels))
from aif360.algorithms.postprocessing.reject_option_classification import RejectOptionClassification
ROC = RejectOptionClassification(unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups,
low_class_thresh=0.01, high_class_thresh=0.99,
num_class_thresh=100, num_ROC_margin=50,
metric_name="Statistical parity difference",
metric_ub=0.05, metric_lb=-0.05)
with torch.no_grad():
dataset_orig_valid_pred = dataset_orig_valid.copy(deepcopy=True)
dataset_orig_valid_pred.scores = truncmodel(X_valid)[:,0].reshape(-1,1).numpy()
ROC = ROC.fit(dataset_orig_valid, dataset_orig_valid_pred)
roc_thresh = ROC.classification_threshold
# Transform the validation set
dataset_transf_valid_pred = ROC.predict(dataset_orig_valid_pred)
display(Markdown("#### Validation set - With Critic + ROC fairness"))
display(Markdown("##### Transformed predictions"))
metric_valid_aft = compute_metrics(dataset_orig_valid, dataset_transf_valid_pred, unprivileged_groups, privileged_groups)
display(Markdown("##### Classification Report"))
print(classification_report(y_valid, dataset_transf_valid_pred.labels))
```
| github_jupyter |
# File: Plots for import analysis
Project: Trade war on labor market\
Author: Xing Xu\
Created in Nov. 2021\
Description: Plots for import tariff exposure\
Industry and county tariff changes are plotted.\
This file uses data from import analysis.\
I thank Professor Kim Ruhl for teaching me how to do choropleths.
```
# Geopandas for Geoplotting
import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
from shapely.geometry import Point
import geopandas
# set directory
import os
os.chdir(r'C:/Users/2xu2/International_trade/data')
```
## Industry import tariff change plot
```
# Data processed from import analysis
industrytariff = pd.read_csv('outputdata/NAICS4_industry_import.csv', index_col = 0)
industrytariff.date = pd.to_datetime(industrytariff.date)
industrytariff.NAICS4 = industrytariff.NAICS4.astype(int)
industrytariff.head()
# first get NAICS4 level industry employment in 2017
NAICS4_industry2017 = industrytariff[(industrytariff['date'] >= pd.Timestamp(2017,1,1))&
(industrytariff['date'] <= pd.Timestamp(2017,12,1))]
NAICS4_emp_2017 = NAICS4_industry2017.groupby('NAICS4')['emplvl'].sum()
NAICS4_emp_2017 = NAICS4_emp_2017.reset_index()
NAICS4_emp_2017['NAICS2'] = NAICS4_emp_2017.NAICS4.astype(str).str[:-2].astype(int)
NAICS4_emp_2017.head()
# get the NAICS2 employment data to calculate the ratio
NAICS2_emp_2017 = NAICS4_industry2017.groupby('NAICS2')['emplvl'].sum().reset_index()
NAICS2_emp_2017 = NAICS2_emp_2017.rename({'emplvl':'emplvlNAICS2'}, axis = 1)
NAICS4_emp_2017 = pd.merge(NAICS4_emp_2017, NAICS2_emp_2017,
how = "left",
left_on = "NAICS2",
right_on = "NAICS2")
NAICS4_emp_2017['emp_ratio_2017'] = NAICS4_emp_2017['emplvl']/NAICS4_emp_2017['emplvlNAICS2']
NAICS4_emp_ratio = NAICS4_emp_2017.drop(['emplvlNAICS2'], axis = 1)
NAICS4_emp_ratio.head()
```
Now let's set it aside and work with our tariff data.\
Get the industry tariff change from Jan, 2018 before trade-war started to Dec, 2019, before phase-one trade deal was active.
```
# Get the industry weighted tariff change from Jan2018 to Dec2019
subsample = industrytariff[(industrytariff['date'] == pd.Timestamp(2018, 1, 1))|
(industrytariff['date'] == pd.Timestamp(2019, 12, 1))]
# Shift to calculate difference in tariff
subsample['tariff2018Jan'] = subsample.groupby('NAICS4')['weighted_tariff'].shift()
# Only keep shifted data to calculate exposure change
subsample = subsample[subsample['date'] == pd.Timestamp(2019, 12, 1)]
subsample['tariffchange'] = subsample['weighted_tariff'] - subsample['tariff2018Jan']
# Keep the desired columns
subsample = subsample[['NAICS4', 'tariffchange']]
# Naics2 industry level
subsample['NAICS2'] = subsample.NAICS4.astype(str).str[:-2]
subsample.NAICS2 = subsample.NAICS2.astype(int)
subsample.head()
# Bring in NAICS2 industry discriptions
# Only contains descriptions of industry with trade
NAICS2description = pd.read_excel('NAICS2_import_description.xlsx', header = 0)
# markers and color for plots
NAICS2description['marker'] = ["v", ".", "h", "*"]
NAICS2description['color'] = ['green', 'orange', 'navy', 'crimson']
NAICS4plot = pd.merge(subsample, NAICS2description,
how = "left",
left_on = "NAICS2",
right_on = "NAICS2").dropna()
NAICS4plot.head( )
# Merge with employment data
NAICS4plot = pd.merge(NAICS4plot, NAICS4_emp_ratio[['NAICS4', 'emplvl', 'emp_ratio_2017']],
how = "left",
left_on = "NAICS4",
right_on = "NAICS4")
NAICS4plot = NAICS4plot.set_index('NAICS2')
NAICS2description = NAICS2description.set_index('NAICS2')
NAICS4plot.head()
NAICS4plot.index.drop_duplicates()
fig, ax = plt.subplots(figsize = (12, 5))
for i in range(0, 45, 5):
ax.axhline(y = i, linestyle = 'dotted', color = 'lightgrey', zorder= 1)
for i in NAICS4plot.index.drop_duplicates():
scale = NAICS4plot.loc[i, 'emp_ratio_2017']*3000
ax.scatter(NAICS4plot.loc[i, 'emplvl']/1000000,
NAICS4plot.loc[i, 'tariffchange'],
s = scale,
marker = NAICS2description.loc[i, 'marker'],
color = NAICS2description.loc[i, 'color'],
label = NAICS2description.loc[i, 'Industry'], zorder = 2)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12),
fancybox=True, shadow=True, ncol=2, fontsize = 10,
markerscale=0.6)
ax.set_xlabel('US industrial employment, 2017 (million)', fontsize = 10, fontweight='bold')
ax.set_ylabel('Change in import tariffs, 2017-2019 (percentage point)', fontsize = 10, fontweight='bold')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.savefig('output_graph/US_industry_import_tariff_change.svg', bbox_inches='tight')
```
## Geoplot for county import exposure change
```
# Data processed from import analysis
countyexposure = pd.read_csv('outputdata/countyexposure_import.csv', index_col = 0)
# We just need the exposurechange for geographic plotting here
# Choose any specific time will do the job
im_exp_change = countyexposure[countyexposure['date'] == '2018-01-01'].drop(['date', 'exposure', 'emplvl', 'group'], axis = 1)
im_exp_change.head()
# Geographic data of US counties from Census Bureau
counties = geopandas.read_file('cb_2018_us_county_500k\cb_2018_us_county_500k.shp')
counties.STATEFP = counties.STATEFP.astype(int)
counties.GEOID = counties.GEOID.astype(int)
# Drop counties outside US mainland to make the plot reasonable
counties = counties.drop(counties.index[counties['STATEFP'].isin([2, 15, 60, 66, 69, 72, 78])])
countyexposurechange = pd.merge(counties, im_exp_change,
how = 'left',
left_on = 'GEOID',
right_on = 'area_fips')
countyexposurechange.head()
fig, gax = plt.subplots(figsize = (40,6))
# Geoplotting
countyexposurechange.plot(ax=gax, edgecolor='white',
column='exposurechange',
legend=True, legend_kwds={'loc': 'lower right'},
cmap='GnBu', scheme='user_defined',
classification_kwds={'bins':[0.1, 0.4, 0.8, 1.2, 2, 4]})
# Basically the bins are chosen by rounded quantiles
gax.set_axis_off()
plt.savefig('output_graph/County_import_tariff_exposure.svg', bbox_inches = 'tight')
quantiles01 = np.linspace(0, 1 ,8)
im_exp_change['exposurechange'].quantile(quantiles01)
quantiles
```
| github_jupyter |
```
import numpy as np
import pandas as pd
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
#from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import GradientBoostingClassifier
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
#time
from datetime import datetime
from datetime import timedelta
import jieba
import jieba.analyse
jieba.set_dictionary('dict.idkrsi.txt') # 改預設字典
jieba.analyse.set_stop_words("stopword.goatwang.kang.txt") #指定stopwords字典
# get data
# ! conda install pandas-datareader s
#import pandas_datareader as pdr
# visual
# ! pip install mpl-finance
#import matplotlib.pyplot as plt
#import mpl_finance as mpf
#import seaborn as sns
# https://github.com/mrjbq7/ta-lib
# ! pip install ta-lib
#import talib
df_bbs = pd.read_csv("bda2019_dataset/bbs2.csv",encoding="utf-8")
df_forum = pd.read_csv("bda2019_dataset/forum2.csv",encoding="utf-8")
df_news = pd.read_csv("bda2019_dataset/news2.csv",encoding="utf-8")
df_news['comment_count']=0
df_article = pd.concat([df_forum, df_bbs, df_news]) #三個合併
del df_bbs, df_forum, df_news
df_article['post_time'] = pd.to_datetime(df_article['post_time'])
df_article['post_time2'] = df_article['post_time'].dt.date # .dt.date用在dataframe .date()用在一個 #只留日期
#df_article['label'] = 'even'
df_article['content'] = df_article['content'].astype(str).str.replace(',' , ' ').str.replace('\n' , ' ').str.replace('"' , ' ').str.replace("'" , ' ')
df_article['title'] = df_article['title'].astype(str).str.replace(',' , ' ').str.replace('\n' , ' ').str.replace('"' , ' ').str.replace("'" , ' ')
df_article = df_article.sort_values(by=['post_time']).reset_index(drop=True) # 用post_time排序 # 在重設index
df_article.head(2)
#df_article2 = df_article[['post_time2','title','content']]
df_TWSE2018 = pd.read_csv("bda2019_dataset/TWSE2018.csv",encoding="utf-8")
df_TWSE2017 = pd.read_csv("bda2019_dataset/TWSE2017.csv",encoding="utf-8")
df_TWSE2016 = pd.read_csv("bda2019_dataset/TWSE2016.csv",encoding="utf-8")
df_TWSE = pd.concat([df_TWSE2016, df_TWSE2017, df_TWSE2018]) #三年合併
del df_TWSE2016, df_TWSE2017, df_TWSE2018
# ['開盤價(元)', '最高價(元)', '最低價(元)', '收盤價(元)', '成交量(千股)', '成交值(千元)', '成交筆數(筆)', '流通在外股數(千股)', '本益比-TSE', '股價淨值比-TSE']
df_TWSE['證券代碼'] = df_TWSE['證券代碼'].astype(str)
df_TWSE['年月日'] = pd.to_datetime(df_TWSE['年月日'])
df_TWSE['開盤價(元)'] = df_TWSE['開盤價(元)'].str.replace(',' , '').astype('float64') # 1,000 to 1000 to float
df_TWSE['最高價(元)'] = df_TWSE['最高價(元)'].str.replace(',' , '').astype('float64')
df_TWSE['最低價(元)'] = df_TWSE['最低價(元)'].str.replace(',' , '').astype('float64')
df_TWSE['收盤價(元)'] = df_TWSE['收盤價(元)'].str.replace(',' , '').astype('float64')
df_TWSE['成交量(千股)'] = df_TWSE['成交量(千股)'].str.replace(',' , '').astype('float64')
df_TWSE['成交值(千元)'] = df_TWSE['成交值(千元)'].str.replace(',' , '').astype('float64')
df_TWSE['成交筆數(筆)'] = df_TWSE['成交筆數(筆)'].str.replace(',' , '').astype('int64')
df_TWSE['流通在外股數(千股)'] = df_TWSE['流通在外股數(千股)'].str.replace(',' , '').astype('float64')
df_TWSE['本益比-TSE'] = df_TWSE['本益比-TSE'].str.replace(',' , '').astype('float64')
df_TWSE['股價淨值比-TSE'] = df_TWSE['股價淨值比-TSE'].astype('float64')
df_TWSE.head(2)
# 選那家股票
#company_name = '國巨'
company_name = '奇力新'
# 文章包含那家字
#company_words = '被動元件|積層陶瓷電容|MLCC|電感|晶片電阻|車用電子|凱美|同欣電|大毅|君耀|普斯|國巨'
company_words = '被動元件|積層陶瓷電容|MLCC|電感|晶片電阻|車用電子|飛磁|旺詮|美磊|美桀|向華科技|奇力新'
# 漲跌幾%
PA = 0.05
# even幾%
PAE = 0.003
# 用日期排序 再把index重排
#2327
#df_trend = df_TWSE[df_TWSE['證券代碼'].str.contains('國巨')].sort_values(by=['年月日']).reset_index(drop=True)
#2456
#df_trend = df_TWSE[df_TWSE['證券代碼'].str.contains('奇力新')].sort_values(by=['年月日']).reset_index(drop=True)
#2478
#df_trend = df_TWSE[df_TWSE['證券代碼'].str.contains('大毅')].sort_values(by=['年月日']).reset_index(drop=True)
#6271
#df_trend = df_TWSE[df_TWSE['證券代碼'].str.contains('同欣電')].sort_values(by=['年月日']).reset_index(drop=True)
df_trend = df_TWSE[df_TWSE['證券代碼'].str.contains(company_name)].sort_values(by=['年月日']).reset_index(drop=True)
del df_TWSE
df_trend.head(2)
##增欄位:fluctuation幅度 tag漲跌平
df_trend['fluctuation'] = 0.0
df_trend['tag']='--'
df_trend['closeshift'] = 0.0
df_trend.head(2)
# ##增欄位:fluctuation幅度 tag漲跌平
# df_trend['fluctuation'] = 0.0
# df_trend['tag']='--'
# ###計算漲跌
# for index, row in df_trend.iterrows():
# try:
# margin =(float(df_trend.loc[index,'收盤價(元)']) - float(df_trend.loc[index-1,'收盤價(元)']) )/ float(df_trend.loc[index-1,'收盤價(元)'])
# df_trend.loc[index,'fluctuation']=margin
# if margin >=0.03:
# df_trend.loc[index,'tag']='up'
# elif margin <= -0.03:
# df_trend.loc[index,'tag']='down'
# else:
# df_trend.loc[index,'tag']='even'
# except:
# continue
df_trend['closeshift'] = df_trend['收盤價(元)'].shift(periods=1)#.fillna(value=0.0, inplace=True)
#df_trend['closeshift'].fillna(value= 0.0, inplace=True)
df_trend.head(2)
df_trend['fluctuation'] = (df_trend['收盤價(元)'] - df_trend['closeshift']) / df_trend['closeshift']
df_trend.head(2)
print('fluctuation std = ',df_trend['fluctuation'].std(axis=0))
print('fluctuation mean = ',df_trend['fluctuation'].mean(axis=0))
df_trend.loc[df_trend['fluctuation'] >= PA, 'tag'] = 'up'
df_trend.loc[df_trend['fluctuation'] <= -PA, 'tag'] = 'down'
df_trend.loc[(df_trend['fluctuation'] >= -PAE) & (df_trend['fluctuation'] <= PAE), 'tag'] = 'even'
df_trend.head(2)
len(df_trend[df_trend['tag']=='up'])
len(df_trend[df_trend['tag']=='down'])
len(df_trend[df_trend['tag']=='even'])
#df_company = df_article[ df_article['content'].str.contains('國巨')] # df 某欄位 string contains "國巨"
#df_company = df_article[ df_article['content'].str.contains('奇力新')]
#df_company = df_article[ df_article['content'].str.contains('大毅')]
#df_company = df_article[ df_article['content'].str.contains('同欣電 ')]
df_company = df_article[ df_article['content'].str.contains(company_words)]
print(len(df_company))
del df_article
df_company.head(2)
stopwords=list()
with open('stopword.goatwang.kang.txt', 'r',encoding='utf-8') as data:
for stopword in data:
stopwords.append(stopword.strip('\n'))
# 'content'全部切詞
corpus = [] # array
for index, row in df_company.iterrows():
not_cut = df_company.loc[index,'content']
# not_cut = row['description'] # 跟上一行一樣意思
seg_generator = jieba.cut(not_cut, cut_all=False) # genarator
seglist = list(seg_generator) # 整篇文章string切出來的list
# seglist = list(filter(lambda a: a not in stopwords and a != '\n', seglist )) #去除停用詞 #未必需要這步驟
corpus.append(' '.join(seglist)) # ' '.join(seg_generator)也可
df_company["content2"]=corpus
df_company.head(2)
df_trend.loc[2,'年月日'].date() + timedelta(days=-1) == df_trend.loc[1,'年月日'].date()
df_trend.loc[5,'年月日'].date() + timedelta(days=-1) == df_trend.loc[4,'年月日'].date()
d = df_trend.loc[1,'年月日'].date() - df_trend.loc[ 1-1 ,'年月日'].date() #相減差幾天
d
d.days #只取天數
int(d.days) #幾天 轉整數
df_trend.loc[3,'年月日'].date()
df_company[ df_company['post_time2'] == df_trend.loc[3,'年月日'].date() ].head() # 某欄位 == n 的 全部撈出來
# # 演算法
# for index, row in df_2327.iterrows():
# try:
# if df_2327.loc[index,'年月日'].date() + timedelta(days=-1) == df_2327.loc[index-1,'年月日'].date():
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-1), 'label'] = df_2327.loc[index,'tag']
# # 如果股票前一筆差1天 # 那前1天的文章標上當天的漲跌
# elif df_2327.loc[index,'年月日'].date() + timedelta(days=-2) == df_2327.loc[index-1,'年月日'].date():
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-1), 'label'] = df_2327.loc[index,'tag']
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-2), 'label'] = df_2327.loc[index,'tag']
# # 如果股票前一筆差2天 #那前2天的文章標上當天的漲跌
# elif df_2327.loc[index,'年月日'].date() + timedelta(days=-3) == df_2327.loc[index-1,'年月日'].date():
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-1), 'label'] = df_2327.loc[index,'tag']
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-2), 'label'] = df_2327.loc[index,'tag']
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-3), 'label'] = df_2327.loc[index,'tag']
# elif df_2327.loc[index,'年月日'].date() + timedelta(days=-4) == df_2327.loc[index-1,'年月日'].date():
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-1), 'label'] = df_2327.loc[index,'tag']
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-2), 'label'] = df_2327.loc[index,'tag']
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-3), 'label'] = df_2327.loc[index,'tag']
# df_forum.loc[df_forum['post_time2'] == df_2327.loc[index,'年月日'].date() + timedelta(days=-4), 'label'] = df_2327.loc[index,'tag']
# except:
# continue
# 看所有相差的天數
# for index, row in df_2327.iterrows():
# try:
# n = df_2327.loc[index,'年月日'].date() - df_2327.loc[index-1,'年月日'].date()
# print(n)
# except:
# continue
# 最多12天
# 如果股票前一筆差n天 # 那前n天的文章標上當天的漲跌
df_company['label5566']='--'
for index, row in df_trend.iterrows():
try:
n = int((df_trend.loc[index,'年月日'].date() - df_trend.loc[index-1,'年月日'].date()).days ) # 差幾個datetime # 轉天數 # 再轉整數
# print(n)
for i in range(1, n+1):
# print(i)
df_company.loc[df_company['post_time2'] == df_trend.loc[index,'年月日'].date() + timedelta(days=-i), 'label5566'] = df_trend.loc[index,'tag']
except:
continue
print(len(df_company[df_company['label5566']=='down']))
df_company[df_company['label5566']=='down'].head(2)
print(len(df_company[df_company['label5566']=='up']))
df_company[df_company['label5566']=='up'].head(2)
print(len(df_company[df_company['label5566']=='even']))
df_company[df_company['label5566']=='even'].head(2)
df_company = df_company[df_company['label5566'].str.contains('up|down|even')]
import re
features = [] # features=list()
with open('finance.words.txt', 'r',encoding='utf-8') as data:
for line in data:
# line = re.sub('[a-zA-Z0-9\W]', '', line) # 把數字英文去掉
line = re.sub('[0-9]', '', line) # 把數字去掉
features.append(line.replace('\n', '').replace(' ', '')) # 空格 \n去掉
print(len(features))
print(type(features))
features[:10]
#df_keyword1 = pd.read_csv("final_higher_tf_idf_part.csv",encoding="utf-8") #上漲形容詞
#df_keyword2 = pd.read_csv("final_lower_tf_idf_part.csv",encoding="utf-8") #下跌形容詞
#df_keyword = pd.concat([df_keyword1,df_keyword2])
#del df_keyword1,df_keyword2
#df_keyword.head()
#features = df_keyword['key'].to_numpy()
#features
from sklearn.feature_extraction.text import TfidfVectorizer
#features = [ '上漲','下跌','看好','走高','走低','漲停','跌停']
#features = features[:1000]
cv = TfidfVectorizer() #預設有空格就一個feature
#cv = TfidfVectorizer(features) # 設定自己要的詞
r = pd.SparseDataFrame(cv.fit_transform(df_company['content2']),
df_company.index,
cv.get_feature_names(),
default_fill_value=0)
r.fillna(value=0.0, inplace=True)
r.head(2)
# from sklearn.feature_extraction.text import CountVectorizer
# #features = [ '上漲','下跌','看好','走高','走低','漲停','跌停']
# #features = features[:1000]
# #cv = CountVectorizer() #預設有空格就一個feature
# cv = CountVectorizer(vocabulary = features) # 設定自己要的詞
# r = pd.SparseDataFrame(cv.fit_transform(df_company['content2']),
# df_company.index,
# cv.get_feature_names(),
# default_fill_value=0)
# r.head(2)
df_company2 = pd.concat([df_company,r], axis=1)
df_company2.head(2)
#df_company2 = df_company2[df_company2['label5566'].str.contains('up|down|even')] #只取漲跌
Y = df_company2['label5566']
X = df_company2.drop(columns=['author','comment_count','content','id','p_type','page_url','post_time','s_area_name','s_name','title','post_time2','content2','label5566'])
X.fillna(value=0.0, inplace=True)
X.head(2)
Y.head(2)
X = X.to_numpy()
Y = Y.to_numpy()
#將X:features array, Y:lable array 都切成 1:4
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed, stratify=Y )
# 設定 stratify = Y 把每個類別平均
print(len(X_train),len(X_validation))
model_RandomForest = RandomForestClassifier()
model_RandomForest.fit(X_train, Y_train)
print(model_RandomForest.score(X_train, Y_train))
predictions = model_RandomForest.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
from lightgbm.sklearn import LGBMClassifier
model_LGBMClassifier = LGBMClassifier()
model_LGBMClassifier.fit(X_train, Y_train)
print(model_LGBMClassifier.score(X_train, Y_train))
predictions = model_LGBMClassifier.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
model_DecisionTree = DecisionTreeClassifier()
model_DecisionTree.fit(X_train, Y_train)
print(model_DecisionTree.score(X_train, Y_train))
predictions = model_DecisionTree.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
model_GaussianNB = GaussianNB()
model_GaussianNB.fit(X_train, Y_train)
print(model_GaussianNB.score(X_train, Y_train))
predictions = model_GaussianNB.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
model_MultinomialNB = MultinomialNB()
model_MultinomialNB.fit(X_train, Y_train)
print(model_MultinomialNB.score(X_train, Y_train) )
predictions = model_MultinomialNB.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
print(model_MultinomialNB.coef_)
# 用10-Fold CV並且列出平均的效率
from sklearn.model_selection import cross_validate
from sklearn.model_selection import RepeatedStratifiedKFold
# 呼叫單個model MLP
model_LogisticRegression = LogisticRegression()
name = 'LogisticRegression'
kfold = model_selection.RepeatedStratifiedKFold(n_splits=5, n_repeats=1, random_state=seed) #分割 10% cross validation
cv_results = model_selection.cross_validate(model_LogisticRegression, X, Y, cv=kfold, scoring='accuracy')
#model用MLP() cross valitation
print(cv_results['test_score'])
print("%s: %f (%f)" % (name, cv_results['test_score'].mean(), cv_results['test_score'].std()))
print(cv_results['train_score'])
print(cv_results['fit_time'])
print(cv_results['score_time'])
model_LogisticRegression = LogisticRegression()
model_LogisticRegression.fit(X_train, Y_train)
print(model_LogisticRegression.score(X_train, Y_train))
predictions = model_LogisticRegression.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
print(model_LogisticRegression.coef_)
# # 用10-Fold CV並且列出平均的效率
# # 呼叫單個model MLP
# model_svclinear = SVC(kernel='linear')
# name = 'SVC'
# kfold = model_selection.KFold(n_splits=5, random_state=seed) #分割 10% cross validation
# cv_results = model_selection.cross_val_score(model_svclinear, X_train, Y_train, cv=kfold, scoring='accuracy')
# #model用MLP() cross valitation
# print(cv_results)
# print("%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()))
# model_svclinear = SVC(kernel='linear')
# model_svclinear.fit(X_train, Y_train)
# print(model_svclinear.score(X_train, Y_train))
# predictions = model_svclinear.predict(X_validation)
# print(accuracy_score(Y_validation, predictions))
# print(confusion_matrix(Y_validation, predictions))
# print(classification_report(Y_validation, predictions))
# print(model_svclinear.coef_)
# 用10-Fold CV並且列出平均的效率
from sklearn.model_selection import cross_validate
from sklearn.model_selection import RepeatedStratifiedKFold
# 呼叫單個model MLP
from sklearn.svm import LinearSVC
model_LinearSVC = LinearSVC()
name = 'LinearSVC'
kfold = model_selection.RepeatedStratifiedKFold(n_splits=5, n_repeats=1, random_state=seed) #分割 10% cross validation
cv_results = model_selection.cross_validate(model_LinearSVC, X, Y, cv=kfold, scoring='accuracy')
#model用MLP() cross valitation
print(cv_results['test_score'])
print("%s: %f (%f)" % (name, cv_results['test_score'].mean(), cv_results['test_score'].std()))
print(cv_results['train_score'])
print(cv_results['fit_time'])
print(cv_results['score_time'])
from sklearn.svm import LinearSVC
model_LinearSVC = LinearSVC()
model_LinearSVC.fit(X_train, Y_train)
print(model_LinearSVC.score(X_train, Y_train))
predictions = model_LinearSVC.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
print(model_LinearSVC.coef_)
from sklearn.linear_model import SGDClassifier
# 用10-Fold CV並且列出平均的效率
# 呼叫單個model MLP
model_SGDClassifier = SGDClassifier(loss='hinge')
#model_SGDClassifier = SGDClassifier(loss='log')
name = 'SVC'
kfold = model_selection.KFold(n_splits=5, random_state=seed) #分割 10% cross validation
cv_results = model_selection.cross_val_score(model_SGDClassifier, X_train, Y_train, cv=kfold, scoring='accuracy')
#model用MLP() cross valitation
print(cv_results)
print("%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()))
from sklearn.linear_model import SGDClassifier
model_SGDClassifier = SGDClassifier(loss='hinge')
model_SGDClassifier.fit(X_train, Y_train)
print(model_SGDClassifier.score(X_train, Y_train))
predictions = model_SGDClassifier.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
print(model_SGDClassifier.coef_)
model_MLP = MLPClassifier(hidden_layer_sizes=(100,), max_iter=200)
model_MLP.fit(X_train, Y_train)
print(model_MLP.score(X_train, Y_train))
predictions = model_MLP.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
#print(model_MLP.coefs_)
# 用10-Fold CV並且列出平均的效率
from sklearn.model_selection import cross_validate
from sklearn.model_selection import RepeatedStratifiedKFold
# 呼叫單個model MLP
model_MLP = MLPClassifier(hidden_layer_sizes=(100, ),max_iter=200)
name = 'MLP'
kfold = model_selection.RepeatedStratifiedKFold(n_splits=5, n_repeats=1, random_state=seed) #分割 10% cross validation
cv_results = model_selection.cross_validate(model_MLP, X, Y, cv=kfold, scoring='accuracy')
#model用MLP() cross valitation
print(cv_results['test_score'])
print("%s: %f (%f)" % (name, cv_results['test_score'].mean(), cv_results['test_score'].std()))
print(cv_results['train_score'])
print(cv_results['fit_time'])
print(cv_results['score_time'])
cv.get_feature_names()[-10:] # 尾巴100個
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
%matplotlib inline
podaci = pd.read_csv(r'C:\Users\kundi\Moji_radovi\import_data\OLS_DataFrame.csv')
podaci.rename(columns={'Weight (Kilograms)' : 'Masa_tereta'}, inplace = True)
podaci.rename(columns={'Freight Cost (USD)' : 'Cijena_transporta'}, inplace = True)
podaci.rename(columns={'Pack Price' : 'Cijena_paketa'}, inplace = True)
podaci
podaci.drop(columns=['Vendor', 'Unit of Measure (Per Pack)', 'Line Item Quantity', 'Line Item Value', 'Unit Price'], inplace = True)
podaci
podaci.Masa_tereta = pd.to_numeric(podaci['Masa_tereta'], errors = 'coerce')
podaci.Cijena_transporta = pd.to_numeric(podaci['Cijena_transporta'], errors='coerce')
podaci['Masa_tereta'].fillna(podaci['Masa_tereta'].mean(), inplace = True)
podaci['Cijena_transporta'].fillna(podaci['Cijena_transporta'].mean(), inplace = True)
podaci
nova_cijena_transporta = []
for i in range(len(podaci['Cijena_transporta'])):
if podaci['Cijena_transporta'][i] >1 and podaci['Cijena_transporta'][i] <80000:
nova_cijena_transporta.append(podaci['Cijena_transporta'][i])
else:
nova_cijena_transporta.append(podaci['Cijena_transporta'].mean())
nova_masa_tereta = []
for i in range(len(podaci['Masa_tereta'])):
if podaci['Masa_tereta'][i] > 1 and podaci['Masa_tereta'][i] < 45000:
nova_masa_tereta.append(podaci['Masa_tereta'][i])
else:
nova_masa_tereta.append(podaci['Masa_tereta'].mean())
podaci.Masa_tereta = nova_masa_tereta
podaci.Cijena_transporta = nova_cijena_transporta
podaci.info()
podaci.describe()
podaci.shape
plt.boxplot(podaci['Cijena_transporta'])
sns.relplot(x = 'Masa_tereta', y = 'Cijena_transporta', data = podaci)
sns.heatmap(podaci.corr(), annot = True)
podaci.columns
mod = podaci.copy()
mod.set_index('Shipment Mode', inplace=True)
mod.head()
air = mod.loc['Air']
aircharter = mod.loc['Air Charter']
truck = mod.loc['Truck']
ship = mod.loc['Ocean']
aircharter
aircharter.plot(kind='scatter', x = 'Masa_tereta' , y= 'Cijena_transporta', color='g', figsize=(15,5))
plt.title('Međuodnos varijabli')
plt.show()
# USPOREDBA DVAJU VARIJABLI IZ SKUPA
aircharter.plot(kind='scatter', x = 'Country' , y= 'Cijena_transporta', color='g',figsize=(15,5))
plt.title('Međuodnos varijabli')
plt.xticks(rotation=90)
plt.show()
X = aircharter['Masa_tereta']
y = aircharter['Cijena_transporta']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=101)
plt.scatter(X_train, y_train, label = 'Treniranje funkcije', color = 'r', alpha=.2)
plt.scatter(X_test, y_test, label = 'Testiranje funkcije', color = 'g', alpha=.2)
plt.legend()
plt.title('Uvježbavanje modela')
plt.show
LR = LinearRegression()
LR.fit(X_train.values.reshape(-1,1), y_train.values)
prediction = LR.predict(X_test.values.reshape(-1,1))
plt.plot(X_test, prediction, label = 'Linearna regresija',)
plt.scatter(X_test, y_test, label = 'Prave vrijednosti', color = 'r', alpha=0.28)
plt.legend()
plt.title('Linearna regresija')
plt.show()
#PREDIKCIJA ZAVISNE VARIJABLE AKO SE UNESE NEZAVISNA
LR.predict(np.array([[8300]]))[0]
#EVALUACIJA USPJEŠNOSTI MODELA
LR.score(X_test.values.reshape(-1,1), y_test.values)
```
| github_jupyter |
# Fastai Callbacks
### Useful links
* [Medium post implementing simple version of callback system](https://medium.com/@edwardeasling/implementing-callbacks-in-fast-ai-1c23de25b6eb)
* [Fastai docs on callbacks](https://docs.fast.ai/callback.html#Callback)
```
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import PIL
PIL.PILLOW_VERSION = PIL.__version__
from fastai.vision import *
from fastai.metrics import error_rate
bs = 512
path = untar_data(URLs.MNIST)
def _inverse_colours(x):
x.data = 1 - x.data
return x
inverse_colours = TfmPixel(_inverse_colours)
tfms = get_transforms(do_flip=False )
tfms = [tfms[0]+ [inverse_colours()], tfms[1]+ [inverse_colours()]]
data = ImageDataBunch.from_folder(
path,
valid_pct=0.1,
ds_tfms=tfms,
size=26,
bs=bs
).normalize(mnist_stats)
data.show_batch()
class PrintCallback(LearnerCallback):
def on_epoch_end(self, iteration: int, num_batch: int, **kwargs):
print('Epoch ended', iteration, num_batch)
class SilenceRecorder(LearnerCallback):
def __post_init__(self):
self.learn.recorder.silent = True
class SimpleRecorder(LearnerCallback):
def on_train_begin(self, **kwargs:Any)->None:
self.losses = []
def on_step_end(self, iteration: int, last_loss, **kwargs ):
self.losses.append(last_loss)
def on_epoch_end(self, last_loss, smooth_loss, **kwarg):
print('Epoch ended', last_loss, smooth_loss)
def on_epoch_end(self, **kwargs):
losses = self.losses
iterations = range(len(losses))
fig, ax = plt.subplots(1,1)
ax.set_ylabel('Loss')
ax.set_xlabel('Iteration')
ax.plot(iterations, losses)
learn = cnn_learner(data,
models.resnet34,
metrics=error_rate,
callback_fns=[
PrintCallback,
# SilenceRecorder,
# ShowGraph
]
)
```
## Multithreading
Access losses during training in main thread
```
import threading
# from iterable_queue import IterableQueue
from functools import partial
from queue import Queue
class IterableQueue(Queue):
_sentinel = object()
def __iter__(self):
return iter(self.get, self._sentinel)
def close(self):
self.put(self._sentinel)
class NewRecorder(Recorder):
def __init__(self, learn:Learner, add_time:bool=True, silent:bool=False, q: IterableQueue=IterableQueue()):
super().__init__(learn, add_time, silent)
self.q = q
def on_epoch_end(self, last_loss, **kwargs):
print(last_loss)
self.q.put(last_loss)
def on_train_end(self, **kwargs):
print('training ended')
# self.q.close()
class MultiThreaded:
def __init__(self, learn: Learner, data:DataBunch, cbs):
self.q = IterableQueue()
self.learn = learn(data,
models.resnet34,
metrics=error_rate,
callback_fns=[partial(NewRecorder, q=self.q)])
def fit(self, epochs: int):
thread = threading.Thread(target=self.learn.fit_one_cycle, args=(epochs,))
thread.start()
def print_items(self):
for item in self.q:
print(item)
multi_threaded_learner = MultiThreaded(cnn_learner, data, [ShowGraph])
multi_threaded_learner.fit(2)
multi_threaded_learner.print_items()
multi_threaded_learner.fit(2)
for i in multi_threaded_learner.q:
print(i)
```
## Reverse fit_one_cylce
Use callbacks to start with high learning rate and small momentum, decrease and then increase lr and do the inverse to momentum. Copied the `OneCycleScheduler` from the [fastai source code](https://github.com/fastai/fastai/blob/master/fastai/callbacks/one_cycle.py#L8) and modified the `on_train_begin` function.
```
class ReverseOneCycleScheduler(LearnerCallback):
"Reverse the learning rate and momentum cycling of the one cycle policy."
def __init__(self, learn:Learner, lr_max:float =0.003, moms:Floats=(0.95,0.85), div_factor:float=25., pct_start:float=0.3,
final_div:float=None, tot_epochs:int=None, start_epoch:int=None):
super().__init__(learn)
self.lr_max,self.div_factor,self.pct_start,self.final_div = lr_max,div_factor,pct_start,final_div
if self.final_div is None: self.final_div = div_factor*1e4
self.moms=tuple(listify(moms,2))
if is_listy(self.lr_max): self.lr_max = np.array(self.lr_max)
self.start_epoch, self.tot_epochs = start_epoch, tot_epochs
def steps(self, *steps_cfg:StartOptEnd):
"Build anneal schedule for all of the parameters."
return [Scheduler(step, n_iter, func=func)
for (step,(n_iter,func)) in zip(steps_cfg, self.phases)]
def on_train_begin(self, n_epochs:int, epoch:int, **kwargs:Any)->None:
"Initialize our optimization params based on our annealing schedule."
res = {'epoch':self.start_epoch} if self.start_epoch is not None else None
self.start_epoch = ifnone(self.start_epoch, epoch)
self.tot_epochs = ifnone(self.tot_epochs, n_epochs)
n = len(self.learn.data.train_dl) * self.tot_epochs
a1 = int(n * self.pct_start)
a2 = n-a1
self.phases = ((a1, annealing_cos), (a2, annealing_cos))
low_lr = self.lr_max/self.div_factor
# Start with maximum lr and go to lowest and back
self.lr_scheds = self.steps(( self.lr_max, low_lr,), (low_lr, self.lr_max))
# Reverse for momentum
self.mom_scheds = self.steps((self.moms[1], self.moms[0]), self.moms)
self.opt = self.learn.opt
self.opt.lr,self.opt.mom = self.lr_scheds[0].start,self.mom_scheds[0].start
self.idx_s = 0
return res
def on_batch_end(self, train, **kwargs:Any)->None:
"Take one step forward on the annealing schedule for the optim params."
if train:
if self.idx_s >= len(self.lr_scheds): return {'stop_training': True, 'stop_epoch': True}
self.opt.lr = self.lr_scheds[self.idx_s].step()
self.opt.mom = self.mom_scheds[self.idx_s].step()
# when the current schedule is complete we move onto the next
# schedule. (in 1-cycle there are two schedules)
if self.lr_scheds[self.idx_s].is_done:
self.idx_s += 1
def on_epoch_end(self, epoch, **kwargs:Any)->None:
"Tell Learner to stop if the cycle is finished."
if epoch > self.tot_epochs: return {'stop_training': True}
reverse_learn = cnn_learner(data,
models.resnet34,
metrics=error_rate,
callback_fns=[ReverseOneCycleScheduler, ShowGraph])
reverse_learn.fit(4)
reverse_learn.recorder.plot_lr(show_moms=True)
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
monthly_data = pd.read_csv('monthly_data_cleaned.csv', index_col = 'date')
monthly_data.index = pd.to_datetime(monthly_data.index)
monthly_data.Commodity = monthly_data.Commodity.str.lower()
monthly_data.head()
```
In order to better understand the task, I'll take one case study (potatoes in Satara) and then generalise a common function for all other clusters of APMC and commodity.
```
satara_potato = monthly_data[(monthly_data.APMC == 'Satara') & (monthly_data.Commodity == 'potato')]
satara_potato.head()
plt.figure(figsize = (15, 5))
plt.plot(satara_potato.modal_price)
```
Let's check for seasonality in this signal
```
import statsmodels.api as sm
from statsmodels.tsa.stattools import acf
decomposition_add = sm.tsa.seasonal_decompose(satara_potato.modal_price, model= 'additive')
decomposition_mult = sm.tsa.seasonal_decompose(satara_potato.modal_price, model= 'multiplicative')
resid_add = decomposition_add.resid
resid_add = resid_add.dropna().values
resid_mult = decomposition_mult.resid
resid_mult = resid_mult.dropna().values
additive_acf = acf(resid_add)
multiplicative_acf = acf(resid_mult)
if additive_acf.all() < multiplicative_acf.all():
season_type = "additive"
else:
season_type = "multiplicative"
print("This is a/an " + season_type + " type seasonality.")
decomposition = sm.tsa.seasonal_decompose(satara_potato.modal_price, model= season_type)
decomposition.plot()
```
Now I'll try to generalise the steps for each APMC-Commodity cluster.
```
def identify_seasonality(apmc, commodity):
timeseries = monthly_data[(monthly_data.APMC == apmc) & (monthly_data.Commodity == commodity)].modal_price
decomposition_add = sm.tsa.seasonal_decompose(timeseries, model= 'additive')
decomposition_mult = sm.tsa.seasonal_decompose(timeseries, model= 'multiplicative')
resid_add = decomposition_add.resid
resid_add = resid_add.dropna().values
resid_mult = decomposition_mult.resid
resid_mult = resid_mult.dropna().values
additive_acf = acf(resid_add)
multiplicative_acf = acf(resid_mult)
if additive_acf.all() < multiplicative_acf.all():
season_type = "additive"
else:
season_type = "multiplicative"
print("This is a/an " + season_type + " type seasonality.")
decomposition = sm.tsa.seasonal_decompose(timeseries, model= season_type)
decomposition.plot()
apmc = input("Enter an APMC: ")
commodity = input("Enter a relevant commodity: ")
identify_seasonality(apmc, commodity)
apmc = input("Enter an APMC: ")
commodity = input("Enter a relevant commodity: ")
identify_seasonality(apmc, commodity)
```
So this is a generalised function which can work for all valid APMC-Commodity clusters. In order to render the deseasonalised signal, I'll have to modify the function a little.
```
def deseasonalise(apmc, commodity):
timeseries = monthly_data[(monthly_data.APMC == apmc) & (monthly_data.Commodity == commodity)].modal_price
decomposition_add = sm.tsa.seasonal_decompose(timeseries, model= 'additive')
decomposition_mult = sm.tsa.seasonal_decompose(timeseries, model= 'multiplicative')
resid_add = decomposition_add.resid
resid_add = resid_add.dropna().values
resid_mult = decomposition_mult.resid
resid_mult = resid_mult.dropna().values
additive_acf = acf(resid_add)
multiplicative_acf = acf(resid_mult)
if additive_acf.all() < multiplicative_acf.all():
season_type = "additive"
else:
season_type = "multiplicative"
print("This is a/an " + season_type + " type seasonality.")
decomposition = sm.tsa.seasonal_decompose(timeseries, model= season_type)
raw = decomposition.observed
deseasonalised = decomposition.trend
return raw, deseasonalised
apmc = input("Enter an APMC: ")
commodity = input("Enter a relevant commodity: ")
raw, deseasonalised = deseasonalise(apmc, commodity)
plt.plot(raw, label = 'raw')
plt.plot(deseasonalised, label = 'deseasonalised')
plt.legend(loc = 'best')
```
So I have created a method to detect the type of seasonality as well as render a deseasonalised output.
Now I need to formulate a method to compare the commodities' MSPs with their raw and deseasonalised prices. MSPs are available in the msp_mandi dataset.
```
msp_mandi = pd.read_csv('msp_mandi.csv', index_col = 'year')
msp_mandi.head()
msp_mandi.commodity = msp_mandi.commodity.str.lower()
msp_mandi.head()
```
Again, to better understand the data, I will take one case study and try to generalise. I'm taking the case of coconuts in Mumbai
```
coconut = msp_mandi[msp_mandi.commodity == 'coconut']
coconut.index = pd.to_datetime(coconut.index, format = '%Y')
coconut
plt.plot(coconut.msprice)
raw, deseasonalised = deseasonalise('Mumbai', 'coconut')
plt.plot(coconut.msprice, label = 'MSP')
plt.plot(raw, label = 'Raw Prices')
plt.plot(deseasonalised, label = 'Deseaonalised Prices')
plt.legend(loc = 'best')
```
This was for a specific case, let's generalise for all APMC-Commodity clusters
```
def compare_prices(apmc, commodity):
msp = msp_mandi[msp_mandi.commodity == commodity]
msp.index = pd.to_datetime(msp.index, format = '%Y')
raw, deseasonalised = deseasonalise(apmc, commodity)
plt.plot(msp.msprice, label = 'MSP')
plt.plot(raw, label = 'Raw Prices')
plt.plot(deseasonalised, label = 'Deseasonalised Prices')
plt.legend(loc = 'best')
apmc = input("Enter any APMC: ")
commodity = input("Enter any relevant commodity: ")
compare_prices(apmc, commodity)
msp_mandi.to_csv('msp_mandi.csv')
monthly_data.to_csv('monthly_data_cleaned.csv')
```
| github_jupyter |
# Simulating Molecules using VQE
In this tutorial, we introduce the Variational Quantum Eigensolver (VQE), motivate its use, explain the necessary theory, and demonstrate its implementation in finding the ground state energy of molecules.
## Contents
1. [Introduction](#introduction)
2. [The Variational Method of Quantum Mechanics](#varmethod)
1. [Mathematical Background](#backgroundmath)
2. [Bounding the Ground State](#groundstate)
3. [The Variational Quantum Eigensolver](#vqe)
1. [Variational Forms](#varforms)
2. [Simple Variational Forms](#simplevarform)
3. [Parameter Optimization](#optimization)
4. [Example with a Single Qubit Variational Form](#example)
5. [Structure of Common Variational Forms](#commonvarforms)
4. [VQE Implementation in Qiskit](#implementation)
1. [Running VQE on a Statevector Simulator](#implementationstatevec)
2. [Running VQE on a Noisy Simulator](#implementationnoisy)
5. [Problems](#problems)
6. [References](#references)
## Introduction<a id='introduction'></a>
In many applications it is important to find the minimum eigenvalue of a matrix. For example, in chemistry, the minimum eigenvalue of a Hermitian matrix characterizing the molecule is the ground state energy of that system. In the future, the quantum phase estimation algorithm may be used to find the minimum eigenvalue. However, its implementation on useful problems requires circuit depths exceeding the limits of hardware available in the NISQ era. Thus, in 2014, Peruzzo *et al.* proposed VQE to estimate the ground state energy of a molecule using much shallower circuits [1].
Formally stated, given a Hermitian matrix $H$ with an unknown minimum eigenvalue $\lambda_{min}$, associated with the eigenstate $|\psi_{min}\rangle$, VQE provides an estimate $\lambda_{\theta}$ bounding $\lambda_{min}$:
\begin{align*}
\lambda_{min} \le \lambda_{\theta} \equiv \langle \psi(\theta) |H|\psi(\theta) \rangle
\end{align*}
where $|\psi(\theta)\rangle$ is the eigenstate associated with $\lambda_{\theta}$. By applying a parameterized circuit, represented by $U(\theta)$, to some arbitrary starting state $|\psi\rangle$, the algorithm obtains an estimate $U(\theta)|\psi\rangle \equiv |\psi(\theta)\rangle$ on $|\psi_{min}\rangle$. The estimate is iteratively optimized by a classical controller changing the parameter $\theta$ minimizing the expectation value of $\langle \psi(\theta) |H|\psi(\theta) \rangle$.
## The Variational Method of Quantum Mechanics<a id='varmethod'></a>
### Mathematical Background<a id='backgroundmath'></a>
VQE is an application of the variational method of quantum mechanics. To better understand the variational method, some preliminary mathematical background is provided. An eigenvector, $|\psi_i\rangle$, of a matrix $A$ is invariant under transformation by $A$ up to a scalar multiplicative constant (the eigenvalue $\lambda_i$). That is,
\begin{align*}
A |\psi_i\rangle = \lambda_i |\psi_i\rangle
\end{align*}
Furthermore, a matrix $H$ is Hermitian when it is equal to its own conjugate transpose.
\begin{align*}
H = H^{\dagger}
\end{align*}
The spectral theorem states that the eigenvalues of a Hermitian matrix must be real. Thus, any eigenvalue of $H$ has the property that $\lambda_i = \lambda_i^*$. As any measurable quantity must be real, Hermitian matrices are suitable for describing the Hamiltonians of quantum systems. Moreover, $H$ may be expressed as
\begin{align*}
H = \sum_{i = 1}^{N} \lambda_i |\psi_i\rangle \langle \psi_i |
\end{align*}
where each $\lambda_i$ is the eigenvalue corresponding to the eigenvector $|\psi_i\rangle$. Furthermore, the expectation value of the observable $H$ on an arbitrary quantum state $|\psi\rangle$ is given by
\begin{align}
\langle H \rangle_{\psi} &\equiv \langle \psi | H | \psi \rangle
\end{align}
Substituting $H$ with its representation as a weighted sum of its eigenvectors,
\begin{align}
\langle H \rangle_{\psi} = \langle \psi | H | \psi \rangle &= \langle \psi | \left(\sum_{i = 1}^{N} \lambda_i |\psi_i\rangle \langle \psi_i |\right) |\psi\rangle\\
&= \sum_{i = 1}^{N} \lambda_i \langle \psi | \psi_i\rangle \langle \psi_i | \psi\rangle \\
&= \sum_{i = 1}^{N} \lambda_i | \langle \psi_i | \psi\rangle |^2
\end{align}
The last equation demonstrates that the expectation value of an observable on any state can be expressed as a linear combination using the eigenvalues associated with $H$ as the weights. Moreover, each of the weights in the linear combination is greater than or equal to 0, as $| \langle \psi_i | \psi\rangle |^2 \ge 0$ and so it is clear that
\begin{align}
\lambda_{min} \le \langle H \rangle_{\psi} = \langle \psi | H | \psi \rangle = \sum_{i = 1}^{N} \lambda_i | \langle \psi_i | \psi\rangle |^2
\end{align}
The above equation is known as the **variational method** (in some texts it is also known as the variational principle) [2]. It is important to note that this implies that the expectation value of any wave function will always be at least the minimum eigenvalue associated with $H$. Moreover, the expectation value of state $|\psi_{min}\rangle$ is given by $\langle \psi_{min}|H|\psi_{min}\rangle = \langle \psi_{min}|\lambda_{min}|\psi_{min}\rangle = \lambda_{min}$. Thus, as expected, $\langle H \rangle_{\psi_{min}}=\lambda_{min}$.
### Bounding the Ground State<a id='groundstate'></a>
When the Hamiltonian of a system is described by the Hermitian matrix $H$ the ground state energy of that system, $E_{gs}$, is the smallest eigenvalue associated with $H$. By arbitrarily selecting a wave function $|\psi \rangle$ (called an *ansatz*) as an initial guess approximating $|\psi_{min}\rangle$, calculating its expectation value, $\langle H \rangle_{\psi}$, and iteratively updating the wave function, arbitrarily tight bounds on the ground state energy of a Hamiltonian may be obtained.
## The Variational Quantum Eigensolver<a id='vqe'></a>
### Variational Forms<a id='varforms'></a>
A systematic approach to varying the ansatz is required to implement the variational method on a quantum computer. VQE does so through the use of a parameterized circuit with a fixed form. Such a circuit is often called a *variational form*, and its action may be represented by the linear transformation $U(\theta)$. A variational form is applied to a starting state $|\psi\rangle$ (such as the vacuum state $|0\rangle$, or the Hartree Fock state) and generates an output state $U(\theta)|\psi\rangle\equiv |\psi(\theta)\rangle$. Iterative optimization over $|\psi(\theta)\rangle$ aims to yield an expectation value $\langle \psi(\theta)|H|\psi(\theta)\rangle \approx E_{gs} \equiv \lambda_{min}$. Ideally, $|\psi(\theta)\rangle$ will be close to $|\psi_{min}\rangle$ (where 'closeness' is characterized by either state fidelity, or Manhattan distance) although in practice, useful bounds on $E_{gs}$ can be obtained even if this is not the case.
Moreover, a fixed variational form with a polynomial number of parameters can only generate transformations to a polynomially sized subspace of all the states in an exponentially sized Hilbert space. Consequently, various variational forms exist. Some, such as Ry and RyRz are heuristically designed, without consideration of the target domain. Others, such as UCCSD, utilize domain specific knowledge to generate close approximations based on the problem's structure. The structure of common variational forms is discussed in greater depth later in this document.
### Simple Variational Forms<a id='simplevarform'></a>
When constructing a variational form we must balance two opposing goals. Ideally, our $n$ qubit variational form would be able to generate any possible state $|\psi\rangle$ where $|\psi\rangle \in \mathbb{C}^N$ and $N=2^n$. However, we would like the variational form to use as few parameters as possible. Here, we aim to give intuition for the construction of variational forms satisfying our first goal, while disregarding the second goal for the sake of simplicity.
Consider the case where $n=1$. The U3 gate takes three parameters, $\theta, \phi$ and $\lambda$, and represents the following transformation:
\begin{align}
U3(\theta, \phi, \lambda) = \begin{pmatrix}\cos(\frac{\theta}{2}) & -e^{i\lambda}\sin(\frac{\theta}{2}) \\ e^{i\phi}\sin(\frac{\theta}{2}) & e^{i\lambda + i\phi}\cos(\frac{\theta}{2}) \end{pmatrix}
\end{align}
Up to a global phase, any possible single qubit transformation may be implemented by appropriately setting these parameters. Consequently, for the single qubit case, a variational form capable of generating any possible state is given by the circuit:

alt="U3 Variational Form"
width="350"/>
Moreover, this universal 'variational form' only has 3 parameters and thus can be efficiently optimized. It is worth emphasising that the ability to generate an arbitrary state ensures that during the optimization process, the variational form does not limit the set of attainable states over which the expectation value of $H$ can be taken. Ideally, this ensures that the minimum expectation value is limited only by the capabilities of the classical optimizer.
A less trivial universal variational form may be derived for the 2 qubit case, where two body interactions, and thus entanglement, must be considered to achieve universality. Based on the work presented by *Shende et al.* [3] the following is an example of a universal parameterized 2 qubit circuit:

alt="Two Qubit Variational Form"
width="800"/>
Allow the transformation performed by the above circuit to be represented by $U(\theta)$. When optimized variationally, the expectation value of $H$ is minimized when $U(\theta)|\psi\rangle \equiv |\psi(\theta)\rangle \approx |\psi_{min}\rangle$. By formulation, $U(\theta)$ may produce a transformation to any possible state, and so this variational form may obtain an arbitrarily tight bound on two qubit ground state energies, only limited by the capabilities of the classical optimizer.
### Parameter Optimization<a id='optimization'></a>
Once an efficiently parameterized variational form has been selected, in accordance with the variational method, its parameters must be optimized to minimize the expectation value of the target Hamiltonian. The parameter optimization process has various challenges. For example, quantum hardware has various types of noise and so objective function evaluation (energy calculation) may not necessarily reflect the true objective function. Additionally, some optimizers perform a number of objective function evaluations dependent on cardinality of the parameter set. An appropriate optimizer should be selected by considering the requirements of a application.
A popular optimization strategy is gradient decent where each parameter is updated in the direction yielding the largest local change in energy. Consequently, the number of evaluations performed depends on the number of optimization parameters present. This allows the algorithm to quickly find a local optimum in the search space. However, this optimization strategy often gets stuck at poor local optima, and is relatively expensive in terms of the number of circuit evaluations performed. While an intuitive optimization strategy, it is not recommended for use in VQE.
An appropriate optimizer for optimizing a noisy objective function is the *Simultaneous Perturbation Stochastic Approximation* optimizer (SPSA). SPSA approximates the gradient of the objective function with only two measurements. It does so by concurrently perturbing all of the parameters in a random fashion, in contrast to gradient decent where each parameter is perturbed independently. When utilizing VQE in either a noisy simulator or on real hardware, SPSA is a recommended as the classical optimizer.
When noise is not present in the cost function evaluation (such as when using VQE with a statevector simulator), a wide variety of classical optimizers may be useful. Two such optimizers supported by Qiskit Aqua are the *Sequential Least Squares Programming* optimizer (SLSQP) and the *Constrained Optimization by Linear Approximation* optimizer (COBYLA). It is worth noting that COBYLA only performs one objective function evaluation per optimization iteration (and thus the number of evaluations is independent of the parameter set's cardinality). Therefore, if the objective function is noise-free and minimizing the number of performed evaluations is desirable, it is recommended to try COBYLA.
### Example with a Single Qubit Variational Form<a id='example'></a>
We will now use the simple single qubit variational form to solve a problem similar to ground state energy estimation. Specifically, we are given a random probability vector $\vec{x}$ and wish to determine a possible parameterization for our single qubit variational form such that it outputs a probability distribution that is close to $\vec{x}$ (where closeness is defined in terms of the Manhattan distance between the two probability vectors).
We first create the random probability vector in python:
```
import numpy as np
np.random.seed(999999)
target_distr = np.random.rand(2)
# We now convert the random vector into a valid probability vector
target_distr /= sum(target_distr)
```
We subsequently create a function that takes the parameters of our single U3 variational form as arguments and returns the corresponding quantum circuit:
```
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def get_var_form(params):
qr = QuantumRegister(1, name="q")
cr = ClassicalRegister(1, name='c')
qc = QuantumCircuit(qr, cr)
qc.u3(params[0], params[1], params[2], qr[0])
qc.measure(qr, cr[0])
return qc
```
Now we specify the objective function which takes as input a list of the variational form's parameters, and returns the cost associated with those parameters:
```
from qiskit import Aer, execute
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
def get_probability_distribution(counts):
output_distr = [v / NUM_SHOTS for v in counts.values()]
if len(output_distr) == 1:
output_distr.append(0)
return output_distr
def objective_function(params):
# Obtain a quantum circuit instance from the paramters
qc = get_var_form(params)
# Execute the quantum circuit to obtain the probability distribution associated with the current parameters
result = execute(qc, backend, shots=NUM_SHOTS).result()
# Obtain the counts for each measured state, and convert those counts into a probability vector
output_distr = get_probability_distribution(result.get_counts(qc))
# Calculate the cost as the distance between the output distribution and the target distribution
cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)])
return cost
```
Finally, we create an instance of the COBYLA optimizer, and run the algorithm. Note that the output varies from run to run. Moreover, while close, the obtained distribution might not be exactly the same as the target distribution, however, increasing the number of shots taken will increase the accuracy of the output.
```
from qiskit.aqua.components.optimizers import COBYLA
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500, tol=0.0001)
# Create the initial parameters (noting that our single qubit variational form has 3 parameters)
params = np.random.rand(3)
ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params)
# Obtain the output distribution using the final parameters
qc = get_var_form(ret[0])
counts = execute(qc, backend, shots=NUM_SHOTS).result().get_counts(qc)
output_distr = get_probability_distribution(counts)
print("Target Distribution:", target_distr)
print("Obtained Distribution:", output_distr)
print("Output Error (Manhattan Distance):", ret[1])
print("Parameters Found:", ret[0])
```
### Structure of Common Variational Forms<a id='commonvarforms'></a>
As already discussed, it is not possible for a polynomially parameterized variational form to generate a transformation to any state. Variational forms can be grouped into two categories, depending on how they deal with this limitation. The first category of variational forms use domain or application specific knowledge to limit the set of possible output states. The second approach uses a heuristic circuit without prior domain or application specific knowledge.
The first category of variational forms exploit characteristics of the problem domain to restrict the set of transformations that may be required. For example, when calculating the ground state energy of a molecule, the number of particles in the system is known *a priori*. Therefore, if a starting state with the correct number of particles is used, by limiting the variational form to only producing particle preserving transformations, the number of parameters required to span the new transformation subspace can be greatly reduced. Indeed, by utilizing similar information from Coupled-Cluster theory, the variational form UCCSD can obtain very accurate results for molecular ground state energy estimation when starting from the Hartree Fock state. Another example illustrating the exploitation of domain-specific knowledge follows from considering the set of circuits realizable on real quantum hardware. Extant quantum computers, such as those based on super conducting qubits, have limited qubit connectivity. That is, it is not possible to implement 2-qubit gates on arbitrary qubit pairs (without inserting swap gates). Thus, variational forms have been constructed for specific quantum computer architectures where the circuits are specifically tuned to maximally exploit the natively available connectivity and gates of a given quantum device. Such a variational form was used in 2017 to successfully implement VQE for the estimation of the ground state energies of molecules as large as BeH$_2$ on an IBM quantum computer [4].
In the second approach, gates are layered such that good approximations on a wide range of states may be obtained. Qiskit Aqua supports three such variational forms: RyRz, Ry and SwapRz (we will only discuss the first two). All of these variational forms accept multiple user-specified configurations. Three essential configurations are the number of qubits in the system, the depth setting, and the entanglement setting. A single layer of a variational form specifies a certain pattern of single qubit rotations and CX gates. The depth setting says how many times the variational form should repeat this pattern. By increasing the depth setting, at the cost of increasing the number of parameters that must be optimized, the set of states the variational form can generate increases. Finally, the entanglement setting selects the configuration, and implicitly the number, of CX gates. For example, when the entanglement setting is linear, CX gates are applied to adjacent qubit pairs in order (and thus $n-1$ CX gates are added per layer). When the entanglement setting is full, a CX gate is applied to each qubit pair in each layer. The circuits for RyRz corresponding to `entanglement="full"` and `entanglement="linear"` can be seen by executing the following code snippet:
```
from qiskit.aqua.components.variational_forms import RYRZ
entanglements = ["linear", "full"]
for entanglement in entanglements:
form = RYRZ(num_qubits=4, depth=1, entanglement=entanglement)
if entanglement == "linear":
print("=============Linear Entanglement:=============")
else:
print("=============Full Entanglement:=============")
# We initialize all parameters to 0 for this demonstration
print(form.construct_circuit([0] * form.num_parameters).draw(fold=100))
print()
```
Assume the depth setting is set to $d$. Then, RyRz has $n\times (d+1)\times 2$ parameters, Ry with linear entanglement has $2n\times(d + \frac{1}{2})$ parameters, and Ry with full entanglement has $d\times n\times \frac{(n + 1)}{2} + n$ parameters.
## VQE Implementation in Qiskit<a id='implementation'></a>
This section illustrates an implementation of VQE using the programmatic approach. Qiskit Aqua also enables a declarative implementation, however, it reveals less information about the underlying algorithm. This code, specifically the preparation of qubit operators, is based on the code found in the Qiskit Tutorials repository (and as of July 2019, may be found at: https://github.com/Qiskit/qiskit-tutorials ).
The following libraries must first be imported.
```
from qiskit.aqua.algorithms import VQE, ExactEigensolver
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
import numpy as np
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.aqua.components.variational_forms import RYRZ
from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP
from qiskit.aqua.operators import Z2Symmetries
from qiskit import IBMQ, BasicAer, Aer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit import IBMQ
from qiskit.aqua import QuantumInstance
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
from qiskit.providers.aer.noise import NoiseModel
```
### Running VQE on a Statevector Simulator<a id='implementationstatevec'></a>
We demonstrate the calculation of the ground state energy for LiH at various interatomic distances. A driver for the molecule must be created at each such distance. Note that in this experiment, to reduce the number of qubits used, we freeze the core and remove two unoccupied orbitals. First, we define a function that takes an interatomic distance and returns the appropriate qubit operator, $H$, as well as some other information about the operator.
```
def get_qubit_op(dist):
driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
freeze_list = [0]
remove_list = [-3, -2]
repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001)
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles)
shift = energy_shift + repulsion_energy
return qubitOp, num_particles, num_spin_orbitals, shift
```
First, the exact ground state energy is calculated using the qubit operator and a classical exact eigensolver. Subsequently, the initial state $|\psi\rangle$ is created, which the VQE instance uses to produce the final ansatz $\min_{\theta}(|\psi(\theta)\rangle)$. The exact result and the VQE result at each interatomic distance is stored. Observe that the result given by `vqe.run(backend)['energy'] + shift` is equivalent the quantity $\min_{\theta}\left(\langle \psi(\theta)|H|\psi(\theta)\rangle\right)$, where the minimum is not necessarily the global minimum.
When initializing the VQE instance with `VQE(qubitOp, var_form, optimizer, 'matrix')` the expectation value of $H$ on $|\psi(\theta)\rangle$ is directly calculated through matrix multiplication. However, when using an actual quantum device, or a true simulator such as the `qasm_simulator` with `VQE(qubitOp, var_form, optimizer, 'paulis')` the calculation of the expectation value is more complicated. A Hamiltonian may be represented as a sum of a Pauli strings, with each Pauli term acting on a qubit as specified by the mapping being used. Each Pauli string has a corresponding circuit appended to the circuit corresponding to $|\psi(\theta)\rangle$. Subsequently, each of these circuits is executed, and all of the results are used to determine the expectation value of $H$ on $|\psi(\theta)\rangle$. In the following example, we initialize the VQE instance with `matrix` mode, and so the expectation value is directly calculated through matrix multiplication.
Note that the following code snippet may take a few minutes to run to completion.
```
backend = BasicAer.get_backend("statevector_simulator")
distances = np.arange(0.5, 4.0, 0.1)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
for dist in distances:
qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist)
result = ExactEigensolver(qubitOp).run()
exact_energies.append(result['energy'] + shift)
initial_state = HartreeFock(
qubitOp.num_qubits,
num_spin_orbitals,
num_particles,
'parity'
)
var_form = UCCSD(
qubitOp.num_qubits,
depth=1,
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initial_state,
qubit_mapping='parity'
)
vqe = VQE(qubitOp, var_form, optimizer)
results = vqe.run(backend)['energy'] + shift
vqe_energies.append(results)
print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", results, "Exact Energy:", exact_energies[-1])
print("All energies have been calculated")
# Note: If you experience BrokenProcessPool error in the next
# chapter, delete this cell and restart the kernel.
# The error is due to a bug in qiskit and is being looked into.
plt.plot(distances, exact_energies, label="Exact Energy")
plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
```
Note that the VQE results are very close to the exact results, and so the exact energy curve is hidden by the VQE curve.
### Running VQE on a Noisy Simulator<a id='implementationnoisy'></a>
Here, we calculate the ground state energy for H$_2$ using a noisy simulator and error mitigation.
First, we prepare the qubit operator representing the molecule's Hamiltonian:
```
driver = PySCFDriver(atom='H .0 .0 -0.3625; H .0 .0 0.3625', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g')
molecule = driver.run()
num_particles = molecule.num_alpha + molecule.num_beta
qubitOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals).mapping(map_type='parity')
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles)
```
Now, we load a device coupling map and noise model from the IBMQ provider and create a quantum instance, enabling error mitigation:
```
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend("qasm_simulator")
device = provider.get_backend("ibmqx2")
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device.properties())
quantum_instance = QuantumInstance(backend=backend, shots=1000,
noise_model=noise_model,
coupling_map=coupling_map,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30,)
```
Finally, we must configure the optimizer, the variational form, and the VQE instance. As the effects of noise increase as the number of two qubit gates circuit depth increase, we use a heuristic variational form (RYRZ) rather than UCCSD as RYRZ has a much shallower circuit than UCCSD and uses substantially fewer two qubit gates.
The following code may take a few minutes to run to completion.
```
exact_solution = ExactEigensolver(qubitOp).run()
print("Exact Result:", exact_solution['energy'])
optimizer = SPSA(max_trials=100)
var_form = RYRZ(qubitOp.num_qubits, depth=1, entanglement="linear")
vqe = VQE(qubitOp, var_form, optimizer=optimizer)
ret = vqe.run(quantum_instance)
print("VQE Result:", ret['energy'])
```
When noise mitigation is enabled, even though the result does not fall within chemical accuracy (defined as being within 0.0016 Hartree of the exact result), it is fairly close to the exact solution.
## Problems<a id='problems'></a>
1. You are given a Hamiltonian $H$ with the promise that its ground state is close to a maximally entangled $n$ qubit state. Explain which variational form (or forms) is likely to efficiently and accurately learn the ground state energy of $H$. You may also answer by creating your own variational form, and explaining why it is appropriate for use with this Hamiltonian.
2. Calculate the number of circuit evaluations performed per optimization iteration, when using the COBYLA optimizer, the `qasm_simulator` with 1000 shots, and a Hamiltonian with 60 Pauli strings.
3. Use VQE to estimate the ground state energy of BeH$_2$ with an interatomic distance of $1.3$Å. You may re-use the function `get_qubit_op(dist)` by replacing `atom="Li .0 .0 .0; H .0 .0 " + str(dist)` with `atom="Be .0 .0 .0; H .0 .0 -" + str(dist) + "; H .0 .0 " + str(dist)` and invoking the function with `get_qubit_op(1.3)`. Note that removing the unoccupied orbitals does not preserve chemical precision for this molecule. However, to get the number of qubits required down to 6 (and thereby allowing efficient simulation on most laptops), the loss of precision is acceptable. While beyond the scope of this exercise, the interested reader may use qubit tapering operations to reduce the number of required qubits to 7, without losing any chemical precision.
## References<a id='references'></a>
1. Peruzzo, Alberto, et al. "A variational eigenvalue solver on a photonic quantum processor." *Nature communications* 5 (2014): 4213.
2. Griffiths, David J., and Darrell F. Schroeter. Introduction to quantum mechanics. *Cambridge University Press*, 2018.
3. Shende, Vivek V., Igor L. Markov, and Stephen S. Bullock. "Minimal universal two-qubit cnot-based circuits." arXiv preprint quant-ph/0308033 (2003).
4. Kandala, Abhinav, et al. "Hardware-efficient variational quantum eigensolver for small molecules and quantum magnets." Nature 549.7671 (2017): 242.
```
import qiskit
qiskit.__qiskit_version__
```
| github_jupyter |
<a href="https://www.kaggle.com/code/hecshzye/russian-invasion-of-ukraine-2022?scriptVersionId=91952099" target="_blank"><img align="left" alt="Kaggle" title="Open in Kaggle" src="https://kaggle.com/static/images/open-in-kaggle.svg"></a>
# Russian Invasion of Ukraine in 2022
## Performing Exploratory Data Analysis on the ongoing invasion of Ukraine by Russia.
## Covering Equipment Losses & Death Toll & Military Wounded & Prisoner of War of Russians in 2022.

*img source: img source: https://twitter.com/MarcHorat
# Covering
* Equipment Losses
* Death Toll
* Military Wounded.
* Prisoner of War of Russian.
# Dataset
* Main data sources are Armed Forces of Ukraine and Ministry of Defence of Ukraine.
* They gathered data from different points of the country.
* The calculation is complicated by the high intensity of hostilities.
# Sources
* **invaders** - All Russians Prisoner of War (POW).
* **oryxspioenkop** - Ukraine and Russia Equipment Losses. This list only includes destroyed vehicles and equipment of which photo or videographic evidence is available. Therefore, the amount of equipment destroyed is significantly higher than recorded here.
* **liveuamap** - Live Interactive Map with events that happened.
* **Correctiv** - Live monitoring of all sanctions against Russia.
* **Reuters** - Tracking sanctions against Russia.
# Data Dictionary
**Tracking**
* Personnel
* Prisoner of War
* Armored Personnel Carrier
* Multiple Rocket Launcher
* Aircraft
* Anti-aircraft warfare
* Drone
* Field Artillery
* Fuel Tank
* Helicopter
* Military Auto
* Naval Ship
* Tank
**Acronyms**
* POW - Prisoner of War,
* MRL - Multiple Rocket Launcher,
* BUK - Buk Missile System,
* APC - Armored Personnel Carrier,
* drone: UAV - Unmanned Aerial Vehicle, RPA - Remotely Piloted Vehicle.
# Note:
* Each new record is accumulated data from previous days.
* Important. Data will be updated daily
* Notebook & Dataset last updated: 2022/03/22
```
# Import libraries
# Standard
import os
import datetime
import random
import io
from math import sqrt
import pandas as pd
import numpy as np
from sklearn import*
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import OneHotEncoder
# Plots
import matplotlib as plt
%matplotlib inline
import seaborn as sns
import plotly
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots
from plotly.subplots import make_subplots
# Import data
df_pers_rus_loss = pd.read_csv("../input/2022-ukraine-russian-war/russia_losses_personnel.csv")
df_equip_rus_loss = pd.read_csv("../input/2022-ukraine-russian-war/russia_losses_equipment.csv")
# Checking Personnel Losses
df_pers_rus_loss.head(20)
# Checking Equipment Losses
df_equip_rus_loss.head(20)
# More details
print("Shape of df_pers_rus_loss (Personnel): ", df_pers_rus_loss.shape)
print("Length of df_pers_russ_loss (Personnel): ", len(df_pers_rus_loss))
print("\nShape of df_equip_rus_loss (Equipment): ", df_equip_rus_loss.shape)
print("Length of df_equip_rus_loss (Equipment): ", len(df_equip_rus_loss))
df_pers_rus_loss.isnull().sum()
df_equip_rus_loss.isnull().sum()
# Cleaning
# Column "Personnel*" doesn't provide any useful information
#df_pers_rus_loss_2 = df_pers_rus_loss.drop("personnel*", axis=1, inplace=True) # Drop column "Personnel*"
# Column "special equipment" has 19 null values
#df_equip_rus_loss_2 = df_equip_rus_loss.iloc[: , :-1] # Drop column "special equipment"
# Plotting Personnel Losses
x, y = df_pers_rus_loss['date'], df_pers_rus_loss['personnel']
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y,
mode='lines+markers',
name='lines+markers'))
fig.show()
```
Plot showing the number of personnel losses from February to March 2022
```
# Plotting equipment losses
x = df_equip_rus_loss['date']
y1 = df_equip_rus_loss['aircraft']
y2 = df_equip_rus_loss['helicopter']
y3 = df_equip_rus_loss['anti-aircraft warfare']
y4 = df_equip_rus_loss['drone']
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y1,
mode='lines+markers',
name='Aircraft'))
fig.add_trace(go.Scatter(x=x, y=y2,
mode='lines+markers',
name='Helicopter'))
fig.add_trace(go.Scatter(x=x, y=y3,
mode='lines+markers',
name='Anti-Aircraft Warfare'))
fig.add_trace(go.Scatter(x=x, y=y4,
mode='lines+markers',
name='Drone'))
fig.update_layout(legend_orientation="h",
legend=dict(x=0, y=1, traceorder="normal"),
title="Weapons: Air",
xaxis_title="Date",
yaxis_title="Weapons")
fig.show()
```
The number of equipment losses in Air
```
# Equipment losses on Ground
x = df_equip_rus_loss['date']
y1 = df_equip_rus_loss['tank']
y2 = df_equip_rus_loss['field artillery']
y3 = df_equip_rus_loss['APC']
y4 = df_equip_rus_loss['military auto']
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y1,
mode='lines+markers',
name='Tank'))
fig.add_trace(go.Scatter(x=x, y=y2,
mode='lines+markers',
name='Field artillery'))
fig.add_trace(go.Scatter(x=x, y=y3,
mode='lines+markers',
name='APC'))
fig.add_trace(go.Scatter(x=x, y=y4,
mode='lines+markers',
name='Military auto'))
fig.update_layout(legend_orientation="h",
legend=dict(x=0, y=1, traceorder="normal"),
title="Weapons: Ground, Other",
xaxis_title="Date",
yaxis_title="Weapons")
fig.show()
```
The number of equipment losses on Ground
Distribution of Personnel losses in a PIE
```
# Pie plot describing the personnel losses
personnel = df_pers_rus_loss[['personnel', 'POW']]
df_pers_rus_loss_total = personnel.sum(axis=0)[0:]
fig = go.Figure(data=[go.Pie(labels=df_pers_rus_loss_total.keys(), values=df_pers_rus_loss_total.values, hole=0.4,
insidetextorientation='radial',
)])
fig.update_layout(title='Personnel losses', font_size=16, title_x=0.45, annotations=[dict(text='personnel', font_size=20, showarrow=False, height=800, width=700)])
fig.update_traces(textfont_size=15, textinfo='percent')
fig.show()
# Pie plot describing the equipment losses in air
air = df_equip_rus_loss[['aircraft','helicopter', 'drone']]
df_equip_rus_loss_total = air.sum(axis=0)
fig = go.Figure(data=[go.Pie(labels=df_equip_rus_loss_total.keys(), values=df_equip_rus_loss_total.values, hole=0.3,
insidetextorientation='radial',
)])
fig.update_layout(title='Lost Weapons in Air',font_size=15,title_x=0.45,annotations=[dict(text='Air',font_size=20, showarrow=False,height=800,width=700)])
fig.update_traces(textfont_size=15,textinfo='percent')
fig.show()
# Plot for land weapon losses
land = df_equip_rus_loss[['tank','APC', 'field artillery', 'MRL', 'military auto', 'fuel tank', 'anti-aircraft warfare','special equipment']]
df_equip_rus_loss_total = land.sum(axis=0)
fig = go.Figure(data=[go.Pie(labels=df_equip_rus_loss_total.keys(), values=df_equip_rus_loss_total.values,hole=0.35,
insidetextorientation='radial',
)])
fig.update_layout(title='Lost Weapons on Ground',font_size=15,title_x=0.45,annotations=[dict(text='land',font_size=20, showarrow=False,height=800,width=700)])
fig.update_traces(textfont_size=15,textinfo='percent')
fig.show()
```
| github_jupyter |
```
import sys
import numpy as np
import h5py
from plottr.data import datadict as dd
from plottr.data import datadict_storage as dds
```
# Simple timing for writing/reading a datadict
## Write
```
FN = './ddh5_test-1'
%%timeit
nrows = 10000
x = np.arange(nrows, dtype=np.float)
y = np.repeat(np.linspace(0., 1., 1001).reshape(1, -1), nrows, 0)
z = np.arange(y.size, dtype=np.float).reshape(y.shape)
# print(f"total size = {(x.nbytes + y.nbytes + z.nbytes) * 1e-6} MB")
data = dd.DataDict(
x=dict(values=x, unit='nA'),
y=dict(values=y, unit='nB'),
z=dict(values=z, unit='nC', axes=['x', 'y']),
)
if not data.validate():
raise ValueError
dds.datadict_to_hdf5(data, FN)
```
## Read back
```
%%timeit
ret_data = dds.datadict_from_hdf5(FN)
size = sum([ret_data.data_vals(k).nbytes for k in ['x', 'y', 'z']]) * 1e-6
# print(f"total size = {size} MB")
```
## Appending row by row
```
FN = './ddh5_test-2'
nrows = 100
%%timeit
x = np.array([0.])
y = np.linspace(0., 1., 1001).reshape(1, -1)
z = np.arange(y.size, dtype=np.float).reshape(y.shape)
data = dd.DataDict(
x=dict(values=x, unit='nA'),
y=dict(values=y, unit='nB'),
z=dict(values=z, unit='nC', axes=['x', 'y']),
)
dds.datadict_to_hdf5(data, FN, append_mode=dds.AppendMode.none)
for n in range(nrows):
data = dd.DataDict(
x=dict(values=np.array([n+1], dtype=np.float), unit='nA'),
y=dict(values=y, unit='nB'),
z=dict(values=z, unit='nC', axes=['x', 'y']),
)
dds.datadict_to_hdf5(data, FN, append_mode=dds.AppendMode.all)
```
It's important to note that the bulk of this time is just for opening the files. Below we can see that opening the HDF5 file in append mode takes us around 3 ms.
```
%%timeit
with h5py.File(FN+'.dd.h5', 'a') as f:
# just do something of no effect.
dsets = list(f['data'].keys())
```
# Bare HDF5 benchmarking
## appending row by row, resize every time
```
%%timeit
FN = './hdf5_test.h5'
nrows = 100
x = np.array([0.])
y = np.linspace(0., 1., 1001).reshape(1, -1)
z = np.arange(y.size, dtype=np.float).reshape(y.shape)
with h5py.File(FN, 'w', libver='latest') as f:
grp = f.create_group('data')
for dn, d in ('x', x), ('y', y), ('z', z):
grp.create_dataset(dn, maxshape=tuple([None] + list(d.shape[1:])), data=d)
for n in range(nrows):
with h5py.File(FN, 'a', libver='latest') as f:
grp = f['data']
for dn, d in ('x', x), ('y', y), ('z', z):
ds = grp[dn]
ds.resize(tuple([ds.shape[0]+1] + list(ds.shape[1:])))
ds[-1:] = d
ds.flush()
f.flush()
```
| github_jupyter |
# Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebook, you'll be using [VGGNet](https://arxiv.org/pdf/1409.1556.pdf) trained on the [ImageNet dataset](http://www.image-net.org/) as a feature extractor. Below is a diagram of the VGGNet architecture.
<img src="assets/cnnarchitecture.jpg" width=700px>
VGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.
You can read more about transfer learning from [the CS231n course notes](http://cs231n.github.io/transfer-learning/#tf).
## Pretrained VGGNet
We'll be using a pretrained network from https://github.com/machrisaa/tensorflow-vgg. Make sure to clone this repository to the directory you're working from. You'll also want to rename it so it has an underscore instead of a dash.
```
git clone https://github.com/machrisaa/tensorflow-vgg.git tensorflow_vgg
```
This is a really nice implementation of VGGNet, quite easy to work with. The network has already been trained and the parameters are available from this link. **You'll need to clone the repo into the folder containing this notebook.** Then download the parameter file using the next cell.
```
!pip install tqdm
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile(vgg_dir + "vgg16.npy"):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='VGG16 Parameters') as pbar:
urlretrieve(
'https://s3.amazonaws.com/content.udacity-data.com/nd101/vgg16.npy',
vgg_dir + 'vgg16.npy',
pbar.hook)
else:
print("Parameter file already exists!")
```
## Flower power
Here we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the [TensorFlow inception tutorial](https://www.tensorflow.org/tutorials/image_retraining).
```
import tarfile
dataset_folder_path = 'flower_photos'
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile('flower_photos.tar.gz'):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Flowers Dataset') as pbar:
urlretrieve(
'http://download.tensorflow.org/example_images/flower_photos.tgz',
'flower_photos.tar.gz',
pbar.hook)
if not isdir(dataset_folder_path):
with tarfile.open('flower_photos.tar.gz') as tar:
tar.extractall()
tar.close()
```
## ConvNet Codes
Below, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.
Here we're using the `vgg16` module from `tensorflow_vgg`. The network takes images of size $224 \times 224 \times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from [the source code](https://github.com/machrisaa/tensorflow-vgg/blob/master/vgg16.py)):
```
self.conv1_1 = self.conv_layer(bgr, "conv1_1")
self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")
self.pool1 = self.max_pool(self.conv1_2, 'pool1')
self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")
self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")
self.pool2 = self.max_pool(self.conv2_2, 'pool2')
self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")
self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")
self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")
self.pool3 = self.max_pool(self.conv3_3, 'pool3')
self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")
self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")
self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")
self.pool4 = self.max_pool(self.conv4_3, 'pool4')
self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")
self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")
self.pool5 = self.max_pool(self.conv5_3, 'pool5')
self.fc6 = self.fc_layer(self.pool5, "fc6")
self.relu6 = tf.nn.relu(self.fc6)
```
So what we want are the values of the first fully connected layer, after being ReLUd (`self.relu6`). To build the network, we use
```
with tf.Session() as sess:
vgg = vgg16.Vgg16()
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
with tf.name_scope("content_vgg"):
vgg.build(input_)
```
This creates the `vgg` object, then builds the graph with `vgg.build(input_)`. Then to get the values from the layer,
```
feed_dict = {input_: images}
codes = sess.run(vgg.relu6, feed_dict=feed_dict)
```
```
!pip install scikit-image
import os
import numpy as np
import tensorflow as tf
from tensorflow_vgg import vgg16
from tensorflow_vgg import utils
data_dir = 'flower_photos/'
contents = os.listdir(data_dir)
classes = [each for each in contents if os.path.isdir(data_dir + each)]
```
Below I'm running images through the VGG network in batches.
> **Exercise:** Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).
```
# Set the batch size higher if you can fit in in your GPU memory
batch_size = 10
codes_list = []
labels = []
batch = []
codes = None
with tf.Session() as sess:
# TODO: Build the vgg network here
vgg = vgg16.Vgg16()
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
with tf.name_scope("content_vgg"):
vgg.build(input_)
for each in classes:
print("Starting {} images".format(each))
class_path = data_dir + each
files = os.listdir(class_path)
for ii, file in enumerate(files, 1):
# Add images to the current batch
# utils.load_image crops the input images for us, from the center
img = utils.load_image(os.path.join(class_path, file))
batch.append(img.reshape((1, 224, 224, 3)))
labels.append(each)
# Running the batch through the network to get the codes
if ii % batch_size == 0 or ii == len(files):
# Image batch to pass to VGG network
images = np.concatenate(batch)
# TODO: Get the values from the relu6 layer of the VGG network
feed_dict = {input_: images}
codes_batch = sess.run(vgg.relu6, feed_dict=feed_dict)
# Here I'm building an array of the codes
if codes is None:
codes = codes_batch
else:
codes = np.concatenate((codes, codes_batch))
# Reset to start building the next batch
batch = []
print('{} images processed'.format(ii))
# write codes to file
with open('codes', 'w') as f:
codes.tofile(f)
# write labels to file
import csv
with open('labels', 'w') as f:
writer = csv.writer(f, delimiter='\n')
writer.writerow(labels)
#Test
print(labels[:10])
print(codes[:10])
print(codes.shape)
```
## Building the Classifier
Now that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
```
# read codes and labels from file
import csv
with open('labels') as f:
reader = csv.reader(f, delimiter='\n')
labels = np.array([each for each in reader if len(each) > 0]).squeeze()
with open('codes') as f:
codes = np.fromfile(f, dtype=np.float32)
codes = codes.reshape((len(labels), -1))
#Test
print(labels[:10])
print(codes[:10])
print(codes.shape)
```
### Data prep
As usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!
> **Exercise:** From scikit-learn, use [LabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html) to create one-hot encoded vectors from the labels.
```
from sklearn import preprocessing
label_binarizer = preprocessing.LabelBinarizer()
label_binarizer.fit(classes)
labels_vecs = label_binarizer.transform(labels) # Your one-hot encoded labels array here
#Test
label_binarizer.classes_
print(labels_vecs[:5])
```
Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use [`StratifiedShuffleSplit`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) from scikit-learn.
You can create the splitter like so:
```
ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)
```
Then split the data with
```
splitter = ss.split(x, y)
```
`ss.split` returns a generator of indices. You can pass the indices into the arrays to get the split sets. The fact that it's a generator means you either need to iterate over it, or use `next(splitter)` to get the indices. Be sure to read the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) and the [user guide](http://scikit-learn.org/stable/modules/cross_validation.html#random-permutations-cross-validation-a-k-a-shuffle-split).
> **Exercise:** Use StratifiedShuffleSplit to split the codes and labels into training, validation, and test sets.
```
from sklearn.model_selection import StratifiedShuffleSplit
#shufflesplitter for train and test(valid)
shuffle_train_test = StratifiedShuffleSplit(n_splits=1, test_size=0.2)
shuffle_test_valid = StratifiedShuffleSplit(n_splits=1, test_size=0.5)
train_index, test_valid_index = next(shuffle_train_test.split(codes, labels_vecs))
test_index, valid_index = next(shuffle_test_valid.split(codes[test_valid_index], labels_vecs[test_valid_index]))
train_x, train_y = codes[train_index], labels_vecs[train_index]
val_x, val_y = codes[valid_index], labels_vecs[valid_index]
test_x, test_y = codes[test_index], labels_vecs[test_index]
print("Train shapes (x, y):", train_x.shape, train_y.shape)
print("Validation shapes (x, y):", val_x.shape, val_y.shape)
print("Test shapes (x, y):", test_x.shape, test_y.shape)
```
If you did it right, you should see these sizes for the training sets:
```
Train shapes (x, y): (2936, 4096) (2936, 5)
Validation shapes (x, y): (367, 4096) (367, 5)
Test shapes (x, y): (367, 4096) (367, 5)
```
### Classifier layers
Once you have the convolutional codes, you just need to build a classfier from some fully connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.
> **Exercise:** With the codes and labels loaded, build the classifier. Consider the codes as your inputs, each of them are 4096D vectors. You'll want to use a hidden layer and an output layer as your classifier. Remember that the output layer needs to have one unit for each class and a softmax activation function. Use the cross entropy to calculate the cost.
```
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])
labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])
# TODO: Classifier layers and operations
fully_layer = tf.contrib.layers.fully_connected(inputs=inputs_,\
num_outputs=256,\
weights_initializer=tf.truncated_normal_initializer(stddev=0.1))
logits = tf.contrib.layers.fully_connected(inputs=fully_layer,\
num_outputs=len(classes),\
activation_fn=None,\
weights_initializer=tf.truncated_normal_initializer(stddev=0.1))
# output layer logits
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels_, logits=logits)) # cross entropy loss
optimizer = tf.train.AdamOptimizer().minimize(cost) # training optimizer
# Operations for validation/test accuracy
predicted = tf.nn.softmax(logits)
correct_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
```
### Batches!
Here is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.
```
def get_batches(x, y, n_batches=10):
""" Return a generator that yields batches from arrays x and y. """
batch_size = len(x)//n_batches
for ii in range(0, n_batches*batch_size, batch_size):
# If we're not on the last batch, grab data with size batch_size
if ii != (n_batches-1)*batch_size:
X, Y = x[ii: ii+batch_size], y[ii: ii+batch_size]
# On the last batch, grab the rest of the data
else:
X, Y = x[ii:], y[ii:]
# I love generators
yield X, Y
```
### Training
Here, we'll train the network.
> **Exercise:** So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the `get_batches` function I wrote before to get your batches like `for x, y in get_batches(train_x, train_y)`. Or write your own!
```
epochs = 5
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# TODO: Your training code here
for epoch in range(epochs):
for x, y in get_batches(train_x, train_y):
loss, _ = sess.run([cost,optimizer], feed_dict={inputs_: x, labels_: y})
#if epoch % 5 == 0:
val_accuracy = sess.run(accuracy, feed_dict={inputs_: val_x, labels_: val_y})
print("Epoch: {:>3}, Training Loss: {:.5f}, Validation Accuracy: {:.4f}".format(epoch+1, loss, val_accuracy))
saver.save(sess, "checkpoints/flowers.ckpt")
```
### Testing
Below you see the test accuracy. You can also see the predictions returned for images.
```
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
feed = {inputs_: test_x,
labels_: test_y}
test_acc = sess.run(accuracy, feed_dict=feed)
print("Test accuracy: {:.4f}".format(test_acc))
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.ndimage import imread
```
Below, feel free to choose images and see how the trained classifier predicts the flowers in them.
```
test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg'
test_img = imread(test_img_path)
plt.imshow(test_img)
# Run this cell if you don't have a vgg graph built
if 'vgg' in globals():
print('"vgg" object already exists. Will not create again.')
else:
#create vgg
with tf.Session() as sess:
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
vgg = vgg16.Vgg16()
vgg.build(input_)
with tf.Session() as sess:
img = utils.load_image(test_img_path)
img = img.reshape((1, 224, 224, 3))
feed_dict = {input_: img}
code = sess.run(vgg.relu6, feed_dict=feed_dict)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
feed = {inputs_: code}
prediction = sess.run(predicted, feed_dict=feed).squeeze()
plt.imshow(test_img)
plt.barh(np.arange(5), prediction)
_ = plt.yticks(np.arange(5), label_binarizer.classes_)
```
| github_jupyter |
## Pyro code for examples in MBML book by John Winn
#### Based on version 0.7 of the early access version (www.mbmlbook.com)
Implementation and testing of ideas from the book
```
import matplotlib.pyplot as plt
import numpy as np
import torch
import pyro
import pyro.infer
import pyro.optim
import pyro.distributions as dist
from pyro import param
from pyro.poutine import trace
from pyro import condition
from pyro.optim import Adam, ClippedAdam
from pyro.infer import SVI, Trace_ELBO
from pyro.contrib.autoguide import AutoDiagonalNormal, AutoMultivariateNormal, AutoContinuous
from torch import tensor
from pprint import pprint
import pandas as pd
import matplotlib.pyplot as plt
from os.path import join, exists, basename
display('pyro version: {}'.format(pyro.__version__))
pyro.set_rng_seed(101)
```
# Some warmup exercises to understand distributions
#### Page 17, bullet 4
Define a Bernoulli distribution with a probability estimate of 0.3, then look at frequency of True/False in this disribution
```
murderer = dist.Bernoulli(0.3)
print('num True:', int(sum([pyro.sample('murderer', murderer) for s in range(100)])))
```
#### Page 23, bullet 3
Make the probability of being late conditioned on whether traffic is good or bad
```
late = {'bad':dist.Bernoulli(0.5), 'good':dist.Bernoulli(0.05)}
print('late in bad traffic:', int(sum([pyro.sample('bad', late['bad']) for s in range(100)])),
'late in good traffic:', int(sum([pyro.sample('good', late['good']) for s in range(100)])))
```
#### Page 31, bullet 4
Print out 1000 joint samples of both variables
```
late = {'bad':dist.Bernoulli(0.5), 'good':dist.Bernoulli(0.05)}
print('bad traffic and late', int(sum([pyro.sample('badlate', late['bad']) for s in range(1000)])))
print('bad traffic and on time', 1000-int(sum([pyro.sample('badontime', late['bad']) for s in range(1000)])))
print('good traffic and late', int(sum([pyro.sample('goodlate', late['good']) for s in range(1000)])))
print('good traffic and on time', 1000-int(sum([pyro.sample('goodontime', late['good']) for s in range(1000)])))
```
# Chapter 1
## A murder mystery
#### Pages 13-46
<img src="images/house.png" width="250"/>
**Problem statement:** Mr Black lies dead on the floor. The two murder suspects are Miss Auburn and Major Grey. There are two possible murder weapons, a revolver and a knife. Finally, a grey hair is found and this could either have been dropped by Grey if he is the killer or it could have placed by Auburn if she is the killer. The goal of this problem is to incorporate evidence and update beliefs regarding who the killer might be.
\
**Prior:** Initial suspicion is toward Miss Auburn with a probability of 70%, giving:
\begin{align}
P(murderer=Auburn)=0.7 \\
P(murderer=Grey)=0.3
\end{align}
\
**Weapon:** There are two possible murder weapons, a revolver and a dagger. The probabilities of each being used is conditional on the killer, giving:
\begin{align}
P(weapon=revolver|murderer=Auburn)=0.2 \\
P(weapon=knife|murderer=Auburn)=0.8 \\
P(weapon=revolver|murderer=Grey)=0.9 \\
P(weapon=knife|murderer=Grey)=0.1
\end{align}
\
**Hair:** A hair is found at the crime scene. Indicating Major Grey. However it could also have been planted by Auburn. We think there is a 50% chance that Grey would drop the hair if he is the killer, but only a 5% chance that Auburn would think to plant a grey hair in the crime scene.
\begin{align}
P(hair=true|murderer=Auburn)=0.05 \\
P(hair=false|murderer=Auburn)=0.95 \\
P(hair=true|murderer=Grey)=0.5 \\
P(hair=false|murderer=Grey)=0.5
\end{align}
**Factor graph:**
<img src="images/chapter_1.png" width="250"/>
```
# build murder mystery model
murderer_dict = {0:'Grey', 1:'Auburn'}
weapon_dict = {0:'Knife', 1:'Revolver'}
hair_dict = {0:'Not found', 1:'Found'}
def murder_case():
'''
The murder case model. Weapon and hair
conditional on the murderer.
'''
# probability of murderer (0 is Grey and 1 is Auburn)
murderer = pyro.sample('murderer', dist.Bernoulli(0.7)).item()
# probability of weapon conditional on murderer (0 is knife and 1 is revolver)
weapon = pyro.sample('weapon', {'Grey':dist.Bernoulli(0.9), 'Auburn':dist.Bernoulli(0.2)}[murderer_dict[murderer]])
# probability of hair found conditional on murderer (0 is not found and 1 is found)
hair = pyro.sample('hair', {'Grey':dist.Bernoulli(0.5), 'Auburn':dist.Bernoulli(0.05)}[murderer_dict[murderer]])
```
### We can explore the model using repeated sampling
**We first look at all the variables in the model.** $P(murderer)$, $P(weapon)$, $P(hair)$
These correspond to our initial beliefs.
```
# make plots of the various probabilities involved
num_samples = 1000
traces = []
for _ in range(num_samples):
tr = trace(murder_case).get_trace()
values = {
name: props['value'].item()
for (name, props) in tr.nodes.items()
if props['type'] == 'sample'
}
traces.append(values)
_ = pd.DataFrame(traces).hist()
```
**We can condition the model** and ask what the joint probability for an outcome is. For example, how likely is the outcome that Auburn is the killer, the revolver was used and the hair is found $P(murderer=Auburn, weapon=Revolver, hair=true)$? Note that this is *not* the likelyhood that Auburn is the killer given the evidence, it is the likelyhood of the overall outcome at the outset.
```
# Condition the model
cond_model = condition(murder_case, {
"murderer": tensor(1.),
"weapon": tensor(1.),
"hair": tensor(1.)
})
# setup trace
tr = trace(cond_model).get_trace()
print('Joint probability for this particular outcome: {:.2}'.format(tr.log_prob_sum().exp().item()))
```
**To find the relative probability** of the two potential murderers given the evidence of the revolver and hair we need to compute both. $P(murderer=Auburn|weapon=Revolver, hair=true)$ and $P(murderer=Grey|weapon=Revolver, hair=true)$
```
# Condition the model for Auburn
cond_model = condition(murder_case, {
"murderer": tensor(1.),
"weapon": tensor(1.),
"hair": tensor(1.)
})
tr = trace(cond_model).get_trace()
auburn = tr.log_prob_sum().exp()
# Condition the model for Grey
cond_model = condition(murder_case, {
"murderer": tensor(0.),
"weapon": tensor(1.),
"hair": tensor(1.)
})
# Compute the probabilities
tr = trace(cond_model).get_trace()
grey = tr.log_prob_sum().exp()
# calculate the relative probabilities
auburn_prob = auburn/(auburn+grey)
grey_prob = grey/(auburn+grey)
print('After seeing evidence the probability for Auburn being the murderer is {:.2} and Grey is {:.2}.'.format(auburn_prob, grey_prob))
```
### We can also use variational inference to look at latent variables
This will become useful for larger models.
**To find the probability** of Auborn being the murderer, after seeing the revolver evidence. $P(murderer=Auburn|weapon=Revolver)$
```
def case_guide():
'''
Guide function used to find optimal values of latent variables.
'''
# Constraints ensure facts always remain true during optimization,
# e.g. that the parameter of a Bernoulli is always between 0 and 1
valid_prob = dist.constraints.interval(0., 1.)
mu_p = param('mu_p', tensor(0.7), constraint=valid_prob)
murderer = pyro.sample('murderer', dist.Bernoulli(mu_p))
# probability of weapon conditional on murderer (0 is knife and 1 is revolver)
weapon = pyro.sample('weapon', {'Grey':dist.Bernoulli(0.9), 'Auburn':dist.Bernoulli(0.2)}[murderer_dict[murderer.item()]])
# probability of hair found conditional on murderer (0 is not found and 1 is found)
hair = pyro.sample('hair', {'Grey':dist.Bernoulli(0.5), 'Auburn':dist.Bernoulli(0.05)}[murderer_dict[murderer.item()]])
# remove previous
pyro.clear_param_store()
# Condition the model on having seen the revolver
cond_model = condition(murder_case, {
"weapon": tensor(1.)
})
# Condition the guide on having seen the revolver
cond_case_guide = condition(case_guide, {
"weapon": tensor(1.)
})
adam = Adam({"lr": 0.005, "betas": (0.90, 0.999)})
svi = SVI(cond_model, case_guide, adam, loss=Trace_ELBO())
param_vals = []
for _ in range(2000):
svi.step()
param_vals.append({k: param(k).item() for k in ["mu_p"]})
# plot the parameter
pd.DataFrame(param_vals).plot(subplots=True)
# make plots of the various probabilities involved
traces = []
for _ in range(10000):
tr = trace(case_guide).get_trace()
values = {
name: props['value'].item()
for (name, props) in tr.nodes.items()
if props['type'] == 'sample'
}
traces.append(values)
_ = pd.DataFrame(traces).hist()
# what is the murderer probability now?
tr = trace(case_guide).get_trace()
print('Probability for Auburn being the murderer is now {:.2}'.format(tr.nodes['mu_p']['value'].item()))
```
**To find the probability** of Auborn being the murderer, after seeing the revolver *and* hair evidence $P(murderer=Auburn|weapon=Revolver, hair=true)$. This will be the same value (or at least very similar, depending on how many iterations are used) as the 0.049 from a few cells above where we computed relative probability.
```
%%time
# remove previous
pyro.clear_param_store()
# Condition the model on having seen the revolver and hair
cond_model = condition(murder_case, {
"weapon": tensor(1.),
"hair": tensor(1.)
})
# Condition the guide on having seen the revolver and hair
cond_case_guide = condition(case_guide, {
"weapon": tensor(1.),
"hair": tensor(1.)
})
adam = Adam({"lr": 0.01, "betas": (0.90, 0.999)})
svi = SVI(cond_model, cond_case_guide, adam, loss=Trace_ELBO())
param_vals = []
for _ in range(5000):
svi.step()
param_vals.append({k: param(k).item() for k in ["mu_p"]})
# plot the loss
pd.DataFrame(param_vals).plot(subplots=True)
# make plots of the various probabilities involved
traces = []
for _ in range(10000):
tr = trace(cond_case_guide).get_trace()
values = {
name: props['value'].item()
for (name, props) in tr.nodes.items()
if props['type'] == 'sample'
}
traces.append(values)
_ = pd.DataFrame(traces).hist()
# what is the murderer probability now?
tr = trace(cond_case_guide).get_trace()
print('Probability for Auburn being the murderer is now {:.2}'.format(tr.nodes['mu_p']['value'].item()))
```
# Chapter 2
## Assessing people's skils
#### Pages 47-y
<img src="images/skills.png" width="250"/>
**Problem statement:**
The problem of assessing candidates for a job that requires certain skills is adressed. The idea is that candidates will take a multiple-choice test and we will use model-based machine learning to determine which skills each candidate has (and with what probability) given their answers in the test. We can then use this for tasks such as selecting a shortlist of candidates very likely to have a set of essential skills.
**Prior:** Several assumptions are used to construct the model.
1. Each candidate has either mastered each skill or not.
2. Before seeing any test results, it is equally likely that each candidate does or doesn't have any particular skill.
3. If a candidate has all of the skills neede for a question then they will get the question right, except one time in ten they will make a mistake.
4. If a candidate doesn't have all the skills needed for a question, they will pick an answer at random. Because this is a multiple-choice exam with five answers, there's one in five chance that they get the question right.
5. Whether the candidate gets a question right depends only on what skills that candidate has and not on anything else.
**Factor graph:** To capture these assumptions, for two skills and a single individual, a factor graph is constructed.
<img src="images/chapter_2.png" width="400"/>
**Implement the model**
```
def skill_model():
'''
A model representing the first three questions of the exam.
'''
csharp = pyro.sample('csharp', dist.Bernoulli(0.5))
sql = pyro.sample('sql', dist.Bernoulli(0.5))
hasskills = tensor(1.) if csharp and sql == tensor(1.) else tensor(0.)
iscorrect1 = pyro.sample('iscorrect1', dist.Bernoulli(0.9 if csharp == tensor(1.) else 0.2))
iscorrect2 = pyro.sample('iscorrect2', dist.Bernoulli(0.9 if sql == tensor(1.) else 0.2))
iscorrect3 = pyro.sample('iscorrect3', dist.Bernoulli(0.9 if hasskills == tensor(1.) else 0.2))
```
**Let's take a look at the variables in the model**
```
%%time
traces = []
for _ in range(10000):
tr = trace(skill_model).get_trace()
values = {
name: props['value'].item()
for (name, props) in tr.nodes.items()
if props['type'] == 'sample'
}
traces.append(values)
_ = pd.DataFrame(traces).hist()
plt.tight_layout()
```
## Variational inference
**Define a guide function to help me solve conditioned models**
```
def skill_guide():
'''
Guide function used to find optimal values of latent variables.
'''
valid_prob = dist.constraints.interval(0., 1.)
cs_p = param('cs_p', tensor(0.5), constraint=valid_prob)
sq_p = param('sq_p', tensor(0.5), constraint=valid_prob)
csharp = pyro.sample('csharp', dist.Bernoulli(cs_p))
sql = pyro.sample('sql', dist.Bernoulli(sq_p))
hasskills = tensor(1.) if csharp and sql == tensor(1.) else tensor(0.)
iscorrect1 = pyro.sample('iscorrect1', dist.Bernoulli(0.9 if csharp == tensor(1.) else 0.2))
iscorrect2 = pyro.sample('iscorrect2', dist.Bernoulli(0.9 if sql == tensor(1.) else 0.2))
iscorrect3 = pyro.sample('iscorrect3', dist.Bernoulli(0.9 if hasskills == tensor(1.) else 0.2))
```
**Now get the latent variable probabilities for all outcomes**
```
%%time
data = {'iscorrect1':[], 'iscorrect2':[], 'iscorrect3':[], 'csharp':[], 'sql':[]}
for k in (tensor(0.), tensor(1.)):
for j in (tensor(0.), tensor(1.)):
for i in (tensor(0.), tensor(1.)):
print(i,j,k)
# remove previous
pyro.clear_param_store()
# Condition the model
cond_model = condition(skill_model, {
"iscorrect1": i,
"iscorrect2": j,
"iscorrect3": k
})
# cond_test_guide = condition(test_guide, {
# "iscorrect1": i,
# "iscorrect2": j,
# "iscorrect3": k
# })
adam = Adam({"lr": 0.005, "betas": (0.90, 0.999)})
svi = SVI(model=cond_model,
guide=skill_guide,
optim=adam,
loss=Trace_ELBO())
param_vals = []
losses = []
cs = []
sq = []
for _ in range(5000):
losses.append(svi.step())
cs.append(pyro.param("cs_p").item())
sq.append(pyro.param("sq_p").item())
#param_vals.append({p: param(p).item() for p in ["cs_p", "sq_p"]})
# plot the parameter value
#pd.DataFrame(param_vals).plot(subplots=True)
# plot losses
plt.plot(losses)
plt.title("ELBO {} {} {}".format(i, j, k))
plt.xlabel("step")
plt.ylabel("loss")
plt.show()
plt.subplot(1,2,1)
plt.plot(cs)
plt.ylabel('cs_p')
plt.subplot(1,2,2)
plt.plot(sq)
plt.ylabel('sq_p')
plt.tight_layout()
plt.show()
# what is the probabilities now?
tr = trace(skill_guide).get_trace()
data['iscorrect1'].append(True if i == tensor(1.) else False)
data['iscorrect2'].append(True if j == tensor(1.) else False)
data['iscorrect3'].append(True if k == tensor(1.) else False)
data['csharp'].append(tr.nodes['cs_p']['value'].item())
data['sql'].append(tr.nodes['sq_p']['value'].item())
df = pd.DataFrame(data)
display(df)
```
Looking at the optimization traces there is room for improvement. The values for some of the latent variables do not stabilize before the process is over. Even so, the results nicely agree with the ones in Table 2.4 on page 67 of the book.
## Moving to real data
#### Page 78
```
### First load the data
#
table26 = pd.read_csv(join('ch2', 'RawResponsesAsDictionary.csv'), sep=',', index_col=0)
display(table26.head())
#
skills = pd.read_csv(join('ch2', 'SkillsQuestionsMask.csv'), sep=',', header=None)
skillsT = skills.transpose()
display(skills.head())
display(skillsT.head())
#
questions = pd.read_csv(join('ch2', 'IsCorrect.csv'), sep=',', header=None)
questionsT = questions.transpose()
display(questions.head())
display(questionsT.head())
```
#### Make the plot in figure 2.14
```
#
fig, ax2 = plt.subplots(figsize=(6, 20))
img = ax2.imshow(skillsT,
interpolation='nearest',
cmap = 'magma',
vmin=0,
vmax=1)
plt.axis('off')
fig.tight_layout()
#
fig, ax1 = plt.subplots(figsize=(6, 3))
img = ax1.imshow(questionsT,
interpolation='nearest',
cmap = 'magma',
vmin=0,
vmax=1)
plt.axis('off')
fig.tight_layout()
display(skillsT.shape)
display(questionsT.shape)
# convert skills needed to a list of indexes
skills_needed_list = [skillsT.index[skillsT[s] == True].tolist() for s in skillsT.columns]
skills_needed_list
```
#### Build the model using pyro plates
```
def test_model_without_plate_one_person(data, skillsneeded, num_skills):
'''
A model representing all questions of the exam.
'''
num_exams_taken = 1 # how many exams were taken, i.e. how many people
num_questions = data.shape[0] # number of questions in each exam
print(num_questions)
skills = []
for i in range(num_skills):
skills.append(pyro.sample('skill{}'.format(i), dist.Bernoulli(0.5)))
skills = np.array(skills)
# now sample probability of having the questions right
hasskills = []
iscorrect = []
for i in range(num_questions):
hasskills.append(all(skills[skillsneeded[i]]))
iscorrect.append(pyro.sample('iscorrect{}'.format(i),
dist.Bernoulli(0.9 if hasskills[i] == True else 0.2), obs=data[i]))
return iscorrect
%%time
def test_model_without_plate(data, skillsneeded):
'''
A model representing all questions of the exam.
'''
num_exams_taken = data.shape[0] # how many exams were taken, i.e. how many people
num_questions = data.shape[1] # number of questions in each exam
skills = []
for i in range(num_exams_taken):
skills.append(pyro.sample('skill{}'.format(i), dist.Bernoulli(0.5)))
# now sample probability of having the questions right
hasskills = []
iscorrect = []
for i in range(num_exams_taken):
for j in range(num_questions):
hasskills.append(all(skills[skillsneeded[i]]))
iscorrect.append(pyro.sample('iscorrect{}'.format(i),
dist.Bernoulli(0.9 if hasskills[i] == True else 0.2), obs=data[i][j]))
def guide(data, skillsneeded):
'''
'''
num_exams_taken = data.shape[0] # how many exams were taken, i.e. how many people
num_questions = data.shape[1] # number of questions in each exam
valid_prob = dist.constraints.interval(0., 1.)
params = []
for i in range(num_exams_taken):
params.append(param('skill_param{}'.format(i), tensor(0.5), constraint=valid_prob))
skills = []
for i in range(num_exams_taken):
skills.append(pyro.sample('skill{}'.format(i), dist.Bernoulli(params[i])))
# now sample probability of having the questions right
hasskills = []
iscorrect = []
for i in range(num_exams_taken):
for j in range(num_questions):
hasskills.append(all(skills[skillsneeded[i]]))
iscorrect.append(pyro.sample('iscorrect{}'.format(i),
dist.Bernoulli(0.9 if hasskills[i] == True else 0.2), obs=data[i][j]))
# prepare data for the Pyro model
data = questionsT.to_numpy()
person_idx = data.shape[0]
question_idx = data.shape[1]
skills_needed_list = [torch.tensor(s).long() for s in skills_needed_list]
# make guide function
# guide = AutoContinuous(test_model_without_plate)
# Reset parameter values
pyro.clear_param_store()
# Define the number of optimization steps
n_steps = 12000
# Setup the optimizer
adam_params = {"lr": 0.01}
optimizer = Adam(adam_params)
# Setup the inference algorithm
elbo = Trace_ELBO(num_particles=3)
svi = SVI(test_model_without_plate, guide, optimizer, loss=elbo)
# Do gradient steps
for step in range(n_steps):
elbo = svi.step(data, skills_needed_list)
if step % 500 == 0:
print("[%d] ELBO: %.1f" % (step, elbo))
data[1][2]
data, skills_needed_list, 7, 1, question_idx-1
test_model_without_plate_one_person(questions.to_numpy()[:, 1], skills_needed_list, 7)
# def test_model_plate(data, skillsneeded, num_skills, person_idx, question_idx):
# '''
# A model representing all questions of the exam.
# '''
# num_exams_taken = data.shape[0] # how many exams were taken, i.e. how many people
# num_questions = data.shape[1] # number of questions in each exam
# # priors for the skills as plate
# with pyro.plate('person', num_exams_taken):
# skills = pyro.sample('skills', dist.Bernoulli(0.5*torch.ones(num_skills)))
# # now sample probability of having the questions right
# with pyro.plate('data', num_questions):
# hasskills = list(map(all, skills[person_idx][skillsneeded[question_idx]])) # apply the and operation for skills needed
# iscorrect = pyro.sample('iscorrect',
# dist.Bernoulli(0.9 if hasskills[question_idx] == True else 0.2), obs=data)
# return iscorrect
def test_model_plate(data, skillsneeded, num_skills, person_idx, question_idx):
'''
A model representing all questions of the exam.
'''
num_exams_taken = data.shape[0] # how many exams were taken, i.e. how many people
num_questions = data.shape[1] # number of questions in each exam
# priors for a persons skills as plate
with pyro.plate('sk', num_skills):
skills = pyro.sample('skills', dist.Bernoulli(0.5))
# now sample probability of having the questions right
# with pyro.plate('data', num_questions):
# # apply the and operation for skills needed
# hasskills = pyro.sample('hasskills',
# dist.Bernoulli(1.0 if all(skills[skillsneeded[question_idx]]) == True else 0.0),
# obs=torch.tensor(data[person_idx]))
# print(hasskills)
# iscorrect = pyro.sample('iscorrect',
# dist.Bernoulli(0.9 if hasskills == True else 0.2),
# obs=torch.tensor(data[person_idx]))
for i in pyro.plate("data_loop", len(data[person_idx])):
# apply the and operation for skills needed
hasskills = pyro.sample('hasskills{}'.format(i),
dist.Bernoulli(1.0 if all(skills[skillsneeded[question_idx]]) == True else 0.0),
obs=torch.tensor(data[person_idx][i]))
print(hasskills)
iscorrect = pyro.sample('iscorrect{}'.format(i),
dist.Bernoulli(0.9 if hasskills == True else 0.2),
obs=torch.tensor(data[person_idx][i]))
#return iscorrect
def guide(data, skillsneeded, num_skills, person_idx, question_idx):
'''
A model representing all questions of the exam.
'''
num_exams_taken = data.shape[0] # how many exams were taken, i.e. how many people
num_questions = data.shape[1] # number of questions in each exam
valid_prob = dist.constraints.interval(0., 1.)
# priors for a persons skills as plate
with pyro.plate('sk', num_skills):
mu_p = param('mu_p', tensor(0.5), constraint=valid_prob)
skills = pyro.sample('skills', dist.Bernoulli(mu_p))
# # now sample probability of having the questions right
# with pyro.plate('data', num_questions):
# hasskills = torch.tensor(all(skills[skillsneeded[question_idx]])) # apply the and operation for skills needed
# iscorrect = pyro.sample('iscorrect',
# dist.Bernoulli(0.9 if hasskills == True else 0.2), obs=torch.tensor(data[person_idx]))
# return dist.Categorical(iscorrect)
# prepare data for the Pyro model
data = questionsT.to_numpy()
person_idx = data.shape[0]
question_idx = data.shape[1]
skills_needed_list = [torch.tensor(s).long() for s in skills_needed_list]
y_hat = test_model_plate(data=data,
skillsneeded=skills_needed_list,
num_skills=7,
person_idx=1,
question_idx=1)
AutoDiagonalNormal(test_model_plate)
%%time
# get exam data from first person
data = questionsT.to_numpy()
# make guide function
guide = AutoContinuous(test_model_plate)
# Reset parameter values
pyro.clear_param_store()
# Define the number of optimization steps
n_steps = 120
# Setup the optimizer
adam_params = {"lr": 0.01}
optimizer = ClippedAdam(adam_params)
# Setup the inference algorithm
elbo = Trace_ELBO(num_particles=3)
svi = SVI(test_model_plate, guide, optimizer, loss=elbo)
# Do gradient steps
for step in range(n_steps):
elbo = svi.step(data, skills_needed_list, 7, 1, question_idx-1)
if step % 500 == 0:
print("[%d] ELBO: %.1f" % (step, elbo))
skills = pyro.plate('x', pyro.sample('skills', dist.Bernoulli(0.5*torch.ones(5))))
skills
p = pyro.param("p", torch.randn(5, 4, 3, 2).exp(),
constraint=dist.constraints.simplex)
x = pyro.sample("x", dist.Categorical(torch.ones(4)))
y = pyro.sample("y", dist.Categorical(torch.ones(3)))
with pyro.plate("z_plate", 5):
p_xy = p[..., x, y, :] # Not compatible with enumeration!
z = pyro.sample("z", dist.Categorical(p_xy))
z
```
# Code scraps
```
import xml.etree.ElementTree as ET
tree = ET.parse('./mbml/ch2/InputData.objml')
root = tree.getroot()
for child in root:
print(child.tag)
# get a list of the skills
print('\n<getting list of skills>')
print(root[0].tag)
print(root[0][0].tag)
questions = []
for child in root[0][0]:
#print(child.text)
questions.append(child.text)
print(questions)
# get which skills are needed for each question
print('\n<getting skills for questions>')
print(root[0].tag)
print(root[0][1].tag)
skillsforq = []
for child in root[0][1]:
temp = []
for grandchild in child:
#print(grandchild.text)
temp.append(int(grandchild.text))
skillsforq.append(temp)
print(skillsforq)
# get raw responses
print('\n<getting raw responses>')
print(root[1].tag)
raw = []
for child in root[1]:
temp = []
for grandchild in child:
#print(grandchild.text)
temp.append(int(grandchild.text))
raw.append(temp)
print(raw)
# get whether response is correct or not
print('\n<getting response correctness>')
print(root[2].tag)
iscorrect = []
for child in root[2]:
temp = []
for grandchild in child:
#print(grandchild.text)
temp.append(True if grandchild.text == 'True' else False)
iscorrect.append(temp)
print(iscorrect)
# get correct answers for the questions
print('\n<getting correct answers>')
print(root[3].tag)
correct = []
for child in root[3]:
correct.append(int(child.text))
print(correct)
# get which skills participants state they have
print('\n<getting stated skills>')
print(root[4].tag)
haveskill = []
for child in root[4]:
temp = []
for grandchild in child:
temp.append(True if grandchild.text == 'True' else False)
haveskill.append(temp)
print(haveskill)
### Start putting the stuff together ###
# add in a row of NaN to stated skills (since the first row aren't participant answers)
haveskill.insert(0, ['NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN'])
print(haveskill)
# add in the correct answers in front of the given answers
raw.insert(0, correct)
print(raw)
```
#### Make dataframe from this data (same as table 2.6)
```
rownames = ['ANS'] + ['P{}'.format(s) for s in range(1, 23)]
colnames = ['S{}'.format(s) for s in range(1, 8)] + ['Q{}'.format(s) for s in range(1, len(raw[0])+1)]
answers_df = pd.DataFrame(raw)
answers_df.index = rownames
answers_df.columns = colnames[7:]
skills_df = pd.DataFrame(haveskill)
skills_df.index = rownames
skills_df.columns = colnames[:7]
table26 = skills_df.join(answers_df)
table26.to_csv('./mbml/ch2/table26.tsv', sep='\t', index=True)
display(table26)
```
| github_jupyter |
Check which version is installed on your machine and please upgrade if needed.
```
import plotly
plotly.__version__
```
Now let's load the dependencies/packages that we need in order to get a simple stream going.
```
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
import numpy as np
```
#### Overview
In this example we're going to be streaming to two different types of traces on the same plotting surface via subplots.
#### Getting Set Up
Let's get at least two streaming tokens for this task.
```
stream_tokens = tls.get_credentials_file()['stream_ids']
token_1 = stream_tokens[-1] # I'm getting my stream tokens from the end to ensure I'm not reusing tokens
token_2 = stream_tokens[-2]
print token_1
print token_2
```
Now let's create some `stream id objects` for each token.
```
stream_id1 = dict(token=token_1, maxpoints=60)
stream_id2 = dict(token=token_2, maxpoints=60)
```
The set up of this plot will contain one pie chart on the left and a bar chart on the right that will display the same information. This is possible because they are both charts that display "counts" for categroical variables.
We will have three categories, which are brilliantly named 'one', 'two', and 'three'. Later we'll randomly generate count data and stream it to our plot.
```
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Bar(
x=['one', 'two', 'three'],
y=[4, 3, 2],
xaxis='x2',
yaxis='y2',
marker=dict(color="maroon"),
name='Random Numbers',
stream=stream_id2,
showlegend=False
)
trace2 = go.Pie(
labels=['one','two','three'],
values=[20,50,100],
domain=dict(x=[0, 0.45]),
text=['one', 'two', 'three'],
stream=stream_id1,
sort=False,
)
data = [trace1, trace2]
layout = go.Layout(
xaxis2=dict(
domain=[0.5, 0.95],
anchor='y2'
),
yaxis2=dict(
domain=[0, 1],
anchor='x2'
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='simple-inset-stream')
```
Now let's set up some `stream link objects` and start streaming some data to our plot
```
s_1 = py.Stream(stream_id=token_1)
s_2 = py.Stream(stream_id=token_2)
```
#### Start Streaming
```
s_1.open()
s_2.open()
import time
import datetime
import numpy as np
while True:
nums = np.random.random_integers(0,10, size=(3))
s_1.write(dict(labels=['one', 'two', 'three'], values=nums, type='pie'))
s_2.write(dict(x=['one', 'two', 'three'], y=nums, type='bar', marker=dict(color=["blue", "orange", "green"])))
time.sleep(0.8)
s_1.close()
s_2.close()
```
You can see this stream live below:
```
tls.embed('streaming-demos','122')
from IPython.display import display, HTML
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))
! pip install publisher --upgrade
import publisher
publisher.publish(
'subplot-streaming', 'python/subplot-streaming//', 'Streaming in Plotly',
'Streaming in Plotly with Python', name="Streaming with Subplots",
title = 'Streaming in Subplots with Plotly',
thumbnail='', language='python',
layout='user-guide', has_thumbnail='false',
ipynb= '~notebook_demo/83')
```
| github_jupyter |
```
import sys
import numpy as np
import datetime
import dill
from constant import *
from environment import *
from behavior import *
from utils import utils
from utils.chronometer import Chronometer
sys.path.append('../Nurture/server/notification/')
from nurture.learning.agents import *
from nurture.learning.state import State
# environment setup
rewardCriteria = {
ANSWER_NOTIFICATION_ACCEPT: 1,
ANSWER_NOTIFICATION_IGNORE: 0,
ANSWER_NOTIFICATION_DISMISS: -5,
}
environment = MTurkSurveyUser(
filePaths=[
'survey/ver2_mturk/results/01_1st_Batch_3137574_batch_results.csv',
'survey/ver2_mturk/results/02_Batch_3148398_batch_results.csv',
'survey/ver2_mturk/results/03_Batch_3149214_batch_results.csv',
],
filterFunc=(lambda r: ord(r['rawWorkerID'][-1]) % 3 == 2),
)
behavior = ExtraSensoryBehavior([
'behavior/data/2.txt',
'behavior/data/4.txt',
'behavior/data/5.txt',
'behavior/data/6.txt',
])
simulationLengthDay = 140
stepWidthMinutes = 1
behavior.printSummary()
# simulation setup
chronometer = Chronometer(skipFunc=(lambda hour, _m, _d: hour < 10 or hour >= 22))
lastNotificationMinute = 0
lastNotificationHour = 0
lastNotificationNumDays = 0
# statistics
simulationResults = []
totalReward = 0.
numSteps = 0
# helper functions
def _get_time_of_day(currentHour, currentMinute):
return currentHour / 24. + currentMinute / 24. / 60.
def _get_day_of_week(currentDay, currentHour, currentMinute):
return currentDay / 7. + currentHour / 7. / 24. + currentMinute / 7. / 24. / 60.
def _get_motion(original_activity):
mapping = {
utils.STATE_ACTIVITY_STATIONARY: State.MOTION_STATIONARY,
utils.STATE_ACTIVITY_WALKING: State.MOTION_WALKING,
utils.STATE_ACTIVITY_RUNNING: State.MOTION_RUNNING,
utils.STATE_ACTIVITY_DRIVING: State.MOTION_DRIVING,
utils.STATE_ACTIVITY_COMMUTE: State.MOTION_DRIVING,
}
return mapping[original_activity]
def _printResults(results):
notificationEvents = [r for r in results if r['decision']]
numNotifications = len(notificationEvents)
numAcceptedNotis = len([r for r in notificationEvents if r['reward'] > 0])
numDismissedNotis = len([r for r in notificationEvents if r['reward'] < 0])
answerRate = numAcceptedNotis / numNotifications if numNotifications > 0 else 0.
dismissRate = numDismissedNotis / numNotifications if numNotifications > 0 else 0.
numActionedNotis = numAcceptedNotis + numDismissedNotis
responseRate = numAcceptedNotis / numActionedNotis if numActionedNotis > 0 else 0.
totalReward = sum([r['reward'] for r in results])
expectedNumDeliveredNotifications = sum([r['probOfAnswering'] for r in results])
deltaDays = results[-1]['context']['numDaysPassed'] - results[0]['context']['numDaysPassed'] + 1
print(" reward=%f / step=%d (%f)" % (totalReward, len(results), totalReward / len(results)))
print(" %d notifications have been sent (%.1f / day):" % (numNotifications, numNotifications / deltaDays))
print(" - %d are answered (%.2f%%)" % (numAcceptedNotis, answerRate * 100.))
print(" - %d are dismissed (%.2f%%)" % (numDismissedNotis, dismissRate * 100.))
print(" - response rate: %.2f%%" % (responseRate * 100.))
print(" Expectation of total delivered notifications is %.2f" % expectedNumDeliveredNotifications)
def _filterByWeek(results, week):
startDay = week * 7
endDay = startDay + 7
return [r for r in results
if startDay <= r['context']['numDaysPassed'] < endDay]
utils.STATE_ACTIVITY_COMMUTE
numDaysPassed, currentHour, currentMinute, currentDay = chronometer.forward(stepWidthMinutes)
toBePrintedWeek = 0
agent = TensorForceDQNAgent()
agent.agent = DQNAgent(
states=dict(type='float', shape=(15,)),
actions=dict(type='int', num_actions=2),
network=[
dict(type='dense', size=20),
dict(type='dense', size=20)
],
batched_observe=False,
actions_exploration={
'type': 'epsilon_decay',
'initial_epsilon': 0.3,
'final_epsilon': 0.05,
'timesteps': 80000,
},
)
#agent = QLearningAgent()
while numDaysPassed < simulationLengthDay:
# get environment info (user context)
lastNotificationTime = utils.getDeltaMinutes(
numDaysPassed, currentHour, currentMinute,
lastNotificationNumDays, lastNotificationHour, lastNotificationMinute,
)
#stateLastNotification = utils.getLastNotificationState(lastNotificationTime)
stateLocation, stateActivity = behavior.getLocationActivity(
currentHour, currentMinute, currentDay)
probAnsweringNotification, probIgnoringNotification, probDismissingNotification = (
environment.getResponseDistribution(
currentHour, currentMinute, currentDay,
stateLocation, stateActivity, lastNotificationTime,
)
)
probAnsweringNotification, probIgnoringNotification, probDismissingNotification = utils.normalize(
probAnsweringNotification, probIgnoringNotification, probDismissingNotification)
# prepare observations
state = State(
timeOfDay=_get_time_of_day(currentHour, currentMinute),
dayOfWeek=_get_day_of_week(currentDay, currentHour, currentMinute),
motion=_get_motion(stateActivity),
location=stateLocation,
notificationTimeElapsed=lastNotificationTime,
ringerMode=np.random.choice(a=State.allRingerModeValues()),
screenStatus=np.random.choice(a=State.allScreenStatusValues()),
)
# small hack - some agent keeps track of time
try:
agent.last_notification_time -= datetime.timedelta(minutes=stepWidthMinutes)
except:
pass
# get action
sendNotification = agent.get_action(state)
# calculate reward
if not sendNotification:
reward = 0
else:
userReaction = np.random.choice(
a=[ANSWER_NOTIFICATION_ACCEPT, ANSWER_NOTIFICATION_IGNORE, ANSWER_NOTIFICATION_DISMISS],
p=[probAnsweringNotification, probIgnoringNotification, probDismissingNotification],
)
reward = rewardCriteria[userReaction]
lastNotificationNumDays = numDaysPassed
lastNotificationHour = currentHour
lastNotificationMinute = currentMinute
agent.feed_reward(reward)
# log this session
simulationResults.append({
'context': {
'numDaysPassed': numDaysPassed,
'hour': currentHour,
'minute': currentMinute,
'day': currentDay,
'location': stateLocation,
'activity': stateActivity,
'lastNotification': lastNotificationTime,
},
'probOfAnswering': probAnsweringNotification,
'probOfIgnoring': probIgnoringNotification,
'probOfDismissing': probDismissingNotification,
'decision': sendNotification,
'reward': reward,
})
# get the next decision time point
numDaysPassed, currentHour, currentMinute, currentDay = chronometer.forward(stepWidthMinutes)
# print current state
currentWeek = numDaysPassed // 7
if currentWeek > toBePrintedWeek:
print()
print("===== end of week %d ====" % toBePrintedWeek)
_printResults(_filterByWeek(simulationResults, toBePrintedWeek))
toBePrintedWeek = currentWeek
numTotalWeeks = simulationLengthDay // 7
for i in range(numTotalWeeks):
print()
print("===== end of week %d ====" % i)
_printResults(_filterByWeek(simulationResults, i))
for r in simulationResults:
print(r['reward'])
agent.agent.save_model('/tmp/jp_test4/')
#print(agent.agent)
agent.last_send_notification = datetime.datetime.now()
agent.num_steps = 0
agent.on_pickle_save()
dill.dump(agent, open('../Nurture/server/notification/local_data/models/initial/tf-dqn-tuned.p', 'wb'))
agent2 = TensorForceDQNAgent()
from tensorforce.agents import DQNAgent
agent2.agent = DQNAgent(
states=dict(type='float', shape=(15,)),
actions=dict(type='int', num_actions=2),
network=[
dict(type='dense', size=20),
dict(type='dense', size=20)
],
batched_observe=False,
actions_exploration={
'type': 'epsilon_decay',
'initial_epsilon': 0.1,
'final_epsilon': 0.015,
'timesteps': 3000,
},
)
agent2.agent.restore_model('/tmp/jp_test2/')
agent2.on_pickle_save()
dill.dump(agent2, open('../Nurture/server/notification/local_data/models/initial/tf-dqn-tuned.p', 'wb'))
numDaysPassed, currentHour, currentMinute, currentDay = chronometer.forward(stepWidthMinutes)
toBePrintedWeek = 0
agent2 = TensorForceDQNAgent()
agent2.agent = DQNAgent(
states=dict(type='float', shape=(15,)),
actions=dict(type='int', num_actions=2),
network=[
dict(type='dense', size=20),
dict(type='dense', size=20)
],
batched_observe=False,
actions_exploration={
'type': 'epsilon_decay',
'initial_epsilon': 0.1,
'final_epsilon': 0.015,
'timesteps': 3000,
},
)
agent2.agent.restore_model('/tmp/jp_test/')
#agent2.agent.model.network = agent.agent.model.network
#agent2.agent.model.target_network = agent.agent.model.target_network
#agent = QLearningAgent()
#agent2 = agent
while numDaysPassed < 21:
# get environment info (user context)
lastNotificationTime = utils.getDeltaMinutes(
numDaysPassed, currentHour, currentMinute,
lastNotificationNumDays, lastNotificationHour, lastNotificationMinute,
)
#stateLastNotification = utils.getLastNotificationState(lastNotificationTime)
stateLocation, stateActivity = behavior.getLocationActivity(
currentHour, currentMinute, currentDay)
probAnsweringNotification, probIgnoringNotification, probDismissingNotification = (
environment.getResponseDistribution(
currentHour, currentMinute, currentDay,
stateLocation, stateActivity, lastNotificationTime,
)
)
probAnsweringNotification, probIgnoringNotification, probDismissingNotification = utils.normalize(
probAnsweringNotification, probIgnoringNotification, probDismissingNotification)
# prepare observations
state = State(
timeOfDay=_get_time_of_day(currentHour, currentMinute),
dayOfWeek=_get_day_of_week(currentDay, currentHour, currentMinute),
motion=_get_motion(stateActivity),
location=stateLocation,
notificationTimeElapsed=lastNotificationTime,
ringerMode=np.random.choice(a=State.allRingerModeValues()),
screenStatus=np.random.choice(a=State.allScreenStatusValues()),
)
# small hack - some agent keeps track of time
try:
agent2.last_notification_time -= datetime.timedelta(minutes=stepWidthMinutes)
except:
pass
# get action
sendNotification = agent2.get_action(state)
# calculate reward
if not sendNotification:
reward = 0
else:
userReaction = np.random.choice(
a=[ANSWER_NOTIFICATION_ACCEPT, ANSWER_NOTIFICATION_IGNORE, ANSWER_NOTIFICATION_DISMISS],
p=[probAnsweringNotification, probIgnoringNotification, probDismissingNotification],
)
reward = rewardCriteria[userReaction]
lastNotificationNumDays = numDaysPassed
lastNotificationHour = currentHour
lastNotificationMinute = currentMinute
agent2.feed_reward(reward)
# log this session
simulationResults.append({
'context': {
'numDaysPassed': numDaysPassed,
'hour': currentHour,
'minute': currentMinute,
'day': currentDay,
'location': stateLocation,
'activity': stateActivity,
'lastNotification': lastNotificationTime,
},
'probOfAnswering': probAnsweringNotification,
'probOfIgnoring': probIgnoringNotification,
'probOfDismissing': probDismissingNotification,
'decision': sendNotification,
'reward': reward,
})
# get the next decision time point
numDaysPassed, currentHour, currentMinute, currentDay = chronometer.forward(stepWidthMinutes)
# print current state
currentWeek = numDaysPassed // 7
if currentWeek > toBePrintedWeek:
print()
print("===== end of week %d ====" % toBePrintedWeek)
_printResults(_filterByWeek(simulationResults, toBePrintedWeek))
toBePrintedWeek = currentWeek
numTotalWeeks = simulationLengthDay // 7
for i in range(3):
print()
print("===== end of week %d ====" % i)
_printResults(_filterByWeek(simulationResults, i))
d.model.get_components()
agent2.agent.save_model('/tmp/test_new_model/')
```
| github_jupyter |
```
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR, MultiStepLR
import numpy as np
# import matplotlib.pyplot as plt
from math import *
import time
torch.cuda.set_device(2)
torch.set_default_tensor_type('torch.DoubleTensor')
# activation function
def activation(x):
return x * torch.sigmoid(x)
# build ResNet with one blocks
class Net(torch.nn.Module):
def __init__(self,input_width,layer_width):
super(Net,self).__init__()
self.layer_in = torch.nn.Linear(input_width, layer_width)
self.layer1 = torch.nn.Linear(layer_width, layer_width)
self.layer2 = torch.nn.Linear(layer_width, layer_width)
self.layer_out = torch.nn.Linear(layer_width, 1)
def forward(self,x):
y = self.layer_in(x)
y = y + activation(self.layer2(activation(self.layer1(y)))) # residual block 1
output = self.layer_out(y)
return output
dimension = 1
input_width,layer_width = dimension, 4
net = Net(input_width,layer_width).cuda() # network for u on gpu
# defination of exact solution
def u_ex(x):
temp = 1.0
for i in range(dimension):
temp = temp * torch.sin(pi*x[:, i])
u_temp = 1.0 * temp
return u_temp.reshape([x.size()[0], 1])
# defination of f(x)
def f(x):
temp = 1.0
for i in range(dimension):
temp = temp * torch.sin(pi*x[:, i])
u_temp = 1.0 * temp
f_temp = dimension * pi**2 * u_temp
return f_temp.reshape([x.size()[0],1])
# generate points by random
def generate_sample(data_size):
sample_temp = torch.rand(data_size, dimension)
return sample_temp.cuda()
def model(x):
x_temp = x.cuda()
D_x_0 = torch.prod(x_temp, axis = 1).reshape([x.size()[0], 1])
D_x_1 = torch.prod(1.0 - x_temp, axis = 1).reshape([x.size()[0], 1])
model_u_temp = D_x_0 * D_x_1 * net(x)
return model_u_temp.reshape([x.size()[0], 1])
# # Xavier normal initialization for weights:
# # mean = 0 std = gain * sqrt(2 / fan_in + fan_out)
# # zero initialization for biases
# def initialize_weights(self):
# for m in self.modules():
# if isinstance(m,nn.Linear):
# nn.init.xavier_normal_(m.weight.data)
# if m.bias is not None:
# m.bias.data.zero_()
# Uniform initialization for weights:
# U(a, b)
# nn.init.uniform_(tensor, a = 0, b = 1)
# zero initialization for biases
def initialize_weights(self):
for m in self.modules():
if isinstance(m,nn.Linear):
nn.init.uniform_(m.weight.data)
if m.bias is not None:
m.bias.data.zero_()
# # Normal initialization for weights:
# # N(mean = 0, std = 1)
# # nn.init.normal_(tensor, a = 0, b = 1)
# # zero initialization for biases
# def initialize_weights(self):
# for m in self.modules():
# if isinstance(m,nn.Linear):
# nn.init.normal_(m.weight.data)
# if m.bias is not None:
# m.bias.data.zero_()
initialize_weights(net)
for name,param in net.named_parameters():
print(name,param.size())
print(param.detach().cpu())
# loss function to DRM by auto differential
def loss_function(x):
# x = generate_sample(data_size).cuda()
# x.requires_grad = True
u_hat = model(x)
grad_u_hat = torch.autograd.grad(outputs = u_hat, inputs = x, grad_outputs = torch.ones(u_hat.shape).cuda(), create_graph = True)
grad_u_sq = ((grad_u_hat[0]**2).sum(1)).reshape([len(grad_u_hat[0]), 1])
part = torch.sum(0.5 * grad_u_sq - f(x) * u_hat) / len(x)
return part
torch.save(net.state_dict(), 'net_params_DRM_ResNet_Uniform.pkl')
```
| github_jupyter |
Background
https://en.wikipedia.org/wiki/Matrix_(mathematics)
# Tensors
Lets build some intution for what a tensor is.
(possibilities? a function -- of indexes, a set of bases, a transfomation, vectors, an array of numbers, a graph, ?)
## Encoding real world info
Imagine we have a ball and our goal is to throw it as far as we can (2 dimansion, x and y -- t is redundant). We get three attempts (.
Naming convention. The number of dimensions a tensor has and how many dimension each dimension has...
What is a classic example of a linear system? Examples from; health, ecology, physical systems, economics, ...
Do they all encode information in the 'same' way?
## Operations
Tensor vector product. What does it mean? Want some intuition for a contraction.
if A is a linear transformation (shift, rotation, stretch) of x (Ax). Then what is $\mathcal Ax$? Imagine $\mathcal A \in \mathbb R^{l,n,m}$, then the projection of x through the tensor is a collection of
#### Tensor product (kronecker/outer product).
* How can you measure the similarity of two tensors?
* How can you compose two tensors?
*
#### Tensor contractions
why do we care?
Relationship to matmul
Intuitive ways to view it
## As an operator
https://github.com/act65/act65.github.io/blob/master/_drafts/2016-9-26-EmbedLinAlg.md
Duality of linear functions as operators and operands.
https://en.wikipedia.org/wiki/Representation_theory
https://en.wikipedia.org/wiki/Operator_algebra
https://en.wikipedia.org/wiki/General_linear_group
https://en.wikipedia.org/wiki/Group_representation
## Basic properties
* Rank has some weird properties when compared to matrices.
* What about the determinant?
* Inversion is probably hard?
* Exponential increase in size
# Tensor networks
Ok cool, so why do we care about tensor-networks?
Allows us to construct these large tensors from smaller parts.
Show some simple examples.
BUT. What is sacrificed by doing this? Can no longer represent as much. On some lower dimensional manifold in the same high dimensional space.
(want some intuition for this!!! how is a TN on a lower dim manifold? we could also construct ones on higher dim manifolds.)
What if i recursively decompsed the cores and shared them so I only needed one parameter? How is this like a space filling curve?
## As a graph
* If a matrix can be viewed as a bipartide graph, then a tensor...? (draw SVD as a graph! the image in your head)
## Questions
* If a tensor is constructed from a symmetric tensor-network then ...???
*
## Representations
Duals, complex numbers, logic, ...?
| github_jupyter |
# Mask R-CNN - Train on Shapes Dataset
This notebook shows how to train Mask R-CNN on your own dataset. To keep things simple we use a synthetic dataset of shapes (squares, triangles, and circles) which enables fast training. You'd still need a GPU, though, because the network backbone is a Resnet101, which would be too slow to train on a CPU. On a GPU, you can start to get okay-ish results in a few minutes, and good results in less than an hour.
The code of the *Shapes* dataset is included below. It generates images on the fly, so it doesn't require downloading any data. And it can generate images of any size, so we pick a small image size to train faster.
```
import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
# Root directory of the project
ROOT_DIR = os.path.abspath("../../")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn.config import Config
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
from mrcnn.model import log
%matplotlib inline
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
```
## Configurations
```
class ShapesConfig(Config):
"""Configuration for training on the toy shapes dataset.
Derives from the base Config class and overrides values specific
to the toy shapes dataset.
"""
# Give the configuration a recognizable name
NAME = "shapes"
# Train on 1 GPU and 8 images per GPU. We can put multiple images on each
# GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 2
# Number of classes (including background)
NUM_CLASSES = 1 + 3 # background + 3 shapes
# Use small images for faster training. Set the limits of the small side
# the large side, and that determines the image shape.
IMAGE_MIN_DIM = 128
IMAGE_MAX_DIM = 128
# Use smaller anchors because our image and objects are small
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels
# Reduce training ROIs per image because the images are small and have
# few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
TRAIN_ROIS_PER_IMAGE = 32
# Use a small epoch since the data is simple
STEPS_PER_EPOCH = 100
# use small validation steps since the epoch is small
VALIDATION_STEPS = 5
config = ShapesConfig()
config.display()
```
## Notebook Preferences
```
def get_ax(rows=1, cols=1, size=8):
"""Return a Matplotlib Axes array to be used in
all visualizations in the notebook. Provide a
central point to control graph sizes.
Change the default size attribute to control the size
of rendered images
"""
_, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))
return ax
```
## Dataset
Create a synthetic dataset
Extend the Dataset class and add a method to load the shapes dataset, `load_shapes()`, and override the following methods:
* load_image()
* load_mask()
* image_reference()
```
class ShapesDataset(utils.Dataset):
"""Generates the shapes synthetic dataset. The dataset consists of simple
shapes (triangles, squares, circles) placed randomly on a blank surface.
The images are generated on the fly. No file access required.
"""
def load_shapes(self, count, height, width):
"""Generate the requested number of synthetic images.
count: number of images to generate.
height, width: the size of the generated images.
"""
# Add classes
self.add_class("shapes", 1, "square")
self.add_class("shapes", 2, "circle")
self.add_class("shapes", 3, "triangle")
# Add images
# Generate random specifications of images (i.e. color and
# list of shapes sizes and locations). This is more compact than
# actual images. Images are generated on the fly in load_image().
for i in range(count):
bg_color, shapes = self.random_image(height, width)
self.add_image("shapes", image_id=i, path=None,
width=width, height=height,
bg_color=bg_color, shapes=shapes)
def load_image(self, image_id):
"""Generate an image from the specs of the given image ID.
Typically this function loads the image from a file, but
in this case it generates the image on the fly from the
specs in image_info.
"""
info = self.image_info[image_id]
bg_color = np.array(info['bg_color']).reshape([1, 1, 3])
image = np.ones([info['height'], info['width'], 3], dtype=np.uint8)
image = image * bg_color.astype(np.uint8)
for shape, color, dims in info['shapes']:
image = self.draw_shape(image, shape, dims, color)
return image
def image_reference(self, image_id):
"""Return the shapes data of the image."""
info = self.image_info[image_id]
if info["source"] == "shapes":
return info["shapes"]
else:
super(self.__class__).image_reference(self, image_id)
def load_mask(self, image_id):
"""Generate instance masks for shapes of the given image ID.
"""
info = self.image_info[image_id]
shapes = info['shapes']
count = len(shapes)
mask = np.zeros([info['height'], info['width'], count], dtype=np.uint8)
for i, (shape, _, dims) in enumerate(info['shapes']):
mask[:, :, i:i+1] = self.draw_shape(mask[:, :, i:i+1].copy(),
shape, dims, 1)
# Handle occlusions
occlusion = np.logical_not(mask[:, :, -1]).astype(np.uint8)
for i in range(count-2, -1, -1):
mask[:, :, i] = mask[:, :, i] * occlusion
occlusion = np.logical_and(occlusion, np.logical_not(mask[:, :, i]))
# Map class names to class IDs.
class_ids = np.array([self.class_names.index(s[0]) for s in shapes])
return mask.astype(np.bool), class_ids.astype(np.int32)
def draw_shape(self, image, shape, dims, color):
"""Draws a shape from the given specs."""
# Get the center x, y and the size s
x, y, s = dims
if shape == 'square':
cv2.rectangle(image, (x-s, y-s), (x+s, y+s), color, -1)
elif shape == "circle":
cv2.circle(image, (x, y), s, color, -1)
elif shape == "triangle":
points = np.array([[(x, y-s),
(x-s/math.sin(math.radians(60)), y+s),
(x+s/math.sin(math.radians(60)), y+s),
]], dtype=np.int32)
cv2.fillPoly(image, points, color)
return image
def random_shape(self, height, width):
"""Generates specifications of a random shape that lies within
the given height and width boundaries.
Returns a tuple of three valus:
* The shape name (square, circle, ...)
* Shape color: a tuple of 3 values, RGB.
* Shape dimensions: A tuple of values that define the shape size
and location. Differs per shape type.
"""
# Shape
shape = random.choice(["square", "circle", "triangle"])
# Color
color = tuple([random.randint(0, 255) for _ in range(3)])
# Center x, y
buffer = 20
y = random.randint(buffer, height - buffer - 1)
x = random.randint(buffer, width - buffer - 1)
# Size
s = random.randint(buffer, height//4)
return shape, color, (x, y, s)
def random_image(self, height, width):
"""Creates random specifications of an image with multiple shapes.
Returns the background color of the image and a list of shape
specifications that can be used to draw the image.
"""
# Pick random background color
bg_color = np.array([random.randint(0, 255) for _ in range(3)])
# Generate a few random shapes and record their
# bounding boxes
shapes = []
boxes = []
N = random.randint(1, 4)
for _ in range(N):
shape, color, dims = self.random_shape(height, width)
shapes.append((shape, color, dims))
x, y, s = dims
boxes.append([y-s, x-s, y+s, x+s])
# Apply non-max suppression wit 0.3 threshold to avoid
# shapes covering each other
keep_ixs = utils.non_max_suppression(np.array(boxes), np.arange(N), 0.3)
shapes = [s for i, s in enumerate(shapes) if i in keep_ixs]
return bg_color, shapes
# Training dataset
dataset_train = ShapesDataset()
dataset_train.load_shapes(500, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])
dataset_train.prepare()
# Validation dataset
dataset_val = ShapesDataset()
dataset_val.load_shapes(50, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])
dataset_val.prepare()
# Load and display random samples
image_ids = np.random.choice(dataset_train.image_ids, 4)
for image_id in image_ids:
image = dataset_train.load_image(image_id)
mask, class_ids = dataset_train.load_mask(image_id)
visualize.display_top_masks(image, mask, class_ids, dataset_train.class_names)
```
## Create Model
```
# Create model in training mode
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=MODEL_DIR)
# Which weights to start with?
init_with = "coco" # imagenet, coco, or last
if init_with == "imagenet":
model.load_weights(model.get_imagenet_weights(), by_name=True)
elif init_with == "coco":
# Load weights trained on MS COCO, but skip layers that
# are different due to the different number of classes
# See README for instructions to download the COCO weights
model.load_weights(COCO_MODEL_PATH, by_name=True,
exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",
"mrcnn_bbox", "mrcnn_mask"])
elif init_with == "last":
# Load the last model you trained and continue training
model.load_weights(model.find_last(), by_name=True)
```
## Training
Train in two stages:
1. Only the heads. Here we're freezing all the backbone layers and training only the randomly initialized layers (i.e. the ones that we didn't use pre-trained weights from MS COCO). To train only the head layers, pass `layers='heads'` to the `train()` function.
2. Fine-tune all layers. For this simple example it's not necessary, but we're including it to show the process. Simply pass `layers="all` to train all layers.
```
# Train the head branches
# Passing layers="heads" freezes all layers except the head
# layers. You can also pass a regular expression to select
# which layers to train by name pattern.
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=1,
layers='heads')
# Fine tune all layers
# Passing layers="all" trains all layers. You can also
# pass a regular expression to select which layers to
# train by name pattern.
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE / 10,
epochs=2,
layers="all")
# Save weights
# Typically not needed because callbacks save after every epoch
# Uncomment to save manually
model_path = os.path.join(MODEL_DIR, "mask_rcnn_shapes.h5")
model.keras_model.save_weights(model_path)
```
## Detection
```
class InferenceConfig(ShapesConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
inference_config = InferenceConfig()
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=inference_config,
model_dir=MODEL_DIR)
# Get path to saved weights
# Either set a specific path or find last trained weights
# model_path = os.path.join(ROOT_DIR, ".h5 file name here")
model_path = model.find_last()
# Load trained weights
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
# Test on a random image
image_id = random.choice(dataset_val.image_ids)
original_image, image_meta, gt_class_id, gt_bbox, gt_mask =\
modellib.load_image_gt(dataset_val, inference_config,
image_id, use_mini_mask=False)
log("original_image", original_image)
log("image_meta", image_meta)
log("gt_class_id", gt_class_id)
log("gt_bbox", gt_bbox)
log("gt_mask", gt_mask)
visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id,
dataset_train.class_names, figsize=(8, 8))
results = model.detect([original_image], verbose=1)
r = results[0]
visualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'],
dataset_val.class_names, r['scores'], ax=get_ax())
```
## Evaluation
```
# Compute VOC-Style mAP @ IoU=0.5
# Running on 10 images. Increase for better accuracy.
image_ids = np.random.choice(dataset_val.image_ids, 10)
APs = []
for image_id in image_ids:
# Load image and ground truth data
image, image_meta, gt_class_id, gt_bbox, gt_mask =\
modellib.load_image_gt(dataset_val, inference_config,
image_id, use_mini_mask=False)
molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0)
# Run object detection
results = model.detect([image], verbose=0)
r = results[0]
# Compute AP
AP, precisions, recalls, overlaps =\
utils.compute_ap(gt_bbox, gt_class_id, gt_mask,
r["rois"], r["class_ids"], r["scores"], r['masks'])
APs.append(AP)
print("mAP: ", np.mean(APs))
```
| github_jupyter |
```
# Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
# Common imports
import numpy as np
import os
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "finger_p_index"
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)
os.makedirs(IMAGES_PATH, exist_ok=True)
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution)
# Ignore useless warnings (see SciPy issue #5998)
import warnings
warnings.filterwarnings(action="ignore", message="^internal gelsd")
import pandas as pd
import os
FINGER_PATH = os.path.join("datasets", "finger")
def load_finger_data(finger_path =FINGER_PATH, index = 1):
csv_path = os.path.join(finger_path, "%d.csv"%index)
return pd.read_csv(csv_path)
def merge_data(num = 10):
data = load_finger_data()
for i in range(1,num):
data = data.append(load_finger_data(index = i+1), ignore_index=True)
return data
data = merge_data(num = 9)
data.describe()
%matplotlib inline
import matplotlib.pyplot as plt
data.hist(bins=50, figsize=(20,15))
save_fig("attribute_histogram_plots")
plt.show()
from sklearn.model_selection import StratifiedShuffleSplit
data["index"] = data['p_index']*100+data['m_index']
data['index'].hist()
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(data, data["index"]):
data_train = data.loc[train_index]
data_test = data.loc[test_index]
for set_ in (data_train, data_test):
set_.drop("index", axis=1, inplace=True)
finger = data_train.copy()
finger.plot(kind="scatter", x="m_index", y="Tz")
save_fig("bad_visualization_plot")
finger.plot(kind="scatter", x="p_index", y="Tz",alpha=0.1)
save_fig("better_visualization_plot_p_index")
finger.plot(kind="scatter", x="m_index", y="Tz",alpha=0.1)
save_fig("better_visualization_plot_m_index")
# from pandas.tools.plotting import scatter_matrix # For older versions of Pandas
from pandas.plotting import scatter_matrix
attributes = ["Fx", "Tz", "p_index",
"m_index"]
scatter_matrix(finger[attributes], figsize=(12, 8))
save_fig("scatter_matrix_plot")
```
# Prepare the data
```
finger = data_train.drop(['p_index','m_index','Fx','Fy','Fz','Tx','Ty','Tz'], axis=1) # drop labels for training set
finger_label = data_train["p_index"].copy()
finger_label
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
full_pipeline = Pipeline([
('std_scaler', StandardScaler()),
])
finger_pre = full_pipeline.fit_transform(finger)
finger_pre
```
# Select and train a model
```
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(finger_pre, finger_label)
from sklearn.metrics import mean_squared_error
finger_predictions = lin_reg.predict(finger_pre)
lin_mse = mean_squared_error(finger_label, finger_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(random_state=42)
tree_reg.fit(finger_pre, finger_label)
finger_predictions = tree_reg.predict(finger_pre)
tree_mse = mean_squared_error(finger_label, finger_predictions)
tree_rmse = np.sqrt(tree_mse)
tree_rmse
```
# Fine-ture
```
from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, finger_pre, finger_label,
scoring="neg_mean_squared_error", cv=5)
tree_rmse_scores = np.sqrt(-scores)
def display_scores(scores):
print("Scores:", scores)
print("Mean:", scores.mean())
print("Standard deviation:", scores.std())
display_scores(tree_rmse_scores)
lin_scores = cross_val_score(lin_reg, finger_pre, finger_label,
scoring="neg_mean_squared_error", cv=5)
lin_rmse_scores = np.sqrt(-lin_scores)
display_scores(lin_rmse_scores)
from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor(n_estimators=100, random_state=42)
forest_reg.fit(finger_pre, finger_label)
finger_predictions = forest_reg.predict(finger_pre)
forest_mse = mean_squared_error(finger_label, finger_predictions)
forest_rmse = np.sqrt(forest_mse)
forest_rmse
from sklearn.model_selection import cross_val_score
forest_scores = cross_val_score(forest_reg, finger_pre, finger_label,
scoring="neg_mean_squared_error", cv=5)
forest_rmse_scores = np.sqrt(-forest_scores)
display_scores(forest_rmse_scores)
from sklearn.svm import SVR
svm_reg = SVR(kernel="linear")
svm_reg.fit(finger_pre, finger_label)
finger_predictions = svm_reg.predict(finger_pre)
svm_mse = mean_squared_error(finger_label, finger_predictions)
svm_rmse = np.sqrt(svm_mse)
svm_rmse
svm_scores = cross_val_score(svm_reg, finger_pre, finger_label,
scoring="neg_mean_squared_error", cv=5)
svm_rmse_scores = np.sqrt(-svm_scores)
display_scores(svm_rmse_scores)
from sklearn.model_selection import GridSearchCV
param_grid = [
# try 12 (3×4) combinations of hyperparameters
{'bootstrap': [True],'n_estimators': [3, 10, 30,100], 'max_features': [2, 3,4,5]},
# then try 6 (2×3) combinations with bootstrap set as False
{'bootstrap': [False], 'n_estimators': [3, 10,30,100], 'max_features': [2, 3, 4,5]},
]
forest_reg = RandomForestRegressor(random_state=42)
# train across 5 folds, that's a total of (12+6)*5=90 rounds of training
grid_search = GridSearchCV(forest_reg, param_grid, cv=5,
scoring='neg_mean_squared_error',
return_train_score=True)
grid_search.fit(finger_pre, finger_label)
grid_search.best_params_
grid_search.best_estimator_
cvres = grid_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
print(np.sqrt(-mean_score), params)
final_model_forest = grid_search.best_estimator_
final_forest_scores = cross_val_score(final_model_forest, finger_pre, finger_label,
scoring="neg_mean_squared_error", cv=5)
final_forest_rmse_scores = np.sqrt(-final_forest_scores)
display_scores(final_forest_rmse_scores)
final_model_forest = grid_search.best_estimator_
X_test = data_test.drop(['p_index','m_index','Fx','Fy','Fz','Tx','Ty','Tz'], axis=1)
y_test = data_test["p_index"].copy()
X_test_pre = full_pipeline.transform(X_test)
final_forest_predictions = final_model_forest.predict(X_test_pre)
final_forest_mse = mean_squared_error(y_test, final_forest_predictions)
final_forest_rmse = np.sqrt(final_forest_mse)
final_forest_rmse
from sklearn.model_selection import GridSearchCV
param_grid = [
{'kernel': ['linear'], 'C': [10., 30., 100., 300., 1000., 3000., 10000., 30000.0]},
{'kernel': ['rbf'], 'C': [1.0, 3.0, 10., 30., 100., 300., 1000.0],
'gamma': [0.01, 0.03, 0.1, 0.3, 1.0, 3.0]},
]
svm_reg = SVR()
grid_search = GridSearchCV(svm_reg, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=2)
grid_search.fit(finger_pre, finger_label)
negative_mse = grid_search.best_score_
rmse = np.sqrt(-negative_mse)
rmse
final_model_svm = grid_search.best_estimator_
final_svm_scores = cross_val_score(final_model_svm, finger_pre, finger_label,
scoring="neg_mean_squared_error", cv=5)
final_svm_rmse_scores = np.sqrt(-final_svm_scores)
display_scores(final_svm_rmse_scores)
final_model_svm = grid_search.best_estimator_
X_test = data_test.drop(['p_index','m_index','Fx','Fy','Fz','Tx','Ty','Tz'], axis=1)
y_test = data_test["p_index"].copy()
X_test_pre = full_pipeline.transform(X_test)
final_svm_predictions = final_model_svm.predict(X_test_pre)
final_svm_mse = mean_squared_error(y_test, final_svm_predictions)
final_svm_rmse = np.sqrt(final_svm_mse)
final_svm_rmse
```
# Result
```
rmse = [lin_rmse,tree_rmse,forest_rmse,svm_rmse,0,0]
rmse_scores = [lin_rmse_scores.mean(),tree_rmse_scores.mean(),forest_rmse_scores.mean(),svm_rmse_scores.mean(),final_forest_rmse_scores.mean(),final_svm_rmse_scores.mean()]
rmse,rmse_scores
rmse_test = [0,0,0,0,final_forest_rmse,final_svm_rmse]
result = pd.DataFrame([rmse,rmse_scores,rmse_test],index = ['rmse','rmse_mean','rmse_test'],
columns = ['liner','tree','forest','svm','final_forest','final_svm'])
result
name_list = ['liner','tree','forest','svm','final_forest','final_svm']
num_list_1 = rmse
num_list_2 = rmse_scores
num_list_3 = rmse_test
x =list(range(len(num_list_1)))
total_width, n = 0.8, 3
width = total_width / n
plt.bar(x, num_list_1, width=width, label='rmse',fc = 'y')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(x, num_list_2, width=width, label='rmse_mean',tick_label = name_list,fc = 'r')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(x, num_list_3, width=width, label='rmse_test',tick_label = name_list,fc = 'b')
plt.legend()
save_fig("result")
plt.show()
```
# Save
```
Prepare_forest = Pipeline([
('preparation', full_pipeline),
('forest_reg', final_model_forest)
])
import joblib
joblib.dump(Prepare_forest, "final_model_forest_p_index.pkl") # DIFF
#...
my_model_loaded = joblib.load("final_model_forest_p_index.pkl") # DIFF
result.to_csv('images/finger_p_index/result.csv',index = False, header = ['liner','tree','forest','svm','final_forest','final_svm'])
```
| github_jupyter |
<h1>Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"></ul></div>
# Using the Simulation Archive to restart a simulation
The Simulation Archive (SA) is a binary file that can be used to restart a simulation. This can be useful when running a long simulation. REBOUND can restart simulation *exactly* (bit by bit) when using a SA. There are some restriction to when a SA can be used. Please read the corresponding paper (Rein & Tamayo 2017) for details.
We first setup a simulation in the normal way.
```
import rebound
sim = rebound.Simulation()
sim.integrator = "whfast"
sim.dt = 2.*3.1415/365.*6 # 6 days in units where G=1
sim.add(m=1.)
sim.add(m=1e-3,a=1.)
sim.add(m=5e-3,a=2.25)
sim.move_to_com()
```
We then initialize the SA and specify the output filename and output cadence. We can choose the output interval to either correspond to constant intervals in walltime (in seconds) or simulation time. Here, we choose walltime. To choose simulation time instead replace the `walltime` argument with `interval`.
```
sim.automateSimulationArchive("simulationarchive.bin", walltime=1.,deletefile=True)
```
Now, we can run the simulation forward in time.
```
sim.integrate(2e5)
```
Depending on how fast your computer is, the above command may take a couple of seconds. Once the simulation is done, we can delete it from memory and load it back in from the SA. You could do this at a later time. Note that this will even work if the SA file was generated on a different computer with a different operating system and even a different version of REBOUND. See Rein & Tamayo (2017) for a full discussion on machine independent code.
```
sim = None
sim = rebound.Simulation("simulationarchive.bin")
print("Time after loading simulation %.1f" %sim.t)
```
If we want to integrate the simulation further in time and append snapshots to the same SA, then we need to call the `automateSimulationArchive` method again (this is fail safe mechanism to avoid accidentally modifying a SA file). Note that we set the `deletefile` flag to `False`. Otherwise we would create a new empty SA file. This outputs a warning because the file already exists (which is ok since we want to append that file).
```
sim.automateSimulationArchive("simulationarchive.bin", walltime=1.,deletefile=False)
```
Now, let's integrate the simulation further in time.
```
sim.integrate(sim.t+2e5)
```
If we repeat the process, one can see that the SA binary file now includes the new snapshots from the restarted simulation.
```
sim = None
sim = rebound.Simulation("simulationarchive.bin")
print("Time after loading simulation %.1f" %sim.t)
```
A few things to note when restarting a simulation from a SA:
- If you used any additional forces or post-timestep modifications in the original simulation, then those need to be restored after loading a simulation from a SA. A RuntimeWarning may be given related to this indicating the need to reset function pointers after creating a reb_simulation struct with a binary file.
- If you use the symplectic WHFast integrator with the safe mode turned off, then the simulation will be in an unsychronized state after reloading it. If you want to generate an output, then the simulation needs to be synchronized beforehand. See the WHFast tutorial on how to do that.
- If you use the symplectic WHFast integrator with the safe mode turned off in order to combine kepler steps (see the Advanced WHFast tutorial), but want to preserve bitwise reproducibility when integrating to different times in the simulation or to match SimulationArchive snapshots, you need to manually set sim.ri_whfast.keep_unsynchronized = 1. This ensures that the integration state does not change depending on if and when you generate outputs.
- For reproducibility, the SimulationArchive does not output snapshots at the *exact* intervals specified, but rather at the timestep in the integration directly following each interval. This means that if you load from a SimulationArchive and want to reproduce the state in a snapshot later on, you have to pass `exact_finish_time=0` in a call to `sim.integrate`.
| github_jupyter |
# Image Classification using a Multi-Layer Neural Network
Next, we measure the performance of a multi-layer neural network on the MNIST dataset to set a baseline.
The layers of the same are wrapped in an **nn.Sequential** object.
```
# Code adapted from https://github.com/activatedgeek/LeNet-5/
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision.datasets.mnist import MNIST
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
class MultilayerClassifier(nn.Module):
"""
Input - 1x32x32
Output - 10 (Output)
"""
def __init__(self):
super(MultilayerClassifier, self).__init__()
self.fc = nn.Sequential(OrderedDict([
('linear_combination', nn.Linear(32 * 32, 32 * 4)),
('relu1', nn.ReLU()),
('fc2', nn.Linear(32 * 4, 10)),
]))
def forward(self, img):
output = img.view(-1, 32 * 32)
output = self.fc(output)
return output
data_train = MNIST('data/mnist',
download=True,
transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor()]))
data_test = MNIST('data/mnist',
train=False,
download=True,
transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor()]))
data_train_loader = DataLoader(data_train, batch_size=256, shuffle=True, num_workers=8)
data_test_loader = DataLoader(data_test, batch_size=1024, num_workers=8)
net = MultilayerClassifier()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=2e-3)
def train(epoch):
net.train()
loss_list, batch_list = [], []
for i,(images, labels) in enumerate(data_train_loader):
images, labels = Variable(images), Variable(labels)
optimizer.zero_grad()
output = net(images)
loss = criterion(output, labels)
loss_list.append(loss.data.item())
batch_list.append(i+1)
if i % 10 == 0:
print('Train - Epoch %d, Batch: %d, Loss: %f' % (epoch, i, loss.data.item()))
loss.backward()
optimizer.step()
def test():
net.eval()
total_correct = 0
avg_loss = 0.0
for i, (images, labels) in enumerate(data_test_loader):
images, labels = Variable(images), Variable(labels)
output = net(images)
avg_loss += criterion(output, labels).sum()
pred = output.data.max(1)[1]
total_correct += pred.eq(labels.data.view_as(pred)).sum()
avg_loss /= len(data_test)
print('Test Avg. Loss: %f, Accuracy: %f' % (avg_loss.data.item(), float(total_correct) / len(data_test)))
def train_and_test(epoch):
train(epoch)
test()
def main():
for e in range(1, 5): # Change 5 to 16 for better performance
train_and_test(e)
if __name__ == '__main__':
main()
```
The accuracy we get with just two layers is around 97%, which is a huge improvement over single-layer models on the MNIST dataset.
| github_jupyter |
```
from shared_notebook_utils import *
from analysis_algorithms import *
import essentia
import essentia.standard as estd
import random
dataset = Dataset('toy_dataset')
%matplotlib inline
# This notebook contains excerpts from the article: Font, F., & Serra, X. (2016). Tempo Estimation for Music Loops and a Simple Confidence Measure. In Proceedings of the Int. Conf. on Music Information Retrieval (ISMIR).
# License: CC-BY-4.0
```
# Confidence measure
Assuming that we obtain a BPM estimate for a given audio signal, the confidence measure that we propose is based on comparing the duration of the whole audio signal with a multiple of the duration of a single beat according to the estimated BPM. If the actual duration of the signal is close to a multiple of the duration of a single beat, we hypothesise that the BPM estimation is reliable.
We consider the best BPM estimate of a tempo estimation algorithm to be its nearest integer value (see paper for more details).
Given the sample rate $SR$ of an audio signal and its estimated tempo $BPM^e$, we can estimate the duration (or length) of an individual beat in number of samples $l^b$ as
$$l^b = \frac{60 \cdot SR}{BPM^e}.$$
Then, potential durations for the audio signal can be computed as multiples of the individual beat duration, $L[n] = n \cdot l^b$, where $n \geq 1, n \in \mathbb{Z}$.
In our computation, we restrict $n$ to the range $1 \le n \le 128$.
This is decided so that the range can include loops that last from only 1 beat to 128 beats, which would correspond to a maximum of 32 bars in 4/4 meter.
In practice, what we need here is a number big enough such that we wont find loops longer than it.
Given $L$, what we need to see at this point is if any of its elements closely matches the actual length of the original audio signal.
To do that, we take the actual length of the audio signal $l^a$ (in number of samples), compare it with all elements of $L$ and keep the minimum difference found:
$$ \Delta l = \min\{|L[n]-l^a|:n\le 128\}. $$
A value of $\Delta l$ near 0 means that there is a close match between one of the potential lengths and the actual length of the audio signal.
Having computed $\Delta l$, we finally define our confidence measure as
$$
confidence = \begin{cases}
0 & \text{if } \Delta l > \lambda \\
1 - \frac{\Delta l}{\lambda} & \text{otherwise}\\
\end{cases},
$$
where $\lambda$ is a parameter set to half the duration of a single beat ($\lambda = 0.5 \cdot l^b$). In this way, if $l^a$ exactly matches one of the multiples of $l^b$, the confidence will be 1. If $\Delta l$ is as long as half the duration between beats, the confidence will be 0 (see top of the figure below).
The reasoning behind this simple confidence measure is that it is very unlikely that, only by chance, an audio signal has a duration which closely matches a multiple of the beat duration for a given estimated BPM. This means that we assume that there is a relation between the duration of the signal and its BPM, and therefore our proposed confidence will fail if the audio signal contains silence (either at the beginning or at the end) which is not part of the loop itself (i.e.,~ the loop is not *accurately cut*).
To account for this potential problem, we estimate the duration that the audio signal would have if we removed silence at the beginning, at the end, or both at the beginning and at the end.
We take the envelope of the original audio and consider the effective starting point of the loop as being the point in time $t_s$ where the envelope amplitude raises above 5\% of the maximum.
Similarly, we consider the effective end $t_e$ at the *last point* where the envelope goes below the 5\% of the maximum amplitude (or at the end of the audio signal if envelope is still above 5\%).
Taking $t_s$, $t_e$, and $l^a$ (the original signal length), we can then compute three alternative estimates for the duration of the loop ($l_0^{a}$, $l_1^{a}$ and $l_2^{a}$) by *i)* disregarding silence at the beginning ($l_0^{a} = l^a - t_s$), *ii)* disregarding silence a the end ($l_1^{a} = t_e$), and *iii)* disregarding silence both at the beginning and at the end ($l_2^{a} = t_e - t_s$).
Then, we repeat the previously described confidence computation with the three extra duration estimates $l_0^{a}$, $l_1^{a}$ and $l_2^{a}$.
Note that these will produce meaningful results in cases where the original loop contains silence which is not relevant from a musical point of view, but they will not result in meaningful confidence values if the loop contains silence at the beginning or at the end which is in fact part of the loop (i.e.,~which is needed for it seamless repetition).
Our final confidence value is taken as the maximum confidence obtained when using any of $l^{a}$, $l_0^{a}$, $l_1^{a}$ and $l_2^{a}$ estimated signal durations (see bottom of figure below).
Because the confidence measure that we propose only relies on a BPM estimate and the duration of the audio signal, it can be used in combination with any existing tempo estimation algorithm. Also, it is computationally cheap to compute as the most complex operation it requires is the envelope computation. However, this confidence measure should not be applied to content other than music loops as it only produces meaningful results under the assumption that tempo is completely steady across the whole signal.
```
# The following code exemplifies the computation of the confidence measure for two different sound examples
# and generates Figure 1 of the paper.
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(17, 5))
sample_rate=44100
# Top of the figure: loop for which BPM estimation fails
########################################################
# Select and load a sound
# Sound: "edison_140d.wav" by NoiseCollector, got from Freesound at http://www.freesound.org/people/NoiseCollector/sounds/63470/
# License: CC-BY-3.0
selected_sound = dataset.data['63470']
print title('Selected sound id: %s' % selected_sound['id'])
sound_file_path = os.path.join(dataset.dataset_path, selected_sound['wav_sound_path'])
selected_sound['file_path'] = sound_file_path
audio_1 = load_audio_file(file_path=sound_file_path, sample_rate=sample_rate)
bpm_1 = algorithm_rhythm_percival14(selected_sound)['Percival14']['bpm']
bpm_1 = int(round(bpm_1))
IPython.display.display(IPython.display.Audio(sound_file_path), embed=True)
print 'Selected sound ground truth bpm: %.2f' % selected_sound['annotations']['bpm']
print 'Selected sound estimated bpm: %.2f' % bpm_1
# Compute confidence based on "standard" audio signal duration
beat_duration = (60.0 * sample_rate)/bpm_1
L = [beat_duration * n for n in range(1, 128)]
thr_lambda = 0.5 * beat_duration
la = audio_1.shape[0]
delta_l = min([abs(l - la) for l in L])
if delta_l > thr_lambda:
confidence_la = 0.0
else:
confidence_la = (1.0 - float(delta_l) / thr_lambda)
print ' Confidence: %.2f' % confidence_la
# Plot
ax1.plot(normalize2(audio_1), color="gray", alpha=0.5)
ax1.vlines(L, -1, 1, color='black', linewidth=1, linestyle="--")
ax1.vlines([350, la], -1, 1, color='red', linewidth=2)
annotate_point_pair(ax1, r'$l^a$', (0, -0.65), (la, -0.65), xycoords='data', text_offset=16, text_size=16)
annotate_point_pair(ax1, r'$l^b$', (L[1], 0.75), (L[2], 0.75), xycoords='data', text_offset=16, text_size=16)
annotate_point_pair(ax1, r'$\Delta l$', (la, -0.35), (la + delta_l, -0.35), xycoords='data', text_offset=16, textx_offset=-2000, text_size=16)
annotate_point_pair(ax1, r'$\lambda$', (la + delta_l - thr_lambda, 0.85), (la + delta_l, 0.85), xycoords='data', text_offset=16, textx_offset=-2000, text_size=16)
confidence_output = list()
for i in range(0, la*2):
delta = min([abs(l - i) for l in L])
if delta > thr_lambda:
confidence_output.append(0.0)
else:
value = 1.0 - float(delta) / thr_lambda
confidence_output.append(value)
ax1.plot(confidence_output, color=COLORS[2])
ax1.set_xlim((0, la + 44100/2))
ax1.set_ylim((-1, 1))
#ax1.set_xlabel('Time (samples)')
# Bottom of the figure: loop for which BPM estimation works but that has silence at the beggining
#################################################################################################
# Select and load sound and add 100 ms silence at the beginning and at the end
# Sound: "91Apat99999.wav" by NoiseCollector, got from Freesound at http://www.freesound.org/people/NoiseCollector/sounds/43209/
# License: CC-BY-3.0
selected_sound = dataset.data['43209']
print title('Selected sound id: %s' % selected_sound['id'])
sound_file_path = os.path.join(dataset.dataset_path, selected_sound['wav_sound_path'])
selected_sound['file_path'] = sound_file_path
audio_1 = load_audio_file(file_path=sound_file_path, sample_rate=sample_rate)
n_samples_silence = 4410
audio_2 = np.concatenate((np.zeros(n_samples_silence), audio_1, np.zeros(n_samples_silence)))
bpm_2 = algorithm_rhythm_percival14(selected_sound)['Percival14']['bpm']
bpm_2 = int(round(bpm_2))
IPython.display.display(IPython.display.Audio(sound_file_path), embed=True)
print 'Selected sound ground truth bpm: %.2f' % selected_sound['annotations']['bpm']
print 'Selected sound estimated bpm: %.2f' % bpm_2
# Compute confidence based on different durations
beat_duration = (60.0 * sample_rate)/bpm_2
L = [beat_duration * n for n in range(1, 128)] # From 1 beat to 32 beats (would be 32 bars in 4/4)
thr_lambda = 0.5 * beat_duration
z = 0.05 # Percentage of the envelope amplitude that we use to compute start and end of signal
env = estd.Envelope(attackTime=10, releaseTime=10)
envelope = env(essentia.array(audio_2))
env_threshold = envelope.max() * z
envelope_above_threshold = np.where(envelope >= env_threshold)
start_effective_duration = envelope_above_threshold[0][0]
end_effective_duration = envelope_above_threshold[0][-1]
la = audio_2.shape[0]
durations_to_check = [
('Standard duration', la),
('Removed silence beginning', la - start_effective_duration),
('Removed silence end', end_effective_duration),
('Removed slience beginning and end', end_effective_duration - start_effective_duration)
]
for name, duration in durations_to_check:
delta_l = min([abs(l - duration) for l in L])
if delta_l > thr_lambda:
confidence = 0.0
else:
confidence = (1.0 - float(delta_l) / thr_lambda)
print ' Confidence for "%s": %.2f' % (name, confidence)
# Plot
ax2.plot(normalize2(audio_2), color="gray", alpha=0.5)
ax2.plot(normalize2(envelope), color=COLORS[1])
ax2.vlines([l + start_effective_duration for l in L], -1, 1, color='black', linewidth=1, linestyle="--")
ax2.vlines([start_effective_duration, end_effective_duration], -1, 1, color='red', linewidth=2, linestyle=":")
ax2.vlines([350, la], -1, 1, color='red', linewidth=2)
annotate_point_pair(ax2, r'$l^a$', (0, -0.65), (la, -0.65), xycoords='data', text_offset=16, text_size=16)
annotate_point_pair(ax2, r'$l_0^a$', (start_effective_duration, -0.25), (la, -0.25), xycoords='data', text_offset=16, text_size=16)
annotate_point_pair(ax2, r'$l_1^a$', (0, 0.15), (end_effective_duration, 0.15), xycoords='data', text_offset=16, text_size=16)
annotate_point_pair(ax2, r'$l_2^a$', (start_effective_duration, 0.55), (end_effective_duration, 0.55), xycoords='data', text_offset=16, text_size=16)
confidence_output = list()
for i in range(0, la*2):
delta = min([abs(l - i) for l in L])
if delta > thr_lambda:
confidence_output.append(0.0)
else:
value = 1.0 - float(delta) / thr_lambda
confidence_output.append(value)
confidence_output = list(np.zeros(start_effective_duration)) + confidence_output
ax2.plot(confidence_output, color=COLORS[2])
ax2.set_xlim((0, la + 44100/2))
ax2.set_ylim((-1, 1))
ax2.set_xlabel('Time (samples)')
plt.show()
figure_caption = """
**Figure 1**: Visualisation of confidence computation output according to BPM estimation and signal duration (green curves). The top figure shows a loop whose annotated tempo is 140 BPM but the predicted tempo is 119 BPM.
The duration of the signal $l^a$ does not closely match any multiple of $l^b$ (dashed vertical lines), and the output confidence is 0.59 (i.e.,~$1 - \Delta l / \lambda$).
The figure at the bottom shows a loop that contains silence at the beginning and at the end, and for which tempo has been correctly estimated as being 91 BPM.
The yellow curve represents its envelope and the vertical dashed red lines the estimated effective start and end points.
Note that $l_2^a$ closely matches a multiple of $l^b$, resulting in a confidence of 0.97. The output confidence computed with $l^{a}$, $l_0^{a}$ and $l_1^{a}$ produces lower values.
"""
IPython.display.display(IPython.display.Markdown(figure_caption))
```
| github_jupyter |
```
CELOSS = "Cross Entropy"
POLYLOSS = "Poly-tailed Loss"
import wandb
import os
import pickle
import shutil
from pathlib import Path
from typing import List, Union
def get_runs(user="", project="", query={}, **kwargs):
api = wandb.Api()
runs = api.runs(path=f"{user}/{project}", filters=query)
return runs
#dataframes = [run.history(**kwargs) for run in runs]
#return list(zip(runs, dataframes))
# CelebA
queries = {}
## ERM
queries["erm"] = ("kealexanderwang",
{"$and": [{"state": "finished"},
{"group": {"$in": ["2021-10-01_celeba_2", "2021-10-04_cifar"]}},
{"tags": "erm"},
{"tags": {"$ne": "ignore"}},
]
})
## RW
queries["rw"] = ("kealexanderwang",
{"$and": [{"state": "finished"},
{"group": {"$in": ["2021-10-01_celeba_2", "2021-10-04_cifar"]}},
{"tags": "reweighted"},
{"tags": {"$ne": "early-stopped"}},
{"tags": {"$ne": "ignore"}},
]
})
## RW + Early stop
queries["rwes"] = ("kealexanderwang",
{"$and": [{"state": "finished"},
{"group": {"$in": ["2021-10-01_celeba_2", "2021-10-04_cifar"]}},
{"tags": "early-stopped"},
{"tags": "reweighted"},
{"tags": {"$ne": "ignore"}},
]
})
# TODO: Runs below
## RW2 exponentiated
queries["rwexp"] = ("kealexanderwang",
{"$and": [{"state": "finished"},
{"group": {"$in": ["2021-10-03_celeba_exponent", "2021-10-03_cifar_exponent"]}},
{"tags": "reweighted"},
{"tags": {"$ne": "early-stopped"}},
{"tags": {"$ne": "ignore"}},
]
})
## RW-2x
# queries["rw2x"] = ("nschat",
# {"$and": [{"state": "finished"},
# {"group": {"$in": ["2021-09-21_subsampled-celeba", "2021-09-22_cifar"]}},
# {"tags": "reweighted"},
# {"tags": {"$ne": "early-stopped"}},
# ]
# })
## RW-2x + Early stop
# queries["rw2xes"] = ("nschat",
# {"$and": [{"state": "finished"},
# {"group": {"$in": ["2021-09-21_subsampled-celeba", "2021-09-22_cifar"]}},
# {"tags": "early-stopped"},
# {"tags": "reweighted"},
# ]
# })
queries["rwexpes"] = ("kealexanderwang",
{"$and": [{"state": "finished"},
{"group": {"$in": ["2021-10-03_celeba_exponent", "2021-10-03_cifar_exponent"]}},
{"tags": "reweighted"},
{"tags": "early-stopped"},
{"tags": {"$ne": "ignore"}},
]
})
## RW32x
# queries["rw32x"] = ("nschat",
# {"$and": [{"state": "finished"},
# {"group": {"$in": ["2021-09-22_cifar_scaled_up"]}},
# {"tags": "reweighted"},
# {"tags": {"$ne": "early-stopped"}},
# ]
# })
# ## RW32x + Early stop
# queries["rw32xes"] = ("nschat",
# {"$and": [{"state": "finished"},
# {"group": {"$in": ["2021-09-22_cifar_scaled_up"]}},
# {"tags": "early-stopped"},
# {"tags": "reweighted"},
# ]
# })
def parse_run(run):
config = run.config
df = run.history(keys=["test/test_reweighted_acc"])
acc = df["test/test_reweighted_acc"].dropna().iloc[0] # there should only be one logged
assert acc > 0.
stats = {
"name": run.name,
"loss": config["loss_fn/_target_"],
"dataset": config["datamodule/group_datamodule_cls_name"],
"seed": config["seed"],
"acc": acc,
}
return stats
stats_list = []
for query_name, user__query in queries.items():
user, query = user__query
project = "importance-reweighing"
runs = get_runs(user=user, project=project, query=query)
stats_of_runs = [parse_run(run) for run in runs]
for stats in stats_of_runs:
stats["query"] = query_name
stats_list += stats_of_runs
import pandas as pd
df = pd.DataFrame(stats_list)
df[(df["dataset"] == "CelebADataModule") & (df["query"] == "rwes")]
df.head(2)
def remap(old, new, arg):
return new if arg == old else arg
df["loss"] = df["loss"].apply(lambda a: remap("torch.nn.CrossEntropyLoss", CELOSS, a))
df["loss"] = df["loss"].apply(lambda a: remap("src.loss_fns.PolynomialLoss", POLYLOSS, a))
df["query"] = df["query"].apply(lambda a: remap("erm", "No IW", a))
df["query"] = df["query"].apply(lambda a: remap("rw", "IW", a))
df["query"] = df["query"].apply(lambda a: remap("rwexp", "IW-Exp", a))
df["query"] = df["query"].apply(lambda a: remap("rwes", "IW-ES", a))
df["query"] = df["query"].apply(lambda a: remap("rwexpes", "IW-Exp-ES", a))
df.to_csv("results.csv", index=False)
```
# Begin plots
```
import pandas as pd
df = pd.read_csv("results.csv")
df = df.sort_values("loss", ascending=False)
from collections import defaultdict
p_values = {"ImbalancedCIFAR10DataModule": defaultdict(float),
"CelebADataModule": defaultdict(float),
}
from hypothetical.hypothesis import tTest
dataset_name = "ImbalancedCIFAR10DataModule"
df_ = df[df["dataset"] == dataset_name]
for query in df_["query"].unique():
ce_accs = df_.loc[(df_["loss"] == CELOSS) & (df_["query"] == query), ["seed", "acc"]]
poly_accs = df_.loc[(df_["loss"] == POLYLOSS) & (df_["query"] == query), ["seed", "acc"]]
ce_accs = ce_accs.set_index("seed")
poly_accs = poly_accs.set_index("seed")
# if query == "IW":
# ce_accs = ce_accs.drop(index=4) # seed 4 failed for poly loss, so we also drop cross entropy results
acc_pairs = pd.concat([ce_accs.rename(columns={"acc": "ce_acc"}), poly_accs.rename(columns={"acc": "poly_acc"})], axis=1)
ttest = tTest(y1=acc_pairs["poly_acc"],
y2=acc_pairs["ce_acc"],
var_equal=False,
paired=True,
alternative="greater",
alpha=0.05
)
p_value = ttest.test_summary['p-value']
print(f"{query}: {p_value:.5f}")
p_values[dataset_name][query] = p_value
from hypothetical.hypothesis import tTest
dataset_name = "CelebADataModule"
df_ = df[df["dataset"] == dataset_name]
for query in df_["query"].unique():
ce_accs = df_.loc[(df_["loss"] == CELOSS) & (df_["query"] == query), ["seed", "acc"]]
poly_accs = df_.loc[(df_["loss"] == POLYLOSS) & (df_["query"] == query), ["seed", "acc"]]
ce_accs = ce_accs.set_index("seed")
poly_accs = poly_accs.set_index("seed")
acc_pairs = pd.concat([ce_accs.rename(columns={"acc": "ce_acc"}), poly_accs.rename(columns={"acc": "poly_acc"})], axis=1)
ttest = tTest(y1=acc_pairs["poly_acc"],
y2=acc_pairs["ce_acc"],
var_equal=False,
paired=True,
alternative="greater",
alpha=0.05
)
p_value = ttest.test_summary['p-value']
print(f"{query}: {p_value:.6f}")
p_values[dataset_name][query] = p_value
import numpy as np
df_ = df.copy()
df_ = df_.drop(columns=["name"])
df_.loc[:, "ES"] = df_.loc[:, "query"].str.contains("ES")
df_.loc[:, "interp"] = ~df_.loc[:, "ES"]
df_ = df_.melt(id_vars=["dataset", "loss", "acc", "seed", "query"],
var_name="group",
value_name="tmp")
df_ = df_.drop(columns="tmp")
df_ = df_.pivot_table(index=["dataset", "group", "query", "seed"], columns="loss", values="acc")
def hypothesis_test(group):
ttest = tTest(y1=group[POLYLOSS],
y2=group[CELOSS],
var_equal=False,
paired=True,
alternative="greater",
alpha=0.05
)
p_value = ttest.test_summary['p-value']
return p_value
def stderr(x):
return x.std() / len(x) ** 0.5
means = df_.groupby(level=[0,1,2]).agg(np.mean).round(3)
stderrs = df_.groupby(level=[0,1,2]).agg(stderr).round(3)
p_values_df = df_.groupby(level=[0,1,2]).apply(hypothesis_test).round(3)
p_values_df = p_values_df.to_frame(name="p-value")
table = means.merge(stderrs, left_index=True, right_index=True, suffixes=[" mean accuracy", " standard error"])
table = table.merge(p_values_df, left_index=True, right_index=True, suffixes=["", ""])
table = table.reindex(columns=["Cross Entropy mean accuracy", "Cross Entropy standard error", "Poly-tailed Loss mean accuracy", "Poly-tailed Loss standard error", "p-value"])
new_columns = pd.MultiIndex.from_tuples([("Cross Entropy", "mean"), ("Cross Entropy", "standard error"), ("Poly-tailed Loss", "mean"), ("Poly-tailed Loss", "standard error"), ("", "p-value")])
table.columns = new_columns
table
print(table.to_latex())
df_.index
y1 = df_.loc[("ImbalancedCIFAR10DataModule", "interp", "No IW"), "Cross Entropy"]
y2 = df_.loc[("ImbalancedCIFAR10DataModule", "interp", "IW-Exp"), "Poly-tailed Loss"]
y1.mean()
y2.mean()
cifar_p_value = hypothesis_test(pd.concat([y1, y2], axis=1))
def get_corners(rectangle):
b = rectangle
w,h = b.get_width(), b.get_height()
# lower left vertex
x0, y0 = b.xy
# lower right vertex
x1, y1 = x0 + w, y0
# top left vertex
x2, y2 = x0, y0 + h
# top right vertex
x3, y3 = x0 + w, y0 + h
return (x0,y0), (x1,y1), (x2,y2), (x3,y3)
def outline_bracket(left_bar, right_bar, spacing, height):
l0, l1, l2, l3 = get_corners(left_bar)
r0, r1, r2, r3 = get_corners(right_bar)
# lower left
b0 = ((l0[0] + l1[0]) / 2, max(l2[1], r2[1]) + spacing)
# upper left
b1 = (b0[0], max(l2[1] + spacing, r2[1] + spacing) + height)
# upper right
b2 = ((r0[0] + r1[0]) / 2, b1[1])
# lower right
b3 = (b2[0], b0[1])
return b0, b1, b2, b3
```
## Interpolation results
```
df_interp = df[df["query"].isin(["No IW", "IW", "IW-Exp"])]
df_interp
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import style
plt.rc('text', usetex=True)
plt.rc('font', family='times')
palette = ['#E24A33', '#348ABD', '#988ED5', '#777777', '#FBC15E', '#8EBA42', '#FFB5B8']
sns.set_palette(palette)
fig, axes = plt.subplots(figsize=(20, 5), ncols=2)
ax = axes[0]
dataset_name = "ImbalancedCIFAR10DataModule"
bar = sns.barplot(data=df_interp[df_interp["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.9, saturation=0.75, order=["No IW", "IW", "IW-Exp"], ci=68, errcolor=(0, 0, 0, 0.9))
sns.stripplot(data=df_interp[df_interp["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.7, order=["No IW", "IW", "IW-Exp"], dodge=True, edgecolor="black", linewidth=1.7)
ax.set(ylim=[0.4, 0.7])
ax.legend().remove()
ax.set(title=r"Imbalanced Binary CIFAR10")
ax.set(ylabel=r"Test Accuracy")
ax.set(xlabel=None)
ax.set(xlabel=None)
hatches = ["+","+","+", "x", "x", "x"]
for i, b in enumerate(bar.patches):
b.set_hatch(hatches[i])
b.set_edgecolor((1, 1, 1, 1.))
queries = [label.get_text() for label in ax.get_xticklabels()]
for i in range(len(queries)):
query = queries[i]
p_value = p_values[dataset_name][query]
if p_value < 0.05:
star = r"$**$" if p_value < 0.005 else r"$*$"
left_bar = bar.patches[i]
right_bar = bar.patches[i + len(queries)]
bracket = outline_bracket(left_bar, right_bar, spacing=0.02, height=0.005)
b_xs, b_ys = list(zip(*bracket))
ax.plot(b_xs, b_ys, c="k")
ax.text((b_xs[1] + b_xs[2]) / 2, b_ys[1] + 0.005, star, ha="center", va="bottom", color="k", fontsize=30)
if cifar_p_value < 0.05:
star = r"$**$" if cifar_p_value < 0.005 else r"$*$"
left_bar = bar.patches[3]
right_bar = bar.patches[2]
bracket = outline_bracket(left_bar, right_bar, spacing=0.035, height=0.005)
b_xs, b_ys = list(zip(*bracket))
ax.plot(b_xs, b_ys, c="k")
ax.text((b_xs[1] + b_xs[2]) / 2, b_ys[1] + 0.005, star, ha="center", va="bottom", color="k", fontsize=30)
ax.set(xticklabels=["No IW", "IW ($\overline w$)", r"IW ($\overline w^{3/2})$"]) # Put at the end because p_values dict is named using old keys
ax.set_axisbelow(True)
dataset_name = "CelebADataModule"
ax = axes[1]
bar = sns.barplot(data=df_interp[df_interp["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.9, saturation=0.75, order=["No IW", "IW", "IW-Exp"], ci=68, errcolor=(0, 0, 0, 0.9))
sns.stripplot(data=df_interp[df_interp["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.7, order=["No IW", "IW", "IW-Exp"], dodge=True, edgecolor="black", linewidth=1)
ax.set(ylim=[0.7, 0.9])
ax.set(title=r"Subsampled CelebA")
ax.set(ylabel=r"Test Accuracy")
ax.set(xlabel=None)
hatches = ["+","+","+", "x", "x", "x"]
for i, b in enumerate(bar.patches):
b.set_hatch(hatches[i])
b.set_edgecolor((1, 1, 1, 1.))
queries = [label.get_text() for label in ax.get_xticklabels()]
for i in range(len(queries)):
query = queries[i]
p_value = p_values[dataset_name][query]
if p_value < 0.05:
star = r"$**$" if p_value < 0.005 else r"$*$"
left_bar = bar.patches[i]
right_bar = bar.patches[i + len(queries)]
bracket = outline_bracket(left_bar, right_bar, spacing=0.014, height=0.005)
b_xs, b_ys = list(zip(*bracket))
ax.plot(b_xs, b_ys, c="k")
ax.text((b_xs[1] + b_xs[2]) / 2, b_ys[1] + 0.005, star, ha="center", va="bottom", color="k", fontsize=30)
ax.set(xticklabels=["No IW", r"IW ($\overline w$)", r"IW ($\overline w^{2})$"])
ax.set_axisbelow(True)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:], fontsize=20, loc="upper left")
fig.suptitle("Trained to Interpolation", fontsize=30, y=1.02)
fig.savefig("interpolated.pdf", bbox_inches="tight")
```
## Early stopped results
```
df_es = df[df["query"].isin(["IW", "IW-ES", "IW-Exp-ES"])]
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import style
plt.rc('text', usetex=True)
plt.rc('font', family='times')
palette = ['#E24A33', '#348ABD', '#988ED5', '#777777', '#FBC15E', '#8EBA42', '#FFB5B8']
sns.set_palette(palette)
fig, axes = plt.subplots(figsize=(20, 5), ncols=2)
ax = axes[0]
dataset_name = "ImbalancedCIFAR10DataModule"
bar = sns.barplot(data=df_es[df_es["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.9, saturation=0.75, order=["IW", "IW-ES", "IW-Exp-ES"], ci=68, errcolor=(0, 0, 0, 0.9))
sns.stripplot(data=df_es[df_es["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.7, order=["IW", "IW-ES", "IW-Exp-ES"], dodge=True, edgecolor="black", linewidth=1)
ax.set(ylim=[0.4, 0.7])
ax.legend().remove()
ax.set(title=r"Imbalanced Binary CIFAR10")
ax.set(ylabel=r"Test Accuracy")
ax.set(xlabel=None)
hatches = ["+","+","+", "x", "x", "x"]
for i, b in enumerate(bar.patches):
b.set_hatch(hatches[i])
b.set_edgecolor((1, 1, 1, 1.))
queries = [label.get_text() for label in ax.get_xticklabels()]
for i in range(len(queries)):
query = queries[i]
p_value = p_values[dataset_name][query]
if p_value < 0.05:
star = r"$**$" if p_value < 0.005 else r"$*$"
left_bar = bar.patches[i]
right_bar = bar.patches[i + len(queries)]
bracket = outline_bracket(left_bar, right_bar, spacing=0.02, height=0.005)
b_xs, b_ys = list(zip(*bracket))
ax.plot(b_xs, b_ys, c="k")
ax.text((b_xs[1] + b_xs[2]) / 2, b_ys[1] + 0.005, star, ha="center", va="bottom", color="k", fontsize=30)
ax.set(xticklabels=[r"IW ($\overline w$)", r"IW-ES ($\overline w$)", r"IW-ES ($\overline w^{3/2}$)"])
ax.set_axisbelow(True)
dataset_name = "CelebADataModule"
ax = axes[1]
bar = sns.barplot(data=df_es[df_es["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.9, saturation=0.75, order=["IW", "IW-ES", "IW-Exp-ES"], ci=68, errcolor=(0, 0, 0, 0.9))
sns.stripplot(data=df_es[df_es["dataset"] == dataset_name], x="query", y="acc", hue="loss", ax=ax, alpha=0.7, order=["IW", "IW-ES", "IW-Exp-ES"], dodge=True, edgecolor="black", linewidth=1)
ax.set(ylim=[0.7, 0.9])
ax.set(title=r"Subsampled CelebA")
ax.set(ylabel=r"Test Accuracy")
ax.set(xlabel=None)
hatches = ["+","+","+", "x", "x", "x"]
for i, b in enumerate(bar.patches):
b.set_hatch(hatches[i])
b.set_edgecolor((1, 1, 1, 1.))
queries = [label.get_text() for label in ax.get_xticklabels()]
for i in range(len(queries)):
query = queries[i]
p_value = p_values[dataset_name][query]
if p_value < 0.05:
star = r"$**$" if p_value < 0.005 else r"$*$"
left_bar = bar.patches[i]
right_bar = bar.patches[i + len(queries)]
bracket = outline_bracket(left_bar, right_bar, spacing=0.014, height=0.005)
b_xs, b_ys = list(zip(*bracket))
ax.plot(b_xs, b_ys, c="k")
ax.text((b_xs[1] + b_xs[2]) / 2, b_ys[1] + 0.005, star, ha="center", va="bottom", color="k", fontsize=30)
ax.set(xticklabels=[r"IW ($\overline w$)", r"IW-ES ($\overline w$)", r"IW-ES ($\overline w^{2}$)"])
ax.set_axisbelow(True)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:], fontsize=20, loc="upper left")
fig.suptitle("Early-stopped", fontsize=30, y=1.02)
fig.savefig("early-stopped.pdf", bbox_inches="tight")
```
| github_jupyter |
# Welcome to the Retail Demo Store Workshops
The workshops in this project are designed to walk you through incrementally adding functionality to the base Retail Demo Store application. Some of the workshops build on each other so it is recommended to follow the workshops in order unless otherwise instructed as part of an organized event or workshop.
**IMPORTANT: The workshops are implemented using Jupyter notebooks that are designed to be executed from a SageMaker Notebook instance in an AWS account where the Retail Demo Store has been deployed. Therefore, the notebooks may not be fully functional outside AWS such as on your local machine. The Retail Demo Store's deployment templates will create the SageMaker Notebook instance and preload the workshop notebooks for you.**
## Retail Demo Store Architecture
Before opening and walking through the workshops, let's get familiar with the Retail Demo Store architecture and infrastructure deployed into your AWS account. Establishing this foundation will make the workshops more understandable and relatable back to the functionality being enhanced.
The core of the Retail Demo Store is a polyglot microservice architecture deployed as a collection of RESTful web services in [Amazon Elastic Container Service](https://aws.amazon.com/ecs/) (ECS). Several AWS managed services are leveraged to provide build, deployment, authentication, messaging, search, and personalization capabilities.

## Personalization, Messaging, Analytics, and AB Testing Architecture
The Retail Demo Store provides personalized user experiences in the user interface using Amazon Personalize. Amazon Pinpoint and Braze are integrated into the Retail Demo Store workshop environment to provide personalized email messaging capabilities via Amazon Personalize. Amplitude is integrated to provide real-time user behavior analytics. Optimizely is used for feature flagging and AB testing Personalize models.

### Microservices
The **[Users](https://github.com/aws-samples/retail-demo-store/tree/master/src/users)**, **[Products](https://github.com/aws-samples/retail-demo-store/tree/master/src/products)**, **[Carts](https://github.com/aws-samples/retail-demo-store/tree/master/src/carts)**, and **[Orders](https://github.com/aws-samples/retail-demo-store/tree/master/src/orders)** web services located in ECS rectangle in the above diagram provide access to retrieving and updating each respective entity type. These services are built with the [Golang](https://golang.org/) programming language and provide very basic implementations.
The **[Search](https://github.com/aws-samples/retail-demo-store/tree/master/src/search)** service leverages [Amazon Elasticsearch](https://aws.amazon.com/elasticsearch-service/) to power user-entered product queries. The first workshop walks you through creating and populating the index.
The **[Recommendations](https://github.com/aws-samples/retail-demo-store/tree/master/src/recommendations)** service provides personalized user and related product recommendations and personalized ranking of products. In its default launch state, the service lacks the ability to provide personalization and instead provides default recommendations, such as featured products, from the **Products** service. The second workshop steps you through how to use [Amazon Personalize](https://aws.amazon.com/personalize/) to add personalization capabilities in the Recommendations service.
### Web Application
The **[Web Application](https://github.com/aws-samples/retail-demo-store/tree/master/src/web-ui)** provides the user interface for the Retail Demo Store. It is built using the [Vue.js](https://vuejs.org/) JavaScript framework for UI components, [Axios](https://github.com/axios/axios) to communicate with back-end web service APIs, and [AWS Amplify](https://aws.amazon.com/amplify/) to integrate with [Amazon Cognito](https://aws.amazon.com/cognito/) for authentication, and [Amazon Pinpoint](https://aws.amazon.com/pinpoint/) & [Amazon Personalize](https://docs.aws.amazon.com/personalize/latest/dg/recording-events.html) for capturing user behavior and clickstream data.
The Web Application is deployed to an [Amazon S3](https://aws.amazon.com/s3/) bucket and served to end-users using [Amazon CloudFront](https://aws.amazon.com/cloudfront/).
### Support Services
Retail Demo Store's microservices and workshops make extensive use of [AWS Cloud Map](https://aws.amazon.com/cloud-map/) to discover the private addresses of other microservices and [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) to store and discover important system configuration values that effect how the services behave. For example, once the Amazon Personalize campaigns are built in the Personalization workshop, the ARNs are saved as SSM Parameters that the Recommendations microservice uses to retrieve recommendations from Personalize.
You are encouraged to explore these services in the AWS console as you work through the workshops to see how they're utilized by the Retail Demo Store.
### Build and Deployment Pipeline
Retail Demo Store uses [AWS CodePipeline](https://aws.amazon.com/codepipeline/) to automatically build and deploy the microservices and web application when a change is detected in the code repository (AWS CodeCommit or GitHub).
### Source Code
Unless you deployed the Retail Demo Store via a linked GitHub repository (in which case you already have access to the source code in GitHub), you can view all source code for the Retail Demo Store's microservices and notebooks in the [AWS CodeCommit](https://aws.amazon.com/codecommit/) Git repositories deployed in this AWS account. The full project is also available in the GitHub repository under aws-samples: [https://github.com/aws-samples/retail-demo-store](https://github.com/aws-samples/retail-demo-store).
## User Interface Instructions
When the Retail Demo Store project was deployed in your AWS account by CloudFormation, a CloudFront distribution was created that can be used to access the web application. The CloudFormation template provides the URL of the distribution as an Output parameter. Browse to the CloudFormation console in this AWS account, click on the Retail Demo Store's stack, then on the "Outputs" tab, and finally locate the key named "WebURL". Open this URL in a separate web browser tab/window.

When you access the WebURL you should see the Retail Demo Store home page.

### Create Retail Demo Store User Account
#### 1. Access Create Account
Click the "Sign In" button and then the "Create account" link on the sign in view.

#### 2. Complete New Account Form
Complete all fields and be sure to use a valid email, so that you can receive an account confirmation code via email. The user create and confirmation process is provided by Amazon Cognito. If you don't receive the confirmation code email, you can manually confirm your user account by browsing to Amazon Cognito in this AWS account, then select User Pools > Users, find your user and confirm.

#### 3. Confirm Account
Once you receive your confirmation code from Cognito via email, enter it here.

#### 4. Sign In to Your Account

#### 5. Emulate Shopper
The Retail Demo Store provides the ability for you to emulate one of the existing shoppers in the system. This is useful when you want to test the product and search personalization capabilities (after the search and personalization workshops are completed).
Click on your user name in upper right corner and then click on Profile to access the Profile page.

To emulate a shopper, select a shopper from the drop down and click "Save Changes". Once saved, you can browse the storefront. This will be covered in more detail in the workshops.

## Workshop Instructions
Each workshop is implemented as a [Jupyter Notebook](https://jupyter.org/).
> The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.
Open each notebook and follow along by reading and executing the cells sequentially. Use the "run" (">") button at the top of the notebook page to execute each cell.

### Search Workshop
The [Search Workshop](./0-StartHere/Search.ipynb) will walk you through the process of creating an index in Amazon Elasticsearch and loading the index with information on the products in the Retail Demo Store. The Retail Demo Store's Search service uses this index to perform queries based on user-entered search terms.
**[Open Workshop](./0-StartHere/Search.ipynb)**
### Personalization Workshop
The [Personalization Workshop](./1-Personalization/1.1-Personalize.ipynb) will walk you through the process of training and deploying machine learning models using Amazon Personalize to add product recommendations and personalized ranking to the Retail Demo Store. The Retail Demo Store's Recommendation service provides these features.
**[Open Workshop](./1-Personalization/1.1-Personalize.ipynb)**
This part of the workshop also provides an introduction to using Segment as a real-time event pipeline to deliver real-time events to the Personalize datasets you create in the first Personalization workshop.
**[Segment Events Workshop](./1-Personalization/1.2-Real-Time-Events-Segment.ipynb)**
### Customer Data Platform Workshop
Once you deploy Amazon Personalize in your Retail Demo Store, and deploy the Segment real time events pipeline, you can also us the Segment CDP (Personas) to create audiences and pass them into your marketing tools. This workshop shows you how to deploy Segment as a CDP in the Retail Demo Store, and to send Amazon Personalize recommendations to the CDP and other marketing tools.
**[Segment CDP Workshop](./6-CustomerDataPlatforms/6.1-Segment.ipynb)**
### Forecasting Workshop
Coming soon!
### Experimentation Workshop
The [Experimentation Workshop](./3-Experimentation/3.1-Overview.ipynb) demonstrates how to add experimentation to the Retail Demo Store to evaluate the performance of different testing techniques. Three different approaches to experimentation are implemented including A/B testing, interleaved recommendation testing, and multi-armed bandit testing.
**[Open Workshop](./3-Experimentation/3.1-Overview.ipynb)**
Additionally, the Experimentation Workshop shows you how to set up [Amplitude](https://amplitude.com) user beahvior analytics to measure the performance of personalization features exposed in the Retail Demo Store, using Amazon Personalize.
**[Open Workshop](./3-Experimentation/3.5-Amplitude-Performance-Metrics.ipynb)**
### Messaging Workshop
The Messaging Workshop will walk you through adding outbound messaging functionality to the Retail Demo Store:
[Amazon Pinpoint Workshop](./4-Messaging/4.1-Pinpoint.ipynb) demonstrates how to implement dynamic messaging campaigns to automatically send welcome emails, abandoned cart emails, and emails with personalized product recommendations using the same machine learning model used to provide product recommendations in the web application.
**[Open Pinpoint Workshop](./4-Messaging/4.1-Pinpoint.ipynb)**
[Braze Workshop](./4-Messaging/4.2-Braze.ipynb) demonstrates how to implement email campaigns that use Personalize product recommendations to personalize content for Retail Demo Store users.
**[Open Braze Workshop](./4-Messaging/4.2-Braze.ipynb)**
### Conversational AI Workshop
The Conversational AI Workshop will show you how to add a chatbot to the web application using [Amazon Lex](https://aws.amazon.com/lex/). The chatbot will support basic intents/actions such as providing a simple greeting or the store's return policy as well as a more sophisticated product recommendation intent that is powered by a Lambda function will retrieves recommendations from Amazon Personalize.
When combined with the recommendations in the web application and through the messaging workshops, this provides a powerful example of how true omnichannel personalization can be implemented using a decoupled architecture and AWS services.
**[Open Conversational AI Workshop](./5-Conversational/5.1-LexChatbot.ipynb)**
| github_jupyter |
# Explaining `disp` for future ref.
## Notebook using data from `cta-lstchain-extra`
In case you have not cloned `cta-lstchain-extra` repository:
git clone https://github.com/cta-observatory/cta-lstchain-extra
### Some imports...
```
import matplotlib.pyplot as plt
import numpy as np
import astropy.units as u
from copy import deepcopy
from ctapipe.calib import CameraCalibrator
from ctapipe.image import tailcuts_clean
from ctapipe.io import EventSource
from ctapipe.image import hillas_parameters
from ctapipe.visualization import CameraDisplay
from lstchain.reco.utils import *
from lstchain.visualization.camera import *
from lstchain.io import DispContainer, get_standard_config
from lstchain.reco.disp import disp_vector, disp_parameters_event
from ctapipe.utils import get_dataset_path
from ctapipe.io import EventSource
infile = get_dataset_path("gamma_test_large.simtel.gz")
allowed_tels = {1} # select LST1 only
max_events = (
10
) # limit the number of events to analyse in files - None if no limit
cal = CameraCalibrator()
cleaning_method = tailcuts_clean
cleaning_parameters = {
"boundary_thresh": 4,
"picture_thresh": 7,
"min_number_picture_neighbors": 3,
}
source = EventSource(infile, max_events=max_events)
events = [deepcopy(event) for event in source]
```
### We select a bright event
```
intensity = 0
for event in events:
cal(event)
for tid in event.r0.tel.keys():
if event.dl1.tel[tid].image.sum() > intensity:
intensity = event.dl1.tel[tid].image.sum()
bright_event = deepcopy(event)
tel_id = tid
event = bright_event
```
### Image cleaning, hilas parameters and plotting of the shower
```
event = bright_event
tel_id = 31
tel = event.inst.subarray.tel[tel_id]
geom = tel.camera
image = event.dl1.tel[tel_id].image
pixel_signals = tailcuts_clean(geom, image)
cleaned = deepcopy(image)
cleaned[~pixel_signals] = 0
hillas = hillas_parameters(geom, cleaned)
plt.figure(figsize=(12,12))
display = CameraDisplay(geom, cleaned, cmap=plt.get_cmap('viridis'))
display.overlay_moments(hillas, color='lime')
display.add_colorbar()
pointing_alt = event.pointing.array_altitude
pointing_az = event.pointing.array_azimuth
src_pos = sky_to_camera(event.mc.alt, event.mc.az,
tel.optics.equivalent_focal_length,
pointing_alt,
pointing_az,
)
disp = disp_parameters_event(hillas, src_pos.x, src_pos.y)
overlay_source(display, src_pos.x, src_pos.y, color='green', label='True source position')
overlay_disp_vector(display, disp, hillas, color='green', label='MC disp')
# if disp was reconstructed with the norm and side
disp_r = DispContainer()
disp_r.angle = hillas.psi
disp_r.sign = disp.sign
disp_r.norm = disp.norm
disp_r.dx, disp_r.dy = disp_vector(disp_r.norm.value, disp_r.angle.value, disp_r.sign) * u.m
overlay_disp_vector(display, disp_r, hillas, color='red', label='geometrically reconstructed disp and source')
overlay_source(display, hillas.x+disp_r.dx, hillas.y+disp_r.dy, color='red', s=100)
overlay_hillas_major_axis(display, hillas, color='white')
plt.legend()
```
## Disp reconstruction
```
import pandas as pd
from lstchain.reco.dl1_to_dl2 import train_disp_vector
gammas = pd.read_hdf('../../cta-lstchain-extra/reco/sample_data/dl2/ctapipe_diffuse_dl2_tiny.h5')
gammas.hist(figsize=(18,12));
gammas['disp_norm'] = gammas.disp
gammas['disp_dx'] = gammas.src_x - gammas.x
gammas['disp_dy'] = gammas.src_y - gammas.y
gammas['disp_sign'] = np.sign(gammas['disp_dx'])
gammas['disp_angle'] = gammas.psi
training_features = ['intensity', 'width', 'length', 'x', 'y', 'psi', 'phi', 'wl',
'skewness', 'kurtosis', 'r', 'intercept', 'time_gradient']
predict_features = ['disp_dx', 'disp_dy']
custom_config = get_standard_config()
custom_config['regression_features'] = training_features
custom_config['random_forest_regressor_args'] = {'n_jobs': 4,
# 'min_samples_leaf': 5,
# 'max_depth': 50,
# 'n_estimators': 450
}
rf_disp_vec = train_disp_vector(gammas,
custom_config=custom_config,
predict_features=predict_features
)
disp_vec_reco = rf_disp_vec.predict(gammas[training_features])
disp_dx_reco = disp_vec_reco[:,0]
disp_dy_reco = disp_vec_reco[:,1]
reco_src_x = gammas.x + disp_dx_reco
reco_src_y = gammas.y + disp_dy_reco
fig, axes = plt.subplots(1, 2, figsize=(15,6))
axes[0].hist(gammas.disp_dx, bins=50, label='mc');
axes[0].hist(disp_dx_reco, bins=50, alpha=0.75, label='reco');
axes[0].set_title('disp_dx distribution')
axes[1].hist(gammas.disp_dy, bins=50, label='mc');
axes[1].hist(disp_dy_reco, bins=50, alpha=0.75, label='reco');
axes[1].set_title('disp_dy distribution')
plt.legend();
fig, axes = plt.subplots(2, 2, figsize=(15,12))
axes[0,0].hist2d(gammas.disp_dx, disp_dx_reco, bins=60);
axes[0,0].set_xlabel('mc_disp')
axes[0,0].set_ylabel('reco_disp')
axes[0,0].set_title('disp_dx')
axes[0,1].hist2d(gammas.disp_dy, disp_dy_reco, bins=60);
axes[0,1].set_xlabel('mc_disp')
axes[0,1].set_ylabel('reco_disp')
axes[0,1].set_title('disp_dy');
axes[1,0].hist2d(gammas.src_x, reco_src_x, bins=60);
axes[1,0].set_xlabel('mc_src_x')
axes[1,0].set_ylabel('reco_src_x')
axes[1,1].hist2d(gammas.src_y, reco_src_y, bins=60);
axes[1,1].set_xlabel('mc_src_y')
axes[1,1].set_ylabel('reco_src_y');
```
| github_jupyter |
```
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import os
import random
import zipfile
import numpy as np
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
f = open("../../../data/MelbDatathon2017/New/ilnesss.txt", "r")
vocabulary = tf.compat.as_str(f.read()).split(",")
vocabulary[:10]
vocabulary_size = 50000
def build_dataset(words, n_words):
"""Process raw inputs into a dataset."""
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(n_words - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count += 1
data.append(index)
count[0][1] = unk_count
reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reversed_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(vocabulary,
vocabulary_size)
del vocabulary # Hint to reduce memory.
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])
data_index = 0
# Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [skip_window]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
# Backtrack a little bit to avoid skipping words in the end of a batch
data_index = (data_index + len(data) - span) % len(data)
return batch, labels
batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)
for i in range(8):
print(batch[i], reverse_dictionary[batch[i]],
'->', labels[i, 0], reverse_dictionary[labels[i, 0]])
# Step 4: Build and train a skip-gram model.
batch_size = 128
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. Here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64 # Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default():
# Input data.
train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Ops and variables pinned to the CPU because of missing GPU implementation
with tf.device('/cpu:0'):
# Look up embeddings for inputs.
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_inputs)
# Construct the variables for the NCE loss
nce_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
# Compute the average NCE loss for the batch.
# tf.nce_loss automatically draws a new sample of the negative labels each
# time we evaluate the loss.
loss = tf.reduce_mean(
tf.nn.nce_loss(weights=nce_weights,
biases=nce_biases,
labels=train_labels,
inputs=embed,
num_sampled=num_sampled,
num_classes=vocabulary_size))
# Construct the SGD optimizer using a learning rate of 1.0.
optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
# Compute the cosine similarity between minibatch examples and all embeddings.
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(
normalized_embeddings, valid_dataset)
similarity = tf.matmul(
valid_embeddings, normalized_embeddings, transpose_b=True)
# Add variable initializer.
init = tf.global_variables_initializer()
# Step 5: Begin training.
num_steps = 100001
with tf.Session(graph=graph) as session:
# We must initialize all variables before we use them.
init.run()
print('Initialized')
average_loss = 0
for step in xrange(num_steps):
batch_inputs, batch_labels = generate_batch(
batch_size, num_skips, skip_window)
feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
# We perform one update step by evaluating the optimizer op (including it
# in the list of returned values for session.run()
_, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += loss_val
if step % 2000 == 0:
if step > 0:
average_loss /= 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step ', step, ': ', average_loss)
average_loss = 0
# # Note that this is expensive (~20% slowdown if computed every 500 steps)
# if step % 10000 == 0:
# sim = similarity.eval()
# for i in xrange(valid_size):
# valid_word = reverse_dictionary[valid_examples[i]]
# top_k = 8 # number of nearest neighbors
# nearest = (-sim[i, :]).argsort()[1:top_k + 1]
# log_str = 'Nearest to %s:' % valid_word
# for k in xrange(top_k):
# close_word = reverse_dictionary[nearest[k]]
# log_str = '%s %s,' % (log_str, close_word)
# print(log_str)
final_embeddings = normalized_embeddings.eval()
len(reverse_dictionary)
# Step 6: Visualize the embeddings.
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings'
plt.figure(figsize=(18, 18)) # in inches
for i, label in enumerate(labels):
x, y = low_dim_embs[i, :]
plt.scatter(x, y)
plt.annotate(label,
xy=(x, y),
xytext=(5, 2),
textcoords='offset points',
ha='right',
va='bottom')
plt.savefig(filename)
try:
# pylint: disable=g-import-not-at-top
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
plot_only = 13
low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])
labels = [reverse_dictionary[i] for i in xrange(plot_only)]
plot_with_labels(low_dim_embs, labels)
except ImportError:
print('Please install sklearn, matplotlib, and scipy to show embeddings.')
```
| github_jupyter |
## UnderComplete Autoencoders
```
# necessary imports
%matplotlib inline
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
# some imports from bigdl
from bigdl.nn.layer import *
from bigdl.nn.criterion import *
from bigdl.optim.optimizer import *
from bigdl.util.common import *
from bigdl.dataset.transformer import *
from pyspark import SparkContext
sc=SparkContext.getOrCreate(conf=create_spark_conf().setMaster("local[4]").set("spark.driver.memory","2g"))
# function to initialize the bigdl library
init_engine()
# bigdl provides a nice function for downloading and reading mnist dataset
from bigdl.dataset import mnist
mnist_path = "mnist"
images_train, labels_train = mnist.read_data_sets(mnist_path, "train")
# mean and stddev of the pixel values
mean = np.mean(images_train)
std = np.std(images_train)
# parallelize, center and scale the images_train
rdd_images = sc.parallelize(images_train).map(lambda features: (features - mean)/std)
print("total number of images ",rdd_images.count())
# Parameters for training
BATCH_SIZE = 100
NUM_EPOCHS = 2
# Network Parameters
SIZE_HIDDEN = 32
# shape of the input data
SIZE_INPUT = 784
# function for creating an autoencoder
def get_autoencoder(hidden_size, input_size):
# Initialize a sequential type container
module = Sequential()
# create encoder layers
module.add(Linear(input_size, hidden_size))
module.add(ReLU())
# create decoder layers
module.add(Linear(hidden_size, input_size))
module.add(Sigmoid())
return(module)
undercomplete_ae = get_autoencoder( SIZE_HIDDEN, SIZE_INPUT)
# transform dataset to rdd(Sample) from rdd(ndarray). Sample represents a record in the dataset. A sample
# consists of two tensors a features tensor and a label tensor. In our autoencoder features and label will be same
train_data = rdd_images.map(lambda x: Sample.from_ndarray(x.reshape(28*28), x.reshape(28*28)))
# Create an Optimizer
optimizer = Optimizer(
model = undercomplete_ae,
training_rdd = train_data,
criterion = MSECriterion(),
optim_method = Adam(),
end_trigger = MaxEpoch(NUM_EPOCHS),
batch_size = BATCH_SIZE)
# write summary
app_name='undercomplete_autoencoder-'+dt.datetime.now().strftime("%Y%m%d-%H%M%S")
train_summary = TrainSummary(log_dir='/tmp/bigdl_summary',
app_name=app_name)
optimizer.set_train_summary(train_summary)
print("logs to saved to ",app_name)
# run training process
trained_UAE = optimizer.optimize()
# let's check our model performance on the test data
(images, labels) = mnist.read_data_sets(mnist_path, "test")
rdd_test = sc.parallelize(images).map(lambda features: ((features - mean)/std).reshape(28*28)).map(
lambda features: Sample.from_ndarray(features, features))
examples = trained_UAE.predict(rdd_test).take(10)
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(10):
a[0][i].imshow(np.reshape(images[i], (28, 28)))
a[1][i].imshow(np.reshape(examples[i], (28, 28)))
```
| github_jupyter |
# Neural Machine Translation
Neural machine translation is an approach to machine translation that uses a large artificial neural network to predict the likelihood of a sequence of words, typically modeling entire sentences in a single integrated model.
```
import pandas as pd
import numpy as np
import string
from string import digits
import matplotlib.pyplot as plt
%matplotlib inline
import re
import os
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from keras.layers import Input, LSTM, Embedding, Dense, Bidirectional
from keras.layers import Activation, dot, concatenate
from keras.models import Model
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from keras.preprocessing.text import Tokenizer
import tensorflow as tf
from gensim.models import Word2Vec
from tqdm import tqdm_notebook
import nltk
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
```
## Dataset
English - Spanish translation dataset is downloaded from [Tab-delimited Bilingual Sentence Pairs](http://www.manythings.org/anki/).
First a CSV file generated using `preprocess.py` for easy management and access.
During training, dataset is divided randomly in 7:3 ratio.
Dataset from Tab-delimited Bilingual Sentence Pairs is in the format of text file with language1-lagnuage2 seperated by `\t` (tab). For better management, I have opt to create a `CSV file`. `preprocess.py` takes input the `.txt` (`spa.txt`) and cleans the file by converting non-printable characters to printable format and generates the CSV file.
```
usage: preprocess.py [-h] --dataset DATASET [--language_1 LANGUAGE_1]
--language_2 LANGUAGE_2 [--save_file SAVE_FILE]
optional arguments:
-h, --help show this help message and exit
--dataset DATASET, -d DATASET
Path to .txt file downloaded from
http://www.manythings.org/anki/
--language_1 LANGUAGE_1, -l1 LANGUAGE_1
Language-1 name | Default: english
--language_2 LANGUAGE_2, -l2 LANGUAGE_2
Language-2 name
--save_file SAVE_FILE, -s SAVE_FILE
Name of CSV file to be generated | Default:
dataset.csv
```
```
lines = pd.read_csv('dataset/english-spanish-dataset.csv')
lines.shape
lines.english = lines.english.apply(lambda x: x.lower())
lines.spanish = lines.spanish.apply(lambda x: str(x).lower())
exclude = set(string.punctuation)
lines.english = lines.english.apply(lambda x: ''.join(ch for ch in x if ch not in exclude))
lines.spanish = lines.spanish.apply(lambda x: ''.join(ch for ch in x if ch not in exclude))
lines.english = lines.english.apply(lambda x: x.strip())
lines.spanish = lines.spanish.apply(lambda x: x.strip())
lines.english = lines.english.apply(lambda x: re.sub(" +", " ", x))
lines.spanish = lines.spanish.apply(lambda x: re.sub(" +", " ", x))
lines.english = lines.english.apply(lambda x: re.sub("\?\?", '', x))
lines.spanish = lines.spanish.apply(lambda x: re.sub("\?\?", '', x))
lines.spanish = lines.spanish.apply(lambda x : 'START_ '+ x + '_END')
lines.columns
del lines['Unnamed: 0']
lines.sample(10)
vocab_english = set()
for sent in lines.english:
for word in sent.split():
if word not in vocab_english:
vocab_english.add(word)
vocab_spanish = set()
for sent in lines.spanish:
for word in sent.split():
if word not in vocab_spanish:
vocab_spanish.add(word)
length_list=[]
for l in lines.spanish:
length_list.append(len(l.split(' ')))
max_length_spanish = np.max(length_list)
max_length_spanish, np.average(length_list)
length_list=[]
for l in lines.english:
length_list.append(len(l.split(' ')))
max_length_english = np.max(length_list)
max_length_english, np.average(length_list)
input_words = sorted(list(vocab_english))
target_words = sorted(list(vocab_spanish))
num_encoder_tokens = len(vocab_english)
num_decoder_tokens = len(vocab_spanish)
num_encoder_tokens, num_decoder_tokens
num_decoder_tokens += 1 # For zero padding
num_decoder_tokens
input_token_index = dict([(word, i+1) for i, word in enumerate(input_words)])
target_token_index = dict([(word, i+1) for i, word in enumerate(target_words)])
reverse_input_char_index = dict((i, word) for word, i in input_token_index.items())
reverse_target_char_index = dict((i, word) for word, i in target_token_index.items())
lines = shuffle(lines)
lines.head(10)
english = list(lines.english)
spanish = list(lines.spanish)
x = []
y = []
for i in range(len(english)):
x.append(str(english[i]))
y.append(str(spanish[i]))
x = np.array(x)
y = np.array(y)
len(x), len(y)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.1)
X_train.shape, X_test.shape
def generate_batch(X = X_train, y = y_train, batch_size = 128):
''' Generate a batch of data '''
while True:
for j in range(0, len(X), batch_size):
encoder_input_data = np.zeros((batch_size, max_length_english),dtype='float32')
decoder_input_data = np.zeros((batch_size, max_length_spanish),dtype='float32')
decoder_target_data = np.zeros((batch_size, max_length_spanish, num_decoder_tokens),dtype='float32')
for i, (input_text, target_text) in enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])):
for t, word in enumerate(input_text.split()):
encoder_input_data[i, t] = input_token_index[word] # encoder input seq
for t, word in enumerate(target_text.split()):
if t<len(target_text.split())-1:
decoder_input_data[i, t] = target_token_index[word] # decoder input seq
if t>0:
# decoder target sequence (one hot encoded)
# does not include the START_ token
# Offset by one timestep
decoder_target_data[i, t - 1, target_token_index[word]] = 1.
yield([encoder_input_data, decoder_input_data], decoder_target_data)
```
## Embeddings
The embedding layer of the network is initialized first with pre-trained embedding trained using `Word2Vec` (skipgram model) on `english-spanish-dataset.csv` to improve the overall performance of the network.
You can find trained embedding under "RELEASES" section.
You can generate word2vec embeddings using generate_embeddings.py on your own dataset.
```
usage: generate_embeddings.py [-h] --csv CSV --language LANGUAGE [--sg]
[-emb_size EMB_SIZE] [--save_file SAVE_FILE]
optional arguments:
-h, --help show this help message and exit
--csv CSV Path to CSV which is to be read
--language LANGUAGE, -l LANGUAGE
Language whose embedding is to be generated from CSV
file. (It should be the column name in CSV)
--sg Whether to use SkipGram or CBoW model | Default: CBoW
-emb_size EMB_SIZE, -s EMB_SIZE
Size of embedding to generate | Defualt: 256
--save_file SAVE_FILE
Name of embedding file to save | Default:
[skipgram/cbow]-[language]-[embedding_size].model
```
```
latent_dim = 256
english_embedding = Word2Vec.load('embeddings/skipgram-english-256.model')
spanish_embedding = Word2Vec.load('embeddings/skipgram-spanish-256.model')
eng_tok = Tokenizer()
ger_tok = Tokenizer()
eng_tok.fit_on_texts(english)
ger_tok.fit_on_texts(spanish)
# create a weight matrix for words in training docs
encoder_embedding_matrix = np.zeros((num_encoder_tokens, latent_dim))
for word, i in eng_tok.word_index.items():
try:
embedding_vector = english_embedding[word]
if embedding_vector is not None:
encoder_embedding_matrix[i] = embedding_vector
except Exception as e:
print(e)
# create a weight matrix for words in training docs
decoder_embedding_matrix = np.zeros((num_decoder_tokens, latent_dim))
for word, i in ger_tok.word_index.items():
try:
embedding_vector = spanish_embedding[word]
if embedding_vector is not None:
decoder_embedding_matrix[i] = embedding_vector
except Exception as e:
pass
```
## LSTM-Attention Model
Here a simple model with Luong's Attention is used to achieve the task of language translation although more complex models can be built to improve the model's performance. You can read more about basics and backgrounds of NMTs at [tensorflow/nmt](https://github.com/tensorflow/nmt#basic).
I attempt to implement Luong's attention due to its simplicity in understanding as well as implementation.
This diagram explains the basic architecture of the model [Source: background-on-the-attention-mechanism]:
<p align="center"> <img src="results/attention_mechanism.jpg"/> </p>
```
encoder_inputs = Input(shape=(None,))
enc_emb = Embedding(num_encoder_tokens, latent_dim, mask_zero = True, weights=[encoder_embedding_matrix])(encoder_inputs)
encoder_lstm = LSTM(latent_dim*4, return_sequences=True, return_state=True)
encoder_outputs, state_h, state_c = encoder_lstm(enc_emb)
encoder_states = [state_h, state_c]
print('encoder_outputs: ', encoder_outputs)
print('state_h: ', state_h)
print('state_c: ', state_c)
decoder_inputs = Input(shape=(None,))
dec_emb_layer = Embedding(num_decoder_tokens, latent_dim, mask_zero = True, weights=[decoder_embedding_matrix])
dec_emb = dec_emb_layer(decoder_inputs)
decoder_lstm = LSTM(latent_dim*4, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(dec_emb,
initial_state=encoder_states)
attention = dot([decoder_outputs, encoder_outputs], axes=[2, 2])
attention = Activation('softmax', name='attention')(attention)
context = dot([attention, encoder_outputs], axes=[2, 1], name='context')
decoder_combined_context = concatenate([context, decoder_outputs], name='decoder_combined_context')
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_combined_context)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])
model.summary()
train_samples = len(X_train)
val_samples = len(X_test)
batch_size = 16
epochs = 20
```
## Training NMT Model
```
class TrainValTensorBoard(TensorBoard):
def __init__(self, log_dir='./logs', **kwargs):
# Make the original `TensorBoard` log to a subdirectory 'training'
training_log_dir = os.path.join(log_dir, 'training')
super(TrainValTensorBoard, self).__init__(training_log_dir, **kwargs)
# Log the validation metrics to a separate subdirectory
self.val_log_dir = os.path.join(log_dir, 'validation')
def set_model(self, model):
# Setup writer for validation metrics
self.val_writer = tf.summary.FileWriter(self.val_log_dir)
super(TrainValTensorBoard, self).set_model(model)
def on_epoch_end(self, epoch, logs=None):
# Pop the validation logs and handle them separately with
# `self.val_writer`. Also rename the keys so that they can
# be plotted on the same figure with the training metrics
logs = logs or {}
val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}
for name, value in val_logs.items():
summary = tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value.item()
summary_value.tag = name
self.val_writer.add_summary(summary, epoch)
self.val_writer.flush()
# Pass the remaining logs to `TensorBoard.on_epoch_end`
logs = {k: v for k, v in logs.items() if not k.startswith('val_')}
super(TrainValTensorBoard, self).on_epoch_end(epoch, logs)
def on_train_end(self, logs=None):
super(TrainValTensorBoard, self).on_train_end(logs)
self.val_writer.close()
log_dir = 'eng-spa-weights'
logging = TrainValTensorBoard(log_dir=log_dir)
checkpoint = ModelCheckpoint(os.path.join(log_dir, 'ep{epoch:03d}-val_loss{val_loss:.3f}-val_acc{val_acc:.3f}.h5'),
monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1)
# To retrain first load the trained model!
#model.load_weights('eng-spa-weights/ep015-val_loss3.445-val_acc0.592.h5')
# model.fit_generator(generator = generate_batch(X_train, y_train, batch_size = batch_size),
# steps_per_epoch = train_samples//batch_size,
# epochs=epochs,
# validation_data = generate_batch(X_test, y_test, batch_size = batch_size),
# validation_steps = val_samples//batch_size,
# callbacks=[logging, checkpoint, reduce_lr, early_stopping])
# Save trained Model
#model.save_weights('eng-spa-weights/final_weights.h5')
```
## Inferencing NMT Model
```
# Loading the model
model.load_weights('eng-spa-weights/final_weights.h5')
# Encode the input sequence to get the "thought vectors"
encoder_model = Model(encoder_inputs, [encoder_outputs] + encoder_states)
# Decoder setup
# Below tensors will hold the states of the previous time step
decoder_state_input_h = Input(shape=(latent_dim*4,))
decoder_state_input_c = Input(shape=(latent_dim*4,))
encoder_inf_input = Input(shape=(None, latent_dim*4))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
dec_emb2= dec_emb_layer(decoder_inputs) # Get the embeddings of the decoder sequence
# To predict the next word in the sequence, set the initial states to the states from the previous time step
decoder_outputs2, state_h2, state_c2 = decoder_lstm(dec_emb2, initial_state=decoder_states_inputs)
decoder_states2 = [state_h2, state_c2]
attention = dot([decoder_outputs2, encoder_inf_input], axes=[2, 2])
print('Attention: ', attention)
attention = Activation('softmax', name='attention')(attention)
print('Softmax: ', attention)
context = dot([attention, encoder_inf_input], axes=[2, 1])
print('Context: ', context)
decoder_combined_context = concatenate([context, decoder_outputs2])
print('Combined Context: ', decoder_combined_context)
decoder_outputs2 = decoder_dense(decoder_combined_context) # A dense softmax layer to generate prob dist. over the target vocabulary
# Final decoder model
decoder_model = Model(
[decoder_inputs, encoder_inf_input] + decoder_states_inputs,
[decoder_outputs2] + decoder_states2)
encoder_model.summary()
encoder_model.output
decoder_model.summary()
decoder_model.input, decoder_model.output
def decode_sequence(input_seq):
# Encode the input as state vectors.
[encoder_output, h, c] = encoder_model.predict(input_seq)
states_value = [h, c]
# Generate empty target sequence of length 1.
target_seq = np.zeros((1,1))
# Populate the first character of target sequence with the start character.
target_seq[0, 0] = target_token_index['START_']
# Sampling loop for a batch of sequences
# (to simplify, here we assume a batch of size 1).
#return
stop_condition = False
decoded_sentence = ''
while not stop_condition:
output_tokens, h, c = decoder_model.predict([target_seq, encoder_output] + states_value)
# Sample a token
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_char = reverse_target_char_index[sampled_token_index]
decoded_sentence += ' '+sampled_char
# Exit condition: either hit max length
# or find stop character.
if (sampled_char == '_END' or
len(decoded_sentence) > 100):
stop_condition = True
# Update the target sequence (of length 1).
target_seq = np.zeros((1,1))
target_seq[0, 0] = sampled_token_index
# Update states
states_value = [h, c]
return decoded_sentence
layers = decoder_model.layers
for l in layers:
print('%s\tname:%s' % (str(l), l.name))
assert(model.layers[7] == model.get_layer('attention'))
attention_layer = decoder_model.get_layer('attention') # or model.layers[7]
attention_model = Model(inputs=decoder_model.inputs, outputs=decoder_model.outputs + [attention_layer.output])
print(attention_model)
print(attention_model.output_shape, attention_model.input_shape)
attention_model.summary()
def attent_and_generate(input_seq):
decoded_sentence = []
[encoder_output, h, c] = encoder_model.predict(input_seq)
states_value = [h, c]
target_seq = np.zeros((1,1))
target_seq[0, 0] = target_token_index['START_']
stop_condition = False
attention_density = []
index = []
while not stop_condition:
output_tokens, h, c, attention = attention_model.predict([target_seq, encoder_output] + states_value)
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_char = reverse_target_char_index[sampled_token_index]
decoded_sentence.append(sampled_char)
if (sampled_char.endswith('_END')) or len(decoded_sentence) > 50:
stop_condition = True
states_value = [h, c]
target_seq = np.zeros((1,1))
target_seq[0, 0] = sampled_token_index
attention_density.append((sampled_char, attention[0][0]))
return np.array(attention_density), ' '.join(decoded_sentence)
def visualize(text, encoder_input):
attention_weights, decoded_sent = attent_and_generate(encoder_input)
plt.clf()
plt.figure(figsize=(10,10))
mats = []
dec_inputs = []
for dec_ind, attn in attention_weights:
mats.append(attn[:len(text[0].split(' '))].reshape(-1))
dec_inputs.append(dec_ind)
attention_mat = np.transpose(np.array(mats))
fig, ax = plt.subplots(figsize=(8, 8))
ax.imshow(attention_mat)
ax.set_xticks(np.arange(attention_mat.shape[1]))
ax.set_yticks(np.arange(attention_mat.shape[0]))
ax.set_xticklabels([inp for inp in dec_inputs])
ax.set_yticklabels([w for w in str(text[0]).split(' ')])
ax.tick_params(labelsize=15)
ax.tick_params(axis='x', labelrotation=90)
plt.show()
return decoded_sent
```
### Some Samples generated from the trained model
```
train_gen = generate_batch(X_train, y_train, batch_size = 1)
k=-1
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: all over the world are the cars in japan
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "all over the world are the cars in japan"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: I did everything for you
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "I did everything for you"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: Tom and Mary no longer talk to each other
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "Tom and Mary no longer talk to each other"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: Tom is the happiest person in the world in the world now
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "Tom is the happiest person in the world in the world now"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: I've been taking apple classes
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "I've been taking apple classes"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: the dog is beautiful
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "the dog is beautiful"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: Tom is able to walk on his hands
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "Tom is able to walk on his hands"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: that is my dress
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "that is my dress"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: Mary looks a lot like her mother
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "Mary looks a lot like her mother"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: Tom asked Maria to call him after dinner
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "Tom asked Maria to call him after dinner"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: I do not have money to buy the book
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "I do not have money to buy the book"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: his name is known by everyone in this city
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "his name is known by everyone in this city"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: what time do you come in
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "what time do you come in"
```
k+=1
(encoder_input, actual_output), _ = next(train_gen)
print(X_train[k:k+1])
decoded_sent = visualize(X_train[k:k+1], encoder_input)
# Translation of Prediction from Google Translator: arrive at the house of work at seven o'clock seven o'clock
print('Input English Sentence:', X_train[k:k+1][0])
print('Actual spanish:', y_train[k:k+1][0][6:-4])
print('Predicted spanish:', decoded_sent[:-4])
```
Translation of Predicted Spanish (Source: Google Translator): "arrive at the house of work at seven o'clock seven o'clock"
| github_jupyter |
```
# Bonus de Pandas
# 1. importa pandas y numpy
# 2. Crea un DataFrame df con las columnas 'Col1': [1,2,3,4,5,6,7,8] y 'Col2': [-2,4,-6,8,1,2,3,4]
# 3. añade una columna 'Col3' con [8,7,6,5,4,5,2,3]
# 4. Selecciona solo 'Col2', ¿de qué tipo es?
# 5. Selecciona 'Col1' y 'Col3'
# 6. Selecciona todas las filas donde Col1 sea mayor de 2 y Col3 mayor de 2 también
# 7. Selecciona las filas donde 'Col1' es >2 y 'Col3' > 2 y asígnalo a la variable df_mayor_de_dos
# 8. Si seleccionamos parte o un DataFrame entero
# dependiendo de si hay distintos tipos de datos en el trozo leído
# o si son del mismo tipo y de si las nuevas escrituras son del mismo
# tipo que el anterior o de un nuevo tipo,
# se trabaja con referencias o con copias
# Pista:
# df.is_copy() --> True/False
# df._is_view() --> True/False
# 9. Si quieres poner en una variable un DataFrame DISTINTO y no un "enlace" a otro, hay que usar copy()
# 10. Vamos a afianzar LOC e ILOC
# En numpy se accede a las filas y columnas directamente
# seleccionamos la fila 2 y la columna 2
# En un DataFrame tenemos índices (filas) y columnas
# En un DataFrame usamos SIEMPRE loc o iloc para acceder a las filas y columas
# 11. ILOC es con i de integer, usa NÚMEROS. df.iloc[número_de_fila, número_de_columna]
# En iloc se ponen NÚMEROS, y si se puede, se cogen esas filas y columnas
# Usando df_mayor_de_dos selecciona las tres primeras filas y las columnas segunda, tercera, cuarta y quinta
# los números para filas/columnas empiezan en 0 y es primero_que_coges:primero_que_NO_coges
# vemos que los números de ILOC es nuestra cuenta en el DataFrame, NO SON ni los índices ni las columnas.
# Ejemplo: si una columna se llama '7', NO tiene que ver con nuestra cuenta. Una columna llamada '7' puede ser la primera columna
# y una fila con índice '8' puede ser mi primera fila del DataFrame. ¡ES MUY IMPORTANTE!
# LOC nos sirve para seleccionar filas/columnas con SU NOMBRE de índice y de columna
#
# El nombre de las columnas son strings, tienen que existir. Un string que no exista te dará un error
# Los índices son números, puedes intentar que los busque y si no existen, no pasa nada
# 0:10 --> coge los que puedas
# ['Col2', 'Col3'] --> strings que existan
# 12. Incluye una columna 'Col4' con ['buenos','días', '¿qué', 'tal', 'estás?']
# Warning: estás intentando cambiar un valor en un trozo pequeño de DataFrame que viene de un DataFrame grande
# Lo cambia en el pequeño
# si quiero evitar el Warning, o hago una copia y "rompo" el enlace al que apunta (del trozo de DataFrame pequeño al DataFrame grande)
# o lo cambio en el grande (y se vería el cambio en el trozo pequeño)
# 13. Quiero usar 'Col4' como índices de df_mayor_de_dos
# ¡No ha cambiado! Me ha enseñado cómo quedaría, TENGO que igualarlo en la variable para cambiarlo
# ¡Cambiado!
# uso LOC para coger 'días', '¿qué', 'estás?' y 'Col1', 'Col3'
# Selecciono lo mismo con ILOC
# 14. Vamos a borrar una columa, 'Col2'
# Tanto drop como set_index NECESITAN que los iguale a la variable o usar el argumento INPLACE = True dentro del método
# DROP borra y no es reversible, es una forma de asegurarse de que lo quieres borrar
# SET_INDEX borra los índices anteriores y es irreversible, es una forma de asegurarse de que lo quieres borrar
```
### Resumen
* en numpy se accede directamente a las filas y columnas: np_array[2:4,6:8]
* en pandas se accede directamente a columnas: mi_df[['col1', 'col2', 'col3']]
* en pandas para acceder a filas y columnas se usa LOC o ILOC
* ILOC: numeras las filas y columnas SIN MIRAR el nombre de columnas e índices. Si es numérico intenta cogerlo si existe, string tiene que existir.
* LOC: filas y columnas por su nombre. Si es numérico intenta cogerlo si existe, string tiene que existir.
* LOC/ILOC cogen trozos de DataFrame. Si cambio el original grande, cambia en el trozo también
* Para trabajar con OTRO DataFrame se usa copy(): me_refiero_al_mismo = df soy_otro_nuevo = df.copy()
* Para seleccionar filas que cumplan condiciones en columnas: df[(df['Col1'] > 2) & (df['Col3'] > 5)] NO AND/OR SÍ &/|
* Para añadir una columna: df['nueva_col']=[1,2,3,4]
* Para borrar una columna: df = df.drop(...) IGUALO o df.drop(..., inplace = True), tengo que CONFIRMAR porque se va a BORRAR
* Para cambiar los índices por los valores de una columna: df = df.set_index('Col1') o df.set_index(..., inplace = True), tengo que CONFIRMAR porque se va a BORRAR
| github_jupyter |
# Getting Started
## Using Cameras
```
import cameratransform as ct
# intrinsic camera parameters
f = 6.2 # in mm
sensor_size = (6.17, 4.55) # in mm
image_size = (3264, 2448) # in px
# initialize the camera
cam = ct.Camera(ct.RectilinearProjection(focallength_mm=f,
sensor=sensor_size,
image=image_size),
ct.SpatialOrientation(elevation_m=10,
tilt_deg=45))
```
```
cam.elevation_m = 34.027
cam.tilt_deg = 83.307926
cam.roll_deg = -1.916219
```
```
cam.imageFromSpace([3.17, 8, 0])
```
```
cam.imageFromSpace([[3.17, 8, 0],
[3.17, 8, 10],
[4.12, 10, 0],
[4.12, 10, 10]])
```
```
cam.spaceFromImage([2445, 1569])
cam.spaceFromImage([2445, 1569], X=10)
```
```
%matplotlib inline
import matplotlib.pyplot as plt
# display a top view of the image
im = plt.imread("CameraImage.jpg")
top_im = cam.getTopViewOfImage(im, [-150, 150, 50, 300], scaling=0.5, do_plot=True)
plt.xlabel("x position in m")
plt.ylabel("y position in m");
```
## Fitting
```
import cameratransform as ct
import numpy as np
import matplotlib.pyplot as plt
im = plt.imread("CameraImage2.jpg")
camera = ct.Camera(ct.RectilinearProjection(focallength_px=3863.64, image=im))
```
```
feet = np.array([[1968.73191418, 2291.89125757], [1650.27266115, 2189.75370951], [1234.42623164, 2300.56639535], [ 927.4853119 , 2098.87724083], [3200.40162013, 1846.79042709], [3385.32781138, 1690.86859965], [2366.55011031, 1446.05084045], [1785.68269333, 1399.83787022], [ 889.30386193, 1508.92532749], [4107.26569943, 2268.17045783], [4271.86353701, 1889.93651518], [4007.93773879, 1615.08452509], [2755.63028039, 1976.00345458], [3356.54352228, 2220.47263494], [ 407.60113016, 1933.74694958], [1192.78987735, 1811.07247163], [1622.31086201, 1707.77946355], [2416.53943619, 1775.68148688], [2056.81514201, 1946.4146027 ], [2945.35225814, 1617.28314118], [1018.41322935, 1499.63957113], [1224.2470045 , 1509.87120351], [1591.81599888, 1532.33339856], [1701.6226147 , 1481.58276189], [1954.61833888, 1405.49985098], [2112.99329583, 1485.54970652], [2523.54106057, 1534.87590467], [2911.95610793, 1448.87104305], [3330.54617013, 1551.64321531], [2418.21276457, 1541.28499777], [1771.1651859 , 1792.70568482], [1859.30409241, 1904.01744759], [2805.02878512, 1881.00463747], [3138.67003071, 1821.05082989], [3355.45215983, 1910.47345815], [ 734.28038607, 1815.69614796], [ 978.36733356, 1896.36507827], [1350.63202232, 1979.38798787], [3650.89052382, 1901.06620751], [3555.47087822, 2332.50027861], [ 865.71688784, 1662.27834394], [1115.89438493, 1664.09341647], [1558.93825646, 1671.02167477], [1783.86089289, 1679.33599881], [2491.01579305, 1707.84219953], [3531.26955813, 1729.08486338], [3539.6318973 , 1776.5766387 ], [4150.36451427, 1840.90968707], [2112.48684812, 1714.78834459], [2234.65444134, 1756.17059266]])
heads = np.array([[1968.45971142, 2238.81171866], [1650.27266115, 2142.33767714], [1233.79698528, 2244.77321846], [ 927.4853119 , 2052.2539967 ], [3199.94718145, 1803.46727222], [3385.32781138, 1662.23146061], [2366.63609066, 1423.52398752], [1785.68269333, 1380.17615549], [ 889.30386193, 1484.13026407], [4107.73533808, 2212.98791584], [4271.86353701, 1852.85753597], [4007.93773879, 1586.36656606], [2755.89171994, 1938.22544024], [3355.91105749, 2162.91833832], [ 407.60113016, 1893.63300333], [1191.97371829, 1777.60995028], [1622.11915337, 1678.63975025], [2416.31761434, 1743.29549618], [2056.67597009, 1910.09072955], [2945.35225814, 1587.22557592], [1018.69818061, 1476.70099517], [1224.55272475, 1490.30510731], [1591.81599888, 1510.72308329], [1701.45016126, 1460.88834824], [1954.734384 , 1385.54008964], [2113.14023137, 1465.41953732], [2523.54106057, 1512.33125811], [2912.08384338, 1428.56110628], [3330.40769371, 1527.40984208], [2418.21276457, 1517.88006678], [1770.94524662, 1761.25436746], [1859.30409241, 1867.88794433], [2804.69006305, 1845.10009734], [3138.33130864, 1788.53351052], [3355.45215983, 1873.21402971], [ 734.49504829, 1780.27688131], [ 978.1022294 , 1853.9484135 ], [1350.32991656, 1938.60371039], [3650.89052382, 1863.97713098], [3556.44897343, 2278.37901052], [ 865.41437575, 1633.53969555], [1115.59187284, 1640.49747358], [1558.06918395, 1647.12218082], [1783.86089289, 1652.74740383], [2491.20950909, 1677.42878081], [3531.11177814, 1696.89774656], [3539.47411732, 1745.49398176], [4150.01023142, 1803.35570469], [2112.84669376, 1684.92115685], [2234.65444134, 1724.86402238]])
camera.addObjectHeightInformation(feet, heads, 0.75, 0.03)
```
```
horizon = np.array([[418.2195998, 880.253216], [3062.54424509, 820.94125636]])
camera.addHorizonInformation(horizon, uncertainty=10)
```
```
camera.setGPSpos("66°39'53.4\"S 140°00'34.8\"")
lm_points_px = np.array([[2091.300935, 892.072126], [2935.904577, 824.364956]])
lm_points_gps = ct.gpsFromString([("66°39'56.12862''S 140°01'20.39562''", 13.769),
("66°39'58.73922''S 140°01'09.55709''", 21.143)])
lm_points_space = camera.spaceFromGPS(lm_points_gps)
camera.addLandmarkInformation(lm_points_px, lm_points_space, [3, 3, 5])
```
```
trace = camera.metropolis([
ct.FitParameter("elevation_m", lower=0, upper=100, value=20),
ct.FitParameter("tilt_deg", lower=0, upper=180, value=80),
ct.FitParameter("heading_deg", lower=-180, upper=180, value=90),
ct.FitParameter("roll_deg", lower=-180, upper=180, value=0)
], iterations=1e4)
```
```
camera.plotTrace()
plt.tight_layout()
```
```
camera.plotFitInformation(im)
plt.legend();
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
%pylab inline
import px4tools.ulog
import pandas
import os
import pickle
import scipy.interpolate
import px4tools.version
pandas.__version__
px4tools.version.git_revision
d_gyro = px4tools.ulog.cached_log_processing(
log='/home/jgoppert/logs/19_19_32.ulg',
msg_filter='sensor_gyro',
processing_func=lambda x: x['sensor_gyro_0'].resample('1 s').agg('mean'),
save_path='./logs/19_19_32-sensor_gyro_0.pkl',
force_processing=False)[:'4 h']
d_gyro.t_sensor_gyro_0__f_x.plot()
d_gyro.t_sensor_gyro_0__f_y.plot()
d_gyro.t_sensor_gyro_0__f_z.plot()
gyro_debiased = (d_gyro.t_sensor_gyro_0__f_x - d_gyro.t_sensor_gyro_0__f_x.ffill().rolling('1 h min').mean().bfill())
gyro_debiased.plot()
gcf().autofmt_xdate()
var = np.sqrt(gyro_debiased['2 h': ].var())
dt = 0.001
sigma_gyro = np.sqrt(var*dt)
sigma_gyro
np.rad2deg(9.8e-5)
ps_data = px4tools.power_spectrum(d_gyro.t_sensor_gyro_0__f_x, cross_points = (-1, 0, 0.5))
ps_data
ps_data[0][0]['val']**2*2
px4tools.ulog.noise_analysis_sensor(
d_gyro[:'4.99 h'],
'sensor_gyro_0',
allan_args={'poly_order':4})
d_accel = px4tools.ulog.cached_log_processing(
log='/home/jgoppert/logs/19_19_32.ulg',
msg_filter='sensor_accel',
processing_func=lambda x: x['sensor_accel_0'].resample('1 s').agg('mean'),
save_path='./logs/19_19_32-sensor_accel_0.pkl',
force_processing=False)
px4tools.ulog.noise_analysis_sensor(
d_accel[:'4.9 h'],
'sensor_accel_0',
allan_args={'poly_order':2})
d_baro = px4tools.ulog.cached_log_processing(
log='/home/jgoppert/logs/19_19_32.ulg',
msg_filter='sensor_baro',
processing_func=lambda x: x['sensor_baro_0'].resample('100 ms').agg('mean'),
save_path='./logs/19_19_32-sensor_baro_0.pkl',
force_processing=False)
px4tools.ulog.plot_allan_std_dev(d_baro.t_sensor_baro_0__f_altitude,
poly_order=2, min_intervals=200)
px4tools.ulog.plot_autocorrelation(d_baro.t_sensor_baro_0__f_altitude)
d_mag = px4tools.ulog.cached_log_processing(
log='/home/jgoppert/logs/19_19_32.ulg',
msg_filter='sensor_mag',
processing_func=lambda x: x['sensor_mag_0'].resample('1 s').agg('mean'),
save_path='./logs/19_19_32-sensor_mag_0.pkl',
force_processing=False)
d_mag.t_sensor_mag_0__f_x.plot()
d_mag.t_sensor_mag_0__f_y.plot()
d_mag.t_sensor_mag_0__f_z.plot()
np.sqrt(d_mag.t_sensor_mag_0__f_x**2 + d_mag.t_sensor_mag_0__f_y**2 + d_mag.t_sensor_mag_0__f_z**2).mean()
d_mag.t_sensor_mag_0__f_x.plot()
d_mag.t_sensor_mag_0__f_y.plot()
d_mag.t_sensor_mag_0__f_z.plot()
px4tools.ulog.plot_allan_std_dev(d_mag.t_sensor_mag_0__f_x[:'4.99 h'],
poly_order=2)
px4tools.ulog.plot_autocorrelation(d_mag.t_sensor_mag_0__f_x['1 h':'4.99 h'],
poly_order=2)
d_mag2 = px4tools.ulog.cached_log_processing(
log='/home/jgoppert/logs/01-03-17-mhkabir-pixhawk2.ulg',
msg_filter='sensor_mag',
processing_func=lambda x: x['sensor_mag_0'].resample('1 s').agg('mean'),
save_path='./logs/01-03-17-mhkabir-pixhawk-mag-0.pkl',
force_processing=False)
mag_norm = np.linalg.norm(
np.vstack([d_mag2.t_sensor_mag_0__f_x.ffill(),
d_mag2.t_sensor_mag_0__f_y.ffill(),
d_mag2.t_sensor_mag_0__f_z.ffill()]), axis=0)
mag_norm.mean()
px4tools.ulog.plot_allan_std_dev(d_mag2.t_sensor_mag_0__f_x[:'4.99 h']/mag_norm.mean(),
poly_order=2)
px4tools.ulog.plot_autocorrelation(
d_mag2.t_sensor_mag_0__f_x['1 h':'4.99 h'], poly_order=2)
d_mag = d_mag2['1 m': '4 h']
B_b = np.array([
d_mag.t_sensor_mag_0__f_x.ffill(),
d_mag.t_sensor_mag_0__f_y.ffill(),
d_mag.t_sensor_mag_0__f_z.ffill()]).T
B_b_mean = B_b.mean(axis=0)
B_b_mean[2] = 0
B_b[:,2] = 0
mag_heading_error = pandas.Series(
np.arcsin(np.cross(B_b_mean, B_b)[:,2]/np.linalg.norm(B_b, axis=1)/np.linalg.norm(B_b_mean)),
d_mag.index, name='heading error')
mag_heading_error.plot()
ylabel('heading error, rad')
res_mag = px4tools.plot_allan_std_dev(mag_heading_error)
legend()
title('Magnetic Heading Allan Variance')
res_mag
px4tools.ulog.plot_autocorrelation(
mag_heading_error, poly_order=2)
```
| github_jupyter |
## Group number 8 - "Summer Products and Sales in Online"
## Yarden Elharar
## Nicole Ben Haim
## Noam Ifragan
## Tali Riskin
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
```
https://www.kaggle.com/jmmvutu/summer-products-and-sales-in-ecommerce-wish
```
url= "https://raw.githubusercontent.com/TaliRiskin/group8/main/summer-products-with-rating-and-performance_2020-08.csv"
file_df= pd.read_csv(url)
file_df.head()
file_df.dtypes
file_df.isnull().sum().sort_values(ascending=False)
file_df['product_variation_size_id']=file_df['product_variation_size_id'].loc[(file_df.product_variation_size_id == 'XS')| (file_df.product_variation_size_id == 'S')|(file_df.product_variation_size_id == 'M')|(file_df.product_variation_size_id == 'L')|(file_df.product_variation_size_id == 'XL')].copy()
file_df['product_variation_size_id']
file_df['countries_shipped_to'].dropna().isnull().sum()
file_df['product_color']=file_df['product_color'].copy()
file_df['product_color']
file_df['rating_count'].isnull().sum()
file_df['units_sold'].isnull().sum()
tags=file_df['tags'].str.split(',',expand= True).copy()
file_df['tags']=tags[3]
file_df['tags']
newfile=file_df[['tags','countries_shipped_to', 'product_color','rating_count','units_sold','price','product_variation_size_id','uses_ad_boosts' ]].copy()
newfile
newfile.isnull().sum()
newfile=newfile.dropna()
newfile.isnull().sum()
newfile.reset_index()
corrs = newfile.corr(method = 'kendall')
plt.figure(figsize=(15,10)) #figure size
sns.heatmap(corrs, cmap='coolwarm', center=0, annot = True);
features = ['countries_shipped_to','rating_count','units_sold','price','product_variation_size_id','uses_ad_boosts']
fig, axes = plt.subplots(3,2,figsize=(15,15))
plt.subplots_adjust(wspace=0.5, hspace = 0.3)
axes = axes.flatten()
for i,att in enumerate(features):
sns.histplot(x=att, data=newfile, ax=axes[i])
newfile.plot(subplots=True, layout=(5,4), kind='box', figsize=(12,14), patch_artist=True)
plt.subplots_adjust(wspace=0.5);
boosts_list=newfile[newfile['uses_ad_boosts']==1].reset_index().copy()
boosts_list
newfile['uses_ad_boosts'].value_counts().plot.pie(autopct='%1.1f%%')
sns.regplot(x='uses_ad_boosts',y='units_sold',data=v);
without_boosts_list=newfile[newfile['uses_ad_boosts']==0].reset_index().copy()
without_boosts_list
sns.regplot(x='uses_ad_boosts',y='units_sold',data=m);
```
תובנה 1:
ערכנו בדיקה האם קיים קשר בין שיווק דיגטלי לבין מכירות. ראינו כי הרוב בוחרים לא לקחת שיווק דיגטלי ולאחר מכן רצינו לראות האם זה משפיע על המכירות
הממצאים מראים כי כמות המכירות כמעט זהה במקרים בהם השתמשו בשיווק לבין מקרים בהם לא השתמשו בשיווק
תובנה ששונה ממה שחשבנו, שבדרך כלל נהוג לחשוב ששיווק דיגיטלי מקדם מכירות
```
sns.regplot(x='units_sold', y='price', data=newfile);
```
תובנה 2 - מצאנו שישנו קשר רציף בין יחידות שנמכרו לבין המחיר, על פי הגרף המוצג ניתן לראות שבכל כמות שנמכרת , טווח המחירים המומלץ ביותר למכירת פרטי לבוש הוא בין 8-9 יורו.
```
newfile['product_color'].value_counts().plot.pie(autopct='%1.1f%%')
rotem=newfile.groupby('product_color')['units_sold'].sum().reset_index()
rotem.sort_values('units_sold',ascending = False).reset_index()
```
תובנה 3- ראינו בהיסטוגרמה שצבע הפריטים שכמותו בין הגבוהים במלאי כגון צהוב, הוא לא בין הצבעים הנמכרים ביותר ולכן יש ליצור הלימה בין כמות הפריטים במלאי לבין כמות הפריטים שנמכרים מכל צבע.
| github_jupyter |
## Import modules. Remember it is always good practice to do this at the beginning of a notebook.
If you don't have seaborn, you can install it with conda install seaborn
### Use notebook magic to render matplotlib figures inline with notebook cells.
Let's begin!
We'll use pandas read_csv function to read in our data.
Let's take a look at the data to make sure it looks right with head, and then look at the shape of the dataframe
That's a lot of data. Let's take a random subsampling of the full dataframe to make playing with the data faster. This is something you may consider doing when you have large datasets and want to do data exploration. Pandas has a built-in method called sample that will do this for you.
We can use this to try some of our plotting functions. We will start with two variables in the dataset, PCE and HOMO energy.
There are multiple packages you can use for plotting. Pandas has some built-in object-oriented methods we can try first.
Oops! We used the wrong dataset. The full dataset took a while to plot. We can use %%timeit to see how long that took.
Note that %%timeit repeats the function call a number of times and averages it. You can alter this behavior by changing the defaults. Let's see how long it takes to plot our subsample:
That's a lot quicker! It doesn't scale perfectly with datasize (plotting took about 1/5 of the time with 1/10 of the data) likely due to code overhead.
But the default plot settings are pretty ugly. We can take advantage of the object-oriented nature of pandas plots to modify the output.
That's a bit butter, but we can still make improvements, like adding gridlines, making the y-axis label more accurate, increasing size, and adjusting the aspect ratio.
Note that we used LaTeX notation to create the subscript text. LaTeX can be used to generate mathematical expressions, symbols, and Greek letters for figures. One reference guide is included here: https://www.overleaf.com/learn/latex/Subscripts_and_superscripts
Take a moment to try to figure out the following using the pandas documentation:
* How to change the x range to be 2 to 10
* How to change the y range to be -6 to 2
* How to change the font size to 18
* how to change the colors and transparency.
You can access the documentation [here](https://pandas.pydata.org/pandas-docs/stable/visualization.html).
### An aside: Matplotlib can also be used to plot datasets in a similar fashion
Pandas visualization toolbox is a convenience feature built on top of Matplotlib.
Note that pandas can also be used like matplotlib to create subplots. It just has a slightly different notation:
### Back to pandas: Quick dataset exploration tools
A very useful tool for quickly exploring relationships between variables in a dataset is the built-in pandas scatterplot matrix:
That's a lot of information in one figure! Note the funky id plot at the left. IDs are the molecule ids and don't contain any useful information. Let's make that a column index before moving on.
OK, let's move on to density plots. These show the probability density of particular values for a variable. Notice how we used an alternate way of specifying plot type.
We can plot two different visualizations on top of each other, for instance, the density plot and a histogram plot. Since the density plot has a different y axis than the density plot, make sure to use a secondary y axis
### Alternate plot styles
As pandas is built on Matplotlib, you can use Matplotlib to alter then plot style. Styles are essentially a set of defaults for the plot appearance, so you don't have to modify them all yourselves. Let's try the ggplot style that mimics the ggplot2 style output from R.
You can find the list of matplotlib styles [here](https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html)
### Seaborn improvements
Matplotlib can be used to create publication-quality images, but has some limitations-- including capabilities with 3D plots. There's another package Seaborn, that has a lot of built-in styles for very high-quality plots. Let's take a look at some of the options available:
### In class exercise
Fix the above subplots so they aren't as shoddy. Add titles, increase font size, change colors and alpha, and change the margins and layout so they are side by side.
| github_jupyter |
## Importing Necessary Libraries
```
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tabulate import tabulate
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
%matplotlib inline
```
## Data Upload
```
train_data = pd.read_csv("train.csv")
df_train = train_data.copy()
test_data = pd.read_csv("test.csv")
df_test = test_data.copy()
#train_data.head()
#test_data.head()
print(df_train.shape, df_test.shape)
print(tabulate(df_train.describe().T,headers=df_train.describe().T.columns,tablefmt="psql"))
pd.DataFrame(df_train.dtypes,columns=['Type']).T
```
### Number of Mıssing Values in Training and Test Sets
```
#df_train[df_train.isnull().values]
NaN_numbers_train = pd.DataFrame(df_train.isna().sum())
NaN_numbers_train = NaN_numbers_train[pd.DataFrame(df_train.isna().sum()).T.any()].T
NaN_numbers_train.rename(index={0: 'Missing'})
```
Alley, PoolQC, Fence, MiscFeature parameters are mostly missing. They should be treated accordingly !
```
NaN_numbers_test = pd.DataFrame(df_test.isna().sum())
NaN_numbers_test = NaN_numbers_test[pd.DataFrame(df_test.isna().sum()).T.any()].T
NaN_numbers_test.rename(index={0: 'Missing'})
```
### Data Type Conversion for Categorical Variables
```
df_train['MSZoning'] = df_train['MSZoning'].astype(CategoricalDtype())
df_train['Street'] = df_train['Street'].astype(CategoricalDtype())
df_train['Alley'] = df_train['Alley'].astype(CategoricalDtype())
df_train['LotShape'] = df_train['LotShape'].astype(CategoricalDtype())
df_train['YearBuilt'] = df_train['YearBuilt'].astype(CategoricalDtype())
df_train['YearRemodAdd'] = df_train['YearRemodAdd'].astype(CategoricalDtype())
df_train['OverallQual'] = df_train['OverallQual'].astype(CategoricalDtype()) #Included in Features
df_train['OverallCond'] = df_train['OverallCond'].astype(CategoricalDtype()) #Included in Features
df_test['MSZoning'] = df_test['MSZoning'].astype(CategoricalDtype())
df_test['Street'] = df_test['Street'].astype(CategoricalDtype())
df_test['Alley'] = df_test['Alley'].astype(CategoricalDtype())
df_test['LotShape'] = df_test['LotShape'].astype(CategoricalDtype())
df_test['YearBuilt'] = df_test['YearBuilt'].astype(CategoricalDtype())
df_test['YearRemodAdd'] = df_test['YearRemodAdd'].astype(CategoricalDtype())
df_test['OverallQual'] = df_test['OverallQual'].astype(CategoricalDtype()) #Included in Features
df_test['OverallCond'] = df_test['OverallCond'].astype(CategoricalDtype()) #Included in Features
df_train['MSZoning'].unique()
```
## Visualizations to Explore the Data
```
sns.set(style="white", palette="muted", color_codes=True)
# Set up the matplotlib figure
f, axes = plt.subplots(2, 2, figsize=(16, 8), sharex=False)
sns.despine(left=True)
sns.barplot(x='MSZoning',y='SalePrice',data=df_train, ax=axes[0, 0]);
# Plot a filled kernel density estimate
sns.distplot(df_train['SalePrice'], hist=False, color="g", kde_kws={"shade": True}, ax=axes[0, 1],
fit=stats.norm);
#Gaussian Fit for Price Distribution
(mu, sigma) = stats.norm.fit(df_train['SalePrice'])
#print("mu={0}, sigma={1}".format(mu, sigma))
axes[0,1].legend(["normal dist. fit ($\mu=${0:.2g}, $\sigma=${1:.2f})".format(mu, sigma)],loc="upper right")
# Plot a filled kernel density estimate
#sns.distplot(df_train['Street'], hist=False, color="b", kde_kws={"shade": True}, ax=axes[1, 0]);
sns.barplot(x='Street',y='SalePrice',data=df_train, ax=axes[1, 0]);
sns.barplot(x='LotShape',y='SalePrice',data=df_train, ax=axes[1, 1]);
#plt.setp(axes, yticks=[])
plt.tight_layout()
sns.set(style="white", palette="muted", color_codes=True)
# Set up the matplotlib figure
f, axes = plt.subplots(2, 1, figsize=(16, 8), sharex=False)
sns.despine(left=True)
chart = sns.barplot(x='YearBuilt',y='SalePrice',data=df_train, ax=axes[0])
chart.set_xticklabels(chart.get_xticklabels(),rotation="vertical");
# Plot a filled kernel density estimate
chart = sns.barplot(x='YearRemodAdd',y='SalePrice',data=df_train, ax=axes[1]);
chart.set_xticklabels(chart.get_xticklabels(),rotation="vertical");
#plt.setp(axes, yticks=[])
plt.tight_layout()
sns.set(style="white", palette="muted", color_codes=True)
# Set up the matplotlib figure
f, axes = plt.subplots(2, 1, figsize=(16, 8), sharex=False)
sns.despine(left=True)
sns.barplot(x='OverallQual',y='SalePrice',data=df_train, ax=axes[0]);
# Plot a filled kernel density estimate
sns.barplot(x='OverallCond',y='SalePrice',data=df_train, ax=axes[1]);
#plt.setp(axes, yticks=[])
plt.tight_layout()
df_train=df_train.drop(df_train.loc[df_train['TotalBsmtSF'] == df_train['TotalBsmtSF'].max()].index[0])
# Set the width and height of the figure
plt.figure(figsize=(16,8))
# Add a Regression line to see the correlation btw bmi and charges
sns.regplot(x=df_train['TotalBsmtSF'], y=df_train['SalePrice'])
plt.show()
```
# Feature Selection & Forming Train, Dev and Test Sets
```
Features = ['OverallCond','OverallQual','TotalBsmtSF']
X = df_train[Features]
y = df_train['SalePrice']
X_test = df_test[Features]
X_train, X_dev, y_train, y_dev = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_dev.shape, X_test.shape, y_train.shape, y_dev.shape)
```
# ML Algorithms
## Linear Regression
```
linreg = LinearRegression(fit_intercept=False)
linreg.fit(X_train, y_train)
#To retrieve the intercept:
#print(linreg.intercept_)
#For retrieving the slope:
#print(linreg.coef_)
y_pred_linreg_dev = linreg.predict(X_dev)
df_linreg = pd.DataFrame({'Actual': y_dev, 'Predicted': y_pred_linreg_dev})
df_linreg
print('Root Mean Squared Error for Linear Regression:', np.sqrt(metrics.mean_squared_error(y_dev, y_pred_linreg_dev)))
print("Accuracy: "+ str(linreg.score(X_dev,y_dev)*100) + "%")
```
## Decision Tree Regression
```
dt = DecisionTreeRegressor(max_depth=10, min_samples_split=5, max_leaf_nodes=40)
dt.fit(X_train, y_train)
y_pred_dt = dt.predict(X_dev)
df_dt = pd.DataFrame({'Actual': y_dev, 'Predicted': y_pred_dt})
df_dt
print('Root Mean Squared Error for Decision Tree Regression:', np.sqrt(metrics.mean_squared_error(y_dev, y_pred_dt)))
print("Accuracy: "+ str(dt.score(X_dev,y_dev)*100) + "%")
```
## Random Forest Regression
```
rf = RandomForestRegressor(max_depth = 20, n_estimators=10, random_state = 42)
rf.fit(X_train, y_train)
y_pred_rf = rf.predict(X_dev)
df_rf = pd.DataFrame({'Actual': y_dev, 'Predicted': y_pred_rf})
df_rf
print('Root Mean Squared Error for Random Forest Regression:', np.sqrt(metrics.mean_squared_error(y_dev, y_pred_rf)))
print("Accuracy: "+ str(rf.score(X_dev,y_dev)*100) + "%")
```
# Creating Submission CSV
```
X_test
# Filling NaN with mean
X_test[X_test.isnull().values]
X_test['TotalBsmtSF'] = X_test['TotalBsmtSF'].fillna(X_test['TotalBsmtSF'].mean())
#X_test=X_test.drop(X_test[X_test.isnull().values].index[0])
X_test[X_test.isnull().values]
y_pred_rf_test = rf.predict(X_test)
df_temp = pd.concat([df_test['Id'],pd.Series(y_pred_rf_test)],axis=1)
df_temp.columns = [['Id', 'SalePrice']]
df_temp.to_csv("Sample_Submission_001.csv",index=False)
```
| github_jupyter |
```
#import trio
import pandas as pd
pd.set_option('max_columns', None)
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#data preparation pkgs
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
#classifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
#metrics
from sklearn.metrics import classification_report, plot_confusion_matrix, confusion_matrix
```
## Widget to upload the data file
```
from google.colab import files
files.upload()
```
# Data Source: Dataset is available on Kaggle.
Find here: https://www.kaggle.com/sid321axn/audit-data
```
data = pd.read_csv("audit_data.csv")
data
!pip install pycaret
```
## EDA
## Check Missing value
```
#check missing value
data.isna().sum()
data.info()
#fill the missing value in Money_Value column
data['Money_Value'] = data['Money_Value'].fillna(data['Money_Value'].mean())
data.isna().sum()
```
## So, no missing value now as we filled the 1 missing value with the mean of the column as it is a numerical column.
```
#Plotting count values of Positive and Negative
data['Risk'].value_counts().plot(kind = 'bar')
```
### 1 means Fraudulent and 0 means Not Fraudulent
#Feature Engineering
```
#Let's create a copy of our main data
def data_preparation(df):
df = df.copy()
return df
```
#### We will do all the processing and feature engineering step on the new_data
```
new_data = data_preparation(data)
new_data
#check the mising value once more
new_data.isna().sum()
location_dummies = pd.get_dummies(new_data['LOCATION_ID'], prefix='location')
new_data = pd.concat([new_data, location_dummies], axis=1)
new_data = new_data.drop('LOCATION_ID', axis=1)
new_data
X = new_data.drop("Risk", axis=1)
y = new_data['Risk']
X
y
#Split the data
X_train, X_test, y_train, y_test = train_test_split(X,y, train_size=0.7, shuffle=True, random_state=21)
print(len(X_train))
print(len(X_test))
print(len(y_train))
print(len(y_test))
X_train
y_test
#Scale the data to make it in the same range
# Only the X_train
scaler = StandardScaler()
scaler.fit(X_train)
X_train = pd.DataFrame(scaler.transform(X_train), index=X_train.index, columns=X_train.columns)
X_test = pd.DataFrame(scaler.transform(X_test), index=X_test.index, columns=X_test.columns)
X_train
X_test
y_train
```
## Model Training
```
logreg = LogisticRegression()
logreg_clf = logreg.fit(X_train, y_train)
d_tree = DecisionTreeClassifier()
d_tree_clf = d_tree.fit(X_train, y_train)
random_forest = RandomForestClassifier()
random_forest_clf = random_forest.fit(X_train, y_train)
xgboost = GradientBoostingClassifier()
xgboost_clf = xgboost.fit(X_train, y_train)
svm = SVC()
svm_clf = svm.fit(X_train, y_train)
linear_kernel = LinearSVC()
linear_kernel_clf = linear_kernel.fit(X_train, y_train)
```
# Evaluation
```
#Logistic Regression
score_log = logreg_clf.score(X_test, y_test)
score_d_tree = d_tree_clf.score(X_test, y_test)
score_random_forest = random_forest_clf.score(X_test, y_test)
score_xgboost = xgboost_clf.score(X_test, y_test)
score_svm = svm_clf.score(X_test, y_test)
score_kernel = linear_kernel_clf.score(X_test, y_test)
print("LOGISTIC REGRESSION:", score_log*100, "%")
print("Decision Tree:", score_d_tree*100, "%")
print("Random Forest:", score_random_forest*100, "%")
print("XGBOOST:", score_xgboost*100, "%")
print("SVM:", score_svm*100, "%")
print("LINEAR KERNEL:", score_kernel*100, "%")
y_pred_logreg = logreg_clf.predict(X_test)
y_pred_dtree = d_tree_clf.predict(X_test)
y_pred_random = random_forest_clf.predict(X_test)
y_pred_xgboost = xgboost_clf.predict(X_test)
y_pred_svm = svm_clf.predict(X_test)
y_pred_linear = linear_kernel_clf.predict(X_test)
clf_logreg = classification_report(y_test, y_pred_logreg)
print(clf_logreg)
plot_confusion_matrix(logreg_clf, X_test, y_test)
clf_dtree = classification_report(y_test, y_pred_dtree)
print(clf_dtree)
plot_confusion_matrix(d_tree_clf, X_test, y_test)
clf_random = classification_report(y_test, y_pred_random)
print(clf_random)
plot_confusion_matrix(random_forest_clf, X_test, y_test)
clf_xgboost = classification_report(y_test, y_pred_xgboost)
print(clf_xgboost)
plot_confusion_matrix(xgboost_clf, X_test, y_test)
clf_svm = classification_report(y_test, y_pred_svm)
print(clf_svm)
plot_confusion_matrix(svm_clf, X_test, y_test)
clf_kernel = classification_report(y_test, y_pred_linear)
print(clf_kernel)
plot_confusion_matrix(linear_kernel_clf, X_test, y_test)
```
| github_jupyter |
# Machines Manufacturing Captal Budgeting Model (Project 1)
Insert your description of the model here and add any additional sections below:
- [**Setup**](#Setup): Runs any imports and other setup
- [**Inputs**](#Inputs): Defines the inputs for the model
## Setup
Setup for the later calculations are here. The necessary packages are imported.
```
from dataclasses import dataclass
import numpy_financial as npf
```
## Inputs
All of the inputs for the model are defined here. A class is constructed to manage the data, and an instance of the class containing the default inputs is created.
```
@dataclass
class ModelInputs:
n_phones: float = 100000
price_scrap: float = 50000
price_phone: float = 2000
cost_machine_adv: float = 1000000
cogs_phone: float = 250
n_life: int = 10
n_machines: int = 5
d_1: float = 100000
g_d: float = 0.2
max_year: float = 20
interest: float = 0.05
# Inputs for bonus problem
elasticity: float = 100
demand_constant: float = 300000
model_data = ModelInputs()
model_data
```
## Revenues
Revenues generated by the company each year consist of goods of sales and
sales of depreciated fixed assets
```
# How many machines in operation per year
def op_sp_machines(current_year):
'''
return the number of machines in operation each year
and whether advertisement is launched this year
'''
op = []
sp = []
if current_year <= model_data.n_machines:
op.append(range(1, current_year)) # purchase one machine before year 5
elif 1+model_data.n_life >= current_year > model_data.n_machines:
op.append(range(1, model_data.n_machines))
elif model_data.n_machines+model_data.n_life >= current_year > 1+model_data.n_life:
sp.append(1) # add depreciated machines to scraped list
else:
op = []
return op, sp
def is_ad(current_year):
is_ad = False
if current_year > model_data.n_machines:
is_ad = True
return is_ad
# Revenues per year
def total_revenues(n_goods_sold, sp_machines):
'''
return the total revenue generated by
the company per year
'''
sales_from_phone = n_goods_sold * model_data.price_phone
if sp_machines > 0: # if there is any machine in the scraped list
sales_from_machine = model_data.price_scrap
else:
sales_from_machine = 0
revenues = sales_from_machine + sales_from_phone
return revenues
# Determine the number of goods sold
def goods_sold(production, demand):
'''
compare which figure is smaller:
production of the phones of demand of the phones
'''
return production if production <= demand else demand
```
## Costs
Costs consist of phones manufacture, purchasing machines and advertisement
```
# cost of purchasing machines
def machines_cost(current_year):
'''
only purcahse machines before year 6
'''
if current_year <= model_data.n_machines:
c_machines = model_data.cost_machine_adv
else:
c_machines = 0
return c_machines
def total_costs(n_goods_sold, machines_cost, ad_cost):
phone_cost = n_goods_sold * model_data.cogs_phone
costs = machines_cost + ad_cost + phone_cost
return costs
```
## Calculating cash flows
```
def cashflows():
'''
return a list that contains each year's cashflow
'''
cashflows = []
demand = model_data.d_1
for i in range(1, model_data.max_year+1):
op_machines = len(op_sp_machines(i)[0]) # number of operating machines
sp_machines = len(op_sp_machines(i)[1]) # number of scraped machines
if is_ad(i) == True:
demand *= (1 + model_data.g_d) # demand of phones if there are ads
c_ad = model_data.cost_machine_adv # cost of advertisement
else:
demand = model_data.d_1 # demand of phones if no ads
c_ad = 0
phones_production = op_machines * model_data.n_phones # how many phones have been produced
n_goods_sold = goods_sold(phones_production, demand)
revenues = total_revenues(n_goods_sold, sp_machines) # total reveneus per year
c_machines = machines_cost(i)
costs = total_costs(n_goods_sold, c_machines, c_ad)
cashflow = revenues - costs
cashflows.append(cashflow)
return cashflows
cash_flows = cashflows()
cash_flows
npv = npf.npv(model_data.interest, cash_flows) # this should ultimately be set to the overally model npv number
npv
```
| github_jupyter |
# Scikit-Learn Classification
- Pandas Documentation: http://pandas.pydata.org/
- Scikit Learn Documentation: http://scikit-learn.org/stable/documentation.html
- Seaborn Documentation: http://seaborn.pydata.org/
```
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
```
## 1. Read data from Files
```
df = pd.read_csv('../data/geoloc_elev.csv')
```
## 2. Quick Look at the data
```
type(df)
df.info()
df.head()
df.tail()
df.describe()
df['source'].value_counts()
df['target'].value_counts()
```
## 3. Visual exploration
```
import seaborn as sns
sns.pairplot(df, hue='target')
```
## 4. Define target
```
y = df['target']
y.head()
```
## 5. Feature engineering
```
raw_features = df.drop('target', axis='columns')
raw_features.head()
```
### 1-hot encoding
```
X = pd.get_dummies(raw_features)
X.head()
```
## 6. Train/Test split
```
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size = 0.3, random_state=0)
```
## 7. Fit a Decision Tree model
```
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(max_depth=3, random_state=0)
model.fit(X_train, y_train)
```
## 8. Accuracy score on benchmark, train and test sets
```
from sklearn.metrics import confusion_matrix, classification_report
y_pred = model.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
pd.DataFrame(cm,
index=["Miss", "Hit"],
columns=['pred_Miss', 'pred_Hit'])
print(classification_report(y_test, y_pred))
```
## 10. Feature Importances
```
importances = pd.Series(model.feature_importances_, index=X.columns)
importances.plot(kind='barh')
```
## 11. Display the decision boundary
```
hticks = np.linspace(-2, 2, 101)
vticks = np.linspace(-2, 2, 101)
aa, bb = np.meshgrid(hticks, vticks)
not_important = np.zeros((len(aa.ravel()), 4))
ab = np.c_[aa.ravel(), bb.ravel(), not_important]
c = model.predict(ab)
cc = c.reshape(aa.shape)
ax = df.plot(kind='scatter', c='target', x='lat', y='lon', cmap='bwr')
ax.contourf(aa, bb, cc, cmap='bwr', alpha=0.2)
```
## Exercise
Iterate and improve on the decision tree model. Now you have a basic pipeline example. How can you improve the score? Try some of the following:
1. change some of the initialization parameters of the decision tree re run the code.
- Does the score change?
- Does the decision boundary change?
2. try some other model like Logistic Regression, Random Forest, SVM, Naive Bayes or any other model you like from [here](http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html)
3. what's the highest score you can get?
| github_jupyter |
```
import os
import json
from docx import Document
from io import StringIO, BytesIO
import re
import pandas as pd
import json
import spacy
from nltk.corpus import stopwords
from gensim.models import LdaModel
from gensim.models.wrappers import LdaMallet
import gensim.corpora as corpora
from gensim.corpora import Dictionary
from gensim import matutils, models
from gensim.models import CoherenceModel
import pyLDAvis.gensim
from docx import Document
from io import StringIO, BytesIO
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams.update({'font.size': 14, 'lines.linewidth': 3})
notebook_dir = os.getcwd()
event_type = 'ANIMAL'
with open(F'../data/sop_jsons/{event_type}.txt') as f:
drugs = json.load(f)
f.close()
type(drugs)
juris, roles, sops = list(), list(), list()
for juri, dct in drugs.items():
for role, sop in dct.items():
juris.append(juri)
roles.append(role)
sops.append(sop)
drugsdf = pd.DataFrame({'juri': juris, 'role': roles, 'sop': sops})
drugsdf.head(3)
drugs_calltaker = drugsdf[drugsdf['role'] == 'call taker']
drugs_dispatcher = drugsdf[drugsdf['role'] == 'dispatcher']
nlp = spacy.load("en_core_web_sm")
# stop_words = set(stopwords.words('english'))
remove = [
"subject:",
"writes:",
"wrote:",
"write:"
]
def multiple_replace(text, unwanted = remove):
"""
Replace unwanted pattern with a space; return a string
"""
reg = re.compile(f"({'|'.join(remove)})")
return reg.sub(" ", text)
"(%s)" % "|".join(remove) == f"({'|'.join(remove)})"
def preprocess(strlist,
min_token_len = 2,
allowed_pos = ['ADV', 'ADJ', 'VERB', 'NOUN']):
# texts = ' '.join(strlist).lower()
res = list()
for string in strlist:
text = string.lower()
doc = nlp(text)
res += [token.lemma_ for token in doc \
if token.is_alpha \
# Spacy considers 'call' as a stop word, which is not suitable for our case
and not token.is_stop \
# and token.text not in stop_words \
and token.pos_ in allowed_pos \
and len(token.lemma_) > min_token_len]
return ' '.join(res)
drugs_calltaker.shape
['mama mele maso'.split(), 'ema ma mama'.split()]
def get_dct_dtmatrix(sops):
corpus = [sop.split() for sop in map(preprocess, sops)]
dictionary = corpora.Dictionary(corpus)
doc_term_matrix = [dictionary.doc2bow(doc) for doc in corpus]
return doc_term_matrix, corpus, dictionary
# drugs_calltaker['sop']
doc_term_matrix, corpus, dictionary = get_dct_dtmatrix(drugs_calltaker['sop'])
corpus[0]
def topics_with_coherence(doc_term_matrix, corpus, dictionary, texts,
N = 10, passes = 20, coherence = 'c_v', random_state = 2020):
num_topic, ldas, scores = list(), list(), list()
# doc_term_matrix = [dictionary.doc2bow(doc) for doc in corpus]
for n in range(1, N+1):
lda = models.LdaModel(corpus = doc_term_matrix,
id2word = dictionary,
num_topics = n,
passes = passes,
random_state = random_state)
coherence_model = CoherenceModel(
model = lda,
texts = corpus,
dictionary = dictionary,
coherence = coherence)
coherence_score = coherence_model.get_coherence()
# mod = {'num_topic': n, 'model': lda, 'coherence_score': coherence_score}
# res[f"num_topic={n}"] = [lda, coherence_score]
num_topic.append(n)
ldas.append(lda)
scores.append(coherence_score)
return pd.DataFrame({
'num_topic':num_topic,
'model': ldas,
'coherence_score': scores
})
drugs_call_coherence_cv = topics_with_coherence(doc_term_matrix, corpus, dictionary, drugs_calltaker['sop'])
drugs_call_coherence_cv
fig, ax = plt.subplots(1, 1, figsize = (12, 8))
ax.plot(drugs_call_coherence_cv.loc[:, 'num_topic'].values,
drugs_call_coherence_cv.loc[:, 'coherence_score'].values)
ax.set_xlabel('number of topics')
ax.set_ylabel('coherence score')
ax.set_title('Coherence Score (c_v) vs Number of Topics')
plt.show()
chosen_model_cv = list(drugs_call_coherence_cv.iloc[1:, :].sort_values('coherence_score')['model'])[-1]
print(chosen_model_cv)
chosen_model_cv.print_topics()
model_cv_2 = list(drugs_call_coherence_cv[drugs_call_coherence_cv['num_topic'] == 2]['model'])[0]
def get_topic(model, doc):
ppdoc = preprocess(doc)
doc_term_arr = dictionary.doc2bow(ppdoc.split())
return sorted(model[doc_term_arr],
key = lambda x: x[1],
reverse = True)[0][0]
sent = list(drugs_calltaker['sop'])#.append(['aa', 'bb'])
sent.append(['This is a test', 'to see if the model works'])
# sent
preprocess(list(drugs_calltaker['sop'])[2])
ppsent = preprocess(sent[1])
doc_term_arr = dictionary.doc2bow(ppsent.split())
chosen_model_cv[doc_term_arr]
# doc_term_arr
list(map(lambda x: get_topic(chosen_model_cv, list(x)), sent))
# umass_6 = list(drugs_call_coherence_umass[drugs_call_coherence_umass['num_topic'] == 4]['model'])[0]
# print(umass_6)
# list(map(lambda x: get_topic(umass_6, list(x)), sent))
drugs_call_coherence_umass = topics_with_coherence(doc_term_matrix, corpus, dictionary,
drugs_calltaker['sop'], coherence = 'u_mass')
fig, ax = plt.subplots(1, 1, figsize = (12, 8))
ax.plot(drugs_call_coherence_umass.loc[:, 'num_topic'].values,
drugs_call_coherence_umass.loc[:, 'coherence_score'].values)
ax.set_xlabel('number of topics')
ax.set_ylabel('coherence score')
ax.set_title('Coherence Score (u_mass) vs Number of Topics')
plt.show()
drugs_call_coherence_cuci = topics_with_coherence(doc_term_matrix, corpus, dictionary,
drugs_calltaker['sop'], coherence = 'c_uci')
fig, ax = plt.subplots(1, 1, figsize = (12, 8))
ax.plot(drugs_call_coherence_cuci.loc[:, 'num_topic'].values,
drugs_call_coherence_cuci.loc[:, 'coherence_score'].values)
ax.set_xlabel('number of topics')
ax.set_ylabel('coherence score')
ax.set_title('Coherence Score (c_uci) vs Number of Topics')
plt.show()
drugs_call_coherence_cnpmi = topics_with_coherence(doc_term_matrix, corpus, dictionary,
drugs_calltaker['sop'], coherence = 'c_npmi')
fig, ax = plt.subplots(1, 1, figsize = (12, 8))
ax.plot(drugs_call_coherence_cnpmi.loc[:, 'num_topic'].values,
drugs_call_coherence_cnpmi.loc[:, 'coherence_score'].values)
ax.set_xlabel('number of topics')
ax.set_ylabel('coherence score')
ax.set_title('Coherence Score (c_npmi) vs Number of Topics')
plt.show()
```
#### Reflection of DRUGS coherence score
- the coherence score is very high for the one-topic model
- this makes sense, because we are looking at docs under the same type "DRUGS"
#### Question
- While the model assigns the documents with the correct topic, does this necessarily mean the documents are similar enough to be consolicated?
- LDA in not stable. How will this instability affect us?
```
# os.listdir('.')
# json_dir = '../data/interim'
# os.chdir(json_dir)
# all_sop = os.listdir('.')
# print(all_sop)
# def load_sop_json(filename):
# cwd = os.getcwd()
# os.chdir(notebook_dir)
# with open(f'../data/interim/{filename}') as f:
# one_type = json.load(f)
# f.close()
# os.chdir(cwd)
# return one_type
# juris_all, roles_all, sops_all = list(), list(), list()
# for filename in all_sop:
# one_type = load_sop_json(filename)
# for juri, dct in one_type.items():
# for role, sop in dct.items():
# juris_all.append(juri)
# roles_all.append(role)
# sops_all.append(sop)
# alldf = pd.DataFrame({'juri': juris_all, 'role': roles_all, 'sop': sops_all})
# alldf
# alldf.iloc[0, :]['sop']
# dt_matrix_all, corpus_all, dictionary_all = get_dct_dtmatrix(sops_all)
# all_coherence = topics_with_coherence(dt_matrix_all, corpus_all, dictionary_all, N = 20)
# all_coherence
# plt.figure(figsize = (12, 8))
# plt.plot(all_coherence.loc[:, 'num_topic'].values, all_coherence.loc[:, 'coherence_score'].values)
# plt.show()
```
| github_jupyter |
```
test_index = 0
```
#### testing
```
from load_data import *
# load_data()
```
## Loading the data
```
from load_data import *
X_train,X_test,y_train,y_test = load_data()
len(X_train),len(y_train)
len(X_test),len(y_test)
```
## Test Modelling
```
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
class Test_Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.c1 = nn.Conv2d(1,64,5)
self.c2 = nn.Conv2d(64,128,5)
self.c3 = nn.Conv2d(128,256,5)
self.fc4 = nn.Linear(256*10*10,256)
self.fc6 = nn.Linear(256,128)
self.fc5 = nn.Linear(128,4)
def forward(self,X):
preds = F.max_pool2d(F.relu(self.c1(X)),(2,2))
preds = F.max_pool2d(F.relu(self.c2(preds)),(2,2))
preds = F.max_pool2d(F.relu(self.c3(preds)),(2,2))
# print(preds.shape)
preds = preds.view(-1,256*10*10)
preds = F.relu(self.fc4(preds))
preds = F.relu(self.fc6(preds))
preds = self.fc5(preds)
return preds
device = torch.device('cuda')
BATCH_SIZE = 32
IMG_SIZE = 112
model = Test_Model().to(device)
optimizer = optim.SGD(model.parameters(),lr=0.1)
criterion = nn.CrossEntropyLoss()
EPOCHS = 12
from tqdm import tqdm
PROJECT_NAME = 'Weather-Clf'
import wandb
# test_index += 1
# wandb.init(project=PROJECT_NAME,name=f'test-{test_index}')
# for _ in tqdm(range(EPOCHS)):
# for i in range(0,len(X_train),BATCH_SIZE):
# X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device)
# y_batch = y_train[i:i+BATCH_SIZE].to(device)
# model.to(device)
# preds = model(X_batch.float())
# preds.to(device)
# loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long))
# optimizer.zero_grad()
# loss.backward()
# optimizer.step()
# wandb.log({'loss':loss.item()})
# wandb.finish()
# for index in range(10):
# print(torch.argmax(preds[index]))
# print(y_batch[index])
# print('\n')
class Test_Model(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1,16,5)
self.conv2 = nn.Conv2d(16,32,5)
self.conv3 = nn.Conv2d(32,64,5)
self.conv4 = nn.Conv2d(64,128,5)
self.conv5 = nn.Conv2d(128,256,3)
self.fc1 = nn.Linear(256,64)
self.fc2 = nn.Linear(64,128)
self.fc3 = nn.Linear(128,64)
self.fc4 = nn.Linear(64,128)
self.fc5 = nn.Linear(128,6)
def forward(self,X):
preds = F.max_pool2d(F.relu(self.conv1(X)),(2,2))
preds = F.max_pool2d(F.relu(self.conv2(preds)),(2,2))
preds = F.max_pool2d(F.relu(self.conv3(preds)),(2,2))
preds = F.max_pool2d(F.relu(self.conv4(preds)),(2,2))
preds = F.max_pool2d(F.relu(self.conv5(preds)),(2,2))
print(preds.shape)
# preds = preds.view(-1,1)
# preds = F.relu(self.fc1(preds))
# preds = F.relu(self.fc2(preds))
# preds = F.relu(self.fc3(preds))
# preds = F.relu(self.fc4(preds))
# preds = F.relu(self.fc5(preds))
# return preds
model = Test_Model().to(device)
optimizer = optim.SGD(model.parameters(),lr=0.1)
criterion = nn.CrossEntropyLoss()
test_index += 1
wandb.init(project=PROJECT_NAME,name=f'test-{test_index}')
for _ in tqdm(range(EPOCHS)):
for i in range(0,len(X_train),BATCH_SIZE):
X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device)
y_batch = y_train[i:i+BATCH_SIZE].to(device)
model.to(device)
preds = model(X_batch.float())
preds.to(device)
loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long))
optimizer.zero_grad()
loss.backward()
optimizer.step()
wandb.log({'loss':loss.item()})
wandb.finish()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/VGGatGitHub/Quantum-Chain/blob/master/Vaccine_Distribution.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#Note you need to do the pip install and git clone only once!
#That is, at the begining of your runtime on the Google Colab.
```
## Preamble - set up the repo and dependences
```
#!curl -H "X-Auth-Token: YourAPIkey" -X DELETE https://cloud.dwavesys.com/sapi/problems/7211d196-cfc6-4630-84d0-f42ae5d55f0f
#for private repo use:
#!git clone https://Userneme:Pasword@github.com/YourGitHub/Repo.git
!git clone https://github.com/VGGatGitHub/Quantum-Chain.git
#https://www.youtube.com/watch?v=bErs0dxC1aY&list=PLPvKnT7dgEsuhec_yW9oxcZ6gg9SfRFFV
#https://docs.ocean.dwavesys.com/en/latest/overview/install.html#installoceansoftware
#!python -m venv ocean
#!\Scripts\activate
!pip install dwave-ocean-sdk
!dwave setup #API endpoint URL: https://cloud.dwavesys.com/sapi/
!git clone https://github.com/perrygeo/simanneal.git
!cd ./simanneal/ && pip install -e .
```
##Restart here!
```
#pip install -e git+https://github.com/perrygeo/simanneal.git # latest from github
#!pip install simanneal # from pypi
!pip show simanneal # from pypi
#you may have to restart you runtime after instalatins are compleat!
import sys
f_loc="./simanneal/tests/"
if f_loc not in sys.path: sys.path.append(f_loc)
#you may have to restart you runtime after instalatins are compleat!
import random
import sys
import time
from helper import distance, cities, distance_matrix
from simanneal import Annealer
if sys.version_info.major >= 3: # pragma: no cover
from io import StringIO
else:
from StringIO import StringIO
#you may have to restart you runtime after instalatins are compleat!
```
##Define a map ploting function
```
#!pip install geopandas
!pip show geopandas
!pip install shapely
import pandas as pd
import geopandas
import matplotlib.pyplot as plt
#import argparse
#sources:
#https://geopandas.org/io.html?highlight=states
#https://medium.com/@erikgreenj/mapping-us-states-with-geopandas-made-simple-d7b6e66fa20d
zipfile = "zip:///content/Quantum-Chain/states_21basic.zip"
states = geopandas.read_file(zipfile)
states.head()
states[states.STATE_ABBR == 'CA'].plot()
states[states.SUB_REGION == 'Pacific'].plot()
#original function plot_map from QAlpha team in the CDL-Quantum/Hackathon2020
def plot_map(cities,*arg,**kwarg):
#VGG note that our cities list has positive values for the Longitude
data_list=[[key, cities[key][0], cities[key][1]] for key in cities.keys()]
df = pd.DataFrame(data_list)
#City,Latitude,Longitude
df.columns=['City','Latitude','Longitude']
gdf_all = geopandas.GeoDataFrame(
df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude))
if 'state' in kwarg:
state=kwarg['state']
if state=='CA':
ax = states[states.STATE_ABBR == 'CA'].plot(
color='white', edgecolor='black')
ax.set_xlim(xmin=-125, xmax=-114)
ax.set_ylim(ymin=32, ymax=43)
else:
world = geopandas.read_file(
geopandas.datasets.get_path('naturalearth_lowres'))
# Restrict to the USA only. 'United States of America'
ax = world[world.name == 'United States of America'].plot(
color='white', edgecolor='black')
gdf_all.plot(ax=ax, color='gray')
ax.set_xlim(xmin=-130, xmax=-65)
ax.set_ylim(ymin=20, ymax=55)
if 'itinerary' in kwarg:
itinerary=kwarg['itinerary']
if len(itinerary)>1:
data_list=[[city, cities[city][0], cities[city][1]] for city in itinerary]
df_visit = pd.DataFrame(data_list)
df_visit.columns = ['City','Latitude','Longitude']
df_start = df_visit[df_visit['City'].isin([itinerary[0]])]
df_end = df_visit[df_visit['City'].isin([itinerary[-1]])]
gdf_visit = geopandas.GeoDataFrame(
df_visit, geometry=geopandas.points_from_xy(df_visit.Longitude, df_visit.Latitude))
gdf_start = geopandas.GeoDataFrame(
df_start, geometry=geopandas.points_from_xy(df_start.Longitude, df_start.Latitude))
gdf_end = geopandas.GeoDataFrame(
df_end, geometry=geopandas.points_from_xy(df_end.Longitude, df_end.Latitude))
# plot the ``GeoDataFrame``
x_values=gdf_visit.values.T[2]
y_values=gdf_visit.values.T[1]
plt.plot(x_values,y_values)
gdf_visit.plot(ax=ax, color='blue')
gdf_start.plot(ax=ax, color='green')
gdf_end.plot(ax=ax, color='red')
ax.legend(['Path','All cites', 'To Visit','Start','End'])
ax.set_yticks([])
ax.set_xticks([])
ax.set_aspect(1.2)
plt.show()
def plot_map2(cities, open_cities, closed_cities):
data_list=[[key, cities[key][0], cities[key][1]] for key in cities.keys()]
df = pd.DataFrame(data_list)
#City,Latitude,Longitude
df.columns=['City','Latitude','Longitude']
data_list=[[city, cities[city][0], cities[city][1]] for city in open_cities]
df_open = pd.DataFrame(data_list)
df_open.columns = ['City','Latitude','Longitude']
data_list=[[city, cities[city][0], cities[city][1]] for city in closed_cities]
df_closed = pd.DataFrame(data_list)
df_closed.columns = ['City','Latitude','Longitude']
gdf_open = geopandas.GeoDataFrame(
df_open, geometry=geopandas.points_from_xy(df_open.Longitude, df_open.Latitude))
gdf_closed = geopandas.GeoDataFrame(
df_closed, geometry=geopandas.points_from_xy(df_closed.Longitude, df_closed.Latitude))
world = geopandas.read_file(
geopandas.datasets.get_path('naturalearth_lowres'))
# We restrict to South America.
ax = world[world.name == 'United States of America'].plot(
color='white', edgecolor='black')
# We can now plot our ``GeoDataFrame``
gdf_open.plot(ax=ax, color='blue')
gdf_closed.plot(ax=ax, color='gray')
ax.set_xlim(xmin=-130, xmax=-65)
ax.set_ylim(ymin=20, ymax=55)
ax.set_yticks([])
ax.set_xticks([])
ax.set_aspect(1.2)
ax.legend(['Delivery target', 'Other cities'])
plt.show()
```
#Step1: Optimize the distribution impact
```
import sys
!pwd
!ls
f_loc="/content/Quantum-Chain/"
if f_loc not in sys.path: sys.path.append(f_loc)
import os
print(os.getcwd())
for dirname, _, filenames in os.walk(f_loc): #f_loc
for filename in filenames:
#print(os.path.join(dirname, filename))
try:
if filename.index('knapsack') >= 0:
print(os.path.join(dirname, filename))
pass
except:
pass
from knapsack import *
csv_data_path="/content/Quantum-Chain/"
csv_data_file=csv_data_path+"H_Beds.csv"
number_of_symulations=3
hospital_beds_max=200000
#total vaccines for initial distribution
max_people=hospital_beds_max
#the next few coments are related to the GDP-sick people assesment
#int(hospital_beds_max/(39/100))
#assuming 3x13% are hospitalized and maxout the full hospital capacity!
#we use a fudge factor of 3 insted of the 13% statistical value
print(f'Performing of {number_of_symulations} simulations.',
f'Considering full capacity for {max_people} people at one time.')
%time solution=solve_nodes_using_csv(csv_data_file,max_people,num_reads=number_of_symulations,verbose=True)
len(solution)
%time solution=solve_nodes_using_csv(csv_data_file, max_people, num_reads=number_of_symulations, value_r=0.01, weight_r=0.02, verbose=True)
len(solution)
cities=solution[0]['closed_cities']+solution[0]['open_cities']
len(cities)
#original uscities file from https://simplemaps.com/data/us-cities
df0=pd.read_csv(csv_data_file)
uscities_file=csv_data_path+"uscities.csv"
uscities=pd.read_csv(uscities_file)
my_cities={}
for (i,city) in enumerate(df0["City"]):
for (j,city_ascii) in enumerate(uscities["city_ascii"]):
if city in cities and city==city_ascii and df0["State"][i][1:]==uscities["state_id"][j]:
my_cities[city]=(uscities["lat"][j],uscities["lng"][j])
plot_map2(my_cities,solution[0]['open_cities'],solution[0]['closed_cities'])
```
#Step 2: Vehicle Transportation Schedule
based on the annealing for the Travelling Salesman Problem
https://github.com/perrygeo/simanneal
##Define the Annealer functoins and test them
```
%%time
#see ./simanneal/examples/salesman.py
# -*- coding: utf-8 -*-
from __future__ import print_function
import math
import random
from simanneal import Annealer
def distance(a, b):
"""Calculates distance between two latitude-longitude coordinates."""
R = 3963 # radius of Earth (miles)
lat1, lon1 = math.radians(a[0]), math.radians(a[1])
lat2, lon2 = math.radians(b[0]), math.radians(b[1])
return math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2)) * R
class TravellingSalesmanProblem(Annealer):
"""Test annealer with a travelling salesman problem.
"""
# pass extra data (the distance matrix) into the constructor
def __init__(self, state, distance_matrix):
self.distance_matrix = distance_matrix
super(TravellingSalesmanProblem, self).__init__(state) # important!
def move(self):
"""Swaps two cities in the route."""
# no efficiency gain, just proof of concept
# demonstrates returning the delta energy (optional)
initial_energy = self.energy()
a = random.randint(0, len(self.state) - 1)
b = random.randint(0, len(self.state) - 1)
self.state[a], self.state[b] = self.state[b], self.state[a]
return self.energy() - initial_energy
def energy(self):
"""Calculates the length of the route."""
e = 0
for i in range(len(self.state)):
e += self.distance_matrix[self.state[i-1]][self.state[i]]
return e
if __name__ == '__main__':
# latitude and longitude for the twenty largest U.S. cities
cities = {
'New York': (40.72, -74.00),
'Los Angeles': (34.05, -118.25),
'Chicago': (41.88, -87.63),
'Houston': (29.77, -95.38),
'Phoenix': (33.45, -112.07),
'Philadelphia': (39.95, -75.17),
'San Antonio': (29.53, -98.47),
'Dallas': (32.78, -96.80),
'San Diego': (32.78, -117.15),
'San Jose': (37.30, -121.87),
'Detroit': (42.33, -83.05),
'San Francisco': (37.78, -122.42),
'Jacksonville': (30.32, -81.70),
'Indianapolis': (39.78, -86.15),
'Austin': (30.27, -97.77),
'Columbus': (39.98, -82.98),
'Fort Worth': (32.75, -97.33),
'Charlotte': (35.23, -80.85),
'Memphis': (35.12, -89.97),
'Baltimore': (39.28, -76.62)
}
# initial state, a randomly-ordered itinerary
init_state = list(cities.keys())
random.shuffle(init_state)
# create a distance matrix
distance_matrix = {}
for ka, va in cities.items():
distance_matrix[ka] = {}
for kb, vb in cities.items():
if kb == ka:
distance_matrix[ka][kb] = 0.0
else:
distance_matrix[ka][kb] = distance(va, vb)
tsp = TravellingSalesmanProblem(init_state, distance_matrix)
tsp.set_schedule(tsp.auto(minutes=0.2))
# since our state is just a list, slice is the fastest way to copy
tsp.copy_strategy = "slice"
state, e = tsp.anneal()
while state[0] != 'New York':
state = state[1:] + state[:1] # rotate NYC to start
print()
print("%i mile route:" % e)
print(" ➞ ".join(state))
cities.update(my_cities)
plot_map(cities,itinerary=state)
def make_itinerary(current_location,initial_state):
if current_location not in initial_state:
initial_state.append(current_location)
print("\nAdding your current location to the initial list!")
# populate your cities list with coordinate information
my_cities={}
for city in initial_state:
if city in cities.keys():
my_cities[city]=cities[city]
else:
print("No location coordinates for ",city)
if city==current_location:
print("Add your location coordinates!")
return
# initial state, a randomly-ordered itinerary
init_state = initial_state
random.shuffle(init_state)
# create a distance matrix
distance_matrix = {}
for ka, va in my_cities.items():
distance_matrix[ka] = {}
for kb, vb in my_cities.items():
if kb == ka:
distance_matrix[ka][kb] = 0.0
else:
distance_matrix[ka][kb] = distance(va, vb)
tsp = TravellingSalesmanProblem(init_state, distance_matrix)
'''
tsp.set_schedule(tsp.auto(minutes=0.2))
# since our state is just a list, slice is the fastest way to copy
tsp.copy_strategy = "slice"
'''
itinerary, miles = tsp.anneal()
while itinerary[0] != current_location:
itinerary = itinerary[1:] + itinerary[:1] # rotate to start correctly
print()
print("%i mile route:" % miles)
print(" ➞ ".join(itinerary))
return itinerary, miles
```
##Create the travel itinerary
```
%%time
#initial_state = ['New York City', 'Los Angeles','Dallas', 'Philadelphia', 'Houston','San Diego']
initial_state = ['Santa Cruz','San Luis Obispo','San Jose','Stockton','Santa Rosa']
current_location= 'San Francisco'
itinerary, miles = make_itinerary(current_location,initial_state)
print(itinerary[0:2])
print(itinerary[2:4])
print(itinerary[4:6])
plot_map(cities,state='CA',itinerary=itinerary)
```
| github_jupyter |
```
# # https://stackoverflow.com/questions/22994423/difference-between-np-random-seed-and-np-random-randomstate
# # np.random.seed(18)
# np.random.RandomState(18)
import os
import sys
import os.path as path
project_dir = '.'
data_dir = path.join('.','hvc_data')
url = path.join(data_dir, 'hvc_annotations.csv')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df = pd.read_csv(url)
df.drop('filename', axis=1, inplace = True)
df.head(2)
df = df[:100]
df.shape
# one hot encoding of labels
one_hot_df = pd.concat([
df[["image_path"]],
pd.get_dummies(df.gender, prefix="gender"),
pd.get_dummies(df.imagequality, prefix="imagequality"),
pd.get_dummies(df.age, prefix="age"),
pd.get_dummies(df.weight, prefix="weight"),
pd.get_dummies(df.carryingbag, prefix="carryingbag"),
pd.get_dummies(df.footwear, prefix="footwear"),
pd.get_dummies(df.emotion, prefix="emotion"),
pd.get_dummies(df.bodypose, prefix="bodypose"),
], axis = 1)
one_hot_df.head().T
path.abspath(path.join(data_dir,'processed'))
os.getcwd()
# Custom batch generator
# -------
# Good one - https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly
# https://towardsdatascience.com/image-augmentation-14a0aafd0498
# https://towardsdatascience.com/writing-custom-keras-generators-fe815d992c5a
# https://medium.com/the-artificial-impostor/custom-image-augmentation-with-keras-70595b01aeac
# https://towardsdatascience.com/keras-data-generators-and-how-to-use-them-b69129ed779c
# Good one - https://www.kaggle.com/nikhilroxtomar/generators-for-keras-model
import keras
import numpy as np
import cv2
from keras.preprocessing.image import ImageDataGenerator, img_to_array
# Label columns per attribute
_gender_cols_ = [col for col in one_hot_df.columns if col.startswith("gender")]
_imagequality_cols_ = [col for col in one_hot_df.columns if col.startswith("imagequality")]
_age_cols_ = [col for col in one_hot_df.columns if col.startswith("age")]
_weight_cols_ = [col for col in one_hot_df.columns if col.startswith("weight")]
_carryingbag_cols_ = [col for col in one_hot_df.columns if col.startswith("carryingbag")]
_footwear_cols_ = [col for col in one_hot_df.columns if col.startswith("footwear")]
_emotion_cols_ = [col for col in one_hot_df.columns if col.startswith("emotion")]
_bodypose_cols_ = [col for col in one_hot_df.columns if col.startswith("bodypose")]
class PersonDataGenerator(keras.utils.Sequence):
"""
Ground truth data generator
https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence
"""
def __init__(self, df, batch_size = 32, input_size = (224, 224),
location = '.', augmentations = None, save_dir = '',
shuffle = False):
self.df = df
self.image_size = input_size
self.batch_size = batch_size
self.shuffle = shuffle
self.augmentation = augmentations #ImageDataGenerator instance
self.location = location
self.save_dir = path.abspath(save_dir) # path.abspath(path.join(self.location,'processed'))
self.on_epoch_end()
if not path.isdir(self.save_dir):
os.mkdirs(self.save_dir, exist_ok=True)
def __len__(self):
"""
Number of batch in the Sequence.
"""
return int(np.floor(self.df.shape[0] / self.batch_size))
def __getitem__(self, index):
"""
Gets batch at position index.
fetch batched images and targets
"""
# slice function - https://www.w3schools.com/python/ref_func_slice.asp
batch_slice = slice(index * self.batch_size, (index + 1) * self.batch_size)
items = self.df.iloc[batch_slice]
images = np.stack([cv2.imread(path.join(self.location, item["image_path"])) for _, item in items.iterrows()])
if self.augmentation:
if self.save_dir:
images = self.augmentation.flow(images,
batch_size=self.batch_size,
save_to_dir=self.save_dir,
save_prefix='aug').next()
else:
images = self.augmentation.flow(images,
batch_size=self.batch_size).next()
target = {
"gender_output": items[_gender_cols_].values,
"image_quality_output": items[_imagequality_cols_].values,
"age_output": items[_age_cols_].values,
"weight_output": items[_weight_cols_].values,
"bag_output": items[_carryingbag_cols_].values,
"pose_output": items[_bodypose_cols_].values,
"footwear_output": items[_footwear_cols_].values,
"emotion_output": items[_emotion_cols_].values,
}
return images, target
def on_epoch_end(self):
"""
Shuffles/sample the df and thereby
updates indexes after each epoch
Method called at the end of every epoch.
"""
if self.shuffle == True:
self.df = self.df.sample(frac=1).reset_index(drop=True)
# frac --> take sample of the given df, sample size is given as fraction number
# reset_index drop --> use the drop parameter to avoid the old index being added as a column
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html
from sklearn.model_selection import train_test_split
train_df, val_df = train_test_split(one_hot_df, test_size=0.15, random_state=18)
train_df.shape, val_df.shape
def blur(img):
return (cv2.blur(img,(5,5)))
def get_random_eraser(input_img, p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):
img_h, img_w, img_c = input_img.shape
p_1 = np.random.rand()
if p_1 > p:
return input_img
while True:
s = np.random.uniform(s_l, s_h) * img_h * img_w
r = np.random.uniform(r_1, r_2)
w = int(np.sqrt(s / r))
h = int(np.sqrt(s * r))
left = np.random.randint(0, img_w)
top = np.random.randint(0, img_h)
if left + w <= img_w and top + h <= img_h:
break
if pixel_level:
c = np.random.uniform(v_l, v_h, (h, w, img_c))
else:
c = np.random.uniform(v_l, v_h)
input_img[top:top + h, left:left + w, :] = c
return input_img
def blur_cutout(img):
img =blur(img)
img = get_random_eraser(img)
return img
train_aug = ImageDataGenerator(rescale=1/255.0,
horizontal_flip=True,
rotation_range=30,
brightness_range=[0.2,0.8],
channel_shift_range=100,
preprocessing_function=blur_cutout
)
val_aug = ImageDataGenerator(rescale=1/255.0)
# create train and validation data generators
train_gen = PersonDataGenerator(train_df, batch_size=32,
input_size=(224, 224), location = data_dir,
augmentations=train_aug, shuffle=True)
valid_gen = PersonDataGenerator(train_df, batch_size=32,
input_size=(224, 224), location = data_dir,
augmentations=val_aug)
images, targets = next(iter(train_gen))
# get number of output units from data
images, targets = next(iter(train_gen))
num_units = { k.split("_output")[0]:v.shape[1] for k, v in targets.items()}
num_units
# %tensorflow_version 1.x
import cv2
import json
import numpy as np
import pandas as pd
from functools import partial
from pathlib import Path
from tqdm import tqdm
# from google.colab.patches import cv2_imshow
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from keras.applications import VGG16
from keras.layers.core import Dropout
from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras.layers import Input
from keras.models import Model
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
backbone = VGG16(
weights=None,
include_top=False,
input_tensor=Input(shape=(224, 224, 3))
)
neck = backbone.output
neck = Flatten(name="flatten")(neck)
neck = Dense(512, activation="relu")(neck)
def build_tower(in_layer):
# redundant
# neck = Dropout(0.2)(in_layer)
# neck = Dense(128, activation="relu")(neck)
neck = Dropout(0.3)(in_layer)
neck = Dense(128, activation="relu")(neck)
return neck
def build_head(name, incoming):
return Dense(
num_units[name], activation="softmax", name=f"{name}_output"
)(incoming)
# heads
gender = build_head("gender", build_tower(neck))
image_quality = build_head("image_quality", build_tower(neck))
age = build_head("age", build_tower(neck))
weight = build_head("weight", build_tower(neck))
bag = build_head("bag", build_tower(neck))
footwear = build_head("footwear", build_tower(neck))
emotion = build_head("emotion", build_tower(neck))
pose = build_head("pose", build_tower(neck))
model = Model(
inputs=backbone.input,
outputs=[gender, image_quality, age, weight, bag, footwear, pose, emotion]
)
# freeze backbone
for layer in backbone.layers:
layer.trainable = False
# losses = {
# "gender_output": "binary_crossentropy",
# "image_quality_output": "categorical_crossentropy",
# "age_output": "categorical_crossentropy",
# "weight_output": "categorical_crossentropy",
# }
# loss_weights = {"gender_output": 1.0, "image_quality_output": 1.0, "age_output": 1.0}
opt = SGD(lr=0.001, momentum=0.9)
model.compile(
optimizer=opt,
loss="categorical_crossentropy",
# loss_weights=loss_weights,
metrics=["accuracy"]
)
model.fit_generator(
generator=train_gen,
validation_data=valid_gen,
epochs=5)
# use_multiprocessing=True,
# workers=6,
# epochs=10,
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices()) # list of DeviceAttributes
import tensorflow as tf
tf.test.is_gpu_available() # True/False
# Or only check for gpu's with cuda support
tf.test.is_gpu_available(cuda_only=True)
a = np.random.uniform(low=0, high=255, size=(10,32,32,3))
a
a = a/255.0
a
```
| github_jupyter |
## Dependencies
```
!pip install --quiet /kaggle/input/kerasapplications
!pip install --quiet /kaggle/input/efficientnet-git
import warnings, glob
from tensorflow.keras import Sequential, Model
import efficientnet.tfkeras as efn
from cassava_scripts import *
seed = 0
seed_everything(seed)
warnings.filterwarnings('ignore')
```
### Hardware configuration
```
# TPU or GPU detection
# Detect hardware, return appropriate distribution strategy
strategy, tpu = set_up_strategy()
AUTO = tf.data.experimental.AUTOTUNE
REPLICAS = strategy.num_replicas_in_sync
print(f'REPLICAS: {REPLICAS}')
```
# Model parameters
```
BATCH_SIZE = 8 * REPLICAS
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 5
TTA_STEPS = 0 # Do TTA if > 0
```
# Augmentation
```
def data_augment(image, label):
p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_1 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_2 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_3 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
# Flips
image = tf.image.random_flip_left_right(image)
image = tf.image.random_flip_up_down(image)
if p_spatial > .75:
image = tf.image.transpose(image)
# Rotates
if p_rotate > .75:
image = tf.image.rot90(image, k=3) # rotate 270º
elif p_rotate > .5:
image = tf.image.rot90(image, k=2) # rotate 180º
elif p_rotate > .25:
image = tf.image.rot90(image, k=1) # rotate 90º
# Pixel-level transforms
if p_pixel_1 >= .4:
image = tf.image.random_saturation(image, lower=.7, upper=1.3)
if p_pixel_2 >= .4:
image = tf.image.random_contrast(image, lower=.8, upper=1.2)
if p_pixel_3 >= .4:
image = tf.image.random_brightness(image, max_delta=.1)
# Crops
if p_crop > .7:
if p_crop > .9:
image = tf.image.central_crop(image, central_fraction=.7)
elif p_crop > .8:
image = tf.image.central_crop(image, central_fraction=.8)
else:
image = tf.image.central_crop(image, central_fraction=.9)
elif p_crop > .4:
crop_size = tf.random.uniform([], int(HEIGHT*.8), HEIGHT, dtype=tf.int32)
image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])
# # Crops
# if p_crop > .6:
# if p_crop > .9:
# image = tf.image.central_crop(image, central_fraction=.5)
# elif p_crop > .8:
# image = tf.image.central_crop(image, central_fraction=.6)
# elif p_crop > .7:
# image = tf.image.central_crop(image, central_fraction=.7)
# else:
# image = tf.image.central_crop(image, central_fraction=.8)
# elif p_crop > .3:
# crop_size = tf.random.uniform([], int(HEIGHT*.6), HEIGHT, dtype=tf.int32)
# image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])
return image, label
```
## Auxiliary functions
```
# Datasets utility functions
def resize_image(image, label):
image = tf.image.resize(image, [HEIGHT, WIDTH])
image = tf.reshape(image, [HEIGHT, WIDTH, CHANNELS])
return image, label
def process_path(file_path):
name = get_name(file_path)
img = tf.io.read_file(file_path)
img = decode_image(img)
img, _ = scale_image(img, None)
# img = center_crop(img, HEIGHT, WIDTH)
return img, name
def get_dataset(files_path, shuffled=False, tta=False, extension='jpg'):
dataset = tf.data.Dataset.list_files(f'{files_path}*{extension}', shuffle=shuffled)
dataset = dataset.map(process_path, num_parallel_calls=AUTO)
if tta:
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
dataset = dataset.map(resize_image, num_parallel_calls=AUTO)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTO)
return dataset
```
# Load data
```
database_base_path = '/kaggle/input/cassava-leaf-disease-classification/'
submission = pd.read_csv(f'{database_base_path}sample_submission.csv')
display(submission.head())
TEST_FILENAMES = tf.io.gfile.glob(f'{database_base_path}test_tfrecords/ld_test*.tfrec')
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
print(f'GCS: test: {NUM_TEST_IMAGES}')
model_path_list = glob.glob('/kaggle/input/74-cassava-leaf-effnetb5-5-fold-65-512x512/*.h5')
model_path_list.sort()
print('Models to predict:')
print(*model_path_list, sep='\n')
```
# Model
```
def model_fn(input_shape, N_CLASSES):
inputs = L.Input(shape=input_shape, name='input_image')
base_model = efn.EfficientNetB5(input_tensor=inputs,
include_top=False,
weights=None,
pooling='avg')
x = L.Dropout(.25)(base_model.output)
output = L.Dense(N_CLASSES, activation='softmax', name='output')(x)
output_healthy = L.Dense(1, activation='sigmoid', name='output_healthy')(x)
output_cmd = L.Dense(1, activation='sigmoid', name='output_cmd')(x)
model = Model(inputs=inputs, outputs=[output, output_healthy, output_cmd])
return model
with strategy.scope():
model = model_fn((None, None, CHANNELS), N_CLASSES)
model.summary()
```
# Test set predictions
```
files_path = f'{database_base_path}test_images/'
test_size = len(os.listdir(files_path))
test_preds = np.zeros((test_size, N_CLASSES))
for model_path in model_path_list:
print(model_path)
K.clear_session()
model.load_weights(model_path)
if TTA_STEPS > 0:
test_ds = get_dataset(files_path, tta=True).repeat()
ct_steps = TTA_STEPS * ((test_size/BATCH_SIZE) + 1)
preds = model.predict(test_ds, steps=ct_steps, verbose=1)[:(test_size * TTA_STEPS)]
preds = np.mean(preds.reshape(test_size, TTA_STEPS, N_CLASSES, order='F'), axis=1)
test_preds += preds / len(model_path_list)
else:
test_ds = get_dataset(files_path, tta=False)
x_test = test_ds.map(lambda image, image_name: image)
test_preds += model.predict(x_test)[0] / len(model_path_list)
test_preds = np.argmax(test_preds, axis=-1)
test_names_ds = get_dataset(files_path)
image_names = [img_name.numpy().decode('utf-8') for img, img_name in iter(test_names_ds.unbatch())]
submission = pd.DataFrame({'image_id': image_names, 'label': test_preds})
submission.to_csv('submission.csv', index=False)
display(submission.head())
```
| github_jupyter |
```
%matplotlib inline
import numpy as np
import scipy as sp
import six
from matplotlib.pyplot import *
'''
Checking the policies and q-values of the learned models for dropout=0.8 and epoch60
'''
data11 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runB.npz')
data21 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runB.npz')
data51 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runB.npz')
data61 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts20000-runB.npz')
vloss = data11['vloss']
scores = data21['scores'][:,0]
initialq = data51['qvals'][:,0]
opts = data61['opts']
qfuncs = data61['qs'][:,0,:,:]
sorted_score_ix = np.flip(np.argsort(initialq), 0)
sorted_scores = scores[sorted_score_ix]
sorted_initialq = initialq[sorted_score_ix]
sorted_opts = opts[sorted_score_ix,:]
sorted_qfuncs = qfuncs[sorted_score_ix,:,:]
for r in six.moves.range(scores.shape[0]):
six.print_('{:2d}: score {:.3f} initialq {:.2f} opt {}'.format(r, sorted_scores[r], sorted_initialq[r], sorted_opts[r,:]))
for t in six.moves.range(6):
six.print_(' step {} qfunc [ {} ]'.format(t, ' '.join(['{:.2f}'.format(q) for q in sorted_qfuncs[r,t,:]])))
pass
'''
Let's look for the cases where the policy is correct until the last step, and the last step is wrong.
And good models.
'''
good_ix = [10,13,26,27] # last steps end up being 2
final3 = [7,12,19,20,22,23] # last step should've been 3
final2 = [0,29] # last step should've been 2
# now we can do a preliminary robust matrix evaluation for the good models and the last step should be 2 models
model_ixs = np.concatenate([good_ix, final2])
six.print_(model_ixs)
rmat = np.zeros((model_ixs.shape[0],model_ixs.shape[0]))
# rmat[rmodel,cmodel] = the value of rmodel's policy in cmodel
for pix in six.moves.range(model_ixs.shape[0]):
policy = sorted_opts[model_ixs[pix],0,:]
last_act = policy[-1]
six.print_(last_act)
for eix in six.moves.range(model_ixs.shape[0]):
# qfunc of last step
last_q = sorted_qfuncs[model_ixs[eix],-1,:]
#six.print_(last_q)
rmat[pix,eix] = last_q[last_act]
six.print_(rmat)
#six.print_(np.min(rmat,axis=0))
six.print_(np.min(rmat,axis=1)[:,np.newaxis])
'''
Checking the policies and q-values of the learned models for dropout=1.0 and epoch13
'''
data11 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/stats-runA.npz')
data12 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/stats-runB.npz')
data21 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runA.npz')
data22 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runB.npz')
data51 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runA.npz')
data52 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runB.npz')
data61 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runA.npz')
data62 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runB.npz')
vloss = np.concatenate([data11['vloss'],data12['vloss']])
scores = np.concatenate([data21['scores'][:,0],data22['scores'][:,0]])
initialq = np.concatenate([data51['qvals'][:,0],data52['qvals'][:,0]])
opts = np.vstack([data61['opts'],data62['opts']])
qfuncs = np.vstack([data61['qs'][:,0,:,:],data62['qs'][:,0,:,:]])
sorted_score_ix = np.flip(np.argsort(initialq), 0)
sorted_score_ix = np.arange(0,100)
sorted_scores = scores[sorted_score_ix]
sorted_initialq = initialq[sorted_score_ix]
sorted_opts = opts[sorted_score_ix,:]
sorted_qfuncs = qfuncs[sorted_score_ix,:,:]
for r in six.moves.range(scores.shape[0]):
six.print_('{:2d}: score {:.3f} initialq {:.2f} opt {}'.format(r, sorted_scores[r], sorted_initialq[r], sorted_opts[r,:]))
for t in six.moves.range(6):
six.print_(' step {} qfunc [ {} ]'.format(t, ' '.join(['{:.2f}'.format(q) for q in sorted_qfuncs[r,t,:]])))
pass
'''
Let's look for the cases where the policy is correct until the last step, and the last step is wrong.
And good models.
'''
good2 = [5,13,34,46,62,84] # last steps end up being 2
good3 = [3,7,14,26,47,50,63,75] # last steps end up being 3
final2 = [4,11,16,17,20,29,33,39,43,52,55,66,67,93] # last step should've been 2
final3 = [6] # last step should've been 3
# now we can do a preliminary robust matrix evaluation for the good models and the last step should be 2 models
model_ixs = np.concatenate([good2, final2])
six.print_(model_ixs)
rmat = np.zeros((model_ixs.shape[0],model_ixs.shape[0]))
# rmat[rmodel,cmodel] = the value of rmodel's policy in cmodel
for pix in six.moves.range(model_ixs.shape[0]):
policy = sorted_opts[model_ixs[pix],0,:]
last_act = policy[-1]
#six.print_(last_act)
for eix in six.moves.range(model_ixs.shape[0]):
# qfunc of last step
last_q = sorted_qfuncs[model_ixs[eix],-1,:]
#six.print_(last_q)
rmat[pix,eix] = last_q[last_act]
six.print_(rmat)
six.print_(np.mean(rmat,axis=1))
six.print_(np.min(rmat,axis=1))
'''
Checking the policies and q-values of the learned models for dropout=0.8 and epoch23
'''
data11 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runA.npz')
data12 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runC.npz')
data13 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runD.npz')
data21 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runA.npz')
data22 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runC.npz')
data23 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories400-real1-runD.npz')
data31 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real0-runA.npz')
data32 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real0-runC.npz')
data33 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories400-real0-runD.npz')
data41 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype1-trajectories400-runA.npz')
data42 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype1-trajectories400-runC.npz')
data43 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype1-trajectories400-runD.npz')
data51 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runA.npz')
data52 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runC.npz')
data53 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runD.npz')
data61 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runA.npz')
data62 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runC.npz')
data63 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runD.npz')
vloss = np.concatenate([data11['vloss'],data12['vloss'],data13['vloss']])
scores = np.concatenate([data21['scores'][:,0],data22['scores'][:,0],data23['scores'][:,0]])
#trueqvals = np.concatenate([data21['qvals'][:,0],data22['qvals'][:,0],data23['qvals'][:,0]])
#falseqvals = np.concatenate([data31['qvals'][:,0],data32['qvals'][:,0],data33['qvals'][:,0]])
rewards = np.concatenate([data41['rewards'][:,0],data42['rewards'][:,0],data43['rewards'][:,0]])
initialq = np.concatenate([data51['qvals'][:,0],data52['qvals'][:,0],data53['qvals'][:,0]])
opts = np.vstack([data61['opts'],data62['opts'],data63['opts']])
qfuncs = np.vstack([data61['qs'][:,0,:,:],data62['qs'][:,0,:,:],data63['qs'][:,0,:,:]])
sorted_score_ix = np.flip(np.argsort(initialq), 0)
sorted_scores = scores[sorted_score_ix]
sorted_initialq = initialq[sorted_score_ix]
sorted_opts = opts[sorted_score_ix,:]
sorted_qfuncs = qfuncs[sorted_score_ix,:,:]
for r in six.moves.range(scores.shape[0]):
six.print_('{:2d}: score {:.3f} initialq {:.2f} opt {}'.format(r, sorted_scores[r], sorted_initialq[r], sorted_opts[r,:]))
for t in six.moves.range(6):
six.print_(' step {} qfunc [ {} ]'.format(t, ' '.join(['{:.2f}'.format(q) for q in sorted_qfuncs[r,t,:]])))
pass
'''
Let's look for the cases where the policy is correct until the last step, and the last step is wrong.
And good models.
'''
good2 = [5,6,8,9,10,11,12,13,14,15,17,18,20,21,22,23,24,26,27,29,30,31,33,35,36,40,43,44,46,61,66,67,77,97] # last steps end up being 2
good3 = [4,89] # last steps end up being 3
final2 = [0,1,3,7,16,25,38,39,41,47,49,50,52,58,62,64,70,71,75,98] # last step should've been 2
final3 = [] # last step should've been 3
six.print_(len(good2))
six.print_(len(final2))
# now we can do a preliminary robust matrix evaluation for the good models and the last step should be 2 models
model_ixs = np.concatenate([good2, final2])
six.print_(model_ixs)
rmat = np.zeros((model_ixs.shape[0],model_ixs.shape[0]))
# rmat[rmodel,cmodel] = the value of rmodel's policy in cmodel
for pix in six.moves.range(model_ixs.shape[0]):
policy = sorted_opts[model_ixs[pix],0,:]
last_act = policy[-1]
#six.print_(last_act)
for eix in six.moves.range(model_ixs.shape[0]):
# qfunc of last step
last_q = sorted_qfuncs[model_ixs[eix],-1,:]
#six.print_(last_q)
rmat[pix,eix] = last_q[last_act]
#six.print_(rmat)
six.print_(np.mean(rmat,axis=1))
six.print_(np.min(rmat,axis=1))
'''
Now let's look at the extended version with all 100 models for no dropout.
'''
data11 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/stats-runA.npz')
data12 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/stats-runB.npz')
data21 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runA.npz')
data22 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runB.npz')
data51 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runA.npz')
data52 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runB.npz')
data61 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runA.npz')
data62 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runB.npz')
data71 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/rme-rtype1-trajectories500-runA.npz')
data72 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/rme-rtype1-trajectories500-runB.npz')
vloss = np.concatenate([data11['vloss'],data12['vloss']])
scores = np.concatenate([data21['scores'][:,0],data22['scores'][:,0]])
initialq = np.concatenate([data51['qvals'][:,0],data52['qvals'][:,0]])
opts = np.vstack([data61['opts'],data62['opts']])[:,0,:]
qfuncs = np.vstack([data61['qs'][:,0,:,:],data62['qs'][:,0,:,:]])
# each row is a policy
evals = np.vstack([data71['evals'],data72['evals']]).T
#six.print_(evals)
eval_avg = np.mean(evals,axis=1)
sorted_avg_ix = np.flip(np.argsort(eval_avg), 0)
eval_min = np.min(evals,axis=1)
sorted_min_ix = np.flip(np.argsort(eval_min), 0)
eval_per = np.percentile(evals,0.25,axis=1)
sorted_per_ix = np.flip(np.argsort(eval_per), 0)
#six.print_(sorted_avg_ix)
#six.print_(sorted_min_ix)
for r in six.moves.range(evals.shape[0]):
ix = sorted_per_ix[r]
six.print_('model_ix {:2d}: policy {} score {:.3f} initialq {:.3f} eval_avg {:.3f} eval_min {:.3f} per {:.3f}'.format(
ix, opts[ix,:], scores[ix], initialq[ix], eval_avg[ix], eval_min[ix], eval_per[ix]))
'''
Now let's look at the extended version with all 100 models for with dropout.
'''
data11 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runA.npz')
data12 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runC.npz')
data13 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runD.npz')
data21 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runA.npz')
data22 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runC.npz')
data23 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories400-real1-runD.npz')
data31 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real0-runA.npz')
data32 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real0-runC.npz')
data33 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories400-real0-runD.npz')
data41 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype1-trajectories400-runA.npz')
data42 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype1-trajectories400-runC.npz')
data43 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype1-trajectories400-runD.npz')
data51 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runA.npz')
data52 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runC.npz')
data53 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runD.npz')
data61 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runA.npz')
data62 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runC.npz')
data63 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runD.npz')
data71 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/rme-rtype1-trajectories500-runA.npz')
data72 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/rme-rtype1-trajectories500-runC.npz')
data73 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/rme-rtype1-trajectories500-runD.npz')
vloss = np.concatenate([data11['vloss'],data12['vloss'],data13['vloss']])
scores = np.concatenate([data21['scores'][:,0],data22['scores'][:,0],data23['scores'][:,0]])
rewards = np.concatenate([data41['rewards'][:,0],data42['rewards'][:,0],data43['rewards'][:,0]])
initialq = np.concatenate([data51['qvals'][:,0],data52['qvals'][:,0],data53['qvals'][:,0]])
opts = np.vstack([data61['opts'],data62['opts'],data63['opts']])[:,0,:]
qfuncs = np.vstack([data61['qs'][:,0,:,:],data62['qs'][:,0,:,:],data63['qs'][:,0,:,:]])
# each row is a policy
evals = np.vstack([data71['evals'],data72['evals'],data73['evals']]).T
#six.print_(evals)
eval_avg = np.mean(evals,axis=1)
sorted_avg_ix = np.flip(np.argsort(eval_avg), 0)
eval_min = np.min(evals,axis=1)
sorted_min_ix = np.flip(np.argsort(eval_min), 0)
eval_per = np.percentile(evals,0.25,axis=1)
sorted_per_ix = np.flip(np.argsort(eval_per), 0)
#six.print_(sorted_avg_ix)
#six.print_(sorted_min_ix)
for r in six.moves.range(evals.shape[0]):
ix = sorted_per_ix[r]
six.print_('model_ix {:2d}: policy {} score {:.3f} initialq {:.3f} eval_avg {:.3f} eval_min {:.3f} per {:.3f}'.format(
ix, opts[ix,:], scores[ix], initialq[ix], eval_avg[ix], eval_min[ix], eval_per[ix]))
'''
Now let's look at proper RME with no dropout
'''
def get_ranks(sorted_indices):
ranks = np.zeros(sorted_indices.shape,dtype=np.int)
for i in six.moves.range(sorted_indices.shape[0]):
ranks[sorted_indices[i]] = i+1
return ranks
def array2str(arr):
inner = ' '.join('{:.3f}'.format(x) for x in arr)
return '[{}]'.format(inner)
data11 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/stats-runA.npz')
data12 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/stats-runB.npz')
data21 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runA.npz')
data22 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runB.npz')
data31 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype2-trajectories400-runA.npz')
data32 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype2-trajectories400-runB.npz')
data51 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runA.npz')
data52 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runB.npz')
data61 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runA.npz')
data62 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runB.npz')
data71 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/rmeproper-rtype1-rollouts1000-trajectories200-runA.npz')
data72 = np.load('experiments/test2_model_small-dropout10-shuffle0-data-test2-n100000-l5-random.pickle/rmeproper-rtype1-rollouts1000-trajectories200-runB.npz')
# each row is a real environment
raw_evals = np.vstack([data71['evals'],data72['evals']]).T
eval_ixs = np.arange(raw_evals.shape[0])
vloss = np.concatenate([data11['vloss'],data12['vloss']])[:,-1]
scores = np.concatenate([data21['scores'][:,0],data22['scores'][:,0]])
behavior = np.concatenate([data31['rewards'][:,0],data32['rewards'][:,0]]) / 4.0
initialq = np.concatenate([data51['qvals'][:,0],data52['qvals'][:,0]])
opts = np.vstack([data61['opts'],data62['opts']])[:,0,:]
#qfuncs = np.vstack([data61['qs'][:,0,:,:],data62['qs'][:,0,:,:]])
def normalizeRME(raw_evals):
'''
Find the global mean, and then shift each row's mean to be the global mean.
'''
#six.print_(raw_evals)
globalmean = np.mean(raw_evals)
shifts = globalmean - np.mean(raw_evals, axis=0)
new_evals = raw_evals + shifts[np.newaxis,:]
#six.print_(globalmean)
#six.print_(shifts)
#six.print_(new_evals)
return new_evals
def printmatrixs(es,ixs,scores,behavior,shift=False):
if shift:
temp_es = normalizeRME(es)
else:
temp_es = es
for r in six.moves.range(ixs.shape[0]):
ix = ixs[r]
six.print_('policy model_ix {:2d}: score {:.3f} behavior {:3f} {}'.format(
ix, scores[ix], behavior[ix], temp_es[r,:]))
#six.print_('avg {:2d}: {:.3f} | min {:2d}: {:.3f} | per {:2d}: {:.3f}'.format(
# ranked_avg_ix[ix], eval_avg[ix], ranked_min_ix[ix], eval_min[ix], ranked_per_ix[ix], eval_per[ix]))
#six.print_('std other {:2d}: {:.3f} | std own {:2d}: {:.3f}'.format(
# ranked_std_ix[ix], eval_std[ix], ranked_stdt_ix[ix], eval_stdt[ix]))
def computemetric(es):
# compute the metric
# currently using average eval
temp_es = normalizeRME(es)
# ignore self predictions completely
# unfortunately doesn't seem to make that big of a difference
temp_es_other = temp_es * (1.0 - np.eye(temp_es.shape[0]))
metric = np.mean(temp_es_other,axis=1)
#metric = np.min(es,axis=1)
#metric = np.percentile(es,0.5,axis=1)
#metric = np.std(es,axis=0)
return metric
# try removing some of them
def remove_worst(es,ixs):
metric = computemetric(es)
metricix = np.flip(np.argsort(metric), 0)
#metricix = np.argsort(metric)
worst_ix = metricix[-1]
metric2 = computemetric(es)
metrix2ix = np.flip(np.argsort(metric2), 0)
best_ix = metrix2ix[0]
if metrix2ix.shape[0] > 1:
best_ix2 = metrix2ix[1]
six.print_('Removing worst ix {:2d}: score {:.4f} behavior {:3f}'.format(
ixs[worst_ix], scores[ixs[worst_ix]], behavior[ixs[worst_ix]]))
six.print_(' = Current best ix {:2d}: score {:.4f} behavior {:3f}'.format(
ixs[best_ix], scores[ixs[best_ix]], behavior[ixs[best_ix]]))
if metrix2ix.shape[0] > 1:
six.print_(' = Current 2nd best ix {:2d}: score {:.4f} behavior {:3f}'.format(
ixs[best_ix2], scores[ixs[best_ix2]], behavior[ixs[best_ix2]]))
mask = np.ones(es.shape[0],dtype=bool)
mask[worst_ix] = False
es = es[mask,:]
es = es[:,mask]
ixs = ixs[mask]
return es, ixs
def analyzeRME(raw_evals, eval_ixs, scores, vloss, behavior, initialq):
# show initial average means
#temp_es = normalizeRME(raw_evals)
temp_es = raw_evals
metric = np.mean(temp_es,axis=1)
metricix = np.flip(np.argsort(metric), 0)
six.print_('Initial models ordered by average eval (normalized): {}'.format(metricix))
six.print_('Corresponding average evals: {}'.format(metric[metricix]))
# look at correlation between behavior and scores
figure()
title('rtype 2')
plot(behavior,scores,'.',color='#0000ff')
xlabel('behavior')
ylabel('scores')
# initial matrix
six.print_('Initial matrix limited to the top 6 models')
top6 = metricix[:6]
raw_evals2 = raw_evals[top6,:]
raw_evals2 = raw_evals2[:,top6]
eval_ixs2 = eval_ixs[top6]
six.print_('Normalized:')
printmatrixs(raw_evals2, eval_ixs2, scores, behavior, shift=True)
six.print_('Original:')
printmatrixs(raw_evals2, eval_ixs2, scores, behavior, shift=False)
for i in six.moves.range(38):
raw_evals, eval_ixs = remove_worst(raw_evals, eval_ixs)
#if i > 35 and i < 39:
# printmatrixs(raw_evals, eval_ixs, scores)
six.print_('Normalized:')
printmatrixs(raw_evals, eval_ixs, scores, behavior, shift=True)
six.print_('Original:')
printmatrixs(raw_evals, eval_ixs, scores, behavior, shift=False)
#six.print_('Raw evals shape {}'.format(raw_evals.shape))
#six.print_('Raw evals ixs {}'.format(eval_ixs))
num_models = raw_evals.shape[0]
#sorted_score_eix = np.flip(np.argsort(scores[eval_ixs]), 0)
#sorted_score_ix = eval_ixs[sorted_score_eix]
#six.print_('Indices sorted by score {}'.format(sorted_score_ix))
# use the top few vloss models to evaluate
if False:
sorted_vloss = vloss[sorted_score_ix,-1]
sorted_vloss_ix = np.argsort(sorted_vloss)
ranked_vloss_ix = get_ranks(sorted_vloss_ix)
topmodels = sorted_vloss_ix[:10]
raw_evals = raw_evals[:,topmodels]
six.print_('Sorted Validation Loss {}'.format(sorted_vloss))
six.print_('Sorted Validation Loss Model Indices {}'.format(sorted_vloss_ix))
six.print_(ranked_vloss_ix)
if False:
eval_avg = np.mean(raw_evals,axis=1)
sorted_avg_eix = np.flip(np.argsort(eval_avg), 0)
sorted_avg_ix = eval_ixs[sorted_avg_eix]
ranked_avg_eix = get_ranks(sorted_avg_eix)
eval_min = np.min(raw_evals,axis=1)
sorted_min_eix = np.flip(np.argsort(eval_min), 0)
sorted_min_ix = eval_ixs[sorted_min_eix]
ranked_min_eix = get_ranks(sorted_min_eix)
eval_per = np.percentile(raw_evals,0.25,axis=1)
sorted_per_eix = np.flip(np.argsort(eval_per), 0)
sorted_per_ix = eval_ixs[sorted_per_eix]
ranked_per_eix = get_ranks(sorted_per_eix)
eval_max = np.max(raw_evals,axis=1)
sorted_max_eix = np.flip(np.argsort(eval_max), 0)
sorted_max_ix = eval_ixs[sorted_max_eix]
ranked_max_eix = get_ranks(sorted_max_eix)
six.print_('Sorted by avg eval')
six.print_('ixs: {}'.format(array2str(sorted_avg_ix)))
six.print_('scores: {}'.format(array2str(scores[sorted_avg_ix])))
six.print_('Sorted by min eval')
six.print_('scores: {}'.format(array2str(scores[sorted_min_ix])))
six.print_('Sorted by 25% per eval')
six.print_('scores: {}'.format(array2str(scores[sorted_per_ix])))
six.print_('Sorted by max eval')
six.print_('scores: {}'.format(array2str(scores[sorted_max_ix])))
eval_std = np.std(raw_evals,axis=1)
sorted_std_eix = np.argsort(eval_std)
sorted_std_ix = eval_ixs[sorted_std_eix]
ranked_std_eix = get_ranks(sorted_std_eix)
six.print_('Sorted by smallest std of evals by other models')
six.print_('scores: {}'.format(array2str(scores[sorted_std_ix])))
eval_stdt = np.std(raw_evals,axis=0)
sorted_stdt_eix = np.argsort(eval_stdt)
sorted_stdt_ix = eval_ixs[sorted_stdt_eix]
ranked_stdt_eix = get_ranks(sorted_stdt_eix)
six.print_('Sorted by smallest std of own evals')
six.print_('scores: {}'.format(array2str(scores[sorted_stdt_ix])))
analyzeRME(raw_evals, eval_ixs, scores, vloss, behavior, initialq)
'''
Now let's look at proper RME with dropout
'''
def get_ranks(sorted_indices):
ranks = np.zeros(sorted_indices.shape,dtype=np.int)
for i in six.moves.range(sorted_indices.shape[0]):
ranks[sorted_indices[i]] = i+1
return ranks
data11 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runA.npz')
data12 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/stats-runC.npz')
data21 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runA.npz')
data22 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real1-runC.npz')
data31 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real0-runA.npz')
data32 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/mcts-rtype1-rollouts3000-trajectories100-real0-runC.npz')
data41 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype2-trajectories400-runA.npz')
data42 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/policies-rtype2-trajectories400-runC.npz')
data51 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runA.npz')
data52 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/initialq-rtype1-rollouts100000-runC.npz')
data61 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runA.npz')
data62 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/optpolicy-rtype1-rollouts10000-runC.npz')
data71 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/rmeproper-rtype1-rollouts1000-trajectories100-runA.npz')
data72 = np.load('experiments/test2_model_small-dropout8-shuffle0-data-test2-n100000-l5-random.pickle/rmeproper-rtype1-rollouts1000-trajectories100-runC.npz')
# each row is a real environment
raw_evals = np.vstack([data71['evals'],data72['evals']]).T
eval_ixs = np.arange(raw_evals.shape[0])
vloss = np.concatenate([data11['vloss'],data12['vloss']])[:,-1]
scores = np.concatenate([data21['scores'][:,0],data22['scores'][:,0]])
behavior = np.concatenate([data41['rewards'][:,0],data42['rewards'][:,0]]) / 4.0
initialq = np.concatenate([data51['qvals'][:,0],data52['qvals'][:,0]])
opts = np.vstack([data61['opts'],data62['opts']])[:,0,:]
analyzeRME(raw_evals, eval_ixs, scores, vloss, behavior, initialq)
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
question_pt = 'data/v2_OpenEnded_mscoco_val2014_questions.json'
feature_h5_folder = 'data/rcnn_feature' # path to trainval_feature.h5
image_dir = 'data/images/mscoco/images/' # path to mscoco/val2014, containing all mscoco val images
ann_file = 'data/images/mscoco/annotations/instances_val2014.json' # path to mscoco/annotations/instances_val2014.json
%matplotlib inline
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[1])))) # to import shared utils
import torch
import numpy as np
# import pickle
import json
import h5py
import copy
from PIL import Image, ImageFont, ImageDraw, ImageEnhance
import _pickle as cPickle
import re
def invert_dict(d):
return {v: k for k, v in d.items()}
def expand_batch(*args):
return (t.unsqueeze(0) for t in args)
def todevice(tensor, device):
if isinstance(tensor, list) or isinstance(tensor, tuple):
assert isinstance(tensor[0], torch.Tensor)
return [todevice(t, device) for t in tensor]
elif isinstance(tensor, torch.Tensor):
return tensor.to(device)
import pickle
from dataset import Dictionary, VQAFeatureDataset
##prepare data
name = 'val' # train or val
answer_path = os.path.join('data', 'cp-cache', '%s_target.pkl' % name)
name = "train" if name == "train" else "test"
question_path = os.path.join('data', 'vqacp_v2_%s_questions.json' % name)
with open(question_path) as f:
questions = json.load(f)
with open(answer_path, 'rb') as f:
answers = cPickle.load(f)
questions.sort(key=lambda x: x['question_id'])
answers.sort(key=lambda x: x['question_id'])
dictionary = Dictionary.load_from_file('data/dictionary.pkl')
dset = VQAFeatureDataset('val', dictionary, dataset='cpv2',
# cache_image_features=args.cache_features)
cache_image_features=False)
def plot_rect(image, boxes):
img = Image.fromarray(np.uint8(image))
draw = ImageDraw.Draw(img)
for k in range(15):
box = boxes[k,:]
drawrect(draw, box, outline='green', width=3)
img = np.asarray(img)
return img
def drawrect(drawcontext, xy, outline=None, width=0):
x1, y1, x2, y2 = xy
points = (x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)
drawcontext.line(points, fill=outline, width=width)
def _load_image(image_id, dataset):
""" Load an image """
if img_id in dset.image_id2ix['train'].keys():
split = 'train'
img_idx = dset.image_id2ix['train'][img_id]
else:
split = 'val'
img_idx = dset.image_id2ix['val'][img_id]
name = (12 - len(str(image_id))) * '0' + str(image_id)
img = io.imread(os.path.join(image_dir, split+'2014', 'COCO_'+split+'2014_' + name + '.jpg'))
bboxes = torch.from_numpy(np.array(dataset.spatial[split][img_idx][:, :4]))
return img, bboxes
import utils
from torch.autograd import Variable
##choose an image question pair
index = 193
question = questions[index]
img_id = question['image_id']
img, bbox = _load_image(img_id, dset)
print(question['question'])
plot_img = plot_rect(copy.copy(img), bbox)
plt.axis('off')
plt.imshow(plot_img)
v, q, a, b, qid, hint_score = dset.__getitem__(index)
utils.assert_eq(question['question_id'], qid)
v = Variable(v, requires_grad=False).cuda()
q = Variable(q, requires_grad=False).cuda()
hint_score = Variable(hint_score, requires_grad=False).cuda()
import base_model as base_model
from vqa_debias_loss_functions import *
ckpt_path = 'logs/updn/model.pth'
constructor = 'build_%s' % 'baseline0_newatt'
model = getattr(base_model, constructor)(dset, 1024).cuda()
model.w_emb.init_embedding('data/glove6b_init_300d.npy')
model.debias_loss_fn = Plain()
model.eval()
ckpt = torch.load(ckpt_path)
states_ = ckpt
model.load_state_dict(states_)
pred, _,atts = model(v.unsqueeze(0), q.unsqueeze(0), None, None, None)
prediction = torch.argmax(a).data.cpu()
dset.label2ans[prediction]
from torch.nn import functional as F
pred = F.softmax(pred.squeeze(0), dim=0).cpu()
values, indices = pred.topk(5,dim=0, largest=True, sorted=True)
for i in indices:
print(dset.label2ans[i])
def plot_attention(img, boxes, att):
white = np.asarray([255, 255, 255])
pixel_peak = np.zeros((img.shape[0], img.shape[1]))
for k in range(36):
for i in range(int(boxes[k][1]), int(boxes[k][3])):
for j in range(int(boxes[k][0]), int(boxes[k][2])):
pixel_peak[i,j] = max(pixel_peak[i,j], att[k])
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
img[i,j] = white * (1-pixel_peak[i,j]) + img[i,j] * pixel_peak[i,j]
if torch.max(att) > 0.5:
red_box = boxes[torch.argmax(att),:]
img = Image.fromarray(np.uint8(img))
draw = ImageDraw.Draw(img)
drawrect(draw, red_box, outline='red', width=4)
img = np.asarray(img)
return img
if atts.max() < 0.5:
scale = 0.55 / atts.max()
else:
scale = 1.
plot_img = plot_attention(copy.copy(img), bbox, atts.squeeze(0))
plt.axis('off')
plt.imshow(plot_img)
from PIL import Image
name = 'figures/updn' + str(index) + '_mask.jpg'
im = Image.fromarray(plot_img)
im.save(name)
x = range(len(values))
fig, ax = plt.subplots()
y, _ = values.sort(0, descending=False)
y=y.data.numpy()
plt.barh(x, y)
ax.spines['right'].set_color('none') # right边框属性设置为none 不显示
ax.spines['top'].set_color('none') # top边框属性设置为none 不显示
ax.spines['bottom'].set_color('none')
plt.xticks([])
plt.yticks([])
for x, y in enumerate(y):
plt.text(y +0.01, x - 0.1, '%.3f' % y)
name = 'figures/' + str(index) +'_prob.jpg'
plt.savefig(name)
plt.show()
```
| github_jupyter |
```
##################Build Essential DenseNet to Load Pretrained Parameters###############################################
# encoding=utf8
import numpy as np
import tensorflow as tf
def unpickle(file):
import _pickle as cPickle
fo = open(file, 'rb')
dict = cPickle.load(fo,encoding='latin1')
fo.close()
if 'data' in dict:
dict['data'] = dict['data'].reshape((-1, 3, 32, 32)).swapaxes(1, 3).swapaxes(1, 2).reshape(-1, 32*32*3) / 256.
return dict
def load_data_one(f):
batch = unpickle(f)
data = batch['data']
labels = batch['labels']
print ("Loading %s: %d" % (f, len(data)))
return data, labels
def load_data(files, data_dir, label_count):
data, labels = load_data_one(data_dir + '/' + files[0])
for f in files[1:]:
data_n, labels_n = load_data_one(data_dir + '/' + f)
data = np.append(data, data_n, axis=0)
labels = np.append(labels, labels_n, axis=0)
labels = np.array([ [ float(i == label) for i in range(label_count) ] for label in labels ])
return data, labels
def run_in_batch_avg(session, tensors, batch_placeholders, feed_dict={}, batch_size=200):
res = [ 0 ] * len(tensors)
batch_tensors = [ (placeholder, feed_dict[ placeholder ]) for placeholder in batch_placeholders ]
total_size = len(batch_tensors[0][1])
batch_count = (total_size + batch_size - 1) / batch_size
for batch_idx in range(batch_count):
current_batch_size = None
for (placeholder, tensor) in batch_tensors:
batch_tensor = tensor[ batch_idx*batch_size : (batch_idx+1)*batch_size ]
current_batch_size = len(batch_tensor)
feed_dict[placeholder] = tensor[ batch_idx*batch_size : (batch_idx+1)*batch_size ]
tmp = session.run(tensors, feed_dict=feed_dict)
res = [ r + t * current_batch_size for (r, t) in zip(res, tmp) ]
return [ r / float(total_size) for r in res ]
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.01)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.01, shape=shape)
return tf.Variable(initial)
def conv2d(input, in_features, out_features, kernel_size, with_bias=False):
W = weight_variable([ kernel_size, kernel_size, in_features, out_features ])
conv = tf.nn.conv2d(input, W, [ 1, 1, 1, 1 ], padding='SAME')
if with_bias:
return conv + bias_variable([ out_features ])
return conv
def batch_activ_conv(current, in_features, out_features, kernel_size, is_training, keep_prob):
current = tf.contrib.layers.batch_norm(current, scale=True, is_training=is_training, updates_collections=None)
current = tf.nn.relu(current)
current = conv2d(current, in_features, out_features, kernel_size)
current = tf.nn.dropout(current, keep_prob)
return current
def block(input, layers, in_features, growth, is_training, keep_prob):
current = input
features = in_features
for idx in range(layers):
tmp = batch_activ_conv(current, features, growth, 3, is_training, keep_prob)
current = tf.concat((current, tmp),3)
features += growth
return current, features
def avg_pool(input, s):
return tf.nn.avg_pool(input, [ 1, s, s, 1 ], [1, s, s, 1 ], 'VALID')
data_dir = './data'
image_size = 32
image_dim = image_size * image_size * 3
# meta = unpickle(data_dir + '/batches.meta')
# label_names = meta['label_names']
# label_count = len(label_names)
label_count = 10
# train_files = [ 'data_batch_%d' % d for d in range(1, 6) ]
# train_data, train_labels = load_data(train_files, data_dir, label_count)
# pi = np.random.permutation(len(train_data))
# train_data, train_labels = train_data[pi], train_labels[pi]
# test_data, test_labels = load_data([ 'test_batch' ], data_dir, label_count)
# print ("Train:", np.shape(train_data), np.shape(train_labels))
# print ("Test:", np.shape(test_data), np.shape(test_labels))
# data = { 'train_data': train_data,
# 'train_labels': train_labels,
# 'test_data': test_data,
# 'test_labels': test_labels }
depth = 40
weight_decay = 1e-4
layers = int((depth - 4) / 3)
graph = tf.Graph()
xs = tf.placeholder("float", shape=[None, image_dim])
ys = tf.placeholder("float", shape=[None, label_count])
lr = tf.placeholder("float", shape=[])
keep_prob = tf.placeholder(tf.float32)
is_training = tf.placeholder("bool", shape=[])
current = tf.reshape(xs, [ -1, 32, 32, 3 ])
current = conv2d(current, 3, 16, 3)
current, features = block(current, layers, 16, 12, is_training, keep_prob)
current = batch_activ_conv(current, features, features, 1, is_training, keep_prob)
current = avg_pool(current, 2)
current, features = block(current, layers, features, 12, is_training, keep_prob)
current = batch_activ_conv(current, features, features, 1, is_training, keep_prob)
current = avg_pool(current, 2)
current, features = block(current, layers, features, 12, is_training, keep_prob)
current = tf.contrib.layers.batch_norm(current, scale=True, is_training=is_training, updates_collections=None)
current = tf.nn.relu(current)
current = avg_pool(current, 8)
final_dim = features
current = tf.reshape(current, [ -1, final_dim ])
Wfc = weight_variable([ final_dim, label_count ])
bfc = bias_variable([ label_count ])
ys_ = tf.nn.softmax( tf.matmul(current, Wfc) + bfc )
cross_entropy = -tf.reduce_mean(ys * tf.log(ys_ + 1e-12))
l2 = tf.add_n([tf.nn.l2_loss(var) for var in tf.trainable_variables()])
train_step = tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True).minimize(cross_entropy + l2 * weight_decay)
correct_prediction = tf.equal(tf.argmax(ys_, 1), tf.argmax(ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
para_dict={}
for k in tf.global_variables():
if k not in tf.contrib.framework.get_variables_by_suffix('Momentum'):#Load all parameters except ones of optimization functions
para_dict[k.name[:-2]] = k
sess=tf.InteractiveSession()
saver = tf.train.Saver(para_dict)
saver.restore(sess,'./modellog/weightonlypara93.ckpt')
##################End of Pretrained Parameters Loading###############################################
import config
#Nearly all hyperparameters are set in config.py
def weight_shared(weight_arr, name="None", nmeans=4, **kwargs):
"""Apply weight shared """
import cv2
# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Set flags (Just to avoid line break in the code)
flags = cv2.KMEANS_RANDOM_CENTERS
weight_arr_tem = np.reshape(weight_arr,[-1])
_,labels,centroids = cv2.kmeans(np.float32(np.reshape(weight_arr_tem,[-1,1])),nmeans,None,criteria,10,flags)
w_cen = centroids
w_cen = np.asarray(w_cen)
w_cenidx = labels
w_cenidx = np.reshape(w_cenidx,np.shape(weight_arr))
return weight_arr, w_cenidx, w_cen
def apply_prune_weightshared(weights, prune_dict): #Apply K-means quantization
dict_cenidx = {}
dict_cen = {}
for target in config.exc_para:
wl = target
num_cen = config.kmeans_para[wl]
# Get target layer's weights
weight_obj = weights[wl]
weight_arr = weight_obj.eval()
# Calculate centroids
weight_arr, w_cenidx, w_cen = weight_shared(weight_arr, name=wl,
nmeans=num_cen)
#Apply weight shared
dict_cenidx[wl] = w_cenidx
dict_cen[wl] = w_cen
weight_arr_tem = np.reshape(weight_arr,[-1])
w_cenidx_tem = np.reshape(w_cenidx,[-1])
w_cenidx_tem = w_cenidx_tem.astype(int)
w_cen = w_cen
for i in range(len(weight_arr_tem)):
weight_arr_tem[i]=w_cen[w_cenidx_tem[i]]
weight_arr = np.reshape(weight_arr_tem,np.shape(weight_arr))
# Store pruned weights as tensorflow objects
sess.run(weight_obj.assign(weight_arr))
return dict_cenidx,dict_cen
prune_dict = {}
for target in config.exc_para: #choose which layers
wl =target
weight_obj = para_dict[wl]
prune_dict[wl] = np.zeros_like(weight_obj.eval())
dict_cenidx,dict_cen = apply_prune_weightshared(para_dict, prune_dict)
saver.save(sess,'./kmeansmodel/stage1/kmeans128exc.ckpt')#save Kmeans-quantized parameters
#save K-Q mask
import pickle
# create dict
# save dict
f1 = open("C:/Users/lhlne/Desktop/project/densenet/kmeansmodel/stage1/kmeans128exc.txt","wb")
pickle.dump(dict_cenidx, f1)
f1.close()
# load dict
import pickle
f2 = open("C:/Users/lhlne/Desktop/project/densenet/kmeansmodel/stage1/kmeans128exc.txt","rb")
load_list = pickle.load(f2)
f2.close()
# print
print(load_list)
```
| github_jupyter |
```
!cp -r drive/Shareddrives/Virtuon/Machine\ Learning\ Project/Pre_Trained_Model/* /content
from google.colab import drive
drive.mount('/content/drive')
!unzip '/content/drive/Shareddrives/Virtuon/Machine Learning Project/LIP_Dataset/LIP_Dataset.zip'
import numpy as np
import tensorflow as tf
import pandas as pd
import cv2 as cv
from PIL import Image
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import random
from tensorflow.keras.utils import plot_model
from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Input
from tensorflow.keras.models import Sequential, Model
import matplotlib.pyplot as plt
%matplotlib inline
from model import build_model
train_path = 'LIP_Dataset/TrainVal_images/TrainVal_images/train_images/'
val_path = 'LIP_Dataset/TrainVal_images/TrainVal_images/val_images/'
train_labels_path = 'LIP_Dataset/TrainVal_parsing_annotations/TrainVal_parsing_annotations/train_segmentations/'
val_labels_path = 'LIP_Dataset/TrainVal_parsing_annotations/TrainVal_parsing_annotations/val_segmentations/'
train_data = pd.read_csv('LIP_Dataset/TrainVal_images/train_id.txt', header = None)
val_data = pd.read_csv('LIP_Dataset/TrainVal_images/val_id.txt', header = None)
train_paths = pd.read_csv('LIP_Dataset/TrainVal_images/train_id.txt', header = None)
train_paths = train_paths.applymap(lambda x: "".join([ train_path, x, '.jpg' ]))
val_paths = pd.read_csv('LIP_Dataset/TrainVal_images/val_id.txt', header = None)
val_paths = val_paths.applymap(lambda x: "".join([val_path, x, '.jpg']))
train_label_paths = train_data.copy()
train_label_paths = train_label_paths.applymap(lambda x: "".join([train_labels_path, x, '.png']))
val_label_paths = val_data.copy()
val_label_paths = val_label_paths.applymap(lambda x: "".join([val_labels_path, x, '.png']))
train_data = pd.read_csv('LIP_Dataset/TrainVal_images/train_id.txt', header = None)[0]
val_data = pd.read_csv('LIP_Dataset/TrainVal_images/val_id.txt', header = None)[0]
train_paths = train_paths[0].to_numpy()
train_label_paths = train_label_paths[0].to_numpy()
val_paths = val_paths[0].to_numpy()
val_label_paths = val_label_paths[0].to_numpy()
def preprocessing(image, label):
image_string = tf.io.read_file(image)
#Don't use tf.image.decode_image, or the output shape will be undefined
image = tf.io.decode_jpeg(image_string, channels=3)
#This will convert to float values in [0, 1]
image = tf.image.convert_image_dtype(image, tf.uint8)
resized_image = tf.image.resize(image, [im_height, im_height])
#resized_image = tf.image.convert_image_dtype(resized_image, tf.uint8)
image_string = tf.io.read_file(label)
#Don't use tf.image.decode_image, or the output shape will be undefined
image = tf.io.decode_png(image_string, channels = 1)
image = tf.reduce_sum(image, axis = -1)
image = tf.one_hot(image, depth = n_class)
resized_label_image = tf.image.resize(image, [im_height, im_height])
return resized_image, resized_label_image
cs = build_model()
cs.load_weights("model.11-0.8409.hdf5")
im_height, im_width, im_channels = (320,320,3)
n_classes = 20
common_interpolation = 'bilinear'
def random_choice(image_size):
height, width = image_size
crop_height, crop_width = 320, 320
x = random.randint(0, max(0, width - crop_width))
y = random.randint(0, max(0, height - crop_height))
return x, y
def safe_crop(mat, x, y):
crop_height, crop_width = im_height, im_width
if len(mat.shape) == 2:
ret = np.zeros((crop_height, crop_width), np.float32)
else:
ret = np.zeros((crop_height, crop_width, 3), np.float32)
crop = mat[y:y + crop_height, x:x + crop_width]
h, w = crop.shape[:2]
ret[0:h, 0:w] = crop
return ret
test_path = "/content/drive/Shareddrives/Virtuon/download_1.jpg"
test = img_to_array(load_img(test_path))
x,y = random_choice(test.shape[:2])
plt.imshow(safe_crop(test, x, y)/255)
def image(path):
return img_to_array(load_img(path, target_size=(im_height, im_width), interpolation = common_interpolation))
def bodypix_output(path = None, img = False):
if path != None:
img = image(path)
result = bs.predict_single(img)
mask = result.get_mask(threshold = 0.75)
c_mask = result.get_colored_part_mask(mask)
# c_mask = tf.math.argmax(c_mask, axis = -1)
return c_mask
def segnet_output(path):
output = cs.predict(image(path).reshape( (1, im_height, im_width, im_channels) )/255.0)
output = output.reshape((im_height, im_width, n_classes))
return output
load_img("/content/drive/Shareddrives/Virtuon/download_1.jpg")
plt.imshow(tf.math.argmax(segnet_output(test_path), axis = -1))
```
| github_jupyter |
```
import jax.numpy as jnp
from jax import grad, jit, vmap, jacfwd, jacrev
from jax import random
import jax.scipy.sparse as sp
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.axes_grid1 import make_axes_locatable
import networkx as nx
import pandas as pd
from tqdm.auto import tqdm, trange
from scipy.sparse import csc_matrix
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
import claude as cl
from claude import observables as obs
from claude import constraints as const
N = 1000
ba = nx.barabasi_albert_graph(N,30)
gn = nx.scale_free_graph(1000)
ba_adj = np.asarray(nx.adj_matrix(ba).todense())
gn_adj = np.asarray(nx.adj_matrix(gn).todense())
d = np.array(ba_adj.sum(axis=0)).flatten()
dinv = 1/d
din = np.array(gn_adj.sum(axis=0)).flatten()
dout = np.array(gn_adj.sum(axis=1)).flatten()
def plot_adj(adj):
plt.imshow(adj,cmap=matplotlib.cm.get_cmap('gray_r'),vmin=0,vmax=1)
plt.colorbar()
```
# Connectivity
```
m = cl.GraphEnsemble(1000)
m.fit([const.Connectivity(343)], opt_kwargs={'nit':30,'fatol':1e-2,'disp':True})
plt.figure(figsize=[15,5])
plt.subplot(1,3,1)
plot_adj(ba_adj)
plt.subplot(1,3,2)
plot_adj(m.adj_matrix)
plt.subplot(1,3,3)
plt.hist([m.sample().sum() for i in trange(1000)])
```
## Subgraph connectivity
```
m = cl.GraphEnsemble(1000)
m.fit([const.Connectivity(343, nodeset1=np.arange(100))], opt_kwargs={'nit':30,'fatol':1e-2,'disp':True})
plt.figure(figsize=[15,5])
plt.subplot(1,3,1)
plot_adj(ba_adj)
plt.subplot(1,3,2)
plot_adj(m.adj_matrix)
plt.subplot(1,3,3)
plt.hist([np.triu(m.sample()[:100,:100]).sum() for i in trange(1000)])
```
## Connectivity between 2 groups of nodes
```
m = cl.GraphEnsemble(1000)
m.fit([const.Connectivity(343, nodeset1=np.arange(100), nodeset2=np.arange(150,200))], opt_kwargs={'nit':30,'fatol':1e-2,'disp':True})
plt.figure(figsize=[15,5])
plt.subplot(1,3,1)
plot_adj(ba_adj)
plt.subplot(1,3,2)
plot_adj(m.adj_matrix)
plt.subplot(1,3,3)
plt.hist([m.sample()[:100,150:200].sum() for i in trange(1000)])
```
# Fixed degree sequence
### Full degree sequence
```
m = cl.GraphEnsemble(1000)
m.fit([const.DegreeSequence(d)], opt_kwargs={'nit':100,'fatol':1e-2,'disp':True})
#m.fit([const.DegreeSequence(get_din_dout(ba)[0]),const.Connectivity(250, nodeset1=np.arange(30), nodeset2=np.arange(40,50))], opt_kwargs={'nit':100,'fatol':1e-2})
#m.fit([const.DegreeSequence(d[:30], nodeset=np.arange(30))], opt_kwargs={'nit':30,'fatol':1e-2})
plt.figure(figsize=[15,5])
plt.subplot(1,3,1)
plot_adj(ba_adj)
plt.subplot(1,3,2)
plot_adj(m.adj_matrix)
plt.subplot(1,3,3)
plt.plot(d, m.adj_matrix.sum(axis=1),'.')
plt.plot(plt.xlim(),plt.xlim())
```
### Partial degree sequence
```
m = cl.GraphEnsemble(1000)
#m.fit([const.DegreeSequence(get_din_dout(ba)[0]),const.Connectivity(250, nodeset1=np.arange(30), nodeset2=np.arange(40,50))], opt_kwargs={'nit':100,'fatol':1e-2})
m.fit([const.DegreeSequence(d[:50], nodeset=np.arange(50))], opt_kwargs={'nit':30,'fatol':1e-2,'disp':True})
plt.figure(figsize=[25,10])
plt.subplot(1,3,1)
plot_adj(ba_adj)
plt.subplot(1,3,2)
plot_adj(m.adj_matrix)
plt.subplot(1,3,3)
plt.plot(d, '.', markersize=15)
plt.plot(m.adj_matrix.sum(axis=1),'.',markersize=5)
```
### Degree sequence in subgraph
```
m = cl.GraphEnsemble(1000)
#m.fit([const.DegreeSequence(get_din_dout(ba)[0]),const.Connectivity(250, nodeset1=np.arange(30), nodeset2=np.arange(40,50))], opt_kwargs={'nit':100,'fatol':1e-2})
m.fit([const.DegreeSequence(np.arange(50), nodeset=np.arange(50), subgraph_nodeset=np.arange(100))], opt_kwargs={'nit':100,'fatol':1e-2,'disp':True})
#m.fit([const.DegreeSequence(d[:50], nodeset=np.arange(50))], opt_kwargs={'nit':30,'fatol':1e-2})
plt.figure(figsize=[20,5])
plt.subplot(1,3,1)
plot_adj(m.adj_matrix)
plt.subplot(1,3,2)
plt.plot(m.adj_matrix[:50,:100].sum(axis=1),'.')
plt.subplot(1,3,3)
plt.plot(m.adj_matrix.sum(axis=1),'.')
plt.axvline(100,color='red')
```
# Joining constraints
```
m = cl.GraphEnsemble(1000)
m.fit([const.DegreeSequence(get_din_dout(ba)[0]),const.Connectivity(250, nodeset1=np.arange(30), nodeset2=np.arange(40,50))], opt_kwargs={'nit':100,'fatol':1e-2,'disp':True})
plt.figure(figsize=[20,5])
plt.subplot(1,3,1)
plot_adj(ba_adj)
plt.subplot(1,3,2)
plot_adj(m.adj_matrix)
plt.subplot(1,3,3)
plt.hist([m.sample()[:30,40:50].sum() for i in trange(1000)])
```
# Observables
### RWR
```
x = np.zeros(N)
x[np.random.randint(0,N, int(N/100*20))] = 1
#x = np.random.rand(N)
x= x/x.sum()
x = jnp.asarray(x)
lambd = 0.3
def propagate(adj,x,lambd=lambd):
p = adj / jnp.reshape(adj.sum(axis=0), [adj.shape[0],1])
I = jnp.eye(p.shape[0])
return lambd*x.dot(jnp.linalg.inv(I - (1-lambd)*p))
def propagate2(adj,x,i,lambd=lambd):
p = adj / jnp.reshape(adj.sum(axis=0), [adj.shape[0],1])
I = jnp.eye(p.shape[0])
return lambd*x.dot(jnp.linalg.inv(I - (1-lambd)*p))[i]
m = cl.GraphEnsemble(1000)
#m.fit([const.DegreeSequence(d)], opt_kwargs={'nit':100,'fatol':1e-2})
m.fit([const.DegreeSequence(d),const.Connectivity(250, nodeset1=np.arange(30), nodeset2=np.arange(40,50))], opt_kwargs={'nit':50,'fatol':1e-2,'disp':True})
k = obs.RandomWalkWithRestart.eval_transfer_matrix(ba_adj, lambd)
mu = m.predict_mean(obs.RandomWalkWithRestart.func, f_args=[x, lambd, None, k])
sigma = m.predict_std(obs.RandomWalkWithRestart.grad, f_args=[x, lambd, None, k], obs_dim_idx=1)
N_samples = 100
y = propagate(ba_adj, x)
#samples = []
rdmy_ms = np.zeros([len(ba),N_samples])
for i in trange(N_samples):
flag = False
while not flag:
smpl = m.sample()
prop = propagate(smpl,x,lambd)
if np.isnan(propagate(smpl,x)).sum() == 0:
#samples.append(smpl)
rdmy_ms[:,i] = propagate(smpl, x)
flag = True
z = (y - rdmy_ms.mean(axis=1))/rdmy_ms.std(axis=1)
plt.figure(figsize=[13,5])
plt.subplot(121)
plt.plot(rdmy_ms.mean(axis=1),mu,'.')
plt.xlabel('Numerical expected value',fontsize=15)
plt.ylabel('Predicted expected value',fontsize=15)
plt.plot(plt.xlim(),plt.xlim())
plt.subplot(122)
plt.plot(rdmy_ms.std(axis=1),sigma,'.')
plt.xlabel('Numerical std. dev.',fontsize=15)
plt.ylabel('Predicted std. dev.',fontsize=15)
plt.plot(plt.xlim(),plt.xlim())
plt.tight_layout()
```
### ANND
```
mu = m.predict_mean(obs.AverageNeighborDegree.func)
sigma = [m.predict_std(grad(obs.AverageNeighborDegree.func, argnums=0), f_args=[i]) for i in trange(N)]
annd = obs.AverageNeighborDegree.func
N_samples = 100
y = np.asarray(annd(csc_matrix(adj))).flatten()
#samples = []
rdm_annd = np.zeros([N,N_samples])
for i in trange(N_samples):
smpl = csc_matrix(m.sample())
prop = np.asarray(annd(smpl)).flatten()
rdm_annd[:,i] = prop
z = (y - rdm_annd.mean(axis=1))/rdm_annd.std(axis=1)
plt.figure(figsize=[13,5])
plt.subplot(121)
plt.plot(rdm_annd.mean(axis=1),mu,'.')
plt.xlabel('Numerical expected value',fontsize=15)
plt.ylabel('Predicted expected value',fontsize=15)
plt.plot(plt.xlim(),plt.xlim())
plt.subplot(122)
plt.plot(rdm_annd.std(axis=1),sigma,'.')
plt.xlabel('Numerical std. dev.',fontsize=15)
plt.ylabel('Predicted std. dev.',fontsize=15)
plt.plot(plt.xlim(),plt.xlim())
plt.tight_layout()
```
| github_jupyter |
# Comet.ml visualisation
[comet.ml](https://www.comet.ml) is a nice experiment tracking service, please sign-up before proceeding to the exercise.
Also you would need API key you can get from 'Settings' -> 'Account settings' that we save to a config file.
```
%%writefile .comet.config
[comet]
api_key=<YOUR KEY>
logging_file = /tmp/comet.log
logging_file_level = info
! [ ! -z "$COLAB_GPU" ] && pip install skorch comet_ml
from comet_ml import Experiment
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0);
```
## Training a classifier and making predictions
### A toy binary classification task
We load a toy classification task from `sklearn`.
```
import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(1000, 20, n_informative=10, n_classes=2, random_state=0)
X = X.astype(np.float32)
X.shape, y.shape, y.mean()
```
### Defining and training the neural net classifier
```
class ClassifierModule(nn.Module):
def __init__(
self,
num_units=10,
nonlin=F.relu,
dropout=0.5,
):
super(ClassifierModule, self).__init__()
self.dense0 = nn.Linear(20, num_units)
self.nonlin = nonlin
self.dropout = nn.Dropout(dropout)
self.dense1 = nn.Linear(num_units, 10)
self.output = nn.Linear(10, 2)
def forward(self, X, **kwargs):
X = self.nonlin(self.dense0(X))
X = self.dropout(X)
X = F.relu(self.dense1(X))
X = F.softmax(self.output(X), dim=-1)
return X
from skorch import NeuralNetClassifier
net = NeuralNetClassifier(
ClassifierModule,
max_epochs=20,
module__num_units=10,
lr=0.1,
device='cuda', # comment this to train with CPU
)
```
Create Experiment instance for various training info
```
experiment = Experiment(project_name="comet-4")
experiment.log_parameters({'num_units': 10})
net.fit(X, y)
experiment.log_metrics({'valid_loss': net.history[-1, 'valid_loss']})
experiment.end()
```
Now go check comet page / plots
## Task
try a few more experiments with `num_units` in [20, 30, 40]
```
for num_units in <YOUR CODE>: # range from 20 to 30 with step 10
net = NeuralNetClassifier(
ClassifierModule,
max_epochs=20,
module__num_units=num_units,
lr=0.1,
device='cuda', # comment this to train with CPU
)
experiment = Experiment(project_name="comet-4")
experiment.log_parameters({'num_units': num_units})
net.fit(X, y)
experiment.log_metrics({'valid_loss': net.history[-1, 'valid_loss']})
experiment.end()
```
Now go and check comet.ml page / plots
```
```
| github_jupyter |
```
%matplotlib inline
%reload_ext autoreload
%autoreload 2
import numpy as np, pandas as pd, matplotlib.pyplot as plt
from IPython.display import display
from pathlib import Path
def display_all(df):
with pd.option_context("display.max_rows", 10000, "display.max_columns", 10000):
display(df)
data_dir = Path(".")
```
## Data
Load data into dataframe.
```
import itertools
hate_politics_dir = data_dir
def load_data(*path_globs):
df_all = pd.concat([
pd.read_json(json_file, lines=True, encoding="utf-8")
for json_file in itertools.chain(*[ hate_politics_dir.glob(path_glob) for path_glob in path_globs ])
], ignore_index=True)
# take the lastest version of each publication in the dataset
return df_all.sort_values("version").groupby("id").last().sort_values("published_at")
hate_politics = load_data("2019-12-*.jsonl", "2020-01-*.jsonl")
```
Coversions to make things more convenient.
```
def convert(df):
for f in ["published_at", "first_seen_at", "last_updated_at"]:
df[f] = pd.to_datetime(df[f])
df["published_date"] = df.published_at.map(lambda d: d.date())
convert(hate_politics)
hate_politics.head()
```
## Basics
Let's get some idea about the volume of this dataset.
```
from datetime import *
df = hate_politics
def counts_by_day(df):
return df.groupby("published_date").size()
plt.figure(figsize=(12.8, 9.6))
plt.plot(counts_by_day(df));
counts_by_day(df).describe()
counts_by_day(df[df.published_date < date(2020, 1, 1)]).describe()
counts_by_day(df[df.published_date > date(2020, 1, 13)]).describe()
#date_range = pd.date_range(start="2019-12-01", end="2020-01-31", freq="D")
```
Get to know some of the most active authors.
```
authors = df.author.value_counts()
authors.describe()
```
Let's zoom in onto the most active quartile of authors.
```
top_authors = authors[authors >= 7.0]
#plt.figure(figsize=(12.8, 9.6))
plt.hist(top_authors.values, bins=100);
```
There must be many different reasons for a user to be very active. Let's see if we can find a group of authors who posts a consistent number of posts each day. This is measured by the standard deviation of their number of posts everyday.
```
top_author_stats = top_authors.to_frame().apply(
lambda author: counts_by_day(df[df.author == author.name]).describe(),
axis=1)
display_all(top_author_stats)
```
There seems to be quite a few people who on average posts around 5 posts everyday, with a rather low deviation. If we arbitrarily pick the thresholds of average and deviation of daily post number to be 5.0 and 1.2 respectively...
```
consistent_authors = top_author_stats[(top_author_stats["std"] < 1.2) & (top_author_stats["50%"] >= 5.0)]
consistent_authors
```
It could be very interesting to look into each of these authors with the help of some external databases. `macaron5566` (or "馬卡龍5566"), for example, seems to be rather famous and [runs for board master of HatePolitics this year](https://www.ptt.cc/bbs/HatePolitics/M.1583475714.A.204.html). `nawabonga`, on the other hand, apeared in [at](https://gotv.ctitv.com.tw/2019/09/1129415.htm) [least](https://news.ltn.com.tw/news/politics/breakingnews/2802289) [three](https://www.chinatimes.com/realtimenews/20200420002172-260407?chdtv) news articles which quotes its PTT posts. Its posting pattern on HatePolitics is also rather consistent (note that our dataset contains posts between 2019-12-01 and 2020-01-31.)
```
plt.figure(figsize=(12.8, 4.8))
plt.plot(counts_by_day(df[df.author == "macaron5566"]), ".")
plt.show()
counts_by_day(df[df.author == "macaron5566"])
plt.figure(figsize=(12.8, 4.8))
plt.plot(counts_by_day(df[df.author == "nawabonga"]), ".")
plt.show()
counts_by_day(df[df.author == "nawabonga"])
counts_by_day(df[df.author == "erkunden"])
```
However, it is definitely too soon to draw conclusions from these observatios. For one thing, these observations do not hold against the data over a larger time span. If we take the data from 2019-11 to 2020-02 into account, some of the consistencies do not hold anymore.
## i'Analyseur
[i'Analyseur](https://www.ianalyseur.org/) is a tool to look into PTT user activities. Among other features it can show the active time of a user within a day and days of week. Also it can do a cross-analysis of users and the IP addresses they use to connect to PTT. Its database is [updated](https://www.ianalyseur.org/faq/) to 2018-11-08. Now that we have a similar dataset, we can see if the same model of analysis still works for this newer dataset.
Build a pivot table from `author` and `connect_from` columns.
```
lookup_table = (
df[["author", "connect_from"]]
.groupby(["author", "connect_from"]).size().to_frame("count").reset_index()
.pivot("author", "connect_from", "count")
)
def ianalyseur(table, username):
"""
List the IP addresses ever used by user `username`, with all of the users that have ever used each of these IPs and the number of times they have used it.
"""
connect_from_user = table.loc[username]
data = {}
for ip in connect_from_user[connect_from_user > 0].index:
connect_from_ip = table[ip]
for user in connect_from_ip[connect_from_ip > 0].index:
data[(ip, user)] = int(connect_from_ip.loc[user])
return pd.DataFrame(data.values(), index=pd.MultiIndex.from_tuples(data.keys()), columns=["count"])
```
See which users share IP addresses with the user "nawabonga".
```
ianalyseur(lookup_table, "nawabonga")
```
This shows, among other things, that the dataset parser does not separate usernames from nicknames very well and needs improvements. It also shows that user "isaluku" and "kapasky" also often use quite a few of the IP addresses used by "nawabonga". We can find similar results [on i'Analyseur](https://www.ianalyseur.org/user/nawabonga/).
Results on some other users.
```
ianalyseur(lookup_table, "macaron5566")
```
| github_jupyter |
# RoadMap 8 - Torch NN Layers - Activation
1. torch.nn.ELU
2. torch.nn.Hardshrink
3. torch.nn.Hardtanh
4. torch.nn.LeakyReLU
5. torch.nn.LogSigmoid
6. torch.nn.PReLU
7. torch.nn.ReLU
8. torch.nn.ReLU6
9. torch.nn.RReLU
10. torch.nn.SELU
11. torch.nn.Sigmoid
12. torch.nn.Softplus
13. torch.nn.Softshrink
14. torch.nn.Softsign
15. torch.nn.TanH
16. torch.nn.Tanhshrink
17. torch.nn.Threshold
18. torch.nn.Softmin
19. torch.nn.Softmax
20. torch.nn.Softmax2d
21. torch.nn.LogSoftmax
22. torch.nn.AdaptiveLogSoftmaxWithLoss
23. All the above layers as FUNCTIONAL modules
```
import os
import sys
import torch
import numpy as np
import torch.nn as nn
from torchvision import transforms, datasets
from PIL import Image
import cv2
import matplotlib.pyplot as plt
import torchvision
# Functional libraries
import torch.nn.functional as F
```
## Extra Blog Resources
1. https://www.geeksforgeeks.org/activation-functions-neural-networks/
2. https://towardsdatascience.com/activation-functions-and-its-types-which-is-better-a9a5310cc8f
3. https://medium.com/the-theory-of-everything/understanding-activation-functions-in-neural-networks-9491262884e0
```
# Input
image_name = "dog.jpg"
image_pil = Image.open(image_name)
transform = transforms.Compose([transforms.ToTensor()])
image = transform(image_pil).float()
image_nchw = torch.unsqueeze(image, 0)
print(image_nchw.size())
plt.imshow(image_pil)
# Exponential linear Unit Function
'''
1. nn.ELU - Applies element-wise, ELU(x)=max(0,x)+min(0,α∗(exp(x)−1))
- alpha – the α value for the ELU formulation. Default: 1.0
- inplace – can optionally do the operation in-place. Default: False
'''
print("Module implementation")
m = nn.ELU(alpha = 2.0)
input_data = torch.randn(5)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.elu(input_data, alpha=1.0, inplace=False)
print("output = ", output)
print("\n")
```
### Hard Shrinkage Function
2. nn.Hardshrink - Applies the hard shrinkage function element-wise Hardshrink
- lambd – the λ value for the Hardshrink formulation. Default: 0.5
Hard Shrinkage Function:
$$\begin{split}\text{HardShrink}(x) =
\begin{cases}
x, & \text{ if } x > \lambda \\
x, & \text{ if } x < -\lambda \\
0, & \text{ otherwise }
\end{cases}\end{split}
$$
```
print("Module implementation")
m = nn.Hardshrink(lambd = 0.5)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.hardshrink(input_data, lambd = 0.5)
print("output = ", output)
print("\n")
```
### Hard Tanh Function
3. nn.Hardtanh - Applies the hard shrinkage function element-wise Hardshrink
- min_val – minimum value of the linear region range. Default: -1
- max_val – maximum value of the linear region range. Default: 1
- inplace – can optionally do the operation in-place. Default: False
Hard TanH Function:
$$\begin{split}\text{HardTanh}(x) = \begin{cases}
1 & \text{ if } x > \text{max_value} \\
-1 & \text{ if } x < \text{min_value} \\
x & \text{ otherwise } \\
\end{cases}\end{split}$$
```
print("Module implementation")
m = nn.Hardtanh(min_val = 0.1, max_val = 0.5)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.hardtanh(input_data, min_val = 0.1, max_val = 0.5)
print("output = ", output)
print("\n")
```
### Leaky ReLU Function
4. nn.LeakyReLU - Applies element-wise, LeakyReLU(x)=max(0,x)+negative_slope∗min(0,x)
- negative_slope – Controls the angle of the negative slope. Default: 1e-2
- inplace – can optionally do the operation in-place. Default: False
LeakyReLU Function:
\begin{split}\text{LeakyRELU}(x) =
\begin{cases}
x, & \text{ if } x \geq 0 \\
\text{negative_slope} \times x, & \text{ otherwise }
\end{cases}\end{split}
```
print("Module implementation")
m = nn.LeakyReLU(negative_slope = 0.3)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.leaky_relu(input_data, negative_slope = 0.3)
print("output = ", output)
print("\n")
```
### Log Sigmoid Function
4. nn.LogSigmoid - Applies element-wise, Log Sigmoid
$$\text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right)$$
```
print("Module implementation")
m = nn.LogSigmoid()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.logsigmoid(input_data)
print("output = ", output)
print("\n")
```
### P-ReLU Function
5. nn.PReLU - Applies element-wise,PReLU(x)=max(0,x)+a∗min(0,x)
- num_parameters – number of a to learn. Default: 1
- init – the initial value of a .Default: 0.25
PReLU Function:
\begin{split}\text{PReLU}(x) =
\begin{cases}
x, & \text{ if } x \geq 0 \\
ax, & \text{ otherwise }
\end{cases}\end{split}
```
print("Module implementation")
m = nn.PReLU(init=0.4)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.prelu(input_data, weight=torch.tensor([0.4]))
print("output = ", output)
print("\n")
```
### ReLU Function
6. nn.ReLU - Applies element-wise,ReLU(x)=max(0,x)
```
print("Module implementation")
m = nn.ReLU()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.relu(input_data)
print("output = ", output)
print("\n")
```
### ReLU6 Function
7. nn.ReLU6 - Applies the element-wise function ReLU6(x)=min(max(0,x),6)
```
print("Module implementation")
m = nn.ReLU6()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.relu6(input_data)
print("output = ", output)
print("\n")
```
### R-ReLU Function
8. nn.RReLU - Applies the randomized leaky rectified liner unit function element-wise described in the paper Empirical Evaluation of Rectified Activations in Convolutional Network.
- lower – lower bound of the uniform distribution. Default: 1/8
- upper – upper bound of the uniform distribution. Default: 1/3
- inplace – can optionally do the operation in-place. Default: False
RReLU Function:
\begin{split}\text{RReLU}(x) = \begin{cases}
x & \text{if } x \geq 0 \\
ax & \text{ otherwise }
\end{cases},\end{split}
```
print("Module implementation")
m = nn.RReLU(lower = 0.3, upper = 0.6)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.rrelu(input_data, lower = 0.3, upper = 0.6)
print("output = ", output)
print("\n")
```
### SELU Function
9. nn.SELU - Applies element-wise, SELU(x)=scale∗(max(0,x)+min(0,α∗(exp(x)−1))),
with α=1.6732632423543772848170429916717 and
scale=1.0507009873554804934193349852946.
```
print("Module implementation")
m = nn.SELU()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.selu(input_data)
print("output = ", output)
print("\n")
```
### Sigmoid Function
10. nn.Sigmoid - Applies element-wise, Sigmoid
$$\text{Sigmoid}(x) = \frac{1}{1 + \exp(-x)})$$
```
print("Module implementation")
m = nn.Sigmoid()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.sigmoid(input_data)
print("output = ", output)
print("\n")
```
### Softplus Function
11. nn.Softplus - SoftPlus is a smooth approximation to the ReLU function and can be used to constrain the output of a machine to always be positive.
- beta – the β value for the Softplus formulation. Default: 1
- threshold – values above this revert to a linear function. Default: 20
$$\text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))$$
```
print("Module implementation")
m = nn.Softplus(beta=0.1, threshold=10)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.softplus(input_data, beta=0.1, threshold=10)
print("output = ", output)
print("\n")
```
### Softshrink Function
12. nn.Softshrink - Applies the soft shrinkage function elementwise
- lambd – the λ value for the Softshrink formulation. Default: 0.5
SoftShrink Function -
$$\begin{split}\text{SoftShrinkage}(x) =
\begin{cases}
x - \lambda, & \text{ if } x > \lambda \\
x + \lambda, & \text{ if } x < -\lambda \\
0, & \text{ otherwise }
\end{cases}\end{split}$$
```
print("Module implementation")
m = nn.Softshrink(lambd=0.2)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.softshrink(input_data, lambd=0.2)
print("output = ", output)
print("\n")
```
### Softsign Function
13. nn.Softsign - Applies element-wise, the softsign function
Softsign Function -
$$\text{SoftSign}(x) = \frac{x}{ 1 + |x|}$$
```
print("Module implementation")
m = nn.Softsign()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.softsign(input_data)
print("output = ", output)
print("\n")
```
### TanH Function
14. nn.Tanh - Applies element-wise, Tanh function
TanH Function -
$$\text{Tanh}(x) = \tanh(x) = \frac{e^x - e^{-x}} {e^x + e^{-x}}$$
```
print("Module implementation")
m = nn.Tanh()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.tanh(input_data)
print("output = ", output)
print("\n")
```
### TanhShrink Function
15. nn.Tanhshrink - Applies element-wise, Tanhshrink function
Tanhshrink Function -
$$\text{Tanhshrink}(x) = x - \text{Tanh}(x)$$
```
print("Module implementation")
m = nn.Tanhshrink()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.tanhshrink(input_data)
print("output = ", output)
print("\n")
```
### Threshold Function
16. nn.Threshold - Thresholds each element of the input Tensor
- threshold – The value to threshold at
- value – The value to replace with
- inplace – can optionally do the operation in-place. Default: False
Threshold Function -
$$\begin{split}y =
\begin{cases}
x, &\text{ if } x > \text{threshold} \\
\text{value}, &\text{ otherwise }
\end{cases}\end{split}$$
```
print("Module implementation")
m = nn.Threshold(threshold = 0.3, value = 4)
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.threshold(input_data, threshold = 0.3, value = 4)
print("output = ", output)
print("\n")
```
### Softmin Function
17. nn.Softmin - Applies the Softmin function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range (0, 1) and sum to 1
Softmin Function -
$$\text{Softmin}(x_{i}) = \frac{\exp(-x_i)}{\sum_j \exp(-x_j)}$$
```
print("Module implementation")
m = nn.Softmin()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.softmin(input_data)
print("output = ", output)
print("\n")
```
### Softmax Function
18. nn.Softmax - Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range (0,1) and sum to 1
Softmax Function -
$$\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}$$
```
print("Module implementation")
m = nn.Softmax()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.softmax(input_data)
print("output = ", output)
print("\n")
```
### Softmax2d Function
19. nn.Softmax2d - Applies SoftMax over features to each spatial location.
```
print("Module implementation")
m = nn.Softmax2d()
output = m(image_nchw)
print("output shape = ", output.size())
print("\n")
# Visualizing
output = torch.squeeze(output)
transform = transforms.Compose([transforms.ToPILImage(mode=None)])
output_pil = transform(output)
plt.imshow(output_pil)
```
### Log-Softmax Function
20. nn.LogSoftmax - Applies the Log(Softmax(x)) function to an n-dimensional input Tensor. The LogSoftmax formulation can be simplified as
Softmax Function -
$$\text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right)$$
```
print("Module implementation")
m = nn.LogSoftmax()
input_data = torch.randn(10)
output = m(input_data)
print("input = ", input_data)
print("output = ", output)
print("\n")
print("Functional implementation")
output = F.log_softmax(input_data)
print("output = ", output)
print("\n")
```
## Author - Tessellate Imaging - https://www.tessellateimaging.com/
## Monk Library - https://github.com/Tessellate-Imaging/monk_v1
Monk is an opensource low-code tool for computer vision and deep learning
### Monk features
- low-code
- unified wrapper over major deep learning framework - keras, pytorch, gluoncv
- syntax invariant wrapper
### Enables
- to create, manage and version control deep learning experiments
- to compare experiments across training metrics
- to quickly find best hyper-parameters
### At present it only supports transfer learning, but we are working each day to incorporate
- GUI based custom model creation
- various object detection and segmentation algorithms
- deployment pipelines to cloud and local platforms
- acceleration libraries such as TensorRT
- preprocessing and post processing libraries
## To contribute to Monk AI or Pytorch RoadMap repository raise an issue in the git-repo or dm us on linkedin
- Abhishek - https://www.linkedin.com/in/abhishek-kumar-annamraju/
- Akash - https://www.linkedin.com/in/akashdeepsingh01/
| github_jupyter |
Copyright 2021 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.
# IMPORTS
```
import pandas as pd
from google.colab import files
from google.colab import drive
import google.auth
from google.colab import auth
!pip install gcsfs
import gcsfs
!pip install pymysql
import pymysql
!pip install mysql-connector-python
from sqlalchemy import create_engine
import altair as alt
```
# ACCESSING PUBLIC DATA ONLINE
```
# Load data from the internet
co2_data_csv_url = 'https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv'
df = pd.read_csv(co2_data_csv_url)
# View dataset for exploratory analysis.
df[df.iso_code == 'IND'].tail(-5)
```
# ACCESSING GOOGLE DRIVE
```
# Mounting drive
# This will require authentication : Follow the steps as guided
drive.mount('/content/drive')
# Storing data to Drive.
df.to_json('/content/drive/My Drive/owid_co2_data.json')
```
# ACCESSING GOOGLE CLOUD STORAGE (REQUIRES PROJECT AND GCS BUCKET)
```
# Authenticate with Google Cloud Storage
auth.authenticate_user()
# define cloud project and GCS bucket and folder
project_id = 'ai4sg-template-1'
gcs_bucket_folder = 'ai4sg_bucket/sample_folder'
# Config project
!gcloud config set project {project_id}
# There are 2 ways of doing this - using command line and using gcsfs.
df.to_csv('to_upload.csv') # Create a local file on colab disk.
# Upload this file by invoking the command line utility.
!gsutil cp to_upload.csv gs://{gcs_bucket_folder}/
# Copy file directly from python.
credentials, _ = google.auth.default()
_ = gcsfs.GCSFileSystem(project=gcs_project_id, token=credentials) # setup gcsfs for cloud project and authenticate.
df.to_csv(F'gcs://{gcs_bucket_folder}/direct_upload.csv') # pandas will use gcsfs if file path begins with gcs://
```
# ACCESS CloudSQL (MySQL) DB
```
# ACCESSING MySQL DB hosted on GCP (CloudSQL)
project_id = "ai4sg-template-1"
connection_name = "ai4sg-template-1:us-central1:ai4sg-example-db"
#Setting up gcloud instance
!gcloud auth login
!gcloud config set project $project_id
#Setting up a Cloud SQL Proxy
!wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
!chmod +x cloud_sql_proxy
!nohup ./cloud_sql_proxy -instances=$connection_name=tcp:5432 &
!sleep 30s
# Connecting to DB
# engine = create_engine("mysql+pymysql://<USER>:<PASSWORD>@localhost:5432/<DB>")
engine = create_engine("mysql+pymysql://root:wdKvwgkAb1GLgxvF@localhost:5432/sample_db")
# READ DATA
sql = "SELECT * FROM `sample_table`"
df_sql = pd.read_sql(sql, engine)
df_sql.head()
# CREATE DATA TO WRITE TO DB
df2 = df[['iso_code', 'country', 'year', 'co2']].copy()
df2.head()
# WRITE DATA
table_name = 'owid'
df2.to_sql(name=table_name, con=engine, if_exists='replace')
```
| github_jupyter |
В данной работе использовалась гибридная модель рекомендательной системы SVD++ и SlopeOne, где каждой рекомендательной системе был присвоен вес 0.5
```
import os
import numpy as np
import pandas as pd
from numpy import linalg
from surprise import SlopeOne
from surprise import Reader, Dataset
from surprise import SVDpp
os.chdir('/Recommendation system of films/data')
df = pd.read_csv('ratings.csv', delimiter=',')
df = df.drop(['timestamp'], axis=1)
df.info()
df.describe()
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(15,7))
sns.set(style="darkgrid")
sns.countplot(df['rating'])
real=df.groupby(['rating'])['userId'].count()
real=pd.DataFrame(real)
fig = px.line(real)
fig.show()
real=df.groupby(['rating'])['movieId'].count()
real=pd.DataFrame(real)
fig = px.line(real)
fig.show()
real=df.groupby(['userId'])['rating'].count()
real=pd.DataFrame(real)
fig = px.line(real)
fig.show()
plt.figure(figsize=(15,10))
labels=['0.5','1','1.5','2','2.5','3','3.5','4','4.5','5']
colors = ["SkyBlue","PeachPuff",'lightcoral','gold','indigo','teal','magenta','deeppink','green','gray']
plt.pie(df['rating'].value_counts(),labels=labels,colors=colors,
autopct='%1.2f%%', shadow=True, startangle=140)
plt.show()
df['userId'] = df['userId'].astype(str)
df['movieId'] = df['movieId'].astype(str)
df['userId'] = 'person_'+df['userId'].astype(str)
df['movieId'] = 'movie_'+df['movieId'].astype(str)
df_new=df.copy()
df_new=df_new.rename(columns={"movieId": "userId/movieId"})
df_new = df_new.pivot_table(index=['userId'], columns='userId/movieId', values='rating', aggfunc=np.sum).reset_index()
df_new.index=df_new['userId'].values
df_new=df_new.drop(['userId'], axis=1)
minimum_rating = min(df['rating'].values)
maximum_rating = max(df['rating'].values)
print(minimum_rating,maximum_rating)
reader = Reader(rating_scale=(minimum_rating,maximum_rating))
data = Dataset.load_from_df(df[['userId', 'movieId', 'rating']], reader)
svdplpl = SVDpp(lr_all=0.004, reg_all=0.03)
svdplpl.fit(data.build_full_trainset())
svdplpl = SVDpp(lr_all=0.005, reg_all=0.02)
svdplpl.fit(data.build_full_trainset())
df_svdplpl=df_new.copy()
for user in df_new.index:
for movie in df_new.columns:
if str(df_svdplpl.loc[user, movie])=='nan':
df_svdplpl.at[user, movie] = round(svdplpl.predict(user, movie).est,4)
df_svdplpl
slope = SlopeOne()
slope.fit(data.build_full_trainset())
df_slope_one_new=df_new.copy()
for user in df_new.index:
for movie in df_new.columns:
if str(df_slope_one_new.loc[user, movie])=='nan':
df_slope_one_new.at[user, movie] = round(slope.predict(user, movie).est,4)
df_slope_one_new
df_hybrid = df_svdplpl*0.5 + df_slope_one_new*0.5
df_hybrid
```
| github_jupyter |
## Instructions
This sample code demonstrate how the wrapper function "barotropic_eqlat_lwa" in thepython package "hn2016_falwa" computes the finite-amplitude local wave activity
(LWA) from absolute vorticity fields in a barotropic model with spherical geometry according to the definition in Huang & Nakamura (2016,JAS) equation (13). This
sample code reproduces the LWA plots (Fig.4 in HN15) computed based on an absolute vorticity map.
## Contact
Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues
```
from hn2016_falwa.wrapper import barotropic_eqlat_lwa # Module for plotting local wave activity (LWA) plots and
# the corresponding equivalent-latitude profile
from math import pi
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# --- Parameters --- #
Earth_radius = 6.378e+6 # Earth's radius
# --- Load the absolute vorticity field [256x512] --- #
readFile = Dataset('barotropic_vorticity.nc', mode='r')
# --- Read in longitude and latitude arrays --- #
xlon = readFile.variables['longitude'][:]
ylat = readFile.variables['latitude'][:]
clat = np.abs(np.cos(ylat*pi/180.)) # cosine latitude
nlon = xlon.size
nlat = ylat.size
# --- Parameters needed to use the module HN2015_LWA --- #
dphi = (ylat[2]-ylat[1])*pi/180. # Equal spacing between latitude grid points, in radian
area = 2.*pi*Earth_radius**2 *(np.cos(ylat[:,np.newaxis]*pi/180.)*dphi)/float(nlon) * np.ones((nlat,nlon))
area = np.abs(area) # To make sure area element is always positive (given floating point errors).
# --- Read in the absolute vorticity field from the netCDF file --- #
absVorticity = readFile.variables['absolute_vorticity'][:]
readFile.close()
```
## Obtain equivalent-latitude relationship and also the LWA from an absolute vorticity snapshot
```
# --- Obtain equivalent-latitude relationship and also the LWA from the absolute vorticity snapshot ---
Q_ref,LWA = barotropic_eqlat_lwa(ylat,absVorticity,area,Earth_radius*clat*dphi,nlat) # Full domain included
```
## Plotting the results
```
# --- Color axis for plotting LWA --- #
LWA_caxis = np.linspace(0,LWA.max(),31,endpoint=True)
# --- Plot the abs. vorticity field, LWA and equivalent-latitude relationship and LWA --- #
fig = plt.subplots(figsize=(14,4))
plt.subplot(1,3,1) # Absolute vorticity map
c=plt.contourf(xlon,ylat,absVorticity,31)
cb = plt.colorbar(c)
cb.formatter.set_powerlimits((0, 0))
cb.ax.yaxis.set_offset_position('right')
cb.update_ticks()
plt.title('Absolute vorticity [1/s]')
plt.xlabel('Longitude (degree)')
plt.ylabel('Latitude (degree)')
plt.subplot(1,3,2) # LWA (full domain)
plt.contourf(xlon,ylat,LWA,LWA_caxis)
plt.colorbar()
plt.title('Local Wave Activity [m/s]')
plt.xlabel('Longitude (degree)')
plt.ylabel('Latitude (degree)')
plt.subplot(1,3,3) # Equivalent-latitude relationship Q(y)
plt.plot(Q_ref,ylat,'b',label='Equivalent-latitude relationship')
plt.plot(np.mean(absVorticity,axis=1),ylat,'g',label='zonal mean abs. vorticity')
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
plt.ylim(-90,90)
plt.legend(loc=4,fontsize=10)
plt.title('Equivalent-latitude profile')
plt.ylabel('Latitude (degree)')
plt.xlabel('Q(y) [1/s] | y = latitude')
plt.tight_layout()
plt.show()
```
| github_jupyter |
## 2 Layer Neural network with softmax in the final layer
Meichen Lu (meichenlu91@gmail.com) 13rd April 2018
In this notebook, I will implement a simple 2-layer neural network with softmax. Then it will be tested on the MNIST data set.
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
X = mnist.data.astype(float)
y = mnist.target.astype(float)
m = X.shape[1]
# filter out only 0 and 1 and split data
ind = (y < 2).nonzero()
ind = ind[0]
X = X[ind, :]
n = np.shape(X)[0]
y_vec = np.zeros((n,2))
for i in range(n):
y_vec[i,int(y[ind[i]])] = 1
num_train = int(n * 0.8)
X_train = X[0:num_train, :].T
X_test = X[num_train:-1,:].T
y_train = y_vec[0:num_train].T
y_test = y_vec[num_train:-1].T
X_train = X_train/256
X_test = X_test/256
plt.plot(y_train[0,:])
plt.plot(y_train[1,:])
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def fprop(x, y, params):
W1, b1, W2, b2 = [params[key] for key in ('W1', 'b1', 'W2', 'b2')]
z1 = np.dot(W1, x) + b1
a1 = sigmoid(z1)
z2 = np.dot(W2, a1) + b2
a2 = sigmoid(z2)
loss = 0.5*np.linalg.norm(a2-y, axis = 0)**2
ret = {'x': x, 'y': y, 'z1': z1, 'a1': a1, 'z2': z2, 'a2': a2, 'loss': loss}
for key in params:
ret[key] = params[key]
return ret
def bprop_vec(fprop_cache):
# Follows procedure given in notes
n = len(y_train.T)
x, y, z1, a1, z2, a2, loss = [fprop_cache[key] for key in ('x', 'y', 'z1', 'a1', 'z2', 'a2', 'loss')]
delta2 = np.multiply(a2 - y, a2*(1-a2))
dW2 = np.dot(delta2, a1.T)/n
db2 = np.mean(delta2, 1)
db2 = db2.reshape([-1,1])
# Why W2? Shouldn't it be W1??!!
delta1 = np.dot(fprop_cache['W2'].T, delta2) * a1 * (1-a1)
dW1 = np.dot(delta1, x.T)/n
db1 = np.mean(delta1,1)
db1 = db1.reshape([-1,1])
return {'b1': db1, 'W1': dW1, 'b2': db2, 'W2': dW2}
def initialise_param(m, n, n1, n2):
'''
m features, n samples, first layer with n1 cells, second layer with n2 cells
'''
W1 = np.random.randn(n1, m)
b1 = np.random.randn(n1, 1)
W2 = np.random.randn(n2, n1)
b2 = np.random.randn(n2, 1)
params = {'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2}
return params
def train_net_vec(X_train, Y_train, params, max_iter = 200, alpha = 0.5, verbose = False):
'''
Vectorised neural network training
X_train: size m * n
Y_train: size 1 * n
param: initialsed network
'''
n2 = len(y_train)
cost_hist = np.zeros((max_iter,1))
n_corr_hist = np.zeros((max_iter,1))
for i in range(max_iter):
fprop_cache = fprop(X_train, Y_train, params)
z2 = fprop_cache['z2']
y_hat = np.zeros_like(z2)
y_hat[z2.argmax(0),np.arange(len(z2.T))] = 1
n_correct = np.sum(y_hat == Y_train)/n2
cost_hist[i] = np.mean(fprop_cache['loss'])
n_corr_hist[i] = n_correct
if verbose:
print('At iteration {}, cost is {} with {}/{} correct'.format(i, cost_hist[i], n_correct, n))
bprop_cache = bprop_vec(fprop_cache)
[W1, b1, W2, b2] = [params[key] - alpha*bprop_cache[key] for key in ('W1', 'b1', 'W2', 'b2')]
params = {'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2}
neural_net = {'cost_hist': cost_hist, 'n_corr_hist': n_corr_hist, 'params': params}
return neural_net
params = initialise_param(m, n, n1 = 4, n2 = 2)
neural_net = train_net_vec(X_train, y_train, params, max_iter = 400, alpha = 0.5, verbose = False)
plt.figure(figsize=(12, 4))
plt.subplot(1,2,1)
plt.plot(neural_net['cost_hist'])
plt.subplot(1,2,2)
plt.plot(neural_net['n_corr_hist']/n)
plt.plot([0,len(neural_net['n_corr_hist'])], [1,1], 'k--')
```
This scenario is not as good as the logistic regression. Why?
```
# filter out only 0, 1 ,2
X = mnist.data.astype(float)
y = mnist.target.astype(float)
ind = (y < 3).nonzero()
ind = ind[0]
X = X[ind, :]
n = np.shape(X)[0]
y_vec = np.zeros((n,3))
for i in range(n):
y_vec[i,int(y[ind[i]])] = 1
num_train = int(n * 0.8)
X_train = X[0:num_train, :].T
y_train = y_vec[0:num_train].T
X_train = X_train/256
X_test = X_test/256
params = initialise_param(m, n, n1 = 4, n2 = len(y_train))
neural_net = train_net_vec(X_train, y_train, params, max_iter = 1000, alpha = 1, verbose = False)
plt.figure(figsize=(12, 4))
plt.subplot(1,2,1)
plt.plot(neural_net['cost_hist'])
plt.subplot(1,2,2)
plt.plot(neural_net['n_corr_hist']/n)
plt.plot([0,len(neural_net['n_corr_hist'])], [1,1], 'k--')
```
| github_jupyter |
# Starbucks Capstone Challenge
### Introduction
This data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BOGO (buy one get one free). Some users might not receive any offer during certain weeks.
Not all users receive the same offer, and that is the challenge to solve with this data set.
Your task is to combine transaction, demographic and offer data to determine which demographic groups respond best to which offer type. This data set is a simplified version of the real Starbucks app because the underlying simulator only has one product whereas Starbucks actually sells dozens of products.
Every offer has a validity period before the offer expires. As an example, a BOGO offer might be valid for only 5 days. You'll see in the data set that informational offers have a validity period even though these ads are merely providing information about a product; for example, if an informational offer has 7 days of validity, you can assume the customer is feeling the influence of the offer for 7 days after receiving the advertisement.
You'll be given transactional data showing user purchases made on the app including the timestamp of purchase and the amount of money spent on a purchase. This transactional data also has a record for each offer that a user receives as well as a record for when a user actually views the offer. There are also records for when a user completes an offer.
Keep in mind as well that someone using the app might make a purchase through the app without having received an offer or seen an offer.
### Example
To give an example, a user could receive a discount offer buy 10 dollars get 2 off on Monday. The offer is valid for 10 days from receipt. If the customer accumulates at least 10 dollars in purchases during the validity period, the customer completes the offer.
However, there are a few things to watch out for in this data set. Customers do not opt into the offers that they receive; in other words, a user can receive an offer, never actually view the offer, and still complete the offer. For example, a user might receive the "buy 10 dollars get 2 dollars off offer", but the user never opens the offer during the 10 day validity period. The customer spends 15 dollars during those ten days. There will be an offer completion record in the data set; however, the customer was not influenced by the offer because the customer never viewed the offer.
### Cleaning
This makes data cleaning especially important and tricky.
You'll also want to take into account that some demographic groups will make purchases even if they don't receive an offer. From a business perspective, if a customer is going to make a 10 dollar purchase without an offer anyway, you wouldn't want to send a buy 10 dollars get 2 dollars off offer. You'll want to try to assess what a certain demographic group will buy when not receiving any offers.
# Data Sets
The data is contained in three files:
* portfolio.json - containing offer ids and meta data about each offer (duration, type, etc.)
* profile.json - demographic data for each customer
* transcript.json - records for transactions, offers received, offers viewed, and offers completed
Here is the schema and explanation of each variable in the files:
**portfolio.json**
* id (string) - offer id
* offer_type (string) - type of offer ie BOGO, discount, informational
* difficulty (int) - minimum required spend to complete an offer
* reward (int) - reward given for completing an offer
* duration (int) - time for offer to be open, in days
* channels (list of strings)
**profile.json**
* age (int) - age of the customer
* became_member_on (int) - date when customer created an app account
* gender (str) - gender of the customer (note some entries contain 'O' for other rather than M or F)
* id (str) - customer id
* income (float) - customer's income
**transcript.json**
* event (str) - record description (ie transaction, offer received, offer viewed, etc.)
* person (str) - customer id
* time (int) - time in hours since start of test. The data begins at time t=0
* value - (dict of strings) - either an offer id or transaction amount depending on the record
# Problem Statement
* We will be exploring the Starbuck’s Dataset which simulates how people make purchasing decisions and how those decisions are influenced by promotional offers.
* There are three types of offers that can be sent: buy-one-get-one (BOGO), discount, and informational. In a BOGO offer, a user needs to spend a certain amount to get a reward equal to that threshold amount. In a discount, a user gains a reward equal to a fraction of the amount spent. In an informational offer, there is no reward, but neither is there a required amount that the user is expected to spend. Offers can be delivered via multiple channels.
* We will aim to find an answer to the following questions in this notebook.
1. What is the proportion of client who have completed the offers based on Gender?
2. What is the proportion of client who have completed the offers based on their Age?
3. What is the proportion of client who have completed the offers based on their Income Level?
3. What are the most important features that help drive the offers in customers?
## Strategy
* First, I will wrangle and combine the data from offer portfolio, customer profile, and transaction. After which I can merge all the table into one for analysis.
* Secondly, I will work on visualization to provide answers to the questions 1 and 2.
* Finally, I will move on to find the important feature driver for the offers. I plan to test out few models(like, Decision Tree Classifier, Gaussian NB and Random Forest Classifier) before applying one as a fixed solution and provide visualization for the important feature drivers.
## Metrics
I will use accuracy and F-score metrics for comparision and to test out the performance of the models.
Accuracy measures how well a model correctly predicts whether an offer is successful. However, if the percentage of successful or unsuccessful offers is very low, accuracy is not a good measure of model performance. For this situation, evaluating a models' precision and recall provides better insight to its performance. I chose the F1-score metric because it is "a weighted average of the precision and recall metrics".
## Table of Contents
* ### [Table Exploration(Portfolio, Profile, Transcript)](#tableexp)
* ### [Data Cleaning for Tables](#dataclean)
* ### [Preparing Table for analysis](#preptable)
* ### [Data Exploration](#dataexp)
* ### [Evaluating Model](#evmodel)
* ### [Conclusion](#conclusion)
## Importing
```
import sys
!{sys.executable} -m pip install progressbar
print(sys.version)
import pandas as pd
import numpy as np
import progressbar
import math
import json
import seaborn as sns
import matplotlib.pyplot as plt
% matplotlib inline
from sklearn.metrics import fbeta_score, accuracy_score, f1_score
from time import time
import matplotlib.pyplot as pl
import matplotlib.patches as mpatches
# read in the json files
portfolio = pd.read_json('Data/portfolio.json', orient='records', lines=True)
profile = pd.read_json('Data/profile.json', orient='records', lines=True)
transcript = pd.read_json('Data/transcript.json', orient='records', lines=True)
portfolio.shape, profile.shape, transcript.shape
```
<a name="tableexp"></a>
# <span style="color:blue"> Table Exploration (Portfolio, Profile, Transcript)</span>
## Portfolio
```
portfolio
portfolio.info()
ax = portfolio["offer_type"].value_counts().plot.bar(
figsize=(5,5),
fontsize=14,
)
ax.set_title("What are the offer types?", fontsize=20)
ax.set_xlabel("Offers", fontsize=15)
ax.set_ylabel("Frequency", fontsize=15)
sns.despine(bottom=True, left=True)
```
We can see from above that the portfolio table consists of 10 not-null entries that contains information about the offers provided by starbucks. It has channels through which the specific offers are deployed which consists of elements in a list, which has to be handled later in the process.
Finally, We can see a histogram containing a distribution of 3 offer types totalling in 10 entries.
This table needs to be cleaned, which will be done in the next phase.
## Profile
```
profile.head()
profile.info()
```
---
```
#Creating Subplots for distribution based on Gender,Age and Income
sns.set_style('darkgrid')
fig,ax= plt.subplots(1,3,sharex=False, sharey=False,figsize=(12,5))
fig.tight_layout()
# GENDER BASED
profile.gender.value_counts().plot.bar(ax=ax[0],fontsize=10)
ax[0].set_title("Distribution Gender Wise", fontsize=15,color='blue')
ax[0].set_xlabel("Gender", fontsize=10)
ax[0].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
# AGE BASED
profile.age.plot.hist(ax=ax[1],fontsize=10,edgecolor='black')
ax[1].set_title("Distribution Age Wise", fontsize=15,color='blue')
ax[1].set_xlabel("Age", fontsize=10)
ax[1].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
# INCOME BASED
profile.income.plot.hist(ax=ax[2],fontsize=10,edgecolor='black',range=(20000, 120000))
ax[2].set_title("Distribution Income Wise", fontsize=15,color='blue')
ax[2].set_xlabel("Income", fontsize=10)
ax[2].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
plt.show()
```
We can see from above that the profile table consists of 17000 entries with some null elements in the columns gender and income.
Also, from the dashboard above we can see the distribution of the members according to the gender, age and income.
We can also see that in respect to the distribution according to the gender, frequency of male is more than the female with little population towards others.
Secondly, while looking at age wise distribution it is evident that the age group from 50-70 is the highest.
Finally, while looking at the income wise distribution, member with income ranging from 40k- 80k are high than others.
We need to clean this profile table as it contains nll values as well as age value oof 118 which has a lot of frequency and it is due to some data entry error.
## Transcript
```
transcript.head()
transcript.info()
```
We can see that this table consists of 306534 entries which is all populated and contains no null values. However, this table needs to be cleaned and offer should be extracted based on the id while simulataneously classifying it based on the completion,view, and received. This will be done in the data cleaning phase.
---
<a name="dataclean"></a>
# <span style="color:blue"> Data Cleaning for Tables </span>
## Data Cleaning for Portfolio
```
def clean_portfolio(df=portfolio):
"""
Takes the dataframe portfolio and cleans it by creating one-hot encodings.
PARAMETERS:
portfolio dataframe
RETURNS:
A new dataframe consisting of:
- One-hot encoded channels column
- One-hot encoded offer_type column
["id", "difficulty", "duration", "reward", "email", "mobile", "social", "web", "bogo", "discount", "informational"]
"""
# One-hot encode channels column
# https://stackoverflow.com/questions/18889588/create-dummies-from-column-with-multiple-values-in-pandas
channels = portfolio["channels"].str.join(sep="*").str.get_dummies(sep="*")
# One-hot encode offer_type column
offer_type = pd.get_dummies(portfolio['offer_type'])
# Concat one-hot and df
new_df = pd.concat([df, channels, offer_type], axis=1, sort=False)
# Remove channels and offer_type
new_df = new_df.drop(['channels', 'offer_type'], axis=1)
# Organize columns
columns = ["id", "difficulty", "duration", "reward", "email", "mobile", "social", "web", "bogo", "discount", "informational"]
new_df = new_df[columns]
return new_df
cleaned_portfolio= clean_portfolio()
cleaned_portfolio
```
## Data Cleaning for Profile
```
def clean_profile(profile = profile):
"""
Takes the dataframe profile and cleans it by creating one-hot encodings as well as handling null values and error age value 118.
PARAMETERS:
Profile dataframe.
RETURNS:
A new dataframe whithout income values iqual to null and age iqual to 118 as well as one hot encoded columns.
"""
# drop lines with income = nan and age == 118
new_df = profile.drop(profile[(profile["income"].isnull()) & (profile["age"] == 118)].index)
# One-hot encode Gender column
gender_dummies = pd.get_dummies(new_df["gender"])
# Specifying age range and one hot encoding
range_ages = pd.cut(x=new_df["age"], bins=[18, 20, 29, 39, 49, 59, 69, 79, 89, 99, 102])
# One-hot encode ages column
ages_dummies = pd.get_dummies(range_ages)
# Specifying income range and one hot encoding
range_income = pd.cut(x=new_df["income"], bins=[30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000, 110000, 120000])
income_dummies = pd.get_dummies(range_income)
# Concat
new_df = pd.concat([new_df, ages_dummies, income_dummies, gender_dummies], axis=1, sort=False)
# Dropping age,gender,income column
new_df = new_df.drop(["age", "gender", "income"], axis=1)
return new_df
cleaned_profile = clean_profile()
cleaned_profile.head(10)
cleaned_profile.info()
#Creating Subplots for distribution based on Gender,Age and Income for the Newly cleaned Profile data
sns.set_style('darkgrid')
fig,ax= plt.subplots(1,3,sharex=False, sharey=False,figsize=(12,5))
fig.tight_layout()
# GENDER BASED
cleaned_profile[cleaned_profile.columns[21:]].sum().plot.bar(ax=ax[0],fontsize=10)
ax[0].set_title("Cleaned-Distribution Gender Wise", fontsize=15,color='blue')
ax[0].set_xlabel("Gender", fontsize=10)
ax[0].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
# AGE BASED
cleaned_profile[cleaned_profile.columns[2:12]].sum().plot.bar(ax=ax[1],fontsize=10)
ax[1].set_title("Cleaned-Distribution Age Wise", fontsize=15,color='blue')
ax[1].set_xlabel("Age", fontsize=10)
ax[1].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
# INCOME BASED
cleaned_profile[cleaned_profile.columns[12:21]].sum().plot.bar(ax=ax[2],fontsize=10)
ax[2].set_title("Cleaned- Distribution Income Wise", fontsize=15,color='blue')
ax[2].set_xlabel("Income", fontsize=10)
ax[2].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
plt.show()
```
We can see the result of the profile charts displayed above after the table has been cleaned.
## Data Cleaning for Transcript
The transcript table consists of value columns which comprises of dictionary values in which the keys are offer id, amount. We need to first extract these keys before we move on to one hot encoding them.
```
# Functions to create offer id and amount columns from the transcript table.
def create_offer_id_column(val):
if list(val.keys())[0] in ['offer id', 'offer_id']:
return list(val.values())[0]
def create_amount_column(val):
if list(val.keys())[0] in ["amount"]:
return list(val.values())[0]
def clean_transcript(transcript = transcript):
"""
Cleans the Transcript table by setting one hot encoding values.
PARAMETERS:
transcript dataframe
RETURNS:
Cleaned transcript dataframe
"""
#
transcript['offer_id'] = transcript.value.apply(create_offer_id_column)
transcript['amount'] = transcript.value.apply(create_amount_column)
# One-hot encode event column
event = pd.get_dummies(transcript['event'])
# Concat one-hot and df
new_df = pd.concat([transcript, event], axis=1, sort=False)
# Create and Drop Transaction
transaction = new_df[new_df["transaction"]==1]
new_df = new_df.drop(transaction.index)
# Drop
new_df = new_df.drop(columns = ["event","value", "amount", "transaction"])
return new_df
cleaned_transcript = clean_transcript()
cleaned_transcript.head(10)
cleaned_transcript.info()
cleaned_transcript[cleaned_transcript['offer completed']==1].shape
```
<a name="preptable"></a>
# <span style="color:blue"> Preparing Table for Analysis </span>
In order to perform our analysis, we now combine all the tables first before computing anything. The tables cannot be combined directly so we need to perform some operations beforehand.
```
def concat_tables():
# Rename column name id with offer_id
new_portfolio = cleaned_portfolio.rename(columns={"id": "offer_id" })
# Merge cleaned portfolio and transcript
final_transcript = cleaned_transcript.merge(new_portfolio[new_portfolio.columns])
# Rename column id with person to merge with transcript
new_profile = cleaned_profile.rename(columns={"id": "person" })
# Merge profile with transcript on person column
final_transcript = final_transcript.merge(new_profile[new_profile.columns])
# Rename columns on final transcript.
columns_names = ['person', 'time', 'offer_id', 'offer completed', 'offer received',' offer viewed',
'difficulty', 'duration', 'reward', 'email', 'mobile', 'social', 'web', 'bogo', 'discount', 'informational','became_member_on',
"18-20", "20-29", "29-39", "39-49", "49-59", "59-69", "69-79", "79-89", "89-99", "99-102", "30-40K", "40-50K", "50-60K",
"60-70K", "70-80K", "80-90K", "90-100K", "100-110K", "110-120K",
'F', 'M', 'O']
final_transcript.columns = columns_names
# Reorganize columns
cols_order = ['person', 'offer_id', 'time',
'difficulty', 'duration', 'reward', 'email', 'mobile', 'social', 'web', 'bogo', 'discount', 'informational',
'became_member_on',
"18-20", "20-29", "29-39", "39-49", "49-59", "59-69", "69-79", "79-89", "89-99", "99-102", 'F', 'M', 'O',
"30-40K", "40-50K", "50-60K", "60-70K", "70-80K", "80-90K", "90-100K", "100-110K", "110-120K",
'offer received',' offer viewed', 'offer completed'
]
return final_transcript[cols_order]
final_df = concat_tables()
final_df.head()
final_df.info()
final_df.shape
```
<a name="dataexp"></a>
# <span style="color:blue">Data Exploration </span>
```
# Total number of records
n_records = len(final_df.index)
# Number of records where offer completed is equal to 1
completed_1 = final_df[final_df["offer completed"] == 1].shape[0]
# Number of records where offer completed is equal to 0
completed_0 = final_df[final_df["offer completed"] == 0].shape[0]
# TODO: Percentage of offer completed
percent_completed = (completed_1 / completed_0) * 100
# Print the results
print("Total number of records: {}".format(n_records))
print("Individuals that completed offers: {}".format(completed_1))
print("Individuals that did not complete offers: {}".format(completed_0))
print("Percentage of individuals that completed offers: {0:.2f}%".format(percent_completed))
```
### Feature Description
Lets take a final look at what our column in the dataframe means before answering our Primary questions.
* person - Customer id
* offer_id - Offer Registration ID of customers
* time - Time since start of the test. The data begins at time t=0 and is displayed in HOURS
* difficulty - Minimum required spend to complete an offer
* duration - Time for offer to be open, in DAYS
* reward - Reward given for completing an offer
* email, mobile, social, web - Channel where offer was offered
* bogo(buy-one-get-one) , informational, discount - types of offer.
* became_member_on - date when customer created an app account
* 18-102 - Age range of Customers
* F, M , O - Gender of Customers
* 30k- 120k -- Client Income Range
* Offer recieved- Description
* Offer Viewed- Description
* Offer completed- Target Feature
```
#Creating Subplots for distribution based on Gender,Age and Income for the Newly cleaned Profile data
sns.set_style('darkgrid')
my_color= ['b', 'r', 'g', 'y', 'k']
fig,ax= plt.subplots(1,3,figsize=(12,5))
fig.tight_layout()
# GENDER BASED
final_df[final_df['offer completed']==1][['F','M','O']].sum().plot.bar(ax=ax[0],fontsize=10,color=my_color)
ax[0].set_title(" Offer Completed Gender Wise", fontsize=15,color='blue')
ax[0].set_xlabel("Gender", fontsize=10)
ax[0].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
# AGE BASED
age_cols=['18-20','20-29', '29-39', '39-49', '49-59', '59-69', '69-79', '79-89', '89-99','99-102']
final_df[final_df['offer completed']==1][age_cols].sum().plot.bar(ax=ax[1],fontsize=10,color=my_color)
ax[1].set_title("Offer Completed Age Wise", fontsize=15,color='blue')
ax[1].set_xlabel("Age", fontsize=10)
ax[1].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
# INCOME BASED
income_cols=['30-40K', '40-50K', '50-60K', '60-70K','70-80K', '80-90K', '90-100K', '100-110K','110-120K']
final_df[final_df['offer completed']==1][income_cols].sum().plot.bar(ax=ax[2],fontsize=10,color=my_color)
ax[2].set_title("Offer Completed Income Wise", fontsize=15,color='blue')
ax[2].set_xlabel("Income", fontsize=10)
ax[2].set_ylabel("Frequency", fontsize=10)
sns.despine(bottom=True, left=True)
plt.show()
```
From the above charts we can see that the offers that are completed is distributed across Gender, Age and Income.
1. Based on the Gender, Male category has completed the most offers with frequency abit above 16000 and Female category is close to 16000 and the other category has the minimum with near 1000. So, lets focus on male and female because their frequency is very high as compared to others.
2. Based on the Age group, the age range of 49-59 is most active while completing the offers followed by 59-69 and 39-49 age range.
3. Based on the Income level, people with income ranging fromm 50-80k are the most active ones to complete offers.
Now, to get a proper idea about the proportion of these distribution we will extract and compute the above data
#### In order to compute the proportion of male or female within the age range of 29 to 69 with income ranging from 30k to 100k who have commpleted the offer, we need their respective data and the total number of participants in the test.
#### After that we can compute the proportion as:
```
# Finding male profile with age 39-69 and age 30k -100k
male_data= profile[(profile['gender']=='M')& (profile['age']>29)& (profile['age']<69) & (profile['income']>30000)\
& (profile['income']<100000)]
female_data= profile[(profile['gender']=='F')& (profile['age']>29)& (profile['age']<69) & (profile['income']>30000)\
& (profile['income']<100000)]
male_data.shape, female_data.shape
# Appending Both together
merged_mf = male_data.append(female_data)
idx=[]
for person in merged_mf['id']:
ids= final_df[final_df['person']==person].index.tolist()
idx.extend(ids)
percentage = len(idx) * 100 / final_df.shape[0]
print("The clients who have completed the offer are male or female with age range from 29-69 and incomme range between 30,000- 100,000 and their proportion is {0:.2f}%.".format(percentage))
```
# <span style="color:blue">Data preparation for the Model </span>
Before I had speculated that there might be some sort of logical transitions in the operations of the offers which goes like, the customer recieves the offer, views the offer and then completes the offer. But, there does not seem to be any relation between them.
Also as seen in the project description above:
##### There might be a case that someone using the app might make a purchase through the app without having received an offer or seen an offer.
```
final_df[final_df["offer completed"] == 1][["offer received", ' offer viewed', 'informational']].sum()
# Since we are interested in offer completion , lets remove other attributes before going on to creaate a model
final_df = final_df.drop(["offer received", ' offer viewed', 'informational', "became_member_on"], axis=1)
# Lets Split the data into feaure and target label
target = final_df['offer completed']
features = final_df.drop('offer completed', axis = 1)
print(" Number of total features: {} ".format(len(features.columns)))
features.head()
```
## Normalize Numerical Features
```
from sklearn.preprocessing import MinMaxScaler
# Initialize a scaler, then apply it to the features
scaler = MinMaxScaler() # default=(0, 1)
numericals = features.columns[2:6]
features_log_minmax_transform = pd.DataFrame(data = features)
features_log_minmax_transform[numericals] = scaler.fit_transform(features[numericals])
# Show an example of a record with scaling applied
display(features_log_minmax_transform.head(n = 5))
features_final = features_log_minmax_transform[features_log_minmax_transform.columns[2:]]
features_final.head()
```
#### Now that we have normalized the numerical values, we can move forward to splitting the data into training and testing samples.
```
from sklearn.model_selection import train_test_split
# Split the 'features' and 'income' data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features_final,
target,
test_size = 0.20,
random_state = 42,
stratify=target)
# Display result after splitting..
print("results of the split\n------")
print("Training set has {} samples.".format(X_train.shape[0]))
print("Testing set has {} samples.".format(X_test.shape[0]))
print("\nclass distribution\n------")
print('y_train class distribution')
print(y_train.value_counts(normalize=True))
print('y_test class distribution')
print(y_test.value_counts(normalize=True))
```
<a name="evmodel"></a>
# <span style="color:blue">Evaluating Model </span>
### Naive Predictor:
```
accuracy = accuracy_score(y_train,np.ones(len(y_train)))
fscore = fbeta_score(y_train,np.ones(len(y_train)), beta=0.5)
# Print the results
print("Naive Predictor: [Accuracy score: {:.4f}, fscore: {:.4f}]".format(accuracy, fscore))
```
#### Constructing Training and Prediction Pipeline
```
def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
'''
Takes a learning algorithm and uses it to train and predict the samples and returns the performance.
PARAMETERS:
- learner: the learning algorithm to be trained and predicted on
- sample_size: the size of samples (number) to be drawn from training set
- X_train: features training set
- y_train: label training set
- X_test: features testing set
- y_test: label testing set
RETURNS
Performance results for the learning algorithm.
'''
results = {}
# Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])
start = time() # Get start time
learner = learner.fit(X_train[:sample_size], y_train[:sample_size])
end = time() # Get end time
# Calculate the training time
results['train_time'] = end - start
# Get the predictions on the test set(X_test),
# then get predictions on the first 300 training samples(X_train) using .predict()
start = time() # Get start time
predictions_test = learner.predict(X_test)
predictions_train = learner.predict(X_train[:300])
end = time() # Get end time
# Calculate the total prediction time
results['pred_time'] = end - start
# Compute accuracy on the first 300 training samples which is y_train[:300]
results['acc_train'] = accuracy_score(y_train[:300], predictions_train)
# Compute accuracy on test set using accuracy_score()
results['acc_test'] = accuracy_score(y_test, predictions_test)
# Compute F-score on the the first 300 training samples using fbeta_score()
#results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5)
results['f_train'] = f1_score(y_train[:300], predictions_train)
# TODO: Compute F-score on the test set which is y_test
#results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5)
results['f_test'] = f1_score(y_train[:300], predictions_train)
# Success
print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size))
# Return the results
return results
```
#### Initial Model Evaluation
```
def evaluate(results, accuracy, f1):
"""
Uses performance of various learning algorithms to produce visualizations.
PARAMETERS:
- learners: a list of supervised learners
- stats: a list of dictionaries of the statistic results from 'train_predict()'
- accuracy: The score for the naive predictor
- f1: The score for the naive predictor
RETURNS:
NONE
"""
# Create figure
fig, ax = pl.subplots(2, 3, figsize = (11,7))
# Constants
bar_width = 0.3
colors = ['#66FFB2','#CCCC00','#9B3510']
# Super loop to plot four panels of data
for k, learner in enumerate(results.keys()):
for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']):
for i in np.arange(3):
# Creative plot code
ax[j//3, j%3].bar(i+k*bar_width, results[learner][i][metric], width = bar_width, color = colors[k])
ax[j//3, j%3].set_xticks([0.45, 1.45, 2.45])
ax[j//3, j%3].set_xticklabels(["1%", "10%", "100%"])
ax[j//3, j%3].set_xlabel("Training Set Size")
ax[j//3, j%3].set_xlim((-0.1, 3.0))
# Add unique y-labels
ax[0, 0].set_ylabel("Time (in seconds)")
ax[0, 1].set_ylabel("Accuracy Score")
ax[0, 2].set_ylabel("F-score")
ax[1, 0].set_ylabel("Time (in seconds)")
ax[1, 1].set_ylabel("Accuracy Score")
ax[1, 2].set_ylabel("F-score")
# Add titles
ax[0, 0].set_title("Model Training")
ax[0, 1].set_title("Accuracy Score on Training Subset")
ax[0, 2].set_title("F-score on Training Subset")
ax[1, 0].set_title("Model Predicting")
ax[1, 1].set_title("Accuracy Score on Testing Set")
ax[1, 2].set_title("F-score on Testing Set")
# Add horizontal lines for naive predictors
ax[0, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
ax[1, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
ax[0, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
ax[1, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
# Set y-limits for score panels
ax[0, 1].set_ylim((0, 1))
ax[0, 2].set_ylim((0, 1))
ax[1, 1].set_ylim((0, 1))
ax[1, 2].set_ylim((0, 1))
# Create patches for the legend
patches = []
for i, learner in enumerate(results.keys()):
patches.append(mpatches.Patch(color = colors[i], label = learner))
pl.legend(handles = patches, bbox_to_anchor = (-.80, 2.53), \
loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large')
# Aesthetics
pl.suptitle("Performance Metrics for Three Supervised Learning Models", fontsize = 16, y = 1.10)
pl.tight_layout()
pl.show()
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
# Initializing the three models
clf_A = DecisionTreeClassifier(random_state =42) #DecisionTree
clf_B = GaussianNB() #NainveBayes
# n_estimators=10 is a default parameter. Necessary for not error message.
clf_C = RandomForestClassifier(random_state =42, n_estimators=10) #EnsembleMethods
# TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data
samples_100 = int(len(y_train))
samples_10 = int((samples_100 * 10/100))
samples_1 = int((samples_100 * 1)/100)
# Collect results on the learners
results = {}
for clf in [clf_A, clf_B, clf_C]:
clf_name = clf.__class__.__name__
results[clf_name] = {}
for i, samples in enumerate([samples_1, samples_10, samples_100]):
results[clf_name][i] = \
train_predict(clf, samples, X_train, y_train, X_test, y_test)
# Run metrics visualization for the three supervised learning models chosen
evaluate(results, accuracy, fscore)
```
### Model Tuning
```
from sklearn.metrics import precision_score
from sklearn.metrics import make_scorer
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
# Initialize the classifier
clf = RandomForestClassifier(random_state =42, n_estimators=20)
# Create the parameters list you wish to tune, using a dictionary if needed.
parameters = {'max_features':['auto', 'sqrt'], 'min_samples_leaf':[2,4,6,8,10], 'min_samples_split':[2,4,6,8,10]}
# Make an fbeta_score scoring object using make_scorer()
beta= 0.01
#scorer = make_scorer(fbeta_score, beta=beta)
scorer = make_scorer(precision_score)
# Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()
grid_obj = GridSearchCV(clf, parameters, cv=3, scoring=scorer)
# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()
grid_fit = grid_obj.fit(X_train, y_train)
# Get the estimator
best_clf = grid_fit.best_estimator_
# Make predictions using the unoptimized and model
predictions = (clf.fit(X_train, y_train)).predict(X_test)
best_predictions = best_clf.predict(X_test)
# Report the before-and-afterscores
print("Unoptimized model\n------")
print("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = beta)))
print("\nOptimized Model\n------")
print("Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print("Final F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = beta)))
# Print a Confusion Matrix
from sklearn.metrics import confusion_matrix
tn, fp, fn, tp = conf_mtx = confusion_matrix(y_test, best_predictions).ravel()
con_mtx = np.array([[tp, fn],[fp, tn]])
con_mtx
from sklearn.metrics import precision_recall_fscore_support
precision, recall, support, nada = precision_recall_fscore_support(y_test, best_predictions, average='binary', pos_label=1)
print(f"The precision of model is {precision:0.4f}.")
print(f"The recall of model is {recall:0.4f}.")
```
Our goal is a model with better accuracy, for optimization of offer.
* When we obtain a false Positive and we send offers to those who will not respond to complete the offer, this scenario is worth it for the offer.
* When we have a false negative and we do not send offers to those who will complete the offer even if they do not receive the offer, this is accepted as they can complete the offer either way.
With better precision, we have better optimization in sending offers to customers.
#### Lets plot a proper confusion matrix to get a visual idea of the results
```
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
cmap=None,
normalize=True):
"""
Provided a sklearn confusion matrix, visualizes the matrix.
PARAMETERS
---------
cm: confusion matrix from sklearn.metrics.confusion_matrix
target_names: given classification classes such as [0, 1, 2]
the class names, for example: ['high', 'medium', 'low']
title: the text to display at the top of the matrix
cmap: the gradient of the values displayed from matplotlib.pyplot.cm
see http://matplotlib.org/examples/color/colormaps_reference.html
plt.get_cmap('jet') or plt.cm.Blues
normalize: If False, plot the raw numbers
If True, plot the proportions
Usage
-----
plot_confusion_matrix(cm = cm, # confusion matrix created by
# sklearn.metrics.confusion_matrix
normalize = True, # show proportions
target_names = y_labels_vals, # list of names of the classes
title = best_estimator_name) # title of graph
Citiation
---------
http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
"""
import matplotlib.pyplot as plt
import numpy as np
import itertools
accuracy = np.trace(cm) / float(np.sum(cm))
misclass = 1 - accuracy
if cmap is None:
cmap = plt.get_cmap('Wistia')
plt.figure(figsize=(8, 6))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
if target_names is not None:
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if normalize:
plt.text(j, i, "{:0.4f}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
else:
plt.text(j, i, "{:,}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
plt.show()
plot_confusion_matrix(cm = con_mtx,
normalize = False,
target_names = ['positive', 'negative'],
title = "Confusion Matrix")
```
From the above, confusion matrix shows that we have a low false positive number. which indicates a low number of offer submissions to customers who will not complete the offer.
Also, False negative is high, So we could stop sending promotions to anyone who would complete the offer without even receiving the offer.
##### Lets view the best classifier that demonstrated this performance
```
best_clf
```
We can see that the Random Forest classifier performed the best among the three classifiers.
---
## Feature Importance
```
def feature_plot(importances, X_train, y_train, n=5):
# Display the five most important features
indices = np.argsort(importances)[::-1]
columns = X_train.columns.values[indices[:n]]
values = importances[indices][:n]
# Creat the plot
fig = pl.figure(figsize = (12,6))
pl.title(f"Normalized Weights for First {n} Predictive Features", fontsize = 16)
pl.bar(np.arange(n), values, width = 0.6, align="center", color = '#E26741', \
label = "Feature Weight")
pl.bar(np.arange(n) - 0.3, np.cumsum(values), width = 0.2, align = "center", color = '#8E1FEF', \
label = "Cumulative Feature Weight")
pl.xticks(np.arange(n), columns)
#pl.xlim((-0.5, 4.5))
pl.ylabel("Weight", fontsize = 12)
pl.xlabel("Feature", fontsize = 12)
pl.legend(loc = 'upper left')
pl.tight_layout()
sns.despine(bottom=True, left=True)
pl.show()
# Import a supervised learning model that has 'feature_importances_'
# Train the supervised model on the training set using .fit(X_train, y_train)
model = best_clf.fit(X_train, y_train)
# Extract the feature importances using .feature_importances_
importances = model.feature_importances_
# Plot
feature_plot(importances, X_train, y_train, 5)
```
##### From the above graph we can see that our supervised model predicted TOP 5 features that would determine if the offer would be completed by the customers.
* Time, Duration , Reward, Difficulty and Discount are the top 5 feature drivers that estimate the offer completion.
* We need to be aware that the age range and income of cutomers are not much of a factor since they are divided into ranges but would produce more significant effect on feature drivers had it been taken as a whole. But then again, the features above obtained are primarily realted to the offers which is not the same case for age range and income range.
<a name="conclusion"></a>
# <span style="color:blue">Conclusion </span>
### Reflections
During this Udacity Capstone project from Starbucks data, we worked with 3 data files in form of json that consists of portfolio data, profile data and transcript data.
We explored the Starbuck’s Dataset which simulates how people make purchasing decisions and how those decisions are influenced by promotional offers.(Buy one get one, Discount and informational).
* Our focus during this project was on answering the following questions.
1. What is the proportion of client who have completed the offers based on Gender?
2. What is the proportion of client who have completed the offers based on their Age?
3. What is the proportion of client who have completed the offers based on their Income Level?
4. What are the most important features that help drive the offers in customers?
We began this project by first exploring, cleaning the data, merging the three data before proceeding to find answers to our primarily driven queries.
##### For (Q1-Q3), the first 3 questions we found out that: "The clients who have completed the offer are male or female with age range from 29-69 and incomme range between 30,000- 100,000 and their proportion is 62.35%. "
#### For (Q4) we found out that Time, Duration , Reward, Difficulty and Discount are the top 5 feature drivers that estimate the offer completion with Time being the highest impact driver for features.
#### During the process, Creating a supervised model part was especially challenging. Creating the 3 models(Decision Tree Classifier, Gaussian NB and Random Forest Classifier) to aid in prediction of the feature was a challenging yet intriguing step. We compared the performances of these models and found out that Random Forest Works best in this particular scenario.
---
### Future Improvements
* This data set has more potential to solving many queries and it can be utilized to answer many posed questions related customer interaction based on the Age and income as a whole too.
* Testing additional machine learning models.
* Making a web app.
| github_jupyter |
```
%matplotlib inline
```
# Hashing feature transformation using Totally Random Trees
RandomTreesEmbedding provides a way to map data to a
very high-dimensional, sparse representation, which might
be beneficial for classification.
The mapping is completely unsupervised and very efficient.
This example visualizes the partitions given by several
trees and shows how the transformation can also be used for
non-linear dimensionality reduction or non-linear classification.
Points that are neighboring often share the same leaf of a tree and therefore
share large parts of their hashed representation. This allows to
separate two concentric circles simply based on the principal components
of the transformed data with truncated SVD.
In high-dimensional spaces, linear classifiers often achieve
excellent accuracy. For sparse binary data, BernoulliNB
is particularly well-suited. The bottom row compares the
decision boundary obtained by BernoulliNB in the transformed
space with an ExtraTreesClassifier forests learned on the
original data.
```
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
from sklearn.ensemble import RandomTreesEmbedding, ExtraTreesClassifier
from sklearn.decomposition import TruncatedSVD
from sklearn.naive_bayes import BernoulliNB
# make a synthetic dataset
X, y = make_circles(factor=0.5, random_state=0, noise=0.05)
# use RandomTreesEmbedding to transform data
hasher = RandomTreesEmbedding(n_estimators=10, random_state=0, max_depth=3)
X_transformed = hasher.fit_transform(X)
# Visualize result after dimensionality reduction using truncated SVD
svd = TruncatedSVD(n_components=2)
X_reduced = svd.fit_transform(X_transformed)
# Learn a Naive Bayes classifier on the transformed data
nb = BernoulliNB()
nb.fit(X_transformed, y)
# Learn an ExtraTreesClassifier for comparison
trees = ExtraTreesClassifier(max_depth=3, n_estimators=10, random_state=0)
trees.fit(X, y)
# scatter plot of original and reduced data
fig = plt.figure(figsize=(9, 8))
ax = plt.subplot(221)
ax.scatter(X[:, 0], X[:, 1], c=y, s=50, edgecolor='k')
ax.set_title("Original Data (2d)")
ax.set_xticks(())
ax.set_yticks(())
ax = plt.subplot(222)
ax.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, s=50, edgecolor='k')
ax.set_title("Truncated SVD reduction (2d) of transformed data (%dd)" %
X_transformed.shape[1])
ax.set_xticks(())
ax.set_yticks(())
# Plot the decision in original space. For that, we will assign a color
# to each point in the mesh [x_min, x_max]x[y_min, y_max].
h = .01
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# transform grid using RandomTreesEmbedding
transformed_grid = hasher.transform(np.c_[xx.ravel(), yy.ravel()])
y_grid_pred = nb.predict_proba(transformed_grid)[:, 1]
ax = plt.subplot(223)
ax.set_title("Naive Bayes on Transformed data")
ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape))
ax.scatter(X[:, 0], X[:, 1], c=y, s=50, edgecolor='k')
ax.set_ylim(-1.4, 1.4)
ax.set_xlim(-1.4, 1.4)
ax.set_xticks(())
ax.set_yticks(())
# transform grid using ExtraTreesClassifier
y_grid_pred = trees.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
ax = plt.subplot(224)
ax.set_title("ExtraTrees predictions")
ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape))
ax.scatter(X[:, 0], X[:, 1], c=y, s=50, edgecolor='k')
ax.set_ylim(-1.4, 1.4)
ax.set_xlim(-1.4, 1.4)
ax.set_xticks(())
ax.set_yticks(())
plt.tight_layout()
plt.show()
```
| github_jupyter |
```
import drawSvg as draw
import yt
import numpy as np
import ipywidgets
import matplotlib as mpl
from dataclasses import dataclass
class Style(draw.elements._TextContainingElement):
TAG_NAME = 'style'
ds = yt.testing.fake_amr_ds(geometry = "cylindrical")
final_level = 3
grids = []
g = ds.index.select_grids(final_level)[3]
while g is not None:
grids.append(g)
g = g.Parent
grids.sort(key = lambda a: a.Level)
@dataclass
class SpaceScales:
px0: float
px1: float
py0: float
py1: float
x0: float
x1: float
y0: float
y1: float
def x_sc(self, v):
# margin is assumed to have been taken into account already
return ((v - self.x0)/(self.x1 - self.x0)) * (self.px1 - self.px0) + self.px0
def y_sc(self, v):
return ((v - self.y0)/(self.y1 - self.y0)) * (self.py1 - self.py0) + self.py0
def draw_wedge(self, r0, theta0, r1, theta1, fill = "none"):
p = draw.Path(fill = fill, stroke = "black")
p.arc(self.x_sc(0), self.y_sc(0), self.x_sc(r0) - self.x_sc(0), theta0, theta1, cw = False)
p.arc(self.x_sc(0), self.y_sc(0), self.x_sc(r1) - self.x_sc(0), theta1, theta0, cw = True, includeL = True)
p.Z()
return p
def draw_cell(self, x0, y0, x1, y1, fill = "none"):
p = draw.Rectangle(self.x_sc(x0), self.y_sc(y0),
self.x_sc(x1) - self.x_sc(x0),
self.y_sc(y1) - self.y_sc(y0),
fill = fill, stroke = "black")
return p
grids = [
[0, 1, 4, -90, 90, 12],
[0.25, 0.75, 4, 15, 90, 8]
]
n_total = sum(_[2] * _[5] for _ in grids)
n_row = 9
n_col = n_total // n_row
norm = mpl.colors.Normalize(vmin = 0, vmax=n_total - 1)
cmap = mpl.cm.Spectral
print(n_total)
margin = 10
width, height = 600, 400
ibbox = [0, 400, 0, 400]
cbbox = [400, 600, 0, 400]
coord_space = SpaceScales(cbbox[0] + margin, cbbox[1] - margin, cbbox[2] - margin, cbbox[3] + margin, 0, 1, -1.1, 1.1)
index_space = SpaceScales(ibbox[0] + margin, ibbox[1] - margin, ibbox[2] - margin, ibbox[3] + margin, 0, 12, 0, 12)
canvas = draw.Drawing(width = width, height = height, id = "index_coord_figure")
coord_group = draw.Group(id = "coordinate_space_cells")
canvas.append(coord_group)
index_group = draw.Group(id = "index_space_cells")
canvas.append(index_group)
lines_group = draw.Group(id = "coord_index_lines")
canvas.append(lines_group)
cell_side = 1
n = 0
for r0, r1, nr, theta0, theta1, ntheta in grids:
dr = (r1 - r0)/nr
dtheta = (theta1 - theta0)/ntheta
for i in range(nr):
rc0 = r0 + dr * i
rc1 = r0 + dr * (i + 1)
for j in range(ntheta):
thetac0 = theta0 + dtheta * j
thetac1 = theta0 + dtheta * (j + 1)
fill = mpl.colors.to_hex(cmap(norm(n)))
args = {'class': 'cell', 'data-cell-i': f"{i: 3d}", 'data-cell-j': f"{j: 3d}", 'data-cell': f"{n: 3d}",
'data-theta-0': f"{thetac0: 3.2f}", 'data-theta-1': f"{thetac1: 3.2f}", 'data-r-0': f"{rc0: 0.3f}", "data-r-1": f"{rc1: 0.3f}"}
if n == 60:
args['class'] += " highlighted"
g = draw.Group(id = f"coord_cell_{n:02d}")
g.appendTitle(f"cell: {i: 2d} {j: 2d}")
p = coord_space.draw_wedge(rc0, thetac0, rc1, thetac1,
fill = fill)
p.args.update(args)
g.append(p)
coord_group.append(g)
g = draw.Group(id = f"index_cell_{n:02d}")
g.appendTitle(f"cell: {i: 2d} {j: 2d}")
col = n % n_row + 2
row = n // n_row + 2
p = index_space.draw_cell(col * cell_side,
row * cell_side,
(col + 1) * cell_side,
(row + 1) * cell_side,
fill = fill)
p.args.update(args)
g.append(p)
index_group.append(g)
t = (np.pi / 180) * ((thetac0 + thetac1)/2.0)
x0 = coord_space.x_sc((np.cos(t) * (rc0 + rc1)/2))
y0 = coord_space.y_sc((np.sin(t) * (rc0 + rc1)/2))
x1 = index_space.x_sc((col + 0.5) * cell_side)
y1 = index_space.y_sc((row + 0.5) * cell_side)
l = draw.Line(x0, y0, x1, y1)
l.args.update(args)
l.args["class"] += " cell-line"
lines_group.append(l)
n += 1
# Now, let's draw the grids in index space
style = """
.cell {
stroke-width: 2;
}
.cell-line {
visibility: hidden;
}
.cell-line.highlighted {
visibility: visible;
stroke: #555555;
stroke-width: 5;
stroke-linecap: round;
}
"""
canvas.append(Style(style))
display(canvas)
canvas.saveSvg("../content/images/indexing/coordinate_space.svg")
```
| github_jupyter |
<a href="https://colab.research.google.com/github/mk-armah/ibm-ai-engineering/blob/main/IBM_keras_final_project.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
<h1 align = 'center'> Instructions </h1>
<hr/>
A. Build a baseline model (5 marks)
Use the Keras library to build a neural network with the following:
- One hidden layer of 10 nodes, and a ReLU activation function
- Use the adam optimizer and the mean squared error as the loss function.
1. Randomly split the data into a training and test sets by holding 30% of the data for testing. You can use the train_test_splithelper function from Scikit-learn.
2. Train the model on the training data using 50 epochs.
3. Evaluate the model on the test data and compute the mean squared error between the predicted concrete strength and the actual concrete strength. You can use the mean_squared_error function from Scikit-learn.
4. Repeat steps 1 - 3, 50 times, i.e., create a list of 50 mean squared errors.
5. Report the mean and the standard deviation of the mean squared errors.
Submit your Jupyter Notebook with your code and comments.
-------
-------
1. Assignment Topic:
In this project, you will build a regression model using the Keras library to model the same data about concrete compressive strength that we used in labs 3.
2. Concrete Data:
For your convenience, the data can be found here again: https://cocl.us/concrete_data. To recap, the predictors in the data of concrete strength include:
Cement
Blast Furnace Slag
Fly Ash
Water
Superplasticizer
Coarse Aggregate
Fine Aggregate
```
import pandas as pd
import numpy as np
import tensorflow as tf
seed = np.random.seed(42)
#read dataframe from the link provided ===> https://cocl.us/concrete_data
df= pd.read_csv("https://cocl.us/concrete_data")
df.head()
#check for missing values
df.isna().sum()
#splitting the data in dependent and independent variables
X = df.iloc[:,df.columns!="Strength"]
y = df.iloc[:,df.columns=="Strength"]
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler,StandardScaler
from sklearn.metrics import mean_squared_error
from tqdm import tqdm
```
# TASK A
```
model_a = tf.keras.Sequential()
model_a.add(tf.keras.layers.Input(shape = (8,)))
model_a.add(tf.keras.layers.Dense(10,activation = 'relu'))
model_a.add(tf.keras.layers.Dense(1))
def custom_model(epochs,normalize = False,model = model_a):
"""this function returns the error_list of the model for each 50 or 100 epochs of the 50 iterations"""
model.compile(optimizer = 'adam',loss = 'mean_squared_error')
error_list = []
for i in tqdm(range(0,50)):
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3,random_state = i)
if normalize:
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
model.fit(X_train,y_train,epochs = epochs,verbose = 2)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test,y_pred)
error_list.append(mse)
return error_list
model_a_error_list = custom_model(epochs = 50,model = model_a,normalize = False)
print("Mean == >",np.mean(model_a_error_list),"\nStandard Deviation",np.std(model_a_error_list))
```
# TASK B
<h1>B. Normalize the data (5 marks) </h1>
Repeat Part A but use a normalized version of the data. Recall that one way to normalize the data is by subtracting the mean from the individual predictors and dividing by the standard deviation.
How does the mean of the mean squared errors compare to that from Step A?
---
---
```
model_b = tf.keras.Sequential()
model_b.add(tf.keras.layers.Input(shape = (8,)))
model_b.add(tf.keras.layers.Dense(10,activation = 'relu'))
model_b.add(tf.keras.layers.Dense(1))
model_b_error_list = custom_model(epochs = 50,normalize = True,model = model_b) #with Normalization
print("Mean == >",np.mean(model_b_error_list),"\nStandard Deviation",np.std(model_b_error_list))
print("The Difference between Mean of Model A Error List\nand the Mean of Model B Error List is >>> :",np.mean(model_a_error_list) - np.mean(model_b_error_list))
```
# TASK C
C. Increase the number of epochs (5 marks)
Repeat Part B but use 100 epochs this time for training.
How does the mean of the mean squared errors compare to that from Step B?:
-------
-------
```
model_c = tf.keras.Sequential()
model_c.add(tf.keras.layers.Input(shape = (8,)))
model_c.add(tf.keras.layers.Dense(10,activation = 'relu'))
model_c.add(tf.keras.layers.Dense(1))
model_c_error_list = custom_model(epochs = 100,normalize = True,model = model_c) #num of epochs increase to 100, normalization applied
print("Mean == >",np.mean(model_c_error_list),"\nStandard Deviation",np.std(model_c_error_list))
print("The Difference between Mean of Model B Error List\nand the Mean of Model C Error List is >>> :",np.mean(model_b_error_list) - np.mean(model_c_error_list))
```
# TASK D
D. Increase the number of hidden layers (5 marks)
Repeat part B but use a neural network with the following instead:
- Three hidden layers, each of 10 nodes and ReLU activation function.
How does the mean of the mean squared errors compare to that from Step B?
-------
-------
```
model_d = tf.keras.Sequential()
model_d.add(tf.keras.layers.Dense(10,activation = 'relu',input_shape = (8,)))
model_d.add(tf.keras.layers.Dense(10,activation = "relu"))
model_d.add(tf.keras.layers.Dense(1))
model_d.summary()
model_d_error_list = custom_model(epochs = 50,normalize = True,model = model_d)
print("Mean == >",np.mean(model_d_error_list),"\nStandard Deviation",np.std(model_d_error_list))
print("The Difference between Mean of Model B Error List\nand to the Mean of Model D Error List is >>> :",np.mean(model_b_error_list) - np.mean(model_d_error_list))
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.