code stringlengths 38 801k | repo_path stringlengths 6 263 |
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# !pip show plotnine
import pandas as pd
import numpy as np
from pandas.api.types import CategoricalDtype
print(pd.__version__)
print(np.__version__)
# +
from plotnine import * # 시각화 도구인 plotnine import
# 불필요한 warnings을 찍지 않기 위해 import 해오기
import warnings
warnings.filterwarnings('ignore')
# +
#bar_chart 데이터 불러오기
df = pd.read_csv('bar_chart.csv', engine ='python')
df.shape
# -
df.head()
# 캐주얼한 패션몰 수
(ggplot(df)
+ aes(x='가게명', y='질문1')
+ geom_col(fill='skyblue')
+ ggtitle('캐주얼한 패션몰 수')
+ theme(text=element_text(family='NanumSquare'),
axis_text_x=element_text(rotation=70))
)
# +
df_2 = df[['가게명', '질문1']]
df_2.sort_values(by='질문1', inplace=True, ascending=False)
df_2
df_2['가게명_cat'] = df_2['가게명'].astype(CategoricalDtype(categories=df_2['가게명'].values, ordered=True))
(ggplot(df_2)
+ aes(x='가게명_cat', y='질문1')
+ geom_col(fill='skyblue')
+ ggtitle('캐주얼한 패션몰 수')
+ theme(text=element_text(family='NanumSquare'),
axis_text_x=element_text(rotation=70))
+ labs(y='질문1', x='가게명_cat', title='캐주얼한 쇼핑몰 수')
)
# -
# 프랜차이즈 음식점 수
(ggplot(df)
+ aes(x='가게명', y='질문2')
+ geom_col(fill='skyblue')
+ ggtitle('프랜차이즈 음식점 수')
+ theme(text=element_text(family='NanumSquare'),
axis_text_x=element_text(rotation=70))
)
# +
df_3 = df[['가게명', '질문2']]
df_3.sort_values(by='질문2', inplace=True, ascending=False)
df_3
df_3['가게명_cat'] = df_3['가게명'].astype(CategoricalDtype(categories=df_3['가게명'].values, ordered=True))
(ggplot(df_3)
+ aes(x='가게명_cat', y='질문2')
+ geom_col(fill='skyblue')
+ ggtitle('캐주얼한 패션몰 수')
+ theme(text=element_text(family='NanumSquare'),
axis_text_x=element_text(rotation=70))
+ labs(y='질문2', x='가게명_cat', title='프랜차이즈 음식점 수')
)
# -
# 명품점
(ggplot(df)
+ aes(x='가게명', y='질문3')
+ geom_col(fill='skyblue')
+ ggtitle('명품 상점 수')
+ theme(text=element_text(family='NanumSquare'),
axis_text_x=element_text(rotation=70))
)
# +
df_4 = df[['가게명', '질문3']]
df_4.sort_values(by='질문3', inplace=True, ascending=False)
df_4
df_4['가게명_cat'] = df_4['가게명'].astype(CategoricalDtype(categories=df_4['가게명'].values, ordered=True))
(ggplot(df_4)
+ aes(x='가게명_cat', y='질문3')
+ geom_col(fill='skyblue')
+ ggtitle('캐주얼한 패션몰 수')
+ theme(text=element_text(family='NanumSquare'),
axis_text_x=element_text(rotation=70))
+ labs(y='질문3', x='가게명_cat', title='프랜차이즈 음식점 수')
)
# -
| .ipynb_checkpoints/M3_visualize_data_chart-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import matplotlib.pylab as plt
import PIL
class life:
def __init__(self,*kwargs):
if len(kwargs)==0:
size=100
else:
size=kwargs[0]
self.conway=np.zeros((size,size))
def timestep(self):
new_co=self.conway.copy()
for i in range(1,len(self.conway)-1):
for j in range(1,len(self.conway)-1):
number=(self.conway[i+1,j]
+self.conway[i-1,j]
+self.conway[i+1,j+1]
+self.conway[i+1,j-1]
+self.conway[i-1,j+1]
+self.conway[i-1,j-1]
+self.conway[i,j+1]
+self.conway[i,j-1]
)
if(number==3):
new_co[i,j]=1
elif(number==2 and self.conway[i,j]==1):
new_co[i,j]=1
else:
new_co[i,j]=0
self.conway=new_co
def timestep2(self):
number=np.zeros(self.conway.shape)
number[1:-1,1:-1]=(self.conway[2:,2:]+self.conway[:-2,:-2]
+self.conway[:-2,2:]+self.conway[2:,:-2]
+(self.conway[2:,1:-1]+self.conway[:-2,1:-1]
+self.conway[1:-1,2:]+self.conway[1:-1,:-2]))
alive=(self.conway==1)
dead=(self.conway==0)
self.conway=np.zeros(self.conway.shape)
self.conway[alive*(number==2)]=1
self.conway[alive*(number==3)]=1
self.conway[dead*(number==3)]=1
def initial_conditions(self,*kwargs):
print(kwargs,kwargs[0])
self.conway[kwargs[0],kwargs[1]]=1
conway=life(20)
x=[12,12,12,13,14]
y=[2,3,4,4,3]
conway.initial_conditions(x,y)
plt.imshow(conway.conway,origin="lower")
from IPython.display import clear_output
for i in range(40):
clear_output(wait=True)
conway.timestep()
plt.imshow(conway.conway,origin="lower")
plt.show()
conway=life()
x=[92,92,92,93,94]
y=[2,3,4,4,3]
conway.initial_conditions(x,y)
plt.imshow(conway.conway,origin="lower")
for i in range(10):
clear_output(wait=True)
conway.timestep()
plt.imshow(conway.conway,origin="lower")
plt.show()
x=np.array([1,1,2,2,11,11,11,12,12,13,13,14,14,15,16,16,17,17,17,18,21,21,21,22,22,22,23,23,25,25,25,25,35,35,36,36])
y=np.array([4,5,4,5,3,4,5,2,6,1,7,1,7,4,2,6,3,4,5,4,5,6,7,5,6,7,4,8,3,4,8,9,6,7,6,7])
conway=life(40)
conway.initial_conditions(y+15,x)
plt.imshow(conway.conway,origin="lower")
for i in range(1000):
clear_output(wait=True)
conway.timestep()
plt.imshow(conway.conway,origin="lower")
plt.show()
# %timeit conway.timestep()
# %timeit conway.timestep2()
| projects/life/Life.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# # Data Structures
# In simple terms, It is the the collection or group of data in a particular structure.
# ## Lists
# Lists are the most commonly used data structure. Think of it as a sequence of data that is enclosed in square brackets and data are separated by a comma. Each of these data can be accessed by calling it's index value.
#
# Lists are declared by just equating a variable to '[ ]' or list.
a = []
print type(a)
# One can directly assign the sequence of data to a list x as shown.
x = ['apple', 'orange']
# ### Indexing
# In python, Indexing starts from 0. Thus now the list x, which has two elements will have apple at 0 index and orange at 1 index.
x[0]
# Indexing can also be done in reverse order. That is the last element can be accessed first. Here, indexing starts from -1. Thus index value -1 will be orange and index -2 will be apple.
x[-1]
# As you might have already guessed, x[0] = x[-2], x[1] = x[-1]. This concept can be extended towards lists with more many elements.
y = ['carrot','potato']
# Here we have declared two lists x and y each containing its own data. Now, these two lists can again be put into another list say z which will have it's data as two lists. This list inside a list is called as nested lists and is how an array would be declared which we will see later.
z = [x,y]
print z
# Indexing in nested lists can be quite confusing if you do not understand how indexing works in python. So let us break it down and then arrive at a conclusion.
#
# Let us access the data 'apple' in the above nested list.
# First, at index 0 there is a list ['apple','orange'] and at index 1 there is another list ['carrot','potato']. Hence z[0] should give us the first list which contains 'apple'.
z1 = z[0]
print z1
# Now observe that z1 is not at all a nested list thus to access 'apple', z1 should be indexed at 0.
z1[0]
# Instead of doing the above, In python, you can access 'apple' by just writing the index values each time side by side.
z[0][0]
# If there was a list inside a list inside a list then you can access the innermost value by executing z[ ][ ][ ].
# ### Slicing
# Indexing was only limited to accessing a single element, Slicing on the other hand is accessing a sequence of data inside the list. In other words "slicing" the list.
#
# Slicing is done by defining the index values of the first element and the last element from the parent list that is required in the sliced list. It is written as parentlist[ a : b ] where a,b are the index values from the parent list. If a or b is not defined then the index value is considered to be the first value for a if a is not defined and the last value for b when b is not defined.
num = [0,1,2,3,4,5,6,7,8,9]
print num[0:4]
print num[4:]
# You can also slice a parent list with a fixed length or step length.
num[:9:3]
# ### Built in List Functions
# To find the length of the list or the number of elements in a list, **len( )** is used.
len(num)
# If the list consists of all integer elements then **min( )** and **max( )** gives the minimum and maximum value in the list.
min(num)
max(num)
# Lists can be concatenated by adding, '+' them. The resultant list will contain all the elements of the lists that were added. The resultant list will not be a nested list.
[1,2,3] + [5,4,7]
# There might arise a requirement where you might need to check if a particular element is there in a predefined list. Consider the below list.
names = ['Earth','Air','Fire','Water']
# To check if 'Fire' and 'Rajath' is present in the list names. A conventional approach would be to use a for loop and iterate over the list and use the if condition. But in python you can use 'a in b' concept which would return 'True' if a is present in b and 'False' if not.
'Fire' in names
'Rajath' in names
# In a list with elements as string, **max( )** and **min( )** is applicable. **max( )** would return a string element whose ASCII value is the highest and the lowest when **min( )** is used. Note that only the first index of each element is considered each time and if they value is the same then second index considered so on and so forth.
mlist = ['bzaa','ds','nc','az','z','klm']
print max(mlist)
print min(mlist)
# Here the first index of each element is considered and thus z has the highest ASCII value thus it is returned and minimum ASCII is a. But what if numbers are declared as strings?
nlist = ['1','94','93','1000']
print max(nlist)
print min(nlist)
# Even if the numbers are declared in a string the first index of each element is considered and the maximum and minimum values are returned accordingly.
# But if you want to find the **max( )** string element based on the length of the string then another parameter 'key=len' is declared inside the **max( )** and **min( )** function.
print max(names, key=len)
print min(names, key=len)
# But even 'Water' has length 5. **max()** or **min()** function returns the first element when there are two or more elements with the same length.
#
# Any other built in function can be used or lambda function (will be discussed later) in place of len.
#
# A string can be converted into a list by using the **list()** function.
list('hello')
# **append( )** is used to add a element at the end of the list.
lst = [1,1,4,8,7]
lst.append(1)
print lst
# **count( )** is used to count the number of a particular element that is present in the list.
lst.count(1)
# **append( )** function can also be used to add a entire list at the end. Observe that the resultant list becomes a nested list.
lst1 = [5,4,2,8]
lst.append(lst1)
print lst
# But if nested list is not what is desired then **extend( )** function can be used.
lst.extend(lst1)
print lst
# **index( )** is used to find the index value of a particular element. Note that if there are multiple elements of the same value then the first index value of that element is returned.
lst.index(1)
# **insert(x,y)** is used to insert a element y at a specified index value x. **append( )** function made it only possible to insert at the end.
lst.insert(5, 'name')
print lst
# **insert(x,y)** inserts but does not replace element. If you want to replace the element with another element you simply assign the value to that particular index.
lst[5] = 'Python'
print lst
# **pop( )** function return the last element in the list. This is similar to the operation of a stack. Hence it wouldn't be wrong to tell that lists can be used as a stack.
lst.pop()
# Index value can be specified to pop a ceratin element corresponding to that index value.
lst.pop(0)
# **pop( )** is used to remove element based on it's index value which can be assigned to a variable. One can also remove element by specifying the element itself using the **remove( )** function.
lst.remove('Python')
print lst
# Alternative to **remove** function but with using index value is **del**
del lst[1]
print lst
# The entire elements present in the list can be reversed by using the **reverse()** function.
lst.reverse()
print lst
# Note that the nested list [5,4,2,8] is treated as a single element of the parent list lst. Thus the elements inside the nested list is not reversed.
#
# Python offers built in operation **sort( )** to arrange the elements in ascending order.
lst.sort()
print lst
# For descending order, By default the reverse condition will be False for reverse. Hence changing it to True would arrange the elements in descending order.
lst.sort(reverse=True)
print lst
# Similarly for lists containing string elements, **sort( )** would sort the elements based on it's ASCII value in ascending and by specifying reverse=True in descending.
names.sort()
print names
names.sort(reverse=True)
print names
# To sort based on length key=len should be specified as shown.
names.sort(key=len)
print names
names.sort(key=len,reverse=True)
print names
# ### Copying a list
# Most of the new python programmers commit this mistake. Consider the following,
lista= [2,1,4,3]
listb = lista
print listb
# Here, We have declared a list, lista = [2,1,4,3]. This list is copied to listb by assigning it's value and it get's copied as seen. Now we perform some random operations on lista.
lista.pop()
print lista
lista.append(9)
print lista
print listb
# listb has also changed though no operation has been performed on it. This is because you have assigned the same memory space of lista to listb. So how do fix this?
#
# If you recall, in slicing we had seen that parentlist[a:b] returns a list from parent list with start index a and end index b and if a and b is not mentioned then by default it considers the first and last element. We use the same concept here. By doing so, we are assigning the data of lista to listb as a variable.
lista = [2,1,4,3]
listb = lista[:]
print listb
lista.pop()
print lista
lista.append(9)
print lista
print listb
# ##Tuples
# Tuples are similar to lists but only big difference is the elements inside a list can be changed but in tuple it cannot be changed. Think of tuples as something which has to be True for a particular something and cannot be True for no other values. For better understanding, Recall **divmod()** function.
xyz = divmod(10,3)
print xyz
print type(xyz)
# Here the quotient has to be 3 and the remainder has to be 1. These values cannot be changed whatsoever when 10 is divided by 3. Hence divmod returns these values in a tuple.
# To define a tuple, A variable is assigned to paranthesis ( ) or tuple( ).
tup = ()
tup2 = tuple()
# If you want to directly declare a tuple it can be done by using a comma at the end of the data.
27,
# 27 when multiplied by 2 yields 54, But when multiplied with a tuple the data is repeated twice.
2*(27,)
# Values can be assigned while declaring a tuple. It takes a list as input and converts it into a tuple or it takes a string and converts it into a tuple.
tup3 = tuple([1,2,3])
print tup3
tup4 = tuple('Hello')
print tup4
# It follows the same indexing and slicing as Lists.
print tup3[1]
tup5 = tup4[:3]
print tup5
# ### Mapping one tuple to another
(a,b,c)= ('alpha','beta','gamma')
print a,b,c
d = tuple('RajathKumarMP')
print d
# ### Built In Tuple functions
# **count()** function counts the number of specified element that is present in the tuple.
d.count('a')
# **index()** function returns the index of the specified element. If the elements are more than one then the index of the first element of that specified element is returned
d.index('a')
# ## Sets
# Sets are mainly used to eliminate repeated numbers in a sequence/list. It is also used to perform some standard set operations.
#
# Sets are declared as set() which will initialize a empty set. Also set([sequence]) can be executed to declare a set with elements
set1 = set()
print type(set1)
set0 = set([1,2,2,3,3,4])
print set0
# elements 2,3 which are repeated twice are seen only once. Thus in a set each element is distinct.
# ### Built-in Functions
set1 = set([1,2,3])
set2 = set([2,3,4,5])
# **union( )** function returns a set which contains all the elements of both the sets without repition.
set1.union(set2)
# **add( )** will add a particular element into the set. Note that the index of the newly added element is arbitrary and can be placed anywhere not neccessarily in the end.
set1.add(0)
set1
# **intersection( )** function outputs a set which contains all the elements that are in both sets.
set1.intersection(set2)
# **difference( )** function ouptuts a set which contains elements that are in set1 and not in set2.
set1.difference(set2)
# **symmetric_difference( )** function ouputs a function which contains elements that are in one of the sets.
set2.symmetric_difference(set1)
# **issubset( ), isdisjoint( ), issuperset( )** is used to check if the set1/set2 is a subset, disjoint or superset of set2/set1 respectively.
set1.issubset(set2)
set2.isdisjoint(set1)
set2.issuperset(set1)
# **pop( )** is used to remove an arbitrary element in the set
set1.pop()
print set1
# **remove( )** function deletes the specified element from the set.
set1.remove(2)
set1
# **clear( )** is used to clear all the elements and make that set an empty set.
set1.clear()
set1
| .ipynb_checkpoints/03-checkpoint.ipynb |
# ##### 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
#
# 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.
#
# # solve_with_time_limit_sample_sat
# <table align="left">
# <td>
# <a href="https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/sat/solve_with_time_limit_sample_sat.ipynb"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png"/>Run in Google Colab</a>
# </td>
# <td>
# <a href="https://github.com/google/or-tools/blob/master/ortools/sat/samples/solve_with_time_limit_sample_sat.py"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png"/>View source on GitHub</a>
# </td>
# </table>
# First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab.
# !pip install ortools
# +
# #!/usr/bin/env python3
# Copyright 2010-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
#
# 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.
"""Solves a problem with a time limit."""
from ortools.sat.python import cp_model
def SolveWithTimeLimitSampleSat():
"""Minimal CP-SAT example to showcase calling the solver."""
# Creates the model.
model = cp_model.CpModel()
# Creates the variables.
num_vals = 3
x = model.NewIntVar(0, num_vals - 1, 'x')
y = model.NewIntVar(0, num_vals - 1, 'y')
z = model.NewIntVar(0, num_vals - 1, 'z')
# Adds an all-different constraint.
model.Add(x != y)
# Creates a solver and solves the model.
solver = cp_model.CpSolver()
# Sets a time limit of 10 seconds.
solver.parameters.max_time_in_seconds = 10.0
status = solver.Solve(model)
if status == cp_model.OPTIMAL:
print('x = %i' % solver.Value(x))
print('y = %i' % solver.Value(y))
print('z = %i' % solver.Value(z))
SolveWithTimeLimitSampleSat()
| examples/notebook/sat/solve_with_time_limit_sample_sat.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ___
#
# <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
# ___
# # Introduction to Pandas
#
# In this section of the course we will learn how to use pandas for data analysis. You can think of pandas as an extremely powerful version of Excel, with a lot more features. In this section of the course, you should go through the notebooks in this order:
#
# * Introduction to Pandas
# * Series
# * DataFrames
# * Missing Data
# * GroupBy
# * Merging,Joining,and Concatenating
# * Operations
# * Data Input and Output
# ___
| big-data/anaconda/Refactored_Py_DS_ML_Bootcamp-master/my/03-Python-for-Data-Analysis-Pandas/01-Introduction to Pandas.ipynb |
# v2
# 7/11/2018
# +
import argparse
import os
import glob
import numpy as np
import cv2
import torch
import sys
import time
import math
from pathlib import Path
from WSI_handling import wsi
from unet import UNet
from shapely.geometry import Polygon
# -
#-----helper function to split data into batches
def divide_batch(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
# ----- parse command line arguments
parser = argparse.ArgumentParser(description='Make output for entire image using Unet')
parser.add_argument('input_pattern',
help="input filename pattern. try: *.png, or tsv file containing list of files to analyze",
nargs="*")
# +
parser.add_argument('-r', '--resolution', help="image resolution in microns per pixel", default=1, type=float)
parser.add_argument('-c', '--color', help="annotation color to use, default None", default='green', type=str)
parser.add_argument('-a', '--annotation', help="annotation index to use, default largest", default='wsi', type=str)
parser.add_argument('-p', '--patchsize', help="patchsize, default 256", default=256, type=int)
parser.add_argument('-s', '--batchsize', help="batchsize for controlling GPU memory usage, default 10", default=10, type=int)
parser.add_argument('-o', '--outdir', help="outputdir, default ./output/", default="./output/", type=str)
parser.add_argument('-m', '--model', help="model", default="best_model.pth", type=str)
parser.add_argument('-i', '--gpuid', help="id of gpu to use", default=0, type=int)
parser.add_argument('-f', '--force', help="force regeneration of output even if it exists", default=False,
action="store_true")
parser.add_argument('-b', '--basepath',
help="base path to add to file names, helps when producing data using tsv file as input",
default="", type=str)
# -
#args = parser.parse_args(['-s150','-o/mnt/rstor/CSE_BME_AXM788/home/pjl54/test','-r0.25','-a','largest','-m','/home/pjl54/models/nucer_unet_best_model.pth','/mnt/rstor/CSE_BME_AXM788/data/TCGA_Bladder_Cancer/Diagnostic_Images/Elloitt/1stAnnotatedDrElloitt/TCGA-4Z-AA7O-01Z-00-DX1.svs'])
args = parser.parse_args(['-s30','-i0','-p512','-o/mnt/data/home/pjl54/test','-r1','-aall','-m','/mnt/data/home/pjl54/models/crib_PL_1mpp_512p.pth','/mnt/ccipd_data/TCGA_PRAD/2018Jan14/TCGA-EJ-5494-01Z-00-DX1.svs'])
if not (args.input_pattern):
parser.error('No images selected with input pattern')
OUTPUT_DIR = args.outdir
batch_size = args.batchsize
patch_size = args.patchsize
base_stride_size = patch_size//2
# ----- load network
device = torch.device(args.gpuid if torch.cuda.is_available() else 'cpu')
checkpoint = torch.load(args.model, map_location=lambda storage, loc: storage) #load checkpoint to CPU and then put to device https://discuss.pytorch.org/t/saving-and-loading-torch-models-on-2-machines-with-different-number-of-gpu-devices/6666
model = UNet(n_classes=checkpoint["n_classes"], in_channels=checkpoint["in_channels"],
padding=checkpoint["padding"], depth=checkpoint["depth"], wf=checkpoint["wf"],
up_mode=checkpoint["up_mode"], batch_norm=checkpoint["batch_norm"]).to(device)
model.load_state_dict(checkpoint["model_dict"])
model.eval()
print(f"total params: \t{sum([np.prod(p.size()) for p in model.parameters()])}")
# ----- get file list
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
files = []
basepath = args.basepath #
basepath = basepath + os.sep if len(
basepath) > 0 else "" # if the user supplied a different basepath, make sure it ends with an os.sep
if len(args.input_pattern) > 1: # bash has sent us a list of files
files = args.input_pattern
elif args.input_pattern[0].endswith("tsv"): # user sent us an input file
# load first column here and store into files
with open(args.input_pattern[0], 'r') as f:
for line in f:
if line[0] == "#":
continue
files.append(basepath + line.strip().split("\t")[0])
else: # user sent us a wildcard, need to use glob to find files
files = glob.glob(args.basepath + args.input_pattern[0])
def run_model(img_dims,patch_size,stride_size,base_stride_size,batch_size,args,img,annotation):
x_start = int(img_dims[0])
y_start = int(img_dims[1])
w_orig = img.get_coord_at_mpp(img_dims[2] - x_start,input_mpp=img['mpp'],output_mpp=args.resolution)
h_orig = img.get_coord_at_mpp(img_dims[3] - y_start,input_mpp=img['mpp'],output_mpp=args.resolution)
w = int(w_orig + (patch_size - (w_orig % patch_size)))
h = int(h_orig + (patch_size - (h_orig % patch_size)))
base_edge_length = base_stride_size*int(math.sqrt(batch_size))
# need to make sure we don't end up with a last row/column smaller than patch_size
h = h + patch_size if base_edge_length - (h % base_edge_length) else h
w = w + patch_size if base_edge_length - (w % base_edge_length) else w
roi = img.get_tile(args.resolution,(x_start-stride_size//2,y_start-stride_size//2),(w+base_stride_size,h+base_stride_size))
x_points = range(0,np.shape(roi)[0],base_stride_size*int(math.sqrt(batch_size)))
y_points = range(0,np.shape(roi)[1],base_stride_size*int(math.sqrt(batch_size)))
grid_points = [(x,y) for x in x_points for y in y_points]
output = np.zeros([np.shape(roi)[0],np.shape(roi)[1]],dtype='uint8')
for i,batch_points in enumerate(grid_points):
# get the tile of the batch
big_patch = roi[batch_points[0]:(batch_points[0]+base_edge_length+base_stride_size),batch_points[1]:(batch_points[1]+base_edge_length+base_stride_size),:]
big_patch_gpu = torch.from_numpy(big_patch).type('torch.FloatTensor').to(device)
# split the tile into patch_size patches
batch_arr = torch.stack(([big_patch_gpu[x:x+patch_size,y:y+patch_size,:] for y in range(0,np.shape(big_patch_gpu)[1]-base_stride_size,base_stride_size) for x in range(0,np.shape(big_patch_gpu)[0]-base_stride_size,base_stride_size)]))
batch_arr = batch_arr.permute(0,3,1,2) / 255
# ---- get results
output_batch = model(batch_arr)
output_batch = output_batch.argmax(axis=1)
#remove the padding from each tile, we only keep the center
output_batch = output_batch[:,base_stride_size//2:-base_stride_size//2,base_stride_size//2:-base_stride_size//2]
# --- pull from GPU and append to rest of output
output_batch = output_batch.detach().cpu().numpy()
reconst = np.concatenate(np.concatenate(output_batch.reshape(int(np.shape(big_patch)[1]/(patch_size//2))-1,int(np.shape(big_patch)[0]/(patch_size//2))-1,base_stride_size,base_stride_size),axis=2),axis=0)
output[batch_points[0]:(batch_points[0]+np.shape(big_patch)[0]-base_stride_size),batch_points[1]:(batch_points[1]+np.shape(big_patch)[1]-base_stride_size)] = reconst
if(args.annotation.lower() != 'wsi'):
#in case there was extra padding to get a multiple of patch size, remove that as well
_,mask = img.get_annotated_region(args.resolution,args.color,annotation,return_img=False)
output = output[0:mask.shape[0], 0:mask.shape[1]] #remove paddind, crop back
output = np.bitwise_and(output>0,mask>0)*255
return output
for fname in files:
fname = fname.strip()
if(args.annotation.lower() != 'all'):
newfname_class = "%s/%s_class.png" % (OUTPUT_DIR, Path(fname).stem)
if not args.force and os.path.exists(newfname_class):
print("Skipping as output file exists")
continue
print(f"working on file: \t {fname}")
print(f"saving to : \t {newfname_class}")
start_time = time.time()
cv2.imwrite(newfname_class, np.zeros(shape=(1, 1)))
xml_fname = Path(fname).with_suffix('.xml')
if not os.path.exists(xml_fname):
xml_fname = Path(fname).with_suffix('.json')
if os.path.exists(xml_fname):
img = wsi(fname,xml_fname)
stride_size = int(base_stride_size * (args.resolution/img["mpp"]))
if(args.annotation.lower() == 'all'):
annotations_todo = len(img.get_points(args.color,[]))
print(f"working on file: \t {fname}")
for k in range(0,annotations_todo):
print('Working on annotation ' + str(k))
start_time = time.time()
img_dims = img.get_dimensions_of_annotation(args.color,k)
newfname_class = "%s/%s_%d_class.png" % (OUTPUT_DIR, Path(fname).stem,k)
if args.force or not os.path.exists(newfname_class):
output = run_model(img_dims,patch_size,stride_size,base_stride_size,batch_size,args,img,annotation=k)
cv2.imwrite(newfname_class, output)
output = None
print('Elapsed time = ' + str(time.time()-start_time))
else:
if(args.annotation.lower() == 'wsi'):
img_dims = [0,0,img["img_dims"][0][0],img["img_dims"][0][1]]
else:
img_dims = img.get_dimensions_of_annotation(args.color,args.annotation)
if img_dims:
output = run_model(img_dims,patch_size,stride_size,base_stride_size,batch_size,args,img,annotation=args.annotation)
cv2.imwrite(newfname_class, output)
output = None
print('Elapsed time = ' + str(time.time()-start_time))
else:
print('No annotation of color')
else:
print('Could not find ' + str(xml_fname))
| segmentation_epistroma_unet/make_output_unet_cmd_wsi.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Tetris Game
import pygame
import random
pygame.font.init()
# # Global Variables
s_width = 800
s_height = 700
play_width = 300
play_height = 600
block_size = 30
top_left_x = (s_width - play_width) // 2
top_left_y = s_height - play_height
# # Shape Formations
# +
S = [['.....',
'......',
'..00..',
'.00...',
'.....'],
['.....',
'..0..',
'..00.',
'...0.',
'.....']]
Z = [['.....',
'.....',
'.00..',
'..00.',
'.....'],
['.....',
'..0..',
'.00..',
'.0...',
'.....']]
I = [['..0..',
'..0..',
'..0..',
'..0..',
'.....'],
['.....',
'0000.',
'.....',
'.....',
'.....']]
O = [['.....',
'.....',
'.00..',
'.00..',
'.....']]
J = [['.....',
'.0...',
'.000.',
'.....',
'.....'],
['.....',
'..00.',
'..0..',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'...0.',
'.....'],
['.....',
'..0..',
'..0..',
'.00..',
'.....']]
L = [['.....',
'...0.',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..0..',
'..00.',
'.....'],
['.....',
'.....',
'.000.',
'.0...',
'.....'],
['.....',
'.00..',
'..0..',
'..0..',
'.....']]
T = [['.....',
'..0..',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..00.',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'..0..',
'.....'],
['.....',
'..0..',
'.00..',
'..0..',
'.....']]
# -
shapes = [S, Z, I, O, J, L, T]
shape_colors = [(0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 255, 0), (255, 165, 0), (0, 0, 255), (128, 0, 128)]
class Piece(object):
rows = 20 # y
columns = 10 # x
def __init__(self, column, row, shape):
self.x = column
self.y = row
self.shape = shape
self.color = shape_colors[shapes.index(shape)]
self.rotation = 0 # number from 0-3
# # Functions
def create_grid(locked_positions={}):
grid = [[(0,0,0) for x in range(10)] for x in range(20)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j,i) in locked_positions:
c = locked_positions[(j,i)]
grid[i][j] = c
return grid
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((shape.x + j, shape.y + i))
for i, pos in enumerate(positions):
positions[i] = (pos[0] - 2, pos[1] - 4)
return positions
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0)] for i in range(20)]
accepted_positions = [j for sub in accepted_positions for j in sub]
formatted = convert_shape_format(shape)
for pos in formatted:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
global shapes, shape_colors
return Piece(5, 0, random.choice(shapes))
def draw_text_middle(text, size, color, surface):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, 1, color)
surface.blit(label, (top_left_x + play_width/2 - (label.get_width() / 2), top_left_y + play_height/2 - label.get_height()/2))
def draw_grid(surface, row, col):
sx = top_left_x
sy = top_left_y
for i in range(row):
pygame.draw.line(surface, (128,128,128), (sx, sy+ i*30), (sx + play_width, sy + i * 30))
for j in range(col):
pygame.draw.line(surface, (128,128,128), (sx + j * 30, sy), (sx + j * 30, sy + play_height))
def clear_rows(grid, locked):
inc = 0
for i in range(len(grid)-1,-1,-1):
row = grid[i]
if (0, 0, 0) not in row:
inc += 1
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
def draw_next_shape(shape, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', 1, (255,255,255))
sx = top_left_x + play_width + 50
sy = top_left_y + play_height/2 - 100
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
pygame.draw.rect(surface, shape.color, (sx + j*30, sy + i*30, 30, 30), 0)
surface.blit(label, (sx + 10, sy- 30))
def draw_window(surface):
surface.fill((0,0,0))
font = pygame.font.SysFont('comicsans', 60)
label = font.render('TETRIS', 1, (255,255,255))
surface.blit(label, (top_left_x + play_width / 2 - (label.get_width() / 2), 30))
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j], (top_left_x + j* 30, top_left_y + i * 30, 30, 30), 0)
draw_grid(surface, 20, 10)
pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_left_y, play_width, play_height), 5)
def main():
global grid
locked_positions = {}
grid = create_grid(locked_positions)
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
clock = pygame.time.Clock()
fall_time = 0
while run:
fall_speed = 0.27
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
if fall_time/1000 >= fall_speed:
fall_time = 0
current_piece.y += 1
if not (valid_space(current_piece, grid)) and current_piece.y > 0:
current_piece.y -= 1
change_piece = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
elif event.key == pygame.K_UP:
current_piece.rotation = current_piece.rotation + 1 % len(current_piece.shape)
if not valid_space(current_piece, grid):
current_piece.rotation = current_piece.rotation - 1 % len(current_piece.shape)
if event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
if event.key == pygame.K_SPACE:
while valid_space(current_piece, grid):
current_piece.y += 1
current_piece.y -= 1
print(convert_shape_format(current_piece))
shape_pos = convert_shape_format(current_piece)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
if change_piece:
for pos in shape_pos:
p = (pos[0], pos[1])
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
clear_rows(grid, locked_positions)
draw_window(win)
draw_next_shape(next_piece, win)
pygame.display.update()
if check_lost(locked_positions):
run = False
draw_text_middle("You Lost", 40, (255,255,255), win)
pygame.display.update()
pygame.time.delay(2000)
def main_menu():
run = True
while run:
win.fill((0,0,0))
draw_text_middle('Press any key to begin.', 60, (255, 255, 255), win)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main()
pygame.quit()
win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption('Tetris')
main_menu()
| Tetris.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200>
# <br></br>
# <br></br>
#
# ## *Data Science Unit 4 Sprint 3 Assignment 1*
#
# # Recurrent Neural Networks and Long Short Term Memory (LSTM)
#
# 
#
# It is said that [infinite monkeys typing for an infinite amount of time](https://en.wikipedia.org/wiki/Infinite_monkey_theorem) will eventually type, among other things, the complete works of Wiliam Shakespeare. Let's see if we can get there a bit faster, with the power of Recurrent Neural Networks and LSTM.
#
# This text file contains the complete works of Shakespeare: https://www.gutenberg.org/files/100/100-0.txt
#
# Use it as training data for an RNN - you can keep it simple and train character level, and that is suggested as an initial approach.
#
# Then, use that trained RNN to generate Shakespearean-ish text. Your goal - a function that can take, as an argument, the size of text (e.g. number of characters or lines) to generate, and returns generated text of that size.
#
# Note - Shakespeare wrote an awful lot. It's OK, especially initially, to sample/use smaller data and parameters, so you can have a tighter feedback loop when you're trying to get things running. Then, once you've got a proof of concept - start pushing it more!
# +
import numpy as np
with open('./text/100-0.txt', 'rb') as f:
text = f.read()
# + jupyter={"source_hidden": true}
text = text[900:-25000].lower()
chars = list(set(text))
num_chars = len(chars)
txt_size = len(text)
print('Number of unique characters:', num_chars)
print('Total characters in text:', txt_size)
# +
char_to_int = dict((c,i) for i,c in enumerate(chars))
int_to_char = dict((i,c) for i,c in enumerate(chars))
print(char_to_int)
print('-'*50)
print(int_to_char)
integer_encoded = [char_to_int[i] for i in text]
print(len(integer_encoded))
# +
# hyperparameters
iteration = 10
sequence_length = 40
batch_size = round((txt_size /sequence_length)+0.5) # = math.ceil
hidden_size = 500 # size of hidden layer of neurons.
learning_rate = 1e-1
# model parameters
W_xh = np.random.randn(hidden_size, num_chars)*0.01 # weight input -> hidden.
W_hh = np.random.randn(hidden_size, hidden_size)*0.01 # weight hidden -> hidden
W_hy = np.random.randn(num_chars, hidden_size)*0.01 # weight hidden -> output
b_h = np.zeros((hidden_size, 1)) # hidden bias
b_y = np.zeros((num_chars, 1)) # output bias
h_prev = np.zeros((hidden_size,1)) # h_(t-1)
# +
def forwardprop(inputs, targets, h_prev):
# Since the RNN receives the sequence, the weights are not updated during one sequence.
xs, hs, ys, ps = {}, {}, {}, {} # dictionary
hs[-1] = np.copy(h_prev) # Copy previous hidden state vector to -1 key value.
loss = 0 # loss initialization
for t in range(len(inputs)): # t is a "time step" and is used as a key(dic).
xs[t] = np.zeros((num_chars,1))
xs[t][inputs[t]] = 1
hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state.
ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for next chars
ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars.
# Softmax. -> The sum of probabilities is 1 even without the exp() function, but all of the elements are positive through the exp() function.
loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss). Efficient and simple code
# y_class = np.zeros((num_chars, 1))
# y_class[targets[t]] =1
# loss += np.sum(y_class*(-np.log(ps[t]))) # softmax (cross-entropy loss)
return loss, ps, hs, xs
# -
def backprop(ps, inputs, hs, xs, targets):
dWxh, dWhh, dWhy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) # make all zero matrices.
dbh, dby = np.zeros_like(b_h), np.zeros_like(b_y)
dhnext = np.zeros_like(hs[0]) # (hidden_size,1)
# reversed
for t in reversed(range(len(inputs))):
dy = np.copy(ps[t]) # shape (num_chars,1). "dy" means "dloss/dy"
dy[targets[t]] -= 1 # backprop into y. After taking the soft max in the input vector, subtract 1 from the value of the element corresponding to the correct label.
dWhy += np.dot(dy, hs[t].T)
dby += dy
dh = np.dot(W_hy.T, dy) + dhnext # backprop into h.
dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity #tanh'(x) = 1-tanh^2(x)
dbh += dhraw
dWxh += np.dot(dhraw, xs[t].T)
dWhh += np.dot(dhraw, hs[t-1].T)
dhnext = np.dot(W_hh.T, dhraw)
for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients.
return dWxh, dWhh, dWhy, dbh, dby
# +
# %%time
data_pointer = 0
# memory variables for Adagrad
mWxh, mWhh, mWhy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy)
mbh, mby = np.zeros_like(b_h), np.zeros_like(b_y)
for i in range(iteration):
h_prev = np.zeros((hidden_size,1)) # reset RNN memory
data_pointer = 0 # go from start of data
for b in range(batch_size):
inputs = [char_to_int[ch] for ch in text[data_pointer:data_pointer+sequence_length]]
targets = [char_to_int[ch] for ch in text[data_pointer+1:data_pointer+sequence_length+1]] # t+1
if (data_pointer+sequence_length+1 >= len(text) and b == batch_size-1): # processing of the last part of the input data.
# targets.append(char_to_int[txt_data[0]]) # When the data doesn't fit, add the first char to the back.
targets.append(char_to_int[" "]) # When the data doesn't fit, add space(" ") to the back.
# forward
loss, ps, hs, xs = forwardprop(inputs, targets, h_prev)
# print(loss)
# backward
dWxh, dWhh, dWhy, dbh, dby = backprop(ps, inputs, hs, xs, targets)
# perform parameter update with Adagrad
for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y],
[dWxh, dWhh, dWhy, dbh, dby],
[mWxh, mWhh, mWhy, mbh, mby]):
mem += dparam * dparam # elementwise
param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update
data_pointer += sequence_length # move data pointer
if i % 2 == 0:
print ('iter %d, loss: %f' % (i, loss)) # print progress
# -
def predict(test_char, length):
x = np.zeros((num_chars, 1))
x[char_to_int[test_char]] = 1
ixes = []
h = np.zeros((hidden_size,1))
for t in range(length):
h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h)
y = np.dot(W_hy, h) + b_y
p = np.exp(y) / np.sum(np.exp(y))
ix = np.random.choice(range(num_chars), p=p.ravel()) # ravel -> rank0
# "ix" is a list of indexes selected according to the soft max probability.
x = np.zeros((num_chars, 1)) # init
x[ix] = 1
ixes.append(ix) # list
txt = test_char + ''.join(int_to_char[i] for i in ixes)
print ('----\n %s \n----' % (txt, ))
predict('A', 1000)
# + [markdown] colab_type="text" id="zE4a4O7Bp5x1"
# # Resources and Stretch Goals
# + [markdown] colab_type="text" id="uT3UV3gap9H6"
# ## Stretch goals:
# - Refine the training and generation of text to be able to ask for different genres/styles of Shakespearean text (e.g. plays versus sonnets)
# - Train a classification model that takes text and returns which work of Shakespeare it is most likely to be from
# - Make it more performant! Many possible routes here - lean on Keras, optimize the code, and/or use more resources (AWS, etc.)
# - Revisit the news example from class, and improve it - use categories or tags to refine the model/generation, or train a news classifier
# - Run on bigger, better data
#
# ## Resources:
# - [The Unreasonable Effectiveness of Recurrent Neural Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/) - a seminal writeup demonstrating a simple but effective character-level NLP RNN
# - [Simple NumPy implementation of RNN](https://github.com/JY-Yoon/RNN-Implementation-using-NumPy/blob/master/RNN%20Implementation%20using%20NumPy.ipynb) - Python 3 version of the code from "Unreasonable Effectiveness"
# - [TensorFlow RNN Tutorial](https://github.com/tensorflow/models/tree/master/tutorials/rnn) - code for training a RNN on the Penn Tree Bank language dataset
# - [4 part tutorial on RNN](http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/) - relates RNN to the vanishing gradient problem, and provides example implementation
# - [RNN training tips and tricks](https://github.com/karpathy/char-rnn#tips-and-tricks) - some rules of thumb for parameterizing and training your RNN
| module1-rnn-and-lstm/LS_DS_431_RNN_and_LSTM_Assignment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Netflix Movie Recommendation System
# ## Business Problem
#
# <p>Netflix is all about connecting people to the movies they love. To help customers find those movies, they developed world-class movie recommendation system: CinematchSM. Its job is to predict whether someone will enjoy a movie based on how much they liked or disliked other movies. Netflix use those predictions to make personal movie recommendations based on each customer’s unique tastes. And while Cinematch is doing pretty well, it can always be made better.</p>
#
# <p>Now there are a lot of interesting alternative approaches to how Cinematch works that netflix haven’t tried. Some are described in the literature, some aren’t. We’re curious whether any of these can beat Cinematch by making better predictions. Because, frankly, if there is a much better approach it could make a big difference to our customers and our business.</p>
#
# <p>Credits: https://www.netflixprize.com/rules.html</p>
#
# ## Problem Statement
# <p>Netflix provided a lot of anonymous rating data, and a prediction accuracy bar that is 10% better than what Cinematch can do on the same training data set. (Accuracy is a measurement of how closely predicted ratings of movies match subsequent actual ratings.)</p>
#
# ## Sources
# * https://www.netflixprize.com/rules.html
# * https://www.kaggle.com/netflix-inc/netflix-prize-data
# * Netflix blog: https://medium.com/netflix-techblog/netflix-recommendations-beyond-the-5-stars-part-1-55838468f429 (very nice blog)
# * surprise library: http://surpriselib.com/ (we use many models from this library)
# * surprise library doc: http://surprise.readthedocs.io/en/stable/getting_started.html (we use many models from this library)
# * installing surprise: https://github.com/NicolasHug/Surprise#installation
# * Research paper: http://courses.ischool.berkeley.edu/i290-dm/s11/SECURE/a1-koren.pdf (most of our work was inspired by this paper)
# * SVD Decomposition : https://www.youtube.com/watch?v=P5mlg91as1c
#
# <p><b>Real world/Business Objectives and constraints</b></p>
#
# <p><b>Objectives:</b></p>
# 1. Predict the rating that a user would give to a movie that he has not yet rated.<br>
# 2. Minimize the difference between predicted and actual rating (RMSE and MAPE).
#
# <p><b>Constraints:</b></p>
# 1. Some form of interpretability.
# 2. There is no low latency requirement as the recommended movies can be precomputed earlier.
#
# <p><b>Type of Data:</b></p>
# * There are 17770 unique movie IDs.
# * There are 480189 unique user IDs.
# * There are ratings. Ratings are on a five star (integral) scale from 1 to 5.
# <p><b>Data Overview</b></p>
# <b>Data files :</b><br>
#
# 1. combined_data_1.txt
# 2. combined_data_2.txt
# 3. combined_data_3.txt
# 4. combined_data_4.txt
# 5. movie_titles.csv
#
# The first line of each file [combined_data_1.txt, combined_data_2.txt, combined_data_3.txt, combined_data_4.txt] contains the movie id followed by a colon. Each subsequent line in the file corresponds to a customerID, rating from a customer and its date.
# <p style = "font-size: 22px"><b>Example Data Point</b></p>
# <pre>
# 1:
# 1488844,3,2005-09-06
# 822109,5,2005-05-13
# 885013,4,2005-10-19
# 30878,4,2005-12-26
# 823519,3,2004-05-03
# 893988,3,2005-11-17
# 124105,4,2004-08-05
# 1248029,3,2004-04-22
# 1842128,4,2004-05-09
# 2238063,3,2005-05-11
# 1503895,4,2005-05-19
# 2207774,5,2005-06-06
# 2590061,3,2004-08-12
# 2442,3,2004-04-14
# 543865,4,2004-05-28
# 1209119,4,2004-03-23
# 804919,4,2004-06-10
# 1086807,3,2004-12-28
# 1711859,4,2005-05-08
# 372233,5,2005-11-23
# 1080361,3,2005-03-28
# 1245640,3,2005-12-19
# 558634,4,2004-12-14
# 2165002,4,2004-04-06
# 1181550,3,2004-02-01
# 1227322,4,2004-02-06
# 427928,4,2004-02-26
# 814701,5,2005-09-29
# 808731,4,2005-10-31
# 662870,5,2005-08-24
# 337541,5,2005-03-23
# 786312,3,2004-11-16
# 1133214,4,2004-03-07
# 1537427,4,2004-03-29
# 1209954,5,2005-05-09
# 2381599,3,2005-09-12
# 525356,2,2004-07-11
# 1910569,4,2004-04-12
# 2263586,4,2004-08-20
# 2421815,2,2004-02-26
# 1009622,1,2005-01-19
# 1481961,2,2005-05-24
# 401047,4,2005-06-03
# 2179073,3,2004-08-29
# 1434636,3,2004-05-01
# 93986,5,2005-10-06
# 1308744,5,2005-10-29
# 2647871,4,2005-12-30
# 1905581,5,2005-08-16
# 2508819,3,2004-05-18
# 1578279,1,2005-05-19
# 1159695,4,2005-02-15
# 2588432,3,2005-03-31
# 2423091,3,2005-09-12
# 470232,4,2004-04-08
# 2148699,2,2004-06-05
# 1342007,3,2004-07-16
# 466135,4,2004-07-13
# 2472440,3,2005-08-13
# 1283744,3,2004-04-17
# 1927580,4,2004-11-08
# 716874,5,2005-05-06
# 4326,4,2005-10-29
# </pre>
# ## Mapping the real world problem to a Machine Learning Problem
# <p><b>Type of Machine Learning Problem</b></p>
# <p>
# For a given movie and user we need to predict the rating would be given by him/her to the movie.
# The given problem is a Recommendation problem
# It can also seen as a Regression problem
# </p>
# <p><b>Performance metric</b></p>
# 1. Mean Absolute Percentage Error
# 2. Root Mean Square Error
#
# <p><b>Machine Learning Objective and Constraints</b></p>
# 1. Try to Minimize RMSE
# 2. Provide some form of interpretability
# +
from datetime import datetime
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_style("whitegrid")
import os
import random
import matplotlib
import matplotlib.pyplot as plt
from scipy import sparse
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import mean_squared_error
import xgboost as xgb
from surprise import Reader, Dataset
from surprise import BaselineOnly
from surprise import KNNBaseline
from surprise import SVD
from surprise import SVDpp
from surprise.model_selection import GridSearchCV
# -
# ## 1. Reading and Storing Data
# ### Data Pre-processing
if not os.path.isfile("../Data/NetflixRatings.csv"):
#This line: "os.path.isfile("../Data/NetflixRatings.csv")" simply checks that is there a file with the name "NetflixRatings.csv" in the
#in the folder "/Data/". If the file is present then it return true else false
startTime = datetime.now()
data = open("../Data/NetflixRatings.csv", mode = "w") #this line simply creates the file with the name "NetflixRatings.csv" in
#write mode in the folder "Data".
# files = ['../Data/combined_data_1.txt','../Data/combined_data_2.txt', '../Data/combined_data_3.txt', '../Data/combined_data_4.txt']
files = ['../Data/combined_data_2.txt', '../Data/combined_data_4.txt']
for file in files:
print("Reading from file: "+str(file)+"...")
with open(file) as f: #you can think of this command "with open(file) as f" as similar to 'if' statement or a sort of
#loop statement. This command says that as long as this file is opened, perform the underneath operation.
for line in f:
line = line.strip() #line.strip() clears all the leading and trailing spaces from the string, as here each line
#that we are reading from a file is a string.
#Note first line consist of a movie id followed by a semi-colon, then second line contains custID,rating,date
#then third line agains contains custID,rating,date which belong to that movie ID and so on. The format of data
#is exactly same as shown above with the heading "Example Data Point". Check out above.
if line.endswith(":"):
movieID = line.replace(":", "") #this will remove the trailing semi-colon and return us the leading movie ID.
else:
#here, in the below code we have first created an empty list with the name "row "so that we can insert movie ID
#at the first position and rest customerID, rating and date in second position. After that we have separated all
#four namely movieID, custID, rating and date with comma and converted a single string by joining them with comma.
#then finally written them to our output ".csv" file.
row = []
row = [x for x in line.split(",")] #custID, rating and date are separated by comma
row.insert(0, movieID)
data.write(",".join(row))
data.write("\n")
print("Reading of file: "+str(file)+" is completed\n")
data.close()
print("Total time taken for execution of this code = "+str(datetime.now() - startTime))
# creating data frame from our output csv file.
if not os.path.isfile("../Data/NetflixData.pkl"):
startTime = datetime.now()
Final_Data = pd.read_csv("../Data/NetflixRatings.csv", sep=",", names = ["MovieID","CustID", "Ratings", "Date"])
Final_Data["Date"] = pd.to_datetime(Final_Data["Date"])
Final_Data.sort_values(by = "Date", inplace = True)
print("Time taken for execution of above code = "+str(datetime.now() - startTime))
# storing pandas dataframe as a picklefile for later use
if not os.path.isfile("../Data/NetflixData.pkl"):
Final_Data.to_pickle("../Data/NetflixData.pkl")
else:
Final_Data = pd.read_pickle("../Data/NetflixData.pkl")
Final_Data.head()
Final_Data.describe()["Ratings"]
# ### Checking for NaN
print("Number of NaN values = "+str(Final_Data.isnull().sum()))
# ### Removing Duplicates
duplicates = Final_Data.duplicated(["MovieID","CustID", "Ratings"])
print("Number of duplicate rows = "+str(duplicates.sum()))
# ### Basic Statistics
print("Total Data:")
print("Total number of movie ratings = "+str(Final_Data.shape[0]))
print("Number of unique users = "+str(len(np.unique(Final_Data["CustID"]))))
print("Number of unique movies = "+str(len(np.unique(Final_Data["MovieID"]))))
# ### Spliting data into Train and Test(80:20)
# +
if not os.path.isfile("../Data/TrainData.pkl"):
Final_Data.iloc[:int(Final_Data.shape[0]*0.80)].to_pickle("../Data/TrainData.pkl")
Train_Data = pd.read_pickle("../Data/TrainData.pkl")
Train_Data.reset_index(drop = True, inplace = True)
else:
Train_Data = pd.read_pickle("../Data/TrainData.pkl")
Train_Data.reset_index(drop = True, inplace = True)
if not os.path.isfile("../Data/TestData.pkl"):
Final_Data.iloc[int(Final_Data.shape[0]*0.80):].to_pickle("../Data/TestData.pkl")
Test_Data = pd.read_pickle("../Data/TestData.pkl")
Test_Data.reset_index(drop = True, inplace = True)
else:
Test_Data = pd.read_pickle("../Data/TestData.pkl")
Test_Data.reset_index(drop = True, inplace = True)
# -
# ### Basic Statistics in Train data
Train_Data.head()
print("Total Train Data:")
print("Total number of movie ratings in train data = "+str(Train_Data.shape[0]))
print("Number of unique users in train data = "+str(len(np.unique(Train_Data["CustID"]))))
print("Number of unique movies in train data = "+str(len(np.unique(Train_Data["MovieID"]))))
print("Highest value of a User ID = "+str(max(Train_Data["CustID"].values)))
print("Highest value of a Movie ID = "+str(max(Train_Data["MovieID"].values)))
# ### Basic Statistics in Test data
Test_Data.head()
print("Total Test Data:")
print("Total number of movie ratings in Test data = "+str(Test_Data.shape[0]))
print("Number of unique users in Test data = "+str(len(np.unique(Test_Data["CustID"]))))
print("Number of unique movies in Test data = "+str(len(np.unique(Test_Data["MovieID"]))))
print("Highest value of a User ID = "+str(max(Test_Data["CustID"].values)))
print("Highest value of a Movie ID = "+str(max(Test_Data["MovieID"].values)))
# ## 2. Exploratory Data Analysis on Train Data
def changingLabels(number):
return str(number/10**6) + "M"
# +
plt.figure(figsize = (12, 8))
ax = sns.countplot(x="Ratings", data=Train_Data)
ax.set_yticklabels([changingLabels(num) for num in ax.get_yticks()])
plt.tick_params(labelsize = 15)
plt.title("Distribution of Ratings in train data", fontsize = 20)
plt.xlabel("Ratings", fontsize = 20)
plt.ylabel("Number of Ratings(Millions)", fontsize = 20)
plt.show()
# -
Train_Data["DayOfWeek"] = Train_Data.Date.dt.weekday_name
Train_Data.tail()
# ### Number of Ratings per month
plt.figure(figsize = (10,8))
ax = Train_Data.resample("M", on = "Date")["Ratings"].count().plot()
#this above resample() function is a sort of group-by operation.Resample() function can work with dates. It can take months,
#days and years values independently. Here, in parameter we have given "M" which means it will group all the rows Monthly using
#"Date" which is already present in the DataFrame. Now after grouping the rows month wise, we have just counted the ratings
#which are grouped by months and plotted them. So, below plot shows that how many ratings are there per month.
#In resample(), we can also give "6M" for grouping the rows every 6-Monthly, we can also give "Y" for grouping
#the rows yearly, we can also give "D" for grouping the rows by day.
#Resample() is a function which is designed to work with time and dates.
#This "Train_Data.resample("M", on = "Date")["Ratings"].count()" returns a pandas series where keys are Dates and values are
#counts of ratings grouped by months.You can even check it and print it. Then we are plotting it, where it automatically takes
#Dates--which are keys on--x-axis and counts--which are values on--y-axis.
ax.set_yticklabels([changingLabels(num) for num in ax.get_yticks()])
ax.set_title("Number of Ratings per month", fontsize = 20)
ax.set_xlabel("Date", fontsize = 20)
ax.set_ylabel("Number of Ratings Per Month(Millions)", fontsize = 20)
plt.tick_params(labelsize = 15)
plt.show()
# +
#Train_Data.resample("M", on = "Date")["Ratings"].count()
# -
# ### Analysis of Ratings given by user
no_of_rated_movies_per_user = Train_Data.groupby(by = "CustID")["Ratings"].count().sort_values(ascending = False)
no_of_rated_movies_per_user.head()
# +
fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize=(14,7))
sns.kdeplot(no_of_rated_movies_per_user.values, shade = True, ax = axes[0])
axes[0].set_title("PDF", fontsize = 18)
axes[0].set_xlabel("Number of Ratings by user", fontsize = 18)
axes[0].tick_params(labelsize = 15)
sns.kdeplot(no_of_rated_movies_per_user.values, shade = True, cumulative = True, ax = axes[1])
axes[1].set_title("CDF", fontsize = 18)
axes[1].set_xlabel("Number of Ratings by user", fontsize = 18)
axes[1].tick_params(labelsize = 15)
fig.subplots_adjust(wspace=2)
plt.tight_layout()
plt.show()
# -
# * Above PDF graph shows that almost all of the users give very few ratings. There are very few users who's ratings count is high.
# * Similarly, above CDF graph shows that almost 99% of users give very few ratings.
print("Information about movie ratings grouped by users:")
no_of_rated_movies_per_user.describe()
# +
# no_of_rated_movies_per_user.describe()["75%"]
# -
quantiles = no_of_rated_movies_per_user.quantile(np.arange(0,1.01,0.01))
# +
fig = plt.figure(figsize = (10, 6))
axes = fig.add_axes([0.1,0.1,1,1])
axes.set_title("Quantile values of Ratings Per User", fontsize = 20)
axes.set_xlabel("Quantiles", fontsize = 20)
axes.set_ylabel("Ratings Per User", fontsize = 20)
axes.plot(quantiles)
plt.scatter(x = quantiles.index[::5], y = quantiles.values[::5], c = "blue", s = 70, label="quantiles with 0.05 intervals")
plt.scatter(x = quantiles.index[::25], y = quantiles.values[::25], c = "red", s = 70, label="quantiles with 0.25 intervals")
plt.legend(loc='upper left', fontsize = 20)
for x, y in zip(quantiles.index[::25], quantiles.values[::25]):
plt.annotate(s = '({},{})'.format(x, y), xy = (x, y), fontweight='bold', fontsize = 16, xytext=(x-0.05, y+180))
axes.tick_params(labelsize = 15)
# -
quantiles[::5]
print("Total number of ratings below 75th percentile = "+str(sum(no_of_rated_movies_per_user.values<=133)))
print("Total number of ratings above 75th percentile = "+str(sum(no_of_rated_movies_per_user.values>133)))
# ### Analysis of Ratings Per Movie
no_of_ratings_per_movie = Train_Data.groupby(by = "MovieID")["Ratings"].count().sort_values(ascending = False)
fig = plt.figure(figsize = (12, 6))
axes = fig.add_axes([0.1,0.1,1,1])
plt.title("Number of Ratings Per Movie", fontsize = 20)
plt.xlabel("Movie", fontsize = 20)
plt.ylabel("Count of Ratings", fontsize = 20)
plt.plot(no_of_ratings_per_movie.values)
plt.tick_params(labelsize = 15)
axes.set_xticklabels([])
plt.show()
# <b>It is very skewed</b>
# <p>It clearly shows that there are some movies which are very popular and were rated by many users as comapared to other movies</p>
# ### Analysis of Movie Ratings on Day of Week
# +
fig = plt.figure(figsize = (12, 8))
axes = sns.countplot(x = "DayOfWeek", data = Train_Data)
axes.set_title("Day of week VS Number of Ratings", fontsize = 20)
axes.set_xlabel("Day of Week", fontsize = 20)
axes.set_ylabel("Number of Ratings", fontsize = 20)
axes.set_yticklabels([changingLabels(num) for num in ax.get_yticks()])
axes.tick_params(labelsize = 15)
plt.show()
# +
fig = plt.figure(figsize = (12, 8))
axes = sns.boxplot(x = "DayOfWeek", y = "Ratings", data = Train_Data)
axes.set_title("Day of week VS Number of Ratings", fontsize = 20)
axes.set_xlabel("Day of Week", fontsize = 20)
axes.set_ylabel("Number of Ratings", fontsize = 20)
axes.tick_params(labelsize = 15)
plt.show()
# -
average_ratings_dayofweek = Train_Data.groupby(by = "DayOfWeek")["Ratings"].mean()
print("Average Ratings on Day of Weeks")
print(average_ratings_dayofweek)
# ## 3. Creating USER-ITEM sparse matrix from data frame
# +
startTime = datetime.now()
print("Creating USER_ITEM sparse matrix for train Data")
if os.path.isfile("../Data/TrainUISparseData.npz"):
print("Sparse Data is already present in your disk, no need to create further. Loading Sparse Matrix")
TrainUISparseData = sparse.load_npz("../Data/TrainUISparseData.npz")
print("Shape of Train Sparse matrix = "+str(TrainUISparseData.shape))
else:
print("We are creating sparse data")
TrainUISparseData = sparse.csr_matrix((Train_Data.Ratings, (Train_Data.CustID, Train_Data.MovieID)))
print("Creation done. Shape of sparse matrix = "+str(TrainUISparseData.shape))
print("Saving it into disk for furthur usage.")
sparse.save_npz("../Data/TrainUISparseData.npz", TrainUISparseData)
print("Done\n")
print(datetime.now() - startTime)
# +
startTime = datetime.now()
print("Creating USER_ITEM sparse matrix for test Data")
if os.path.isfile("../Data/TestUISparseData.npz"):
print("Sparse Data is already present in your disk, no need to create further. Loading Sparse Matrix")
TestUISparseData = sparse.load_npz("../Data/TestUISparseData.npz")
print("Shape of Test Sparse Matrix = "+str(TestUISparseData.shape))
else:
print("We are creating sparse data")
TestUISparseData = sparse.csr_matrix((Test_Data.Ratings, (Test_Data.CustID, Test_Data.MovieID)))
print("Creation done. Shape of sparse matrix = "+str(TestUISparseData.shape))
print("Saving it into disk for furthur usage.")
sparse.save_npz("../Data/TestUISparseData.npz", TestUISparseData)
print("Done\n")
print(datetime.now() - startTime)
# +
#If you can see above that the shape of both train and test sparse matrices are same, furthermore, how come this shape of sparse
#matrix has arrived:
#Shape of sparse matrix depends on highest value of User ID and highest value of Movie ID.
#Now the user whose user ID is highest is present in both train data and test data. Similarly, the movie whose movie ID is
#highest is present in both train data and test data. Hence, shape of both train and test sparse matrices are same.
# +
rows,cols = TrainUISparseData.shape
presentElements = TrainUISparseData.count_nonzero()
print("Sparsity Of Train matrix : {}% ".format((1-(presentElements/(rows*cols)))*100))
# +
rows,cols = TestUISparseData.shape
presentElements = TestUISparseData.count_nonzero()
print("Sparsity Of Test matrix : {}% ".format((1-(presentElements/(rows*cols)))*100))
# -
# ### Finding Global average of all movie ratings, Average rating per user, and Average rating per movie
def getAverageRatings(sparseMatrix, if_user):
ax = 1 if if_user else 0
#axis = 1 means rows and axis = 0 means columns
sumOfRatings = sparseMatrix.sum(axis = ax).A1 #this will give an array of sum of all the ratings of user if axis = 1 else
#sum of all the ratings of movies if axis = 0
noOfRatings = (sparseMatrix!=0).sum(axis = ax).A1 #this will give a boolean True or False array, and True means 1 and False
#means 0, and further we are summing it to get the count of all the non-zero cells means length of non-zero cells
rows, cols = sparseMatrix.shape
averageRatings = {i: sumOfRatings[i]/noOfRatings[i] for i in range(rows if if_user else cols) if noOfRatings[i]!=0}
return averageRatings
# ### Global Average Rating
Global_Average_Rating = TrainUISparseData.sum()/TrainUISparseData.count_nonzero()
print("Global Average Rating {}".format(Global_Average_Rating))
# ### Average Rating Per User
AvgRatingUser = getAverageRatings(TrainUISparseData, True)
print("Average rating of user 25 = {}".format(AvgRatingUser[25]))
# ### Average Rating Per Movie
AvgRatingMovie = getAverageRatings(TrainUISparseData, False)
print("Average rating of movie 4500 = {}".format(AvgRatingMovie[4500]))
# ### PDF and CDF of Average Ratings of Users and Movies
# +
fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (16, 7))
fig.suptitle('Avg Ratings per User and per Movie', fontsize=25)
user_average = [rats for rats in AvgRatingUser.values()]
sns.distplot(user_average, hist = False, ax = axes[0], label = "PDF")
sns.kdeplot(user_average, cumulative = True, ax = axes[0], label = "CDF")
axes[0].set_title("Average Rating Per User", fontsize=20)
axes[0].tick_params(labelsize = 15)
axes[0].legend(loc='upper left', fontsize = 17)
movie_average = [ratm for ratm in AvgRatingMovie.values()]
sns.distplot(movie_average, hist = False, ax = axes[1], label = "PDF")
sns.kdeplot(movie_average, cumulative = True, ax = axes[1], label = "CDF")
axes[1].set_title("Average Rating Per Movie", fontsize=20)
axes[1].tick_params(labelsize = 15)
axes[1].legend(loc='upper left', fontsize = 17)
plt.subplots_adjust(wspace=0.2, top=0.85)
plt.show()
# -
# ### Cold Start Problem
# #### Cold Start Problem with Users
# +
total_users = len(np.unique(Final_Data["CustID"]))
train_users = len(AvgRatingUser)
uncommonUsers = total_users - train_users
print("Total number of Users = {}".format(total_users))
print("Number of Users in train data= {}".format(train_users))
print("Number of Users not present in train data = {}({}%)".format(uncommonUsers, np.round((uncommonUsers/total_users)*100), 2))
# -
# #### Cold Start Problem with Movies
# +
total_movies = len(np.unique(Final_Data["MovieID"]))
train_movies = len(AvgRatingMovie)
uncommonMovies = total_movies - train_movies
print("Total number of Movies = {}".format(total_movies))
print("Number of Movies in train data= {}".format(train_movies))
print("Number of Movies not present in train data = {}({}%)".format(uncommonMovies, np.round((uncommonMovies/total_movies)*100), 2))
# -
# ## 4. Computing Similarity Matrices
# ### Computing User-User Similarity Matrix
# Calculating User User Similarity_Matrix is __not very easy__(_unless you have huge Computing Power and lots of time_)
row_index, col_index = TrainUISparseData.nonzero()
rows = np.unique(row_index)
for i in rows[:100]:
print(i)
#Here, we are calculating user-user similarity matrix only for first 100 users in our sparse matrix. And we are calculating
#top 100 most similar users with them.
def getUser_UserSimilarity(sparseMatrix, top = 100):
startTimestamp20 = datetime.now()
row_index, col_index = sparseMatrix.nonzero() #this will give indices of rows in "row_index" and indices of columns in
#"col_index" where there is a non-zero value exist.
rows = np.unique(row_index)
similarMatrix = np.zeros(61700).reshape(617,100) # 617*100 = 61700. As we are building similarity matrix only
#for top 100 most similar users.
timeTaken = []
howManyDone = 0
for row in rows[:top]:
howManyDone += 1
startTimestamp = datetime.now().timestamp() #it will give seconds elapsed
sim = cosine_similarity(sparseMatrix.getrow(row), sparseMatrix).ravel()
top100_similar_indices = sim.argsort()[-top:]
top100_similar = sim[top100_similar_indices]
similarMatrix[row] = top100_similar
timeforOne = datetime.now().timestamp() - startTimestamp
timeTaken.append(timeforOne)
if howManyDone % 20 == 0:
print("Time elapsed for {} users = {}sec".format(howManyDone, (datetime.now() - startTimestamp20)))
print("Average Time taken to compute similarity matrix for 1 user = "+str(sum(timeTaken)/len(timeTaken))+"seconds")
fig = plt.figure(figsize = (12,8))
plt.plot(timeTaken, label = 'Time Taken For Each User')
plt.plot(np.cumsum(timeTaken), label='Cumulative Time')
plt.legend(loc='upper left', fontsize = 15)
plt.xlabel('Users', fontsize = 20)
plt.ylabel('Time(Seconds)', fontsize = 20)
plt.tick_params(labelsize = 15)
plt.show()
return similarMatrix
simMatrix = getUser_UserSimilarity(TrainUISparseData, 100)
# <p>We have __401901 Users__ in our training data.<br><br>Average time taken to compute similarity matrix for one user is __3.635 sec.__<br><br>For 401901 users:<br><br>_401901*3.635 == 1460910.135sec == 405.808hours == 17Days_<br><br>Computation of user-user similarity matrix is impossible if computational power is limited. On the other hand, if we try to reduce the dimension say by truncated SVD then it would take even more time because truncated SVD creates dense matrix and amount of multiplication for creation of user-user similarity matrix would increase dramatically.<br><br>__Is there any other way to compute user-user similarity???__<br><br>We maintain a binary Vector for users, which tells us whether we already computed similarity for this user or not..<br><br>
# __OR__<br><br>Compute top (let's just say, 1000) most similar users for this given user, and add this to our datastructure, so that we can just access it(similar users) without recomputing it again. <br><br>__If it is already computed__<br><br>Just get it directly from our datastructure, which has that information. In production time, We might have to recompute similarities, if it is computed a long time ago. Because user preferences changes over time. If we could maintain some kind of Timer, which when expires, we have to update it ( recompute it ). <br><br>Which datastructure to use:<br><br>It is purely implementation dependant.<br><br>
# One simple method is to maintain a **Dictionary Of Dictionaries**.<br><br>
#
# key : userid<br>
# value : Again a dictionary<br>
# key : _Similar User<br>
# value: Similarity Value>
# ### Computing Movie-Movie Similarity Matrix
# +
start = datetime.now()
if not os.path.isfile("../Data/m_m_similarity.npz"):
print("Movie-Movie Similarity file does not exist in your disk. Creating Movie-Movie Similarity Matrix...")
m_m_similarity = cosine_similarity(TrainUISparseData.T, dense_output = False)
print("Done")
print("Dimension of Matrix = {}".format(m_m_similarity.shape))
print("Storing the Movie Similarity matrix on disk for further usage")
sparse.save_npz("../Data/m_m_similarity.npz", m_m_similarity)
else:
print("File exists in the disk. Loading the file...")
m_m_similarity = sparse.load_npz("../Data/m_m_similarity.npz")
print("Dimension of Matrix = {}".format(m_m_similarity.shape))
print(datetime.now() - start)
# -
# ### Does Movie-Movie Similarity Works?
# ### Let's pick random movie and check it's top 10 most similar movies.
movie_ids = np.unique(m_m_similarity.nonzero())
similar_movies_dict = dict()
for movie in movie_ids:
smlr = np.argsort(-m_m_similarity[movie].toarray().ravel())[1:100]
similar_movies_dict[movie] = smlr
movie_titles_df = pd.read_csv("../Data/movie_titles.csv",sep = ",", header = None, names=['MovieID', 'Year_of_Release', 'Movie_Title'], index_col = "MovieID", encoding = "iso8859_2")
movie_titles_df.head()
# ### Similar Movies to: __Godzilla's Revenge__
# +
movieID_GR = 17765
print("Name of the movie -------> "+str(movie_titles_df.loc[movieID_GR][1]))
print("Number of ratings by users for movie {} is {}".format(movie_titles_df.loc[movieID_GR][1], TrainUISparseData[:,movieID_GR].getnnz()))
print("Number of similar movies to {} is {}".format(movie_titles_df.loc[movieID_GR][1], m_m_similarity[movieID_GR].count_nonzero()))
# +
# Meaning of "[:,17765]" means get all the values of column "17765".
# "getnnz()" give count of explicitly-stored values (nonzeros).
# +
all_similar = sorted(m_m_similarity[movieID_GR].toarray().ravel(), reverse = True)[1:]
similar_100 = all_similar[:101]
# -
plt.figure(figsize = (10, 8))
plt.plot(all_similar, label = "All Similar")
plt.plot(similar_100, label = "Top 100 Similar Movies")
plt.title("Similar Movies to Godzilla's Revenge", fontsize = 25)
plt.ylabel("Cosine Similarity Values", fontsize = 20)
plt.tick_params(labelsize = 15)
plt.legend(fontsize = 20)
plt.show()
# ### Top 10 Similar Movies to: __Godzilla's Revenge__
movie_titles_df.loc[similar_movies_dict[movieID_GR][:10]]
# <p>__It seems that Movie-Movie similarity is working perfectly.__</p>
# ## 5. Machine Learning Models
def get_sample_sparse_matrix(sparseMatrix, n_users, n_movies):
startTime = datetime.now()
users, movies, ratings = sparse.find(sparseMatrix)
uniq_users = np.unique(users)
uniq_movies = np.unique(movies)
np.random.seed(15) #this will give same random number everytime, without replacement
userS = np.random.choice(uniq_users, n_users, replace = False)
movieS = np.random.choice(uniq_movies, n_movies, replace = False)
mask = np.logical_and(np.isin(users, userS), np.isin(movies, movieS))
sparse_sample = sparse.csr_matrix((ratings[mask], (users[mask], movies[mask])),
shape = (max(userS)+1, max(movieS)+1))
print("Sparse Matrix creation done. Saving it for later use.")
sparse.save_npz(path, sparse_sample)
print("Done")
print("Shape of Sparse Sampled Matrix = "+str(sparse_sample.shape))
print(datetime.now() - start)
return sparse_sample
# ### Creating Sample Sparse Matrix for Train Data
path = "../Data/TrainUISparseData_Sample.npz"
if not os.path.isfile(path):
print("Sample sparse matrix is not present in the disk. We are creating it...")
train_sample_sparse = get_sample_sparse_matrix(TrainUISparseData, 4000, 400)
else:
print("File is already present in the disk. Loading the file...")
train_sample_sparse = sparse.load_npz(path)
print("File loading done.")
print("Shape of Train Sample Sparse Matrix = "+str(train_sample_sparse.shape))
# ### Creating Sample Sparse Matrix for Test Data
path = "../Data/TestUISparseData_Sample.npz"
if not os.path.isfile(path):
print("Sample sparse matrix is not present in the disk. We are creating it...")
test_sample_sparse = get_sample_sparse_matrix(TestUISparseData, 2000, 200)
else:
print("File is already present in the disk. Loading the file...")
test_sample_sparse = sparse.load_npz(path)
print("File loading done.")
print("Shape of Test Sample Sparse Matrix = "+str(test_sample_sparse.shape))
# ### Finding Global Average of all movie ratings, Average rating per User, and Average rating per Movie (from sampled train)
print("Global average of all movies ratings in Train Sample Sparse is {}".format(np.round((train_sample_sparse.sum()/train_sample_sparse.count_nonzero()), 2)))
# ### Finding Average of all movie ratings
globalAvgMovies = getAverageRatings(train_sample_sparse, False)
print("Average move rating for movie 14890 is {}".format(globalAvgMovies[14890]))
# ### Finding Average rating per User
globalAvgUsers = getAverageRatings(train_sample_sparse, True)
print("Average user rating for user 16879 is {}".format(globalAvgMovies[16879]))
# ### Featurizing data
print("No of ratings in Our Sampled train matrix is : {}".format(train_sample_sparse.count_nonzero()))
print("No of ratings in Our Sampled test matrix is : {}".format(test_sample_sparse.count_nonzero()))
# ### Featurizing data for regression problem
# ### Featurizing Train Data
sample_train_users, sample_train_movies, sample_train_ratings = sparse.find(train_sample_sparse)
# +
if os.path.isfile("../Data/Train_Regression.csv"):
print("File is already present in your disk. You do not have to prepare it again.")
else:
startTime = datetime.now()
print("Preparing Train csv file for {} rows".format(len(sample_train_ratings)))
with open("../Data/Train_Regression.csv", mode = "w") as data:
count = 0
for user, movie, rating in zip(sample_train_users, sample_train_movies, sample_train_ratings):
row = list()
row.append(user) #appending user ID
row.append(movie) #appending movie ID
row.append(train_sample_sparse.sum()/train_sample_sparse.count_nonzero()) #appending global average rating
#----------------------------------Ratings given to "movie" by top 5 similar users with "user"--------------------#
similar_users = cosine_similarity(train_sample_sparse[user], train_sample_sparse).ravel()
similar_users_indices = np.argsort(-similar_users)[1:]
similar_users_ratings = train_sample_sparse[similar_users_indices, movie].toarray().ravel()
top_similar_user_ratings = list(similar_users_ratings[similar_users_ratings != 0][:5])
top_similar_user_ratings.extend([globalAvgMovies[movie]]*(5-len(top_similar_user_ratings)))
#above line means that if top 5 ratings are not available then rest of the ratings will be filled by "movie" average
#rating. Let say only 3 out of 5 ratings are available then rest 2 will be "movie" average rating.
row.extend(top_similar_user_ratings)
#----------------------------------Ratings given by "user" to top 5 similar movies with "movie"------------------#
similar_movies = cosine_similarity(train_sample_sparse[:,movie].T, train_sample_sparse.T).ravel()
similar_movies_indices = np.argsort(-similar_movies)[1:]
similar_movies_ratings = train_sample_sparse[user, similar_movies_indices].toarray().ravel()
top_similar_movie_ratings = list(similar_movies_ratings[similar_movies_ratings != 0][:5])
top_similar_movie_ratings.extend([globalAvgUsers[user]]*(5-len(top_similar_movie_ratings)))
#above line means that if top 5 ratings are not available then rest of the ratings will be filled by "user" average
#rating. Let say only 3 out of 5 ratings are available then rest 2 will be "user" average rating.
row.extend(top_similar_movie_ratings)
#----------------------------------Appending "user" average, "movie" average & rating of "user""movie"-----------#
row.append(globalAvgUsers[user])
row.append(globalAvgMovies[movie])
row.append(rating)
#-----------------------------------Converting rows and appending them as comma separated values to csv file------#
data.write(",".join(map(str, row)))
data.write("\n")
count += 1
if count % 2000 == 0:
print("Done for {}. Time elapsed: {}".format(count, (datetime.now() - startTime)))
print("Total Time for {} rows = {}".format(len(sample_train_ratings), (datetime.now() - startTime)))
# -
Train_Reg = pd.read_csv("../Data/Train_Regression.csv", names = ["User_ID", "Movie_ID", "Global_Average", "SUR1", "SUR2", "SUR3", "SUR4", "SUR5", "SMR1", "SMR2", "SMR3", "SMR4", "SMR5", "User_Average", "Movie_Average", "Rating"])
Train_Reg.head()
print("Number of nan Values = "+str(Train_Reg.isnull().sum().sum()))
# <p><b>User_ID:</b> ID of a this User</p>
#
# <p><b>Movie_ID:</b> ID of a this Movie</p>
#
# <p><b>Global_Average:</b> Global Average Rating</p>
#
# <p><b>Ratings given to this Movie by top 5 similar users with this User:</b> (SUR1, SUR2, SUR3, SUR4, SUR5)</p>
#
# <p><b>Ratings given by this User to top 5 similar movies with this Movie:</b> (SMR1, SMR2, SMR3, SMR4, SMR5)</p>
#
# <p><b>User_Average:</b> Average Rating of this User</p>
#
# <p><b>Movie_Average:</b> Average Rating of this Movie</p>
#
# <p><b>Rating:</b> Rating given by this User to this Movie</p>
print("Shape of Train DataFrame = {}".format(Train_Reg.shape))
# ### Featurizing Test Data
sample_test_users, sample_test_movies, sample_test_ratings = sparse.find(test_sample_sparse)
# +
if os.path.isfile("../Data/Test_Regression.csv"):
print("File is already present in your disk. You do not have to prepare it again.")
else:
startTime = datetime.now()
print("Preparing Test csv file for {} rows".format(len(sample_test_ratings)))
with open("../Data/Test_Regression.csv", mode = "w") as data:
count = 0
for user, movie, rating in zip(sample_test_users, sample_test_movies, sample_test_ratings):
row = list()
row.append(user) #appending user ID
row.append(movie) #appending movie ID
row.append(train_sample_sparse.sum()/train_sample_sparse.count_nonzero()) #appending global average rating
#-----------------------------Ratings given to "movie" by top 5 similar users with "user"-------------------------#
try:
similar_users = cosine_similarity(train_sample_sparse[user], train_sample_sparse).ravel()
similar_users_indices = np.argsort(-similar_users)[1:]
similar_users_ratings = train_sample_sparse[similar_users_indices, movie].toarray().ravel()
top_similar_user_ratings = list(similar_users_ratings[similar_users_ratings != 0][:5])
top_similar_user_ratings.extend([globalAvgMovies[movie]]*(5-len(top_similar_user_ratings)))
#above line means that if top 5 ratings are not available then rest of the ratings will be filled by "movie"
#average rating. Let say only 3 out of 5 ratings are available then rest 2 will be "movie" average rating.
row.extend(top_similar_user_ratings)
#########Cold Start Problem, for a new user or a new movie#########
except(IndexError, KeyError):
global_average_train_rating = [train_sample_sparse.sum()/train_sample_sparse.count_nonzero()]*5
row.extend(global_average_train_rating)
except:
raise
#-----------------------------Ratings given by "user" to top 5 similar movies with "movie"-----------------------#
try:
similar_movies = cosine_similarity(train_sample_sparse[:,movie].T, train_sample_sparse.T).ravel()
similar_movies_indices = np.argsort(-similar_movies)[1:]
similar_movies_ratings = train_sample_sparse[user, similar_movies_indices].toarray().ravel()
top_similar_movie_ratings = list(similar_movies_ratings[similar_movies_ratings != 0][:5])
top_similar_movie_ratings.extend([globalAvgUsers[user]]*(5-len(top_similar_movie_ratings)))
#above line means that if top 5 ratings are not available then rest of the ratings will be filled by "user"
#average rating. Let say only 3 out of 5 ratings are available then rest 2 will be "user" average rating.
row.extend(top_similar_movie_ratings)
#########Cold Start Problem, for a new user or a new movie#########
except(IndexError, KeyError):
global_average_train_rating = [train_sample_sparse.sum()/train_sample_sparse.count_nonzero()]*5
row.extend(global_average_train_rating)
except:
raise
#-----------------------------Appending "user" average, "movie" average & rating of "user""movie"----------------#
try:
row.append(globalAvgUsers[user])
except (KeyError):
global_average_train_rating = train_sample_sparse.sum()/train_sample_sparse.count_nonzero()
row.append(global_average_train_rating)
except:
raise
try:
row.append(globalAvgMovies[movie])
except(KeyError):
global_average_train_rating = train_sample_sparse.sum()/train_sample_sparse.count_nonzero()
row.append(global_average_train_rating)
except:
raise
row.append(rating)
#------------------------------Converting rows and appending them as comma separated values to csv file-----------#
data.write(",".join(map(str, row)))
data.write("\n")
count += 1
if count % 100 == 0:
print("Done for {}. Time elapsed: {}".format(count, (datetime.now() - startTime)))
print("Total Time for {} rows = {}".format(len(sample_test_ratings), (datetime.now() - startTime)))
# -
Test_Reg = pd.read_csv("../Data/Test_Regression.csv", names = ["User_ID", "Movie_ID", "Global_Average", "SUR1", "SUR2", "SUR3", "SUR4", "SUR5", "SMR1", "SMR2", "SMR3", "SMR4", "SMR5", "User_Average", "Movie_Average", "Rating"])
Test_Reg.head()
print("Number of nan Values = "+str(Test_Reg.isnull().sum().sum()))
# <p><b>User_ID:</b> ID of a this User</p>
#
#
#
# <p><b>Movie_ID:</b> ID of a this Movie</p>
#
#
#
# <p><b>Global_Average:</b> Global Average Rating</p>
#
#
#
# <p><b>Ratings given to this Movie by top 5 similar users with this User:</b> (SUR1, SUR2, SUR3, SUR4, SUR5)</p>
#
#
#
# <p><b>Ratings given by this User to top 5 similar movies with this Movie:</b> (SMR1, SMR2, SMR3, SMR4, SMR5)</p>
#
#
# <p><b>User_Average:</b> Average Rating of this User</p>
#
#
# <p><b>Movie_Average:</b> Average Rating of this Movie</p>
#
#
# <p><b>Rating:</b> Rating given by this User to this Movie</p>
print("Shape of Test DataFrame = {}".format(Test_Reg.shape))
# ### Transforming Data for Surprise Models
# #### Transforming Train Data
# - We can't give raw data (movie, user, rating) to train the model in Surprise library.
#
#
# - They have a separate format for TRAIN and TEST data, which will be useful for training the models like SVD, KNNBaseLineOnly....etc..,in Surprise.
#
#
# - We can form the trainset from a file, or from a Pandas DataFrame.
# http://surprise.readthedocs.io/en/stable/getting_started.html#load-dom-dataframe-py
Train_Reg[['User_ID', 'Movie_ID', 'Rating']].head(5)
# +
reader = Reader(rating_scale=(1, 5))
data = Dataset.load_from_df(Train_Reg[['User_ID', 'Movie_ID', 'Rating']], reader)
trainset = data.build_full_trainset()
# -
# #### Transforming Test Data
#
# - For test data we just have to define a tuple (user, item, rating).
# - You can check out this link: https://github.com/NicolasHug/Surprise/commit/86cf44529ca0bbb97759b81d1716ff547b950812
# - Above link is a github of surprise library. Check methods "def all_ratings(self)" and "def build_testset(self)" from line
# 177 to 201(If they modify the file then line number may differ, but you can always check aforementioned two methods).
# - "def build_testset(self)" method returns a list of tuples of (user, item, rating).
testset = list(zip(Test_Reg["User_ID"].values, Test_Reg["Movie_ID"].values, Test_Reg["Rating"].values))
testset[:5]
# ### Applying Machine Learning Models
# <p>We have two Error Metrics.</p>
# <p><b>-> RMSE: Root Mean Square Error: </b>RMSE is the error of each point which is squared. Then mean is calculated. Finally root of that mean is taken as final value.</p>
# <p><b>-> MAPE: Mean Absolute Percentage Error: </b>The mean absolute percentage error (MAPE), also known as mean absolute percentage deviation (MAPD), is a measure of prediction accuracy of a forecasting method.</p>
# <p>where At is the actual value and Ft is the forecast value.</p>
# <p>
# The difference between At and Ft is divided by the actual value At again. The absolute value in this calculation is summed for every forecasted point in time and divided by the number of fitted points n. Multiplying by 100% makes it a percentage error.</p>
# <b>We can also use other regression models. But we are using exclusively XGBoost as it is typically fairly powerful in practice.</b>
error_table = pd.DataFrame(columns = ["Model", "Train RMSE", "Train MAPE", "Test RMSE", "Test MAPE"])
model_train_evaluation = dict()
model_test_evaluation = dict()
def make_table(model_name, rmse_train, mape_train, rmse_test, mape_test):
global error_table
#All variable assignments in a function store the value in the local symbol table; whereas variable references first look
#in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables
#cannot be directly assigned a value within a function (unless named in a global statement),
#although they may be referenced.
error_table = error_table.append(pd.DataFrame([[model_name, rmse_train, mape_train, rmse_test, mape_test]], columns = ["Model", "Train RMSE", "Train MAPE", "Test RMSE", "Test MAPE"]))
error_table.reset_index(drop = True, inplace = True)
# ### Utility Functions for Regression Models
def error_metrics(y_true, y_pred):
rmse = np.sqrt(mean_squared_error(y_true, y_pred))
mape = np.mean(abs((y_true - y_pred)/y_true))*100
return rmse, mape
def train_test_xgboost(x_train, x_test, y_train, y_test, model_name):
startTime = datetime.now()
train_result = dict()
test_result = dict()
clf = xgb.XGBRegressor(n_estimators = 100, silent = False, n_jobs = 10)
clf.fit(x_train, y_train)
print("-"*50)
print("TRAIN DATA")
y_pred_train = clf.predict(x_train)
rmse_train, mape_train = error_metrics(y_train, y_pred_train)
print("RMSE = {}".format(rmse_train))
print("MAPE = {}".format(mape_train))
print("-"*50)
train_result = {"RMSE": rmse_train, "MAPE": mape_train, "Prediction": y_pred_train}
print("TEST DATA")
y_pred_test = clf.predict(x_test)
rmse_test, mape_test = error_metrics(y_test, y_pred_test)
print("RMSE = {}".format(rmse_test))
print("MAPE = {}".format(mape_test))
print("-"*50)
test_result = {"RMSE": rmse_test, "MAPE": mape_test, "Prediction": y_pred_test}
print("Time Taken = "+str(datetime.now() - startTime))
plot_importance(xgb, clf)
make_table(model_name, rmse_train, mape_train, rmse_test, mape_test)
return train_result, test_result
def plot_importance(model, clf):
fig = plt.figure(figsize = (8, 6))
ax = fig.add_axes([0,0,1,1])
model.plot_importance(clf, ax = ax, height = 0.3)
plt.xlabel("F Score", fontsize = 20)
plt.ylabel("Features", fontsize = 20)
plt.title("Feature Importance", fontsize = 20)
plt.tick_params(labelsize = 15)
plt.show()
# ### Utility Functions for Surprise Models
def get_ratings(predictions):
actual = np.array([pred.r_ui for pred in predictions])
predicted = np.array([pred.est for pred in predictions])
return actual, predicted
#in surprise prediction of every data point is returned as dictionary like this:
#"user: 196 item: 302 r_ui = 4.00 est = 4.06 {'actual_k': 40, 'was_impossible': False}"
#In this dictionary, "r_ui" is a key for actual rating and "est" is a key for predicted rating
def get_error(predictions):
actual, predicted = get_ratings(predictions)
rmse = np.sqrt(mean_squared_error(actual, predicted))
mape = np.mean(abs((actual - predicted)/actual))*100
return rmse, mape
# +
my_seed = 15
random.seed(my_seed)
np.random.seed(my_seed)
def run_surprise(algo, trainset, testset, model_name):
startTime = datetime.now()
train = dict()
test = dict()
algo.fit(trainset)
#You can check out above function at "https://surprise.readthedocs.io/en/stable/getting_started.html" in
#"Train-test split and the fit() method" section
#-----------------Evaluating Train Data------------------#
print("-"*50)
print("TRAIN DATA")
train_pred = algo.test(trainset.build_testset())
#You can check out "algo.test()" function at "https://surprise.readthedocs.io/en/stable/getting_started.html" in
#"Train-test split and the fit() method" section
#You can check out "trainset.build_testset()" function at "https://surprise.readthedocs.io/en/stable/FAQ.html#can-i-use-my-own-dataset-with-surprise-and-can-it-be-a-pandas-dataframe" in
#"How to get accuracy measures on the training set" section
train_actual, train_predicted = get_ratings(train_pred)
train_rmse, train_mape = get_error(train_pred)
print("RMSE = {}".format(train_rmse))
print("MAPE = {}".format(train_mape))
print("-"*50)
train = {"RMSE": train_rmse, "MAPE": train_mape, "Prediction": train_predicted}
#-----------------Evaluating Test Data------------------#
print("TEST DATA")
test_pred = algo.test(testset)
#You can check out "algo.test()" function at "https://surprise.readthedocs.io/en/stable/getting_started.html" in
#"Train-test split and the fit() method" section
test_actual, test_predicted = get_ratings(test_pred)
test_rmse, test_mape = get_error(test_pred)
print("RMSE = {}".format(test_rmse))
print("MAPE = {}".format(test_mape))
print("-"*50)
test = {"RMSE": test_rmse, "MAPE": test_mape, "Prediction": test_predicted}
print("Time Taken = "+str(datetime.now() - startTime))
make_table(model_name, train_rmse, train_mape, test_rmse, test_mape)
return train, test
# -
# ## 1. XGBoost 13 Features
# +
x_train = Train_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
x_test = Test_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
y_train = Train_Reg["Rating"]
y_test = Test_Reg["Rating"]
train_result, test_result = train_test_xgboost(x_train, x_test, y_train, y_test, "XGBoost_13")
model_train_evaluation["XGBoost_13"] = train_result
model_test_evaluation["XGBoost_13"] = test_result
# -
# ## 2. Surprise BaselineOnly Model
# ### Predicted Rating
# > $\large\hat{r}_{ui} = \mu + b_u + b_i$<br><br>
#
# - $\mu$: Average Global Ratings in training data<br>
# - $b_u$: User-Bias<br>
# - $b_i$: Item-Bias
#
# ### Optimization Function
# > $\large \sum_{r_ui \in R_{Train}} \left(r_{ui} - (\mu + b_u + b_i)\right)^2 + \lambda \left(b_u^2 + b_i^2 \right). \left[minimize\; b_u, b_i \right]$
# +
bsl_options = {"method":"sgd", "learning_rate":0.01, "n_epochs":25}
algo = BaselineOnly(bsl_options=bsl_options)
#You can check the docs of above used functions at:https://surprise.readthedocs.io/en/stable/prediction_algorithms.html#baseline-estimates-configuration
#at section "Baselines estimates configuration".
train_result, test_result = run_surprise(algo, trainset, testset, "BaselineOnly")
model_train_evaluation["BaselineOnly"] = train_result
model_test_evaluation["BaselineOnly"] = test_result
# -
# ## 3. XGBoost 13 Features + Surprise BaselineOnly Model
# ### Adding predicted ratings from Surprise BaselineOnly model to our Train and Test Dataframe
Train_Reg["BaselineOnly"] = model_train_evaluation["BaselineOnly"]["Prediction"]
Train_Reg.head()
print("Number of nan values = "+str(Train_Reg.isnull().sum().sum()))
Test_Reg["BaselineOnly"] = model_test_evaluation["BaselineOnly"]["Prediction"]
Test_Reg.head()
print("Number of nan values = "+str(Test_Reg.isnull().sum().sum()))
# +
x_train = Train_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
x_test = Test_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
y_train = Train_Reg["Rating"]
y_test = Test_Reg["Rating"]
train_result, test_result = train_test_xgboost(x_train, x_test, y_train, y_test, "XGB_BSL")
model_train_evaluation["XGB_BSL"] = train_result
model_test_evaluation["XGB_BSL"] = test_result
# -
# ## 4. Surprise KNN-Baseline with User-User and Item-Item Similarity
# ### Prediction $\hat{r}_{ui}$ in case of user-user similarity
#
# $\large \hat{r}_{ui} = b_{ui} + \frac{ \sum\limits_{v \in N^k_i(u)}
# \text{sim}(u, v) \cdot (r_{vi} - b_{vi})} {\sum\limits_{v
# \in N^k_i(u)} \text{sim}(u, v)}$
#
# - $\pmb{b_{ui}}$ - Baseline prediction_ of (user,movie) rating which is "$b_{ui} = \mu + b_u + b_i$".
#
# - $ \pmb {N_i^k (u)}$ - Set of __K similar__ users (neighbours) of __user (u)__ who rated __movie(i)__
#
# - _sim (u, v)_ - Similarity between users __u and v__ who also rated movie 'i'. This is exactly same as our hand-crafted features 'SUR'- 'Similar User Rating'. Means here we have taken 'k' such similar users 'v' with user 'u' who also rated movie 'i'. $r_{vi}$ is the rating which user 'v' gives on item 'i'. $b_{vi}$ is the predicted baseline model rating of user 'v' on item 'i'.
# - Generally, it will be cosine similarity or Pearson correlation coefficient.
# - But we use __shrunk Pearson-baseline correlation coefficient__, which is based on the pearsonBaseline similarity ( we take - base line predictions instead of mean rating of user/item)<br><br><br><br>
#
# ### Prediction $\hat{r}_{ui}$ in case of item-item similarity
#
# $\large \hat{r}_{ui} = b_{ui} + \frac{ \sum\limits_{j \in N^k_u(i)}
# \text{sim}(i, j) \cdot (r_{uj} - b_{uj})} {\sum\limits_{j \in
# N^k_u(j)} \text{sim}(i, j)}$
#
# - __Notation is same as of user-user similarity__<br><br><br>
#
#
# #### Documentation you can check at:
# KNN BASELINE: https://surprise.readthedocs.io/en/stable/knn_inspired.html
#
# PEARSON_BASELINE SIMILARITY: http://surprise.readthedocs.io/en/stable/similarities.html#surprise.similarities.pearson_baseline
#
# SHRINKAGE: Neighborhood Models in http://courses.ischool.berkeley.edu/i290-dm/s11/SECURE/a1-koren.pdf
# ### 4.1 Surprise KNN-Baseline with User-User.
# #### Cross- Validation
# +
param_grid = {'sim_options':{'name': ["pearson_baseline"], "user_based": [True], "min_support": [2], "shrinkage": [60, 80, 80, 140]}, 'k': [5, 20, 40, 80]}
gs = GridSearchCV(KNNBaseline, param_grid, measures=['rmse', 'mae'], cv=3)
gs.fit(data)
# best RMSE score
print(gs.best_score['rmse'])
# combination of parameters that gave the best RMSE score
print(gs.best_params['rmse'])
# -
# ### Applying KNNBaseline User-User with best parameters
# +
sim_options = {'name':'pearson_baseline', 'user_based':True, 'min_support':2, 'shrinkage':gs.best_params['rmse']['sim_options']['shrinkage']}
bsl_options = {'method': 'sgd'}
algo = KNNBaseline(k = gs.best_params['rmse']['k'], sim_options = sim_options, bsl_options=bsl_options)
train_result, test_result = run_surprise(algo, trainset, testset, "KNNBaseline_User")
model_train_evaluation["KNNBaseline_User"] = train_result
model_test_evaluation["KNNBaseline_User"] = test_result
# -
# ### 4.2 Surprise KNN-Baseline with Item-Item.
# #### Cross- Validation
# +
param_grid = {'sim_options':{'name': ["pearson_baseline"], "user_based": [False], "min_support": [2], "shrinkage": [60, 80, 80, 140]}, 'k': [5, 20, 40, 80]}
gs = GridSearchCV(KNNBaseline, param_grid, measures=['rmse', 'mae'], cv=3)
gs.fit(data)
# best RMSE score
print(gs.best_score['rmse'])
# combination of parameters that gave the best RMSE score
print(gs.best_params['rmse'])
# -
# #### Applying KNNBaseline Item-Item with best parameters
# +
sim_options = {'name':'pearson_baseline', 'user_based':False, 'min_support':2, 'shrinkage':gs.best_params['rmse']['sim_options']['shrinkage']}
bsl_options = {'method': 'sgd'}
algo = KNNBaseline(k = gs.best_params['rmse']['k'], sim_options = sim_options, bsl_options=bsl_options)
train_result, test_result = run_surprise(algo, trainset, testset, "KNNBaseline_Item")
model_train_evaluation["KNNBaseline_Item"] = train_result
model_test_evaluation["KNNBaseline_Item"] = test_result
# -
# ## 5. XGBoost 13 Features + Surprise BaselineOnly + Surprise KNN Baseline
# ### Adding predicted ratings from Surprise KNN Baseline model to our Train and Test Dataframe
# +
Train_Reg["KNNBaseline_User"] = model_train_evaluation["KNNBaseline_User"]["Prediction"]
Train_Reg["KNNBaseline_Item"] = model_train_evaluation["KNNBaseline_Item"]["Prediction"]
Test_Reg["KNNBaseline_User"] = model_test_evaluation["KNNBaseline_User"]["Prediction"]
Test_Reg["KNNBaseline_Item"] = model_test_evaluation["KNNBaseline_Item"]["Prediction"]
# -
Train_Reg.head()
print("Number of nan values in Train Data "+str(Train_Reg.isnull().sum().sum()))
Test_Reg.head()
print("Number of nan values in Test Data "+str(Test_Reg.isnull().sum().sum()))
# +
x_train = Train_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
x_test = Test_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
y_train = Train_Reg["Rating"]
y_test = Test_Reg["Rating"]
train_result, test_result = train_test_xgboost(x_train, x_test, y_train, y_test, "XGB_BSL_KNN")
model_train_evaluation["XGB_BSL_KNN"] = train_result
model_test_evaluation["XGB_BSL_KNN"] = test_result
# -
# ## 6. Matrix Factorization SVD
# #### Prediction $\hat{r}_{ui}$ is set as:<br>
#
# $\large \hat{r}_{ui} = \mu + b_u + b_i + q_i^Tp_u$
# - $\pmb q_i$ - Representation of item(movie) in latent factor space
#
# - $\pmb p_u$ - Representation of user in new latent factor space<br>
#
# __If user u is unknown, then the bias $b_u$ and the factors $p_u$ are assumed to be zero. The same applies for item i with $b_i$ and $q_i$.__<br><br><br>
#
#
# #### Optimization Problem<br>
#
# $\large \sum_{r_{ui} \in R_{train}} \left(r_{ui} - \hat{r}_{ui} \right)^2 +
# \lambda\left(b_i^2 + b_u^2 + ||q_i||^2 + ||p_u||^2\right) \left[minimize\; b_u, b_i, q_i, p_u \right]$
# <br><br><br>
#
# SVD Documentation: https://surprise.readthedocs.io/en/stable/matrix_factorization.html
# #### Cross- Validation
# +
param_grid = {'n_factors': [5,7,10,15,20,25,35,50,70,90]} #here, n_factors is the equivalent to dimension 'd' when matrix 'A'
#is broken into 'b' and 'c'. So, matrix 'A' will be of dimension n*m. So, matrices 'b' and 'c' will be of dimension n*d and m*d.
gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)
gs.fit(data)
# best RMSE score
print(gs.best_score['rmse'])
# combination of parameters that gave the best RMSE score
print(gs.best_params['rmse'])
# -
# ### Applying SVD with best parameters
# +
algo = SVD(n_factors = gs.best_params['rmse']['n_factors'], biased=True, verbose=True)
train_result, test_result = run_surprise(algo, trainset, testset, "SVD")
model_train_evaluation["SVD"] = train_result
model_test_evaluation["SVD"] = test_result
# -
# ## 7. Matrix Factorization SVDpp with implicit feedback
# #### Prediction $\hat{r}_{ui}$ is set as:<br>
# $\large \hat{r}_{ui} = \mu + b_u + b_i + q_i^T\left(p_u +
# |I_u|^{-\frac{1}{2}} \sum_{j \in I_u}y_j\right)$<br><br>
#
# - $ \pmb{I_u}$ --- the set of all items rated by user u. $|I_u|$ is a length of that set.<br>
#
# - $\pmb{y_j}$ --- Our new set of item factors that capture implicit ratings. Here, an implicit rating describes the fact that a user u rated an item j, regardless of the rating value. $y_i$ is an item vector. For every item j, there is an item vector $y_j$ which is an implicit feedback. Implicit feedback indirectly reflects opinion by observing user behavior including purchase history, browsing history, search patterns, or even mouse movements. Implicit feedback usually denotes the presence or absence of an event. For example, there is a movie 10 where user has just checked the details of the movie and spend some time there, will contribute to implicit rating. Now, since here Netflix has not provided us the details that for how long a user has spend time on the movie, so here we are considering the fact that even if a user has rated some movie then it means that he has spend some time on that movie which contributes to implicit rating.<br><br>
#
# __If user u is unknown, then the bias $b_u$ and the factors $p_u$ are assumed to be zero. The same applies for item i with $b_i$, $q_i$ and $y_i$.__<br><br><br>
#
# #### Optimization Problem
#
# $\large \sum_{r_{ui} \in R_{train}} \left(r_{ui} - \hat{r}_{ui} \right)^2 +
# \lambda\left(b_i^2 + b_u^2 + ||q_i||^2 + ||p_u||^2 + ||y_j||^2\right).\left[minimize\; b_u, b_i, q_i, p_u, y_j \right]$<br><br>
#
# SVDpp Documentation: https://surprise.readthedocs.io/en/stable/matrix_factorization.html
# #### Cross- Validation
# +
param_grid = {'n_factors': [10, 30, 50, 80, 100], 'lr_all': [0.002, 0.006, 0.018, 0.054, 0.10]}
gs = GridSearchCV(SVDpp, param_grid, measures=['rmse', 'mae'], cv=3)
gs.fit(data)
# best RMSE score
print(gs.best_score['rmse'])
# combination of parameters that gave the best RMSE score
print(gs.best_params['rmse'])
# -
# #### Applying SVDpp with best parameters
# +
algo = SVDpp(n_factors = gs.best_params['rmse']['n_factors'], lr_all = gs.best_params['rmse']["lr_all"], verbose=True)
train_result, test_result = run_surprise(algo, trainset, testset, "SVDpp")
model_train_evaluation["SVDpp"] = train_result
model_test_evaluation["SVDpp"] = test_result
# -
# ## 8. XGBoost 13 Features + Surprise BaselineOnly + Surprise KNN Baseline + SVD + SVDpp
# +
Train_Reg["SVD"] = model_train_evaluation["SVD"]["Prediction"]
Train_Reg["SVDpp"] = model_train_evaluation["SVDpp"]["Prediction"]
Test_Reg["SVD"] = model_test_evaluation["SVD"]["Prediction"]
Test_Reg["SVDpp"] = model_test_evaluation["SVDpp"]["Prediction"]
# -
Train_Reg.head()
print("Number of nan values in Train Data "+str(Train_Reg.isnull().sum().sum()))
Test_Reg.head()
print("Number of nan values in Test Data "+str(Test_Reg.isnull().sum().sum()))
# +
x_train = Train_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
x_test = Test_Reg.drop(["User_ID", "Movie_ID", "Rating"], axis = 1)
y_train = Train_Reg["Rating"]
y_test = Test_Reg["Rating"]
train_result, test_result = train_test_xgboost(x_train, x_test, y_train, y_test, "XGB_BSL_KNN_MF")
model_train_evaluation["XGB_BSL_KNN_MF"] = train_result
model_test_evaluation["XGB_BSL_KNN_MF"] = test_result
# -
# ## 9. Surprise KNN Baseline + SVD + SVDpp
# +
x_train = Train_Reg[["KNNBaseline_User", "KNNBaseline_Item", "SVD", "SVDpp"]]
x_test = Test_Reg[["KNNBaseline_User", "KNNBaseline_Item", "SVD", "SVDpp"]]
y_train = Train_Reg["Rating"]
y_test = Test_Reg["Rating"]
train_result, test_result = train_test_xgboost(x_train, x_test, y_train, y_test, "XGB_KNN_MF")
model_train_evaluation["XGB_KNN_MF"] = train_result
model_test_evaluation["XGB_KNN_MF"] = test_result
# -
# ## Summary
error_table2 = error_table.drop(["Train MAPE", "Test MAPE"], axis = 1)
error_table2.plot(x = "Model", kind = "bar", figsize = (14, 8), grid = True, fontsize = 15)
plt.title("Train and Test RMSE and MAPE of all Models", fontsize = 20)
plt.ylabel("Error Values", fontsize = 20)
plt.legend(bbox_to_anchor=(1, 1), fontsize = 20)
plt.show()
error_table.drop(["Train MAPE", "Test MAPE"], axis = 1).style.highlight_min(axis=0)
# # So, far our best model is SVDpp with Test RMSE of 1.067583
| Datascience_With_Python/Machine Learning/Videos/Movie Recommendation System/movie_recommendation_system.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Exercise 13
#
# This particular Automobile Data Set includes a good mix of categorical values as well as continuous values and serves as a useful example that is relatively easy to understand. Since domain understanding is an important aspect when deciding how to encode various categorical values - this data set makes a good case study.
# Read the data into Pandas
# +
import pandas as pd
# Define the headers since the data does not have any
headers = ["symboling", "normalized_losses", "make", "fuel_type", "aspiration",
"num_doors", "body_style", "drive_wheels", "engine_location",
"wheel_base", "length", "width", "height", "curb_weight",
"engine_type", "num_cylinders", "engine_size", "fuel_system",
"bore", "stroke", "compression_ratio", "horsepower", "peak_rpm",
"city_mpg", "highway_mpg", "price"]
# Read in the CSV file and convert "?" to NaN
df = pd.read_csv("http://mlr.cs.umass.edu/ml/machine-learning-databases/autos/imports-85.data",
header=None, names=headers, na_values="?" )
df.head()
# -
df.shape
df.dtypes
obj_df = df.select_dtypes(include=['object']).copy()
obj_df.head()
# # Exercise 13.1
#
# Does the database contain missing values? If so, replace them using one of the methods explained in class
# # Exercise 13.2
#
# Split the data into training and testing sets
#
# Train a Random Forest Regressor to predict the price of a car using the nominal features
# # Exercise 13.3
#
# Create dummy variables for the categorical features
#
# Train a Random Forest Regressor and compare
# # Exercise 13.4
#
# Apply two other methods of categorical encoding
#
# compare the results
| exercises/E13-CategoricalEncoding.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
from astropy.table import Table
from matplotlib import pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif')
rc('font', size=14)
# -
# ## Abundance matching
# This example runs a number of SkyPy modules to create a catalogue of halos, sub-halos and galaxies which are matched together using the [Vale & Ostriker (2004)](https://ui.adsabs.harvard.edu/abs/2004MNRAS.353..189V/abstract) method.
#
# Running the `abundance_matching` example:
# ```bash
# $ skypy abundance_matching.yml --format fits
# ```
# generates an output catalogue for us to load in:
halos = Table.read('halos.fits')
print(halos.info)
# Here we make a quick visual check of the columns.
#
# We have asked for halo masses over a given range (at the same time as halo groupings into sub and parent halos, and galaxy magnitudes):
#
# ```yaml
# tables:
# halos:
# halo_mass, halo_group, parent_halo, galaxy_magnitude: !skypy.halo.abundance_matching.vale_ostriker
# halo_kwargs:
# m_min: 1.0E+9
# m_max: 1.0E+12
# resolution: 1000
# size: 1000
# wavenumber: $wavenumber
# power_spectrum: $power_spectrum
# growth_function: $growth_function
# cosmology: $cosmology
# ```
plt.figure()
plt.hist(halos[halos['parent_halo']]['halo_mass'], histtype='step', bins=np.logspace(9,12,50), label='Parent halos')
plt.hist(halos[~halos['parent_halo']]['halo_mass'], histtype='step', bins=np.logspace(9,12,50), label='Sub halos')
plt.xlabel('$M\,[M_{\odot}]$')
plt.xscale('log')
plt.yscale('log')
plt.legend();
# We also asked to generate galaxy magnitudes:
# ```yaml
# galaxy_kwargs:
# redshift: $slice_z_mid
# M_star: $M_star
# alpha: -0.5
# m_lim: 35
# size: 1000
# ```
plt.figure()
plt.hist(halos['galaxy_magnitude'], histtype='step', bins=50)
plt.xlabel('$m$')
plt.yscale('log');
# We can see the occupation numbers of each halo:
plt.figure()
plt.hist(halos['halo_group'], histtype='step', bins=halos['halo_group'].max())
plt.xlabel('Group');
# And see how the galaxy luminosity and halo mass are related:
plt.figure()
plt.hist2d(halos['halo_mass'], halos['galaxy_magnitude'], bins=[np.logspace(9,12,50), 50])
plt.xscale('log')
plt.xlabel('$M\,[M_{\odot}]$')
plt.ylabel('$m$');
| examples/abundance_matching.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="dIGIo9kpYFqs"
# If the repo was not cloned
from google.colab import drive
drive.mount('/content/drive')
# %cd /content/drive/MyDrive
# !git clone https://github.com/pschultzendorff/pf-pinn
# %cd /content/drive/MyDrive/pf-pinn
# + colab={"base_uri": "https://localhost:8080/"} id="ExFq7xsAYFqs" outputId="8e9778d3-656a-4053-c1aa-78b7554301a5"
# If the repo needs to be updated
from google.colab import drive
drive.mount('/content/drive')
# %cd /content/drive/MyDrive/pf-pinn
# !git pull origin main
# + id="0PPGV_MmYFqs"
# Run tensorboard
# %load_ext tensorboard
# %tensorboard --logdir runs
# + id="lLE47Y__YFqs"
# Speedup and reproducability
import torch
from src import utils_fast as utils
from google.colab import drive
drive.mount('/content/drive')
# %cd /content/drive/MyDrive/pf-pinn
# %env PYTHONOPTIMIZE = TRUE
torch.backends.cudnn.benchmark = True
utils.fix_seeds(0)
# + id="EXDshh0cSWqE"
# Imports
from src import geometry, models
from src import lbfgs_custom_nvb as lbfgs_custom
from src import utils_fast as utils
from src import train_fast as train
from src import visualization as vis
# + [markdown] id="1BghpXbOVMcc"
# ### Set parameters
#
# We use 25 Gauss points per element, since the lateral load example may be more complicated. The loading steps are taken from section 7.2 of *A physics-informed variational DeepONet for predicting the crack path in brittle materials*.
# + id="jJ2bhIgHVMFA"
from typing import List
G_C: float = 2.7
CRACK_WIDTH: float = 0.0125
LAME_LAMBDA: float = 121150.0
LAME_MU: float = 80770.0
NUM_POINTS: int = 16
LOADING_STEP: float = 0.0005
# increasements of 5x10^-4
loads: List[float] = [LOADING_STEP*i for i in range(26)]
# + [markdown] id="omRaKZTuS4Zc"
# ### Generate the geometry
# + colab={"base_uri": "https://localhost:8080/"} id="euQ6l4nGS_0c" outputId="d3c56615-8397-4c82-c8c1-fd67b2bdf8d7"
import numpy as np
import torch
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
x = np.linspace(0, 1, 17)
y = np.linspace(0, 1, 17)
y1_1 = np.linspace(0, y[5], 6)
y1_2 = np.linspace(y[11], 1, 6)
x2 = np.linspace(0, 1, 33)
y2_1 = np.linspace(y[5], y[7], 5)
y2_2 = np.linspace(y[9], y[11], 5)
x3 = np.linspace(0, 1, 65)
y3 = np.linspace(y[7], y[9], 9)
x1v, y1v_1 = np.meshgrid(x, y1_1)
x1v, y1v_2 = np.meshgrid(x, y1_2)
x2v, y2v_1 = np.meshgrid(x2, y2_1)
x2v, y2v_2 = np.meshgrid(x2, y2_2)
x3v, y3v = np.meshgrid(x3, y3)
nodes_l1_1 = np.stack((x1v, y1v_1), axis=2).tolist()
nodes_l1_2 = np.stack((x1v, y1v_2), axis=2).tolist()
nodes_l2_1 = np.stack((x2v, y2v_1), axis=2).tolist()
nodes_l2_2 = np.stack((x2v, y2v_2), axis=2).tolist()
nodes_l3 = np.stack((x3v, y3v), axis=2).tolist()
nodes_lists = [nodes_l1_1, nodes_l1_2, nodes_l2_1, nodes_l2_2, nodes_l3]
elements = []
for nodes in nodes_lists:
for row_id, row in enumerate(nodes[:-1]):
for node_id, node in enumerate(row[:-1]):
elements.append([
node[0],
nodes[row_id+1][node_id+1][0],
node[1],
nodes[row_id+1][node_id+1][1],
])
points, weights = geometry.generate_points_weights(elements, NUM_POINTS, 2)
points_t: torch.Tensor = torch.tensor(points, dtype=torch.float).to(device)
weights_t: torch.Tensor = torch.tensor(weights, dtype=torch.float).to(device).unsqueeze(dim=-1)
print(sum(weights))
x = np.linspace(0, 1, 129)
y = np.flip(np.linspace(0, 1, 129))
xv, yv = np.meshgrid(x, y)
vis_points: np.ndarray = np.stack((xv, yv), axis=2)
vis_points_t: torch.Tensor = torch.tensor(vis_points, dtype=torch.float).to(device)
# + [markdown] id="6EsAuRgxVsvo"
# ### Initialize the history function
# + id="z6-hdgqXVvQk"
def H_init(point: torch.Tensor) -> float:
"""Inital history function.
"""
x, y = point[0], point[1]
if x <= 0.5:
x_dist: float = 0.0
else:
x_dist: float = x-0.5
dist = torch.sqrt(x_dist**2 +(y - 0.5)**2)
B: float = 1000.0 if dist <= CRACK_WIDTH/2 else 1.0
if dist <= CRACK_WIDTH/2:
return B*G_C/(2*CRACK_WIDTH)*(1 - 2*dist/CRACK_WIDTH)
else:
return 0.0
H_init_t: torch.Tensor = torch.tensor([H_init(point) for point in points_t]).unsqueeze(dim=-1).to(device)
H_history: List[torch.Tensor] = [H_init_t]
H_init_vis_t: torch.Tensor = torch.tensor([H_init(point) for point in vis_points_t.flatten(start_dim=0, end_dim=1)]).unsqueeze(dim=-1).to(device)
H_history_vis: List[torch.Tensor] = [H_init_vis_t]
# + [markdown] id="rgj8r9A0XLyc"
# ### Train the model
# + id="WekKk3hzXN6Y"
import os
import torch.optim as optim
loads: List[float] = [LOADING_STEP*i for i in range(16)]
utils.fix_seeds(0)
for i, load in enumerate(loads):
path: str = f'runs/5.2_lateral/history_function/load_{load}'
def train_history():
loss_cfg: utils.LossConfig = utils.LossConfig(
G_c=G_C,
crack_width=CRACK_WIDTH,
lame_lambda=LAME_LAMBDA,
lame_mu=LAME_MU,
dis_field_dim=2,
history=H_history,
irreversibility='history_function',
pen_param=0.5
)
vis_cfg: vis.VisConfig = vis.VisConfig.from_LossConfig(loss_cfg, history=H_history_vis)
loss_func: utils.TotalEnergy = utils.TotalEnergy(loss_cfg, loss_split=True)
pinnbc_cfg: models.PinnBCConfig = models.PinnBCConfig(
depth=3,
in_dim=2,
hidden_dim=50,
boundary_cond=models.forward_5_2_lateral,
dis_field_dim=2,
load=load
)
model: models.PinnBC = models.PinnBC(pinnbc_cfg).float().to(device)
if i >= 1:
model.load_state_dict(torch.load(f'runs/5.2_lateral/history_function/load_{loads[i-1]}/models/best_model.pt'))
for fc in model.pinn.fcs[:-1]:
for param in fc.parameters():
param.requires_grad = False
adam_epochs: int = 2000
lbfgs_epochs: int = 500
else:
adam_epochs: int = 5000
lbfgs_epochs: int = 500
adam_cfg: train.TrainConfig = train.TrainConfig(
points=points_t,
weights=weights_t,
vis_points=vis_points_t,
save_path=path,
epochs=adam_epochs,
patience=600,
patience_lr=200,
save_step=1000,
vis_step=1000,
num_points=NUM_POINTS
)
adam_trainer: train.Trainer = train.Trainer(adam_cfg, pinnbc_cfg, loss_cfg, vis_cfg, model=model, optimizer=optim.Adam(model.parameters()), loss_func=loss_func, jupyter=True)
end_epoch: int = adam_trainer.train()
model.load_state_dict(torch.load(os.path.join(path, 'models', 'best_model.pt')))
lbfgs_cfg: train.TrainConfig = train.TrainConfig(
points=points_t,
weights=weights_t,
vis_points=vis_points_t,
save_path=path,
epochs=lbfgs_epochs,
patience=150,
patience_lr=50,
save_step=100,
vis_step=100,
start_epoch=end_epoch+1,
num_points=NUM_POINTS,
min_handling='adam'
)
lbfgs_trainer: train.Trainer = train.Trainer(lbfgs_cfg, pinnbc_cfg, loss_cfg, vis_cfg,
model=model, optimizer=lbfgs_custom.LBFGSCustom(model.parameters(), line_search_fn='strong_wolfe', tolerance_change=1e-14), loss_func=loss_func, jupyter=True)
lbfgs_trainer.train()
lbfgs_trainer.save_vis()
model.load_state_dict(torch.load(os.path.join(path, 'models', 'best_model.pt')))
vis.update_H(model, points_t, loss_cfg, H_history)
vis.update_H(model, vis_points_t, vis_cfg, H_history_vis)
vis.save_losses([adam_trainer.losses, lbfgs_trainer.losses], ['Adam', 'L-BFGS'], os.path.join(path, 'images', 'losses.png'))
train_history()
# + [markdown] id="2G3tIqS0MPqM"
# ### Finer visualization
# + id="LP7FbbvuMPqM"
x = np.linspace(0, 1, 513)
y = np.flip(np.linspace(0, 1, 513))
xv, yv = np.meshgrid(x, y)
vis_points: np.ndarray = np.stack((xv, yv), axis=2)
vis_points_t: torch.Tensor = torch.tensor(vis_points, dtype=torch.float).to(device)
# + id="DEZk0MaeMPqM" outputId="59962e56-9635-4721-ac3f-a35d236ea794"
for i, load in enumerate(loads):
pinnbc_cfg: models.PinnBCConfig = models.PinnBCConfig(
depth=3,
in_dim=2,
hidden_dim=50,
boundary_cond=models.forward_5_2_lateral,
dis_field_dim=2,
load=load
)
vis_cfg: utils.LossConfig = utils.LossConfig(
G_c=G_C,
crack_width=CRACK_WIDTH,
lame_lambda=LAME_LAMBDA,
lame_mu=LAME_MU,
dis_field_dim=2,
history=[H_history_vis[i]],
irreversibility='history_function',
)
model: models.PinnBC = models.PinnBC(pinnbc_cfg).float().to(device)
model.load_state_dict(torch.load(f'runs/5.2_lateral/history_function/load_{load}/models/best_model.pt'))
vis.visualize_model_2d(model, vis_points_t, vis_cfg, title=True)
# + [markdown] id="N-rhhzOAB4NU"
# ### Without transfer learning
#
# We observe that the loss for the subsequent time steps after the first one does not decrease as much. For these time steps the concept of transfer learning \cite{Goswami} is applied, where all layers of the PINN except the last ones are fixed. We try another run without fixing the layers but the model parameters from the last time step are still taken as initial parameters. It is not neccessary to repeat the first time step, hence we start at the second one.
# + id="NZ9DdwzlB0Ds"
import os
import torch.optim as optim
H_init_t: torch.Tensor = torch.tensor([H_init(point) for point in points_t]).unsqueeze(dim=-1).to(device)
H_history: List[torch.Tensor] = [H_init_t]
H_init_vis_t: torch.Tensor = torch.tensor([H_init(point) for point in vis_points_t.flatten(start_dim=0, end_dim=1)]).unsqueeze(dim=-1).to(device)
H_history_vis: List[torch.Tensor] = [H_init_vis_t]
loads: List[float] = [LOADING_STEP*i for i in range(16)]
utils.fix_seeds(0)
for i, load in enumerate(loads[1:]):
path: str = f'runs/5.2/no_tl/load_{load}'
def train_history():
loss_cfg: utils.LossConfig = utils.LossConfig(
G_c=G_C,
crack_width=CRACK_WIDTH,
lame_lambda=LAME_LAMBDA,
lame_mu=LAME_MU,
dis_field_dim=2,
history=H_history,
irreversibility='history_function',
)
vis_cfg: vis.VisConfig = vis.VisConfig.from_LossConfig(loss_cfg, history=H_history_vis)
loss_func: utils.TotalEnergy = utils.TotalEnergy(loss_cfg, loss_split=True)
pinnbc_cfg: models.PinnBCConfig = models.PinnBCConfig(
depth=3,
in_dim=2,
hidden_dim=50,
boundary_cond=models.forward_5_2_lateral,
dis_field_dim=2,
load=load
)
model: models.PinnBC = models.PinnBC(pinnbc_cfg).float().to(device)
if i >= 2:
model.load_state_dict(torch.load(f'runs/5.2/no_tl/load_{loads[i-1]}/models/best_model.pt'))
adam_epochs: int = 2000
lbfgs_epochs: int = 450
else:
adam_epochs: int = 5000
lbfgs_epochs: int = 1000
adam_cfg: train.TrainConfig = train.TrainConfig(
points=points_t,
weights=weights_t,
vis_points=vis_points_t,
save_path=path,
epochs=adam_epochs,
patience=600,
patience_lr=200,
save_step=1000,
vis_step=1000,
num_points=NUM_POINTS
)
adam_trainer: train.Trainer = train.Trainer(adam_cfg, pinnbc_cfg, loss_cfg, vis_cfg, model=model, optimizer=optim.Adam(model.parameters()), loss_func=loss_func, jupyter=True)
end_epoch: int = adam_trainer.train()
model.load_state_dict(torch.load(os.path.join(path, 'models', 'best_model.pt')))
lbfgs_cfg: train.TrainConfig = train.TrainConfig(
points=points_t,
weights=weights_t,
vis_points=vis_points_t,
save_path=path,
epochs=lbfgs_epochs,
patience=150,
patience_lr=50,
save_step=100,
vis_step=100,
start_epoch=end_epoch+1,
num_points=NUM_POINTS,
min_handling='adam'
)
lbfgs_trainer: train.Trainer = train.Trainer(lbfgs_cfg, pinnbc_cfg, loss_cfg, vis_cfg,
model=model, optimizer=lbfgs_custom.LBFGSCustom(model.parameters(), line_search_fn='strong_wolfe', tolerance_change=1e-14), loss_func=loss_func, jupyter=True)
lbfgs_trainer.train()
lbfgs_trainer.save_vis()
model.load_state_dict(torch.load(os.path.join(path, 'models', 'best_model.pt')))
vis.update_H(model, points_t, loss_cfg, H_history)
vis.update_H(model, vis_points_t, vis_cfg, H_history_vis)
vis.save_losses([adam_trainer.losses, lbfgs_trainer.losses], ['Adam', 'L-BFGS'], os.path.join(path, 'images', 'losses.png'))
train_history()
| section_5.2_lateral.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="-6EeZgbFjnqj" colab_type="code" outputId="d2ab279d-c299-4e57-f5aa-9783b78f16e1" colab={"base_uri": "https://localhost:8080/", "height": 122}
from google.colab import drive
drive.mount('/content/drive')
# + id="hBV76GkHtzPV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ccae4907-0cd4-40f7-db87-8526751a51a1"
# cd drive/My Drive/AlexNet
# + [markdown] id="zDmn9rMWjf_X" colab_type="text"
# ## Loading the important Libraries
# + id="aFHaBz3Njf_a" colab_type="code" colab={}
import csv
import math
import matplotlib.pyplot as plt
import numpy as np
import random
import re
from collections import defaultdict
from data.scorer import score_submission, print_confusion_matrix, score_defaults, SCORE_REPORT
from nltk import word_tokenize
from nltk.corpus import stopwords
from tqdm import tqdm
from sklearn.metrics import accuracy_score
# + [markdown] id="RKE1Irg3jf_e" colab_type="text"
# # Loading the contents
# + id="SICa8kCkjf_g" colab_type="code" colab={}
f_bodies = open('data/train_bodies.csv', 'r', encoding='utf-8')
csv_bodies = csv.DictReader(f_bodies)
bodies = []
for row in csv_bodies:
body_id = int(row['Body ID'])
if (body_id + 1) > len(bodies):
bodies += [None] * (body_id + 1 - len(bodies))
bodies[body_id] = row['articleBody']
f_bodies.close()
body_inverse_index = {bodies[i]: i for i in range(len(bodies))}
all_unrelated, all_discuss, all_agree, all_disagree = [], [], [], [] # each article = (headline, body, stance)
f_stances = open('data/train_stances.csv', 'r', encoding='utf-8')
csv_stances = csv.DictReader(f_stances)
for row in csv_stances:
body = bodies[int(row['Body ID'])]
if row['Stance'] == 'unrelated':
all_unrelated.append((row['Headline'], body, row['Stance']))
elif row['Stance'] == 'discuss':
all_discuss.append((row['Headline'], body, row['Stance']))
elif row['Stance'] == 'agree':
all_agree.append((row['Headline'], body, row['Stance']))
elif row['Stance'] == 'disagree':
all_disagree.append((row['Headline'], body, row['Stance']))
f_stances.close()
# + id="YFdStai1jf_j" colab_type="code" outputId="3c326e03-b8ee-427d-ad58-63660d97f037" colab={"base_uri": "https://localhost:8080/", "height": 85}
print('\tUnrltd\tDiscuss\t Agree\tDisagree')
print('All\t', len(all_unrelated), '\t', len(all_discuss), '\t', len(all_agree), '\t', len(all_disagree))
train_unrelated = all_unrelated[:len(all_unrelated) * 9 // 10]
train_discuss = all_discuss[:len(all_discuss) * 9 // 10]
train_agree = all_agree[:len(all_agree) * 9 // 10]
train_disagree = all_disagree[:len(all_disagree) * 9 // 10]
val_unrelated = all_unrelated[len(all_unrelated) * 9 // 10:]
val_discuss = all_discuss[len(all_discuss) * 9 // 10:]
val_agree = all_agree[len(all_agree) * 9 // 10:]
val_disagree = all_disagree[len(all_disagree) * 9 // 10:]
train_unrelated = all_unrelated[:len(all_unrelated) //100]
train_discuss = all_discuss[:len(all_discuss) //100]
train_agree = all_agree[:len(all_agree) //100]
train_disagree = all_disagree[:len(all_disagree) //100]
val_unrelated = all_unrelated[len(all_unrelated) * 9 // 10:]
val_discuss = all_discuss[len(all_discuss) * 9 // 10:]
val_agree = all_agree[len(all_agree) * 9 // 10:]
val_disagree = all_disagree[len(all_disagree) * 9 // 10:]
val_unrelated = val_unrelated[len(val_unrelated) * 9 // 10:]
val_discuss = val_discuss[len(val_discuss) * 9 // 10:]
val_agree = val_agree[len(val_agree) * 9 // 10:]
val_disagree = val_disagree[len(val_disagree) * 9 // 10:]
print('Train\t', len(train_unrelated), '\t', len(train_discuss), '\t', len(train_agree), '\t', len(train_disagree))
print('Valid.\t', len(val_unrelated), '\t', len(val_discuss), '\t', len(val_agree), '\t', len(val_disagree))
# + [markdown] id="jLqQ6HyJjf_n" colab_type="text"
# # Uniform distribution of Data
# + id="J7DghGyvjf_o" colab_type="code" outputId="a629a81a-07bf-4bb9-e359-5788012c9dac" colab={"base_uri": "https://localhost:8080/", "height": 102}
print('Train\t', len(train_unrelated), '\t', len(train_discuss), '\t', len(train_agree), '\t', len(train_disagree))
print('Valid.\t', len(val_unrelated), '\t', len(val_discuss), '\t', len(val_agree), '\t', len(val_disagree))
train_all = (train_unrelated + train_discuss + train_agree + train_disagree)
# each article = (headline, body, stance)
random.Random(0).shuffle(train_all)
train_all = np.array(train_all)
val_all = val_unrelated + val_discuss + val_agree + val_disagree
random.Random(0).shuffle(val_all)
val_all = np.array(val_all)
print('Train (Total)', train_all.shape, '\tValidation (Total)', val_all.shape)
print(np.count_nonzero(train_all[:, 2] == 'unrelated'), '\t',
np.count_nonzero(train_all[:, 2] == 'discuss'), '\t',
np.count_nonzero(train_all[:, 2] == 'agree'), '\t',
np.count_nonzero(train_all[:, 2] == 'disagree'))
print(np.count_nonzero(val_all[:, 2] == 'unrelated'), '\t',
np.count_nonzero(val_all[:, 2] == 'discuss'), '\t',
np.count_nonzero(val_all[:, 2] == 'agree'), '\t',
np.count_nonzero(val_all[:, 2] == 'disagree'))
# + id="T_AjKJE0jf_s" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 544} outputId="1eeb59fb-5ff0-4bd4-e663-4383d78aef61"
import nltk
nltk.download('stopwords')
nltk.download('punkt')
# Tokenise text
pattern = re.compile("[^a-zA-Z0-9 ]+") # strip punctuation, symbols, etc.
stop_words = set(stopwords.words('english'))
def tokenise(text):
text = pattern.sub('', text.replace('\n', ' ').replace('-', ' ').lower())
text = [word for word in word_tokenize(text) if word not in stop_words]
return text
for i in range(9):
print(train_all[i, 0]);print('Tokenized form is ------>',tokenise(train_all[i, 0]))
print()
# + id="nluM5h7Djf_w" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 292} outputId="9debce67-4353-4009-d50b-fe72c8445761"
# Compute term-frequency of words in documents
def doc_to_tf(text, ngram=1):
words = tokenise(text)
ret = defaultdict(float)
for i in range(len(words)):
for j in range(1, ngram+1):
if i - j < 0:
break
word = [words[i-k] for k in range(j)]
ret[word[0] if ngram == 1 else tuple(word)] += 1.0
return ret
for i in range(5):
print(train_all[i, 0]);print('Term frequency form is ------->',doc_to_tf(train_all[i, 0]))
print()
# + id="i6EcvPa-jf_z" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 71} outputId="7c9dfd40-1502-4d11-eded-35ca24de5493"
print(train_all[0, 0]);print('Term frequency form is ------->',doc_to_tf(train_all[0, 0], ngram=2))
# + id="8Wsw-Gk8jf_3" colab_type="code" outputId="0da2164b-6020-4ec8-d2ec-a876bbab1da3" colab={"base_uri": "https://localhost:8080/", "height": 1000}
# Build corpus of article bodies and headlines in training dataset
corpus = np.r_[train_all[:, 1], train_all[:, 0]] # 0 to 44973 are bodies, 44974 to 89943 are headlines
print(corpus[44974//100])
print(corpus[0])
# + id="_-zEg8tJjf_6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 88} outputId="6b17124c-1a43-4db3-aade-1cde4d3bad88"
# Learn idf of every word in the corpus
df = defaultdict(float)
for doc in tqdm(corpus):
words = tokenise(doc)
seen = set()
for word in words:
if word not in seen:
df[word] += 1.0
seen.add(word)
print(list(df.items())[:10])
# + id="rwqHimhsjf_-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 88} outputId="cfb5eab8-00dd-46e3-b124-c5edb2e9acd1"
num_docs = corpus.shape[0]
idf = defaultdict(float)
for word, val in tqdm(df.items()):
idf[word] = np.log((1.0 + num_docs) / (1.0 + val)) + 1.0 # smoothed idf
print(list(idf.items())[:10])
# + id="BS3VPgzzjgAB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 170} outputId="eeb2579a-6155-4e25-b54b-a314a14d4578"
# Load GLoVe word vectors
f_glove = open("data/glove.6B.50d.txt", "rb") # download from https://nlp.stanford.edu/projects/glove/
glove_vectors = {}
for line in tqdm(f_glove):
glove_vectors[str(line.split()[0]).split("'")[1]] = np.array(list(map(float, line.split()[1:])))
print(glove_vectors['glove'])
# + id="3OQmv5uEjgAH" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 323} outputId="e07c0884-98e3-46a9-d903-0cb96ba68fff"
# Convert a document to GloVe vectors, by computing tf-idf of each word * GLoVe of word / total tf-idf for document
def doc_to_glove(doc):
doc_tf = doc_to_tf(doc)
doc_tf_idf = defaultdict(float)
for word, tf in doc_tf.items():
doc_tf_idf[word] = tf * idf[word]
doc_vector = np.zeros(glove_vectors['glove'].shape[0])
if np.sum(list(doc_tf_idf.values())) == 0.0: # edge case: document is empty
return doc_vector
for word, tf_idf in doc_tf_idf.items():
if word in glove_vectors:
doc_vector += glove_vectors[word] * tf_idf
doc_vector /= np.sum(list(doc_tf_idf.values()))
return doc_vector
for i in range(2):
print(train_all[i, 0], doc_to_glove(train_all[i, 0]))
# + id="beczHFxQjgAN" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 224} outputId="1f852d52-2672-4917-c108-34c2a84f96a7"
# Compute cosine similarity of GLoVe vectors for all headline-body pairs
def dot_product(vec1, vec2):
sigma = 0.0
for i in range(vec1.shape[0]): # assume vec1 and vec2 has same shape
sigma += vec1[i] * vec2[i]
return sigma
def magnitude(vec):
return np.sqrt(np.sum(np.square(vec)))
def cosine_similarity(doc):
headline_vector = doc_to_glove(doc[0])
body_vector = doc_to_glove(doc[1])
if magnitude(headline_vector) == 0.0 or magnitude(body_vector) == 0.0: # edge case: document is empty
return 0.0
return dot_product(headline_vector, body_vector) / (magnitude(headline_vector) * magnitude(body_vector))
for i in range(10):
# unrelated should have lower than rest
print(cosine_similarity(train_all[i]), train_all[i, 2])
print(cosine_similarity(train_all[27069//100]), tokenise(train_all[27069//100, 0]), tokenise(train_all[2706//100, 1])) # edge case
# + id="PN3lxUJnjgAT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 224} outputId="788f8cb9-3f0c-4e65-9b66-6a64147acd17"
# Compute the KL-Divergence of language model (LM) representations of the headline and the body
def divergence(lm1, lm2):
sigma = 0.0
for i in range(lm1.shape[0]): # assume lm1 and lm2 has same shape
sigma += lm1[i] * np.log(lm1[i] / lm2[i])
return sigma
def kl_divergence(doc, eps=0.1):
# Convert headline and body to 1-gram representations
tf_headline = doc_to_tf(doc[0])
tf_body = doc_to_tf(doc[1])
# Convert dictionary tf representations to vectors (make sure columns match to the same word)
words = set(tf_headline.keys()).union(set(tf_body.keys()))
vec_headline, vec_body = np.zeros(len(words)), np.zeros(len(words))
i = 0
for word in words:
vec_headline[i] += tf_headline[word]
vec_body[i] = tf_body[word]
i += 1
# Compute a simple 1-gram language model of headline and body
lm_headline = vec_headline + eps
lm_headline /= np.sum(lm_headline)
lm_body = vec_body + eps
lm_body /= np.sum(lm_body)
# Return KL-divergence of both language models
return divergence(lm_headline, lm_body)
for i in range(10):
# unrelated should have higher than rest
print(kl_divergence(train_all[i]), train_all[i, 2])
print(kl_divergence(train_all[27069//100]), tokenise(train_all[27069//100, 0]), tokenise(train_all[27069//100, 1])) # edge case
# + id="Si_Z0tPtjgAa" colab_type="code" outputId="dd03f7dd-4ca3-409b-dfc9-15e9f31d1012" colab={"base_uri": "https://localhost:8080/", "height": 187}
# Other feature 1
def ngram_overlap(doc):
# Returns how many times n-grams (up to 3-gram) that occur in the article's headline occur on the article's body.
tf_headline = doc_to_tf(doc[0], ngram=3)
tf_body = doc_to_tf(doc[1], ngram=3)
matches = 0.0
for words in tf_headline.keys():
if words in tf_body:
matches += tf_body[words]
return np.power((matches / len(tokenise(doc[1]))), 1 / np.e) # normalise for document length
for i in range(10):
# unrelated should have lower than rest
print(ngram_overlap(train_all[i]), train_all[i, 2])
# + id="FBA0OOgjjgAg" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="4dd1b17c-e003-46ff-8cd2-9fdf42343800"
# Define function to convert (headline, body) to feature vectors for each document
ftrs = [cosine_similarity, kl_divergence, ngram_overlap]
def to_feature_array(doc):
vec = np.array([0.0] * len(ftrs))
for i in range(len(ftrs)):
vec[i] = ftrs[i](doc)
return vec
# Initialise X (matrix of feature vectors) for train dataset
x_train = np.array([to_feature_array(doc) for doc in tqdm(train_all)])
print(x_train[:10])
# + id="_0OqDwJjjgAm" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="1aadc218-c13c-47b4-8cde-856bf406809b"
# Define label <-> int mappings for y
label_to_int = {'agree': 0, 'disagree': 1, 'discuss': 2, 'unrelated': 3}
int_to_label = ['agree', 'disagree', 'discuss', 'unrelated']
# Initialise Y (gold output vector) for train dataset
y_train = np.array([label_to_int[i] for i in train_all[:, 2]])
print(y_train[:10])
# + id="ivPT447FjgAt" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="5ce69256-a96a-4680-f022-9396e820e476"
# Check integrity of X and Y
print(np.where(np.isnan(x_train)))
print(np.where(np.isfinite(x_train) == False))
print(x_train.shape)
print(y_train.shape) # x_train.shape[0] == y_train.shape[0]
# + id="VDh8SmZdjgAz" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 296} outputId="cf623be1-597c-4b01-fe00-72a94e958d98"
# Plot GLoVe distance vs KL-Divergence on a coloured scatter plot with different colours for each label
colours = np.array(['g', 'r', 'b', 'y'])
plt.scatter(list(x_train[:, 0]), list(x_train[:, 1]), c=colours[y_train])
plt.xlabel('Cosine Similarity of GLoVe vectors')
plt.ylabel('KL Divergence of Unigram LMs')
print([(colours[i], int_to_label[i]) for i in range(len(int_to_label))])
plt.show()
# + id="WB_2aFBYjgA5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 119} outputId="69090434-af77-4f7b-b602-80e9a7bc0b26"
# Initialise x (feature vectors) for validation dataset
x_val = np.array([to_feature_array(doc) for doc in tqdm(val_all)])
print(x_val[:5])
# + id="ZppFrbZRjgBB" colab_type="code" outputId="967d7908-0437-4328-c854-ba1976ba7202" colab={"base_uri": "https://localhost:8080/", "height": 34}
# Linear regression model
def mse(pred, gold):
sigma = 0.0
for i in range(pred.shape[0]):
sigma += np.square(pred[i] - gold[i])
return sigma / (2 * pred.shape[0])
print(mse(np.array([0.0, 0.2, 0.5, 0.5, 0.8, 1.0]), np.array([0, 0, 0, 1, 1, 1])))
# + id="MJh77gT_jgBI" colab_type="code" outputId="f6d56794-cf29-4c18-e952-4388f0a1449b" colab={"base_uri": "https://localhost:8080/", "height": 119}
class LinearRegression:
def __init__(self, lrn_rate, n_iter):
self.lrn_rate = lrn_rate
self.n_iter = n_iter
# self.breakpoints = set([n_iter * i // 10 for i in range(1, 11)])
def fit(self, X, Y):
# Learn a model y = intercept + x0*t0 + x1*t1 + x2*t2 + ... that minimises MSE. Need to optimise T
# self.intercept = 0.0
self.model = np.zeros(X.shape[1]) # model[0] = t0, model[1] = t1, etc.
for it in tqdm(range(self.n_iter)):
model_Y = self.transform(X)
# Thetas
for col in range(X.shape[1]):
s = 0.0
for row in range(X.shape[0]):
s += (model_Y[row] - Y[row]) * X[row, col]
self.model[col] -= self.lrn_rate * s / X.shape[0]
# Intercept
# s_int = 0.0
# for row in range(X.shape[0]):
# s_int += (model_Y[row] - Y[row]) * 1.0
# self.intercept -= self.lrn_rate * s_int / X.shape[0]
# if it + 1 in self.breakpoints:
# print('Iteration', it+1, 'MSE:', mse(model_Y, Y))
print('Final MSE:', mse(model_Y, Y))
# print('Intercept:', self.intercept)
print('Model:', self.model)
def transform(self, X):
# Returns a float value for each X. (Regression)
Y = np.zeros(X.shape[0])
for row in range(X.shape[0]):
# s = self.intercept
s = 0.0
for col in range(X.shape[1]):
s += self.model[col] * X[row, col]
Y[row] = s
return Y
def predict(self, X):
# Uses results of transform() for binary classification. For testing only, use OneVAllClassifier for the final run.
Y = self.transform(X)
Y = np.array([(1 if i > 0.5 else 0) for i in Y])
return Y
# Test only
lr = LinearRegression(lrn_rate=0.1, n_iter=100)
lr.fit(x_train[:1000], np.array([(1 if i == 3 else 0) for i in y_train[:1000]]))
print(lr.transform(x_train[1000:1020]))
print('Predicted', lr.predict(x_train[1000:1020]))
print('Actual', np.array([(1 if i == 3 else 0) for i in y_train[1000:1020]]))
# + id="Bzq7y86cjgBO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="a6692d87-6f51-4326-a7d4-5618b1385ea6"
# Logistic regression functions
def sigmoid(Y):
return 1 / (1 + np.exp(Y * -1))
print(sigmoid(np.array([0.0, 0.2, 0.5, 0.5, 0.8, 1.0])))
def logistic_cost(pred, gold):
sigma = 0.0
for i in range(pred.shape[0]):
if gold[i] == 1:
sigma -= np.log(pred[i])
elif gold[i] == 0:
sigma -= np.log(1 - pred[i])
return sigma / pred.shape[0]
print(mse(np.array([0.0, 0.2, 0.5, 0.5, 0.8, 1.0]), np.array([0, 0, 0, 1, 1, 1])))
print(logistic_cost(np.array([0.0, 0.2, 0.5, 0.5, 0.8, 1.0]), np.array([0, 0, 0, 1, 1, 1])))
print(logistic_cost(sigmoid(np.array([0.0, 0.2, 0.5, 0.5, 0.8, 1.0])), np.array([0, 0, 0, 1, 1, 1])))
# + id="dhhEQNrBjgCj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 119} outputId="9740fced-52f5-4bef-932d-2865540b91fa"
# Logistic regression model
class LogisticRegression:
def __init__(self, lrn_rate, n_iter):
self.lrn_rate = lrn_rate
self.n_iter = n_iter
# self.breakpoints = set([n_iter * i // 10 for i in range(1, 11)])
def fit(self, X, Y):
# Learn a model y = x0*t0 + x1*t1 + x2*t2 + ... that minimises MSE. Need to optimise T
self.model = np.zeros(X.shape[1]) # model[0] = t0, model[1] = t1, etc.
for it in tqdm(range(self.n_iter)):
model_Y = self.transform(X)
for col in range(X.shape[1]):
s = 0.0
for row in range(X.shape[0]):
s += (model_Y[row] - Y[row]) * X[row, col]
self.model[col] -= self.lrn_rate * s / X.shape[0]
# if it + 1 in self.breakpoints:
# print('Iteration', it+1, 'loss:', logistic_cost(model_Y, Y))
print('Final loss:', logistic_cost(model_Y, Y))
print('Model:', self.model)
def transform(self, X):
# Returns a float value for each X. (Regression)
Y = np.zeros(X.shape[0])
for row in range(X.shape[0]):
s = 0.0
for col in range(X.shape[1]):
s += self.model[col] * X[row, col]
Y[row] = s
return sigmoid(Y)
def predict(self, X):
# Uses results of transform() for binary classification. For testing only, use OneVAllClassifier for the final run.
Y = self.transform(X)
Y = np.array([(1 if i > 0.5 else 0) for i in Y])
return Y
# Test only
lr = LogisticRegression(lrn_rate=0.1, n_iter=100)
lr.fit(x_train[:1000], np.array([(1 if i == 3 else 0) for i in y_train[:1000]]))
print(lr.transform(x_train[1000:1020]))
print('Predicted', lr.predict(x_train[1000:1020]))
print('Actual', np.array([(1 if i == 3 else 0) for i in y_train[1000:1020]]))
# + id="Zx95eUUQjgCx" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 323} outputId="c7400600-8ab2-4b2c-d82a-6712c406f05d"
# To use linear/logistic regression models to classify multiple classes
class OneVAllClassifier:
def __init__(self, regression, **params):
self.regression = regression
self.params = params
def fit(self, X, Y):
# Learn a model for each parameter.
self.categories = np.unique(Y)
self.models = {}
for cat in self.categories:
ova_Y = np.array([(1 if i == cat else 0) for i in Y])
model = self.regression(**self.params)
model.fit(X, ova_Y)
self.models[cat] = model
print(int_to_label[cat])
def predict(self, X):
# Predicts each x for each different model learned, and returns the category related to the model with the highest score.
vals = {}
for cat, model in self.models.items():
vals[cat] = model.transform(X)
Y = np.zeros(X.shape[0], dtype=np.int)
for row in range(X.shape[0]):
max_val, max_cat = -math.inf, -math.inf
for cat, val in vals.items():
if val[row] > max_val:
max_val, max_cat = val[row], cat
Y[row] = max_cat
return Y
# Test only
ova = OneVAllClassifier(LinearRegression, lrn_rate=0.1, n_iter=100)
ova.fit(x_train[:1000], y_train[:1000])
print('Predicted', ova.predict(x_train[1000:1020]))
print('Actual', y_train[1000:1020])
# + id="Zk0E8CIxjgC7" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 289} outputId="b644e1c0-ce3a-47d3-d308-04a89d02163a"
# Train the linear regression & One-V-All classifier models on the train set
clf = OneVAllClassifier(LinearRegression, lrn_rate=0.1, n_iter=1000)
clf.fit(x_train, y_train)
# + id="Hwul5BmPjgDA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="fbb4c4a8-06a9-455c-cc62-91030739eb12"
# Predict y for validation set
y_pred = clf.predict(x_val)
print(y_pred[:5])
predicted = np.array([int_to_label[i] for i in y_pred])
print(predicted[:5])
print(val_all[:, 2][:5])
# + id="mDT4n8hcjgDH" colab_type="code" colab={}
# Prepare validation dataset format for score_submission in scorer.py
body_ids = [str(body_inverse_index[body]) for body in val_all[:, 1]]
pred_for_cm = np.array([{'Headline': val_all[i, 0], 'Body ID': body_ids[i], 'Stance': predicted[i]} for i in range(len(val_all))])
gold_for_cm = np.array([{'Headline': val_all[i, 0], 'Body ID': body_ids[i], 'Stance': val_all[i, 2]} for i in range(len(val_all))])
# + id="qZ19gzrajgDN" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 374} outputId="22652584-1c15-4149-9582-84d4a17ece86"
# Score using scorer.py (provided in https://github.com/FakeNewsChallenge/fnc-1) on VALIDATION set:
test_score, cm = score_submission(gold_for_cm, pred_for_cm)
null_score, max_score = score_defaults(gold_for_cm)
print_confusion_matrix(cm)
print(SCORE_REPORT.format(max_score, null_score, test_score))
# + id="KAPAdf7djgDc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 663} outputId="718a7827-7fe1-49a2-e48f-14fce394be0e"
# Predict y for validation set using logistic regression instead of linear regression, and compare results of scorer.py
clf_logistic = OneVAllClassifier(LogisticRegression, lrn_rate=0.1, n_iter=1000)
clf_logistic.fit(x_train, y_train)
y_pred = clf_logistic.predict(x_val)
predicted = np.array([int_to_label[i] for i in y_pred])
body_ids = [str(body_inverse_index[body]) for body in val_all[:, 1]]
pred_for_cm = np.array([{'Headline': val_all[i, 0], 'Body ID': body_ids[i], 'Stance': predicted[i]} for i in range(len(val_all))])
gold_for_cm = np.array([{'Headline': val_all[i, 0], 'Body ID': body_ids[i], 'Stance': val_all[i, 2]} for i in range(len(val_all))])
test_score, cm = score_submission(gold_for_cm, pred_for_cm)
null_score, max_score = score_defaults(gold_for_cm)
print()
print_confusion_matrix(cm)
print(SCORE_REPORT.format(max_score, null_score, test_score))
# linear regression performs better, so that model is chosen for the test set
# + id="_FAqt2kQjgDg" colab_type="code" colab={}
# Load test data from CSV
f_tbodies = open('data/competition_test_bodies.csv', 'r', encoding='utf-8')
csv_tbodies = csv.DictReader(f_tbodies)
tbodies = []
for row in csv_tbodies:
body_id = int(row['Body ID'])
if (body_id + 1) > len(tbodies):
tbodies += [None] * (body_id + 1 - len(tbodies))
tbodies[body_id] = row['articleBody']
f_tbodies.close()
tbody_inverse_index = {tbodies[i]: i for i in range(len(tbodies))}
test_all = [] # each article = (headline, body, stance)
f_tstances = open('data/competition_test_stances.csv', 'r', encoding='utf-8')
csv_tstances = csv.DictReader(f_tstances)
for row in csv_tstances:
body = tbodies[int(row['Body ID'])]
test_all.append((row['Headline'], body, row['Stance']))
f_tstances.close()
#test_all = np.array(test_all) # for some reason gives MemoryError
#print(test_all.shape)
# + id="ZBQ98N24jgDk" colab_type="code" outputId="043988a0-acc1-4472-ea9c-0bf5e7e5f859" colab={"base_uri": "https://localhost:8080/", "height": 119}
# Initialise x (feature vectors) and y for test dataset
x_test = np.array([to_feature_array(doc) for doc in tqdm(test_all)])
print(x_test[:5])
# + id="QxykFZawjgDr" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="178ab486-96e2-4e55-ba2a-d2cc0f9a0bde"
# Predict y for test set
y_test = clf.predict(x_test)
print(y_pred[:5])
pred_test = np.array([int_to_label[i] for i in y_test])
print(pred_test[:5])
# + id="TDcxjEWvjgDu" colab_type="code" colab={}
# Prepare test dataset format for score_submission in scorer.py
test_body_ids = [str(tbody_inverse_index[test_all[i][1]]) for i in range(len(test_all))]
test_pred_for_cm = np.array([{'Headline': test_all[i][0], 'Body ID': test_body_ids[i], 'Stance': pred_test[i]} for i in range(len(test_all))])
test_gold_for_cm = np.array([{'Headline': test_all[i][0], 'Body ID': test_body_ids[i], 'Stance': test_all[i][2]} for i in range(len(test_all))])
# + id="iLB_4C26jgDx" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 374} outputId="aeb4ccb1-3f7c-4e76-a628-9872afa84374"
# Score using scorer.py (provided in https://github.com/FakeNewsChallenge/fnc-1) on TEST set:
test_score, cm = score_submission(test_gold_for_cm, test_pred_for_cm)
null_score, max_score = score_defaults(test_gold_for_cm)
print_confusion_matrix(cm)
print(SCORE_REPORT.format(max_score, null_score, test_score))
# + [markdown] id="t_1EH32yjgD2" colab_type="text"
# ## Comparison Models
# + id="SQ22nhrQjgD4" colab_type="code" colab={}
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
import xgboost
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.semi_supervised import LabelPropagation
classifiers=[
(LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=100.0, fit_intercept=True,
intercept_scaling=10, class_weight=None, random_state=None, solver='newton-cg', max_iter=10,
multi_class='multinomial', verbose=0, warm_start=False, n_jobs=None),"Logistic Regression"),
(KNeighborsClassifier(1),"K Nearest Classifier "),
(SVC(C=50.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False),'Support Vector Machine Classifier'),
(QuadraticDiscriminantAnalysis(),'Qudratic Discriminant Analysis'),
(RandomForestClassifier(max_depth=50, n_estimators=10, max_features=1),'Random Forest Classifier'),
(AdaBoostClassifier(base_estimator=None, n_estimators=50, learning_rate=0.01,
algorithm='SAMME.R', random_state=None),'Adaboost Classifier'),
(SGDClassifier(),'SGD Classifier'),
(DecisionTreeClassifier(max_depth=5),'Decision Tree Classifier'),
(xgboost.XGBClassifier(learning_rate=0.1),'XG Boost Classifier'),
(LinearDiscriminantAnalysis(solver='svd', shrinkage=None, priors=None, n_components=None,
store_covariance=False,tol=0.00001),'Linear Discriminant Analysis'),
(GaussianNB(),'Gaussian Naive Bayes')
#(MultinomialNB(alpha=.01),'Multinomial Naive Bayes')
]
# + id="82oymMIwjgD-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="34d7faa7-89e9-43dc-ad58-6124c08a14f3"
score=[];names=[]
for model,name in classifiers:
clf=model.fit(x_train,y_train)
y_pred=clf.predict(x_val)
predicted = np.array([int_to_label[i] for i in y_pred])
body_ids = [str(body_inverse_index[body]) for body in val_all[:, 1]]
pred_for_cm = np.array([{'Headline': val_all[i, 0], 'Body ID': body_ids[i], 'Stance': predicted[i]} for i in range(len(val_all))])
gold_for_cm = np.array([{'Headline': val_all[i, 0], 'Body ID': body_ids[i], 'Stance': val_all[i, 2]} for i in range(len(val_all))])
test_score, cm = score_submission(gold_for_cm, pred_for_cm)
null_score, max_score = score_defaults(gold_for_cm)
print('*'*20);names.append(name)
print(name)
score.append(print_confusion_matrix(cm));
a=SCORE_REPORT.format(max_score, null_score, test_score)
# + id="tqqO4fiYjgEA" colab_type="code" outputId="5abf32e1-fc6c-4c0e-9f00-eed650f698a8" colab={"base_uri": "https://localhost:8080/", "height": 54}
for i in range(len(score)):
score[i]=score[i]*100
print(score)
# + id="-FlAzLN0jgED" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="8537d29a-7216-4f8e-fa8e-8a3ed25b8cdb"
names=['LR','KNC','SVC','QDA','RFC','ADC','SGDC','DTC','XGB','LDA','GNB']
import seaborn as sns
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = score[:]
plt.plot(A)
for i, label in enumerate(names):
plt.text(i,A[i], label)
plt.show()
# + id="ROYyzsLrjgEL" colab_type="code" colab={}
# + id="zpZ7-CLwjgEP" colab_type="code" colab={}
| BaseLine_Results_SimpleML_Models.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + slideshow={"slide_type": "skip"}
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML, IFrame
from ipywidgets import interact
from numpy import cos,sin,pi,tan,log,exp,array,linspace,arange, cross, dot, sqrt
from mpl_toolkits import mplot3d
from matplotlib.patches import FancyArrowPatch
from ipykernel.pylab.backend_inline import flush_figures
# # %matplotlib inline
# %matplotlib inline
plt.rcParams['figure.figsize'] = [8.0, 8.0]
# Uncomment the one that corresponds to your Jupyter theme
# plt.style.use('dark_background')
plt.style.use('default')
# plt.style.use('Solarize_Light2')
# plt.rcParams.update({
# "text.usetex": True,
# # "font.family": "serif",
# })
# + slideshow={"slide_type": "skip"}
# %%HTML
<style>
td {
font-size: 36px
}
</style>
# + [markdown] slideshow={"slide_type": "notes"}
# $\newcommand{\RR}{\mathbb{R}}$
# $\newcommand{\bv}[1]{\begin{bmatrix} #1 \end{bmatrix}}$
# $\renewcommand{\vec}{\mathbf}$
#
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "slide"}
# # One-minute Review
#
# ## Vector Operations
#
# Let $\vec v, \vec w$ be vectors in $\RR^n$ and $c$ a scalar.
#
# | Operation | Notation | Formula | Output |
# |---|---| --- |---|
# | scalar multiplication | $$c \vec v$$ | $$\langle c v_1, \ldots ,c v_n \rangle $$| vector |
# | vector addition | $$\vec v + \vec w$$ | $$\langle v_1 + w_1,\ldots, v_n + w_n \rangle $$| vector |
# | dot product | $$\vec v \cdot \vec w$$ | $$v_1 w_1 + \cdots + v_n w_n $$| scalar |
# | cross product | $$\vec v \times \vec w$$ | $$ \begin{vmatrix} \vec i & \vec j & \vec k \\v_1 & v_2 & v_3 \\ w_1 & w_2 & w_3 \\ \end{vmatrix} $$| 3-vector |
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "slide"}
# # Lecture 04
#
# - Objectives
#
# - Finish geometrical problems with points/lines/planes.
# - Introduce parametrized curves (i.e., vector-valued functions).
#
# - Resources
# - Content
# - Stewart: §12.5–6
# - New Strang: [§2.5](https://cnx.org/contents/oxzXkyFi@5.30:YM6I55EW@6/2-5-Equations-of-Lines-and-Planes-in-Space) [§3.1](https://openstax.org/books/calculus-volume-3/pages/3-1-vector-valued-functions-and-space-curves)
# - Practice
# - [Exercises & Solutions](../exercises/L04-Exercises-Solutions.ipynb)
# - Mooculus:
# - [Lines](https://ximera.osu.edu/mooculus/calculus3/linesAndCurvesInSpace/digInLinesAndCurvesInSpace)
# - [Planes](https://ximera.osu.edu/mooculus/calculus3/normalVectors/digInPlanesInSpace) \*not everything is relevant
# - [Calculus of Vector-valued Functions](https://ximera.osu.edu/mooculus/calculus3/calculusAndVectorValuedFunctions/titlePage)
# - Extras
# - CalcBLUE: [Lines & Planes](https://www.youtube.com/watch?v=owMT-d4RRpw&index=3&list=PL8erL0pXF3JYm7VaTdKDaWc8Q3FuP8Sa7)
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "slide"}
# ### Example
#
# Find the distance between the skew lines given by the expressions $$\bv{ - t \\ t \\ 1 } \text{ and } \bv{ 1 - t \\ 1 + 2t \\ 2 + t} $$
# + tags=[]
p, v = array(((0,0,1), (-1,1,0)))
q, w = array(((1,1,2), (-1,2,1)))
# -
p, v
q,w
q - p
n = cross(v,w)
n
u = dot(q - p, n) / dot(n,n) * n
u
d = sqrt(dot(u,u))
d
# <p style="padding-bottom:40%;"> </p>
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "subslide"}
# # Space Curves
#
# ## aka Vector-Valued Functions
#
# We turn our attention to functions of the form $$\vec r: \RR \to \RR^3$$ or, in component form, $$\vec r(t) = \bv{x(t) \\ y(t) \\ z(t)}.$$
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Examples
#
# We first interpret $\vec r(t)$, as in the specific case of lines, as giving a position vector for each real scalar input $t$. Thus, we can plot these as a set of points, a **curve**.
# + hide_input=true jupyter={"source_hidden": true} slideshow={"slide_type": "fragment"} tags=[]
r1 = lambda t: np.array([t,t**2,t**3])
r2 = lambda t: np.array([cos(2*pi*t),sin(2*pi*t),t])
r3 = lambda t: np.array([cos(8*pi*t),sin(3*pi*t),sin(7*pi*t)])
@interact
def _(t=(-1,1,.05),r={"twist":r1, "helix": r2, "wacky": r3},angle=(-90,120,6),vangle=(0,90,6)):
fig = plt.figure(figsize = (10,10))
ax = fig.add_subplot(111,projection='3d')
s = np.linspace(-1,1,300)
ax.view_init(vangle, angle)
ax.set_autoscale_on(True)
for c in 'xyz':
getattr(ax,f"set_{c}lim")([-1,1]);
getattr(ax,f"set_{c}label")(f"${c}$",size=16)
X,Y,Z = np.column_stack([r(x) for x in s])
# make axes lines
ax.plot([-1,1],[0,0],[0,0],'k')
ax.plot([0,0],[-1,1],[0,0],'k')
ax.plot([0,0],[0,0],[-1,1],'k')
ax.plot(X,Y,Z,alpha=1,lw=3);
ax.quiver(0,0,0,r(t)[0],r(t)[1],r(t)[2])
flush_figures()
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Exercise (via Stewart)
#
# <!--  -->
# + tags=[]
rr = list(range(6))
np.random.shuffle(rr)
rr
tt = np.linspace(0,10,250)
funs = [lambda t: np.array((t*cos(t),t,t*sin(t))),
lambda t: np.array((cos((t-5))**2,sin((t-5))**2,(t-5))),
lambda t: np.array((cos(t),sin(t),cos(2*t))),
lambda t: np.array((cos(8*(t-5)),sin(8*(t-5)),np.exp(.8*(t-5)))),
lambda t: np.array(((t-5),1/(((t-5))**2 + 1),((t-5))**2)),
lambda t: np.array((cos((3*(t-5))),sin((3*(t-5))),1/(1+((3*(t-5)))**2)))]
@interact
def _(angle=(-120,96,6)):
fig = plt.figure(figsize=(12,8))
for i in range(len(funs)):
ax = fig.add_subplot(2,3,i+1,projection='3d')
x,y,z = np.column_stack([funs[rr[i]](t) for t in tt])
ax.plot(x,y,z,lw=3)
ax.view_init(30,angle)
for c in 'xyz':
# getattr(ax,f"set_{c}lim")([-1,1]);
getattr(ax,f"set_{c}label")(f"${c}$",size=12)
ax.set_title(str(i + 1),fontsize=23)
flush_figures();
# + [markdown] tags=[]
# <table>
# <tr>
# <td>A. $$\langle t \cos t, t, t\sin t\rangle$$</td>
# <td>B. $$\langle \cos t, \sin t, 1/(1+t^2)\rangle$$</td>
# <td>C. $$\langle t, 1/(1+t^2),t^2\rangle$$</td>
# <td rowspan="2"> <img src="../img/l04q1.png" width="250"></td>
# </tr>
# <tr>
# <td>D. $$\langle \cos t, \sin t, \cos 2t\rangle$$</td>
# <td>E. $$\langle \cos 8t, \sin 8t, e^{0.8t}\rangle$$</td>
# <td>F. $$\langle \cos^2 t, \sin^2 t, t\rangle$$</td>
# </tr>
# </table>
# -
# <td rowspan="2"> <img src="../img/l04q1.png" width="1000">
# <p styale="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Resource: CalcPlot3D
#
# A quick-and-easy place to visualize a lot of graphs in this course (and one that makes nicer pictures than your instructor, frankly) is Paul Seeburger's [CalcPlot3D](https://www.monroecc.edu/faculty/paulseeburger/calcnsf/CalcPlot3D/).
#
# Bookmark it and keep it on hand for quick visualizations.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Example
#
# Parametrize the curve of the intersection of the cylinder $x^2 +y^2 =4 $ and the plane $x-2y+4z=2$.
# + hide_input=true jupyter={"source_hidden": true} slideshow={"slide_type": "fragment"} tags=[]
@interact
def _(angle=(-96,96,6)):
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x = y = np.linspace(-1,1,101)
x,y = np.meshgrid(x,y)
X = 2*cos(2*pi*x)
Y = 2*sin(2*pi*x)
Z = 2*y
ax.plot_surface(X,Y,Z,alpha=.6,cmap='ocean');
X = 2*x
Y = 2*y
Z = (2-X+2*Y)/4
ax.plot_surface(X,Y,Z,alpha=1,color='purple')
for c in 'xyz':
getattr(ax,f"set_{c}lim")([-2.5,2.5]);
getattr(ax,f"set_{c}label")(f"${c}$",size=16)
# ax.set_zlim([0,8])
# ax.set_zlabel("$z$",size=16)
ax.view_init(30,angle)
flush_figures();
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "slide"}
# # Calculus of Vector-Valued Functions
# + [markdown] slideshow={"slide_type": "fragment"}
# ## Limits
#
# Let $\vec r (t) = \langle x(t),y(t),z(t) \rangle$ then the definition of a limit looks nearly identical to that for scalar-valued funtions. $$\lim_{t \to a} \vec r(t) = \vec L $$ if $|\vec r(t) - \vec L|$ gets arbitrarily small as $t$ approaches $a$.
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "fragment"}
# In other words, $$\lim_{t \to a} \vec r(t) = \bv{\lim_{t \to a} x(t) \\\lim_{t \to a} y(t) \\ \lim_{t \to a} z(t) }$$ where the LHS exists if and only if all limits on the RHS exist.
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "subslide"}
# ## Derivatives
#
# A similar story happens when we try to import the definition of a derivative to this context. $$\vec r'(t) = \lim_{h \to 0} \frac{\vec r(t+h) - \vec r(t)}{h} $$
# + [markdown] slideshow={"slide_type": "fragment"}
# $$ = \bv{x'(t) \\ y'(t) \\ z'(t)}$$
# + [markdown] slideshow={"slide_type": "fragment"}
# ... but the geometric view is actually interesting...
# -
# <p style="padding-bottom:40%;"> </p>
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Example
#
# Consider the curve $\vec r(t) = \langle -t \cos t, t \sin t \rangle $ in the plane for $t \in [0,2\pi]$.
# - Compute $\vec r'(\pi/2)$.
# - Draw several "values" of the difference quotient in the limit definition of the derivative.
# - Interpret the derivative as a vector.
# + hide_input=true jupyter={"source_hidden": true} slideshow={"slide_type": "fragment"} tags=[]
r = lambda t: np.array([- t*cos(t),t*sin(t)])
r2 = lambda t: np.array([cos(2*pi*t),sin(2*pi*t),t])
r3 = lambda t: np.array([cos(8*pi*t),sin(3*pi*t),sin(7*pi*t)])
@interact(h=(-.9,1.5,.05))
def _(h=.9):
fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)
s = np.linspace(0,pi,300)
ax.set_autoscale_on(True)
for c in 'xy':
getattr(ax,f"set_{c}label")(f"${c}$",size=16)
X,Y = np.column_stack([r(x) for x in s])
# make axes lines
ax.plot(X,Y,alpha=1,lw=3);
ax.plot([-1,pi],[0,0],'k')
ax.plot([0,0],[0,pi],'k')
v = r(pi/2+h)-r(pi/2)
ax.quiver([0,0],[pi/2,pi/2],[v[0],h == 0 and pi/2 or v[0]/h ],[v[1],h == 0 and 1 or v[1]/h],color='g',angles='xy', scale_units='xy', scale=1)
flush_figures();
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Quick exercise
#
# What is the derivative of the parametrized line $$\vec r(t) = \vec p + t \vec v ?$$
| lec/mvc-L04.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Webscraping utilizando a Beatiful Soup
#
# 1. Coletar os seguintes dados do site: https://books.toscrape.com/index.html
# - Cátalogo:
# -- Classics
# -- Science Fiction
# -- Business
#
# - Coletar os seguintes dados de cada livro
# -- Nome do Livro
# -- Preço em Libras
# -- Disponível em estoque
#
#
#
# 2. Problema de Negócio
#
# O CEO da livraria ROCKET BOOKS precia saber o que seu concorrente está fazendo. No caso, a Rocket Books vende 3 gêneros de livros Classics, Science Fiction e Business. O CEO gostaria de um dataseet com o que o concorrente está vendendo sobre esses 3 gêneros. Mais uma lista com o preço para um comparativo, e se está ou não disponível no estoque.
#
# 3. Entregável
# - Saída: Simulação da Tabela final e gráfico final
# - Processo: Sequência de passos organizada pela lógica e execução
# - Entrada: Link para as fontes de dados https://books.toscrape.com/index.html
#
# * Um csv com o pedido do CEO
#
# 4. Resolva essas duas teses do CEO
# * Os livros de gênero de negócios são os que tem a melhor avaliação?
# * Os livros com maior preço médio são os que tem a melhor avaliação?
# ## 0.0 Import
import requests
import pandas as pd
from datetime import datetime
from bs4 import BeautifulSoup
import numpy as np
import math
import seaborn as sns
# ### 0.1 Fuctions
def arrumar_euro(lista):
for p in range(len(lista)):
lista[p] = float(lista[p].replace("£", "").strip())
return lista
# ### 1.0 Reading Site
# #### 1.1 GENRE CLASSIC
# +
url_classic = 'https://books.toscrape.com/catalogue/category/books/classics_6/index.html'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) , AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
page = requests.get( url_classic, headers=headers )
soup = BeautifulSoup( page.text, "html.parser")
classic = soup.find( "ol" , class_="row")
#=============================price=============================
classic_price = classic.find_all("p", class_="price_color")
price_classic = [p.get_text() for p in classic_price]
#ajuste de variáveis
price_classic = arrumar_euro(price_classic)
#==========================name==============================
classic_name = classic.find_all("h3")
name_classic = [p.get_text() for p in classic_name]
#=========================rating score=========================
products = soup.find("div", class_="col-sm-8 col-md-9")
products_list = products.find_all("p", class_="star-rating")
#Costumer Avaliable
ca = [p.get("class") for p in products_list]
drop = lambda x: x.remove("star-rating")
list(map(drop, ca))
#===================disponível em estoque====================
classic_est = classic.find_all("p", class_="instock availability")
classic_est = [ list(filter(None, p.get_text().split("\n"))) for p in classic_est]
#new variable
est_classic = []
for p in range(len(classic_est)):
est_classic.append(classic_est[p][1].strip())
data_classic = pd.DataFrame([name_classic, est_classic, price_classic, ca]).T
data_classic.columns = ["name", "storage", "price [£]", "rating"]
valor1 = ""
valor = ""
for p in range(len(data_classic)):
valor = data_classic["rating"][p]
valor1= valor[0]
data_classic["rating"][p] = valor1
data_classic["genre"] = "Classic"
# -
# ### 1.2 Science Ficition
# +
url_classic = 'https://books.toscrape.com/catalogue/category/books/science-fiction_16/index.html'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) , AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
page = requests.get( url_classic, headers=headers )
soup = BeautifulSoup( page.text, "html.parser")
classic = soup.find( "ol" , class_="row")
#=============================price=============================
classic_price = classic.find_all("p", class_="price_color")
price_classic = [p.get_text() for p in classic_price]
#ajuste de variáveis
price_classic = arrumar_euro(price_classic)
#==========================name==============================
classic_name = classic.find_all("h3")
name_classic = [p.get_text() for p in classic_name]
#=========================rating score=========================
products = soup.find("div", class_="col-sm-8 col-md-9")
products_list = products.find_all("p", class_="star-rating")
#Costumer Avaliable
ca = [p.get("class") for p in products_list]
drop = lambda x: x.remove("star-rating")
list(map(drop, ca))
#===================disponível em estoque====================
classic_est = classic.find_all("p", class_="instock availability")
classic_est = [ list(filter(None, p.get_text().split("\n"))) for p in classic_est]
#new variable
est_classic = []
for p in range(len(classic_est)):
est_classic.append(classic_est[p][1].strip())
data_science = pd.DataFrame([name_classic, est_classic, price_classic, ca]).T
data_science.columns = ["name", "storage", "price [£]", "rating"]
valor1 = ""
valor = ""
for p in range(len(data_science)):
valor = data_science["rating"][p]
valor1= valor[0]
data_science["rating"][p] = valor1
data_science["genre"] = "Science Fiction"
# -
# ### 1.3 Genre Business
# +
url_classic = 'https://books.toscrape.com/catalogue/category/books/business_35/index.html'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) , AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
page = requests.get( url_classic, headers=headers )
soup = BeautifulSoup( page.text, "html.parser")
classic = soup.find( "ol" , class_="row")
#=============================price=============================
classic_price = classic.find_all("p", class_="price_color")
price_classic = [p.get_text() for p in classic_price]
#ajuste de variáveis
price_classic = arrumar_euro(price_classic)
#==========================name==============================
classic_name = classic.find_all("h3")
name_classic = [p.get_text() for p in classic_name]
#=========================rating score=========================
products = soup.find("div", class_="col-sm-8 col-md-9")
products_list = products.find_all("p", class_="star-rating")
#Costumer Avaliable
ca = [p.get("class") for p in products_list]
drop = lambda x: x.remove("star-rating")
list(map(drop, ca))
#===================disponível em estoque====================
classic_est = classic.find_all("p", class_="instock availability")
classic_est = [ list(filter(None, p.get_text().split("\n"))) for p in classic_est]
#new variable
est_classic = []
for p in range(len(classic_est)):
est_classic.append(classic_est[p][1].strip())
data_bus = pd.DataFrame([name_classic, est_classic, price_classic, ca]).T
data_bus.columns = ["name", "storage", "price [£]", "rating"]
valor1 = ""
valor = ""
for p in range(len(data_bus)):
valor = data_bus["rating"][p]
valor1= valor[0]
data_bus["rating"][p] = valor1
data_bus["genre"] = "Business"
# -
# ### 1.4 All Dataframes
data_total = pd.merge(data_classic,data_bus, how = 'outer')
data_total = pd.merge(data_total, data_science, how = 'outer')
data_total["rating_number"] = data_total["rating"].apply(lambda x: 1 if x == "One" else
2 if x== "Two" else
3 if x == "Three" else
4 if x == "Four" else
5)
data_total.dtypes
data_total
# ## 2.0 Plots | Data Exploratory
# Temos mais Livros avalidos do gênero Clássico
sns.countplot(x='genre',data=data_total);
# Alguns livros que costumam desnortear no boxplot. Chegam mais acima do primeiro quartil
sns.boxplot(x="genre", y="price [£]", data=data_total,palette='rainbow');
sns.stripplot(x="genre", y="price [£]", data=data_total,palette='rainbow');
# Maior preço médio é dos livros clássicos
df = data_total.copy()
teste = df[['genre', 'price [£]']].groupby('genre').mean().reset_index()
sns.barplot(x="genre", y="price [£]",data=teste);
# #### Livros clássicos
sns.countplot(x='rating',data=data_classic);
# #### Livros Científicos
#
sns.countplot(x='rating',data=data_science);
# #### Livros de Negócios
sns.countplot(x='rating',data=data_bus);
# ### 3.0 Conclusão
# H1. **FALSA** O gênero com maior preço médio tem melhores avaliações.
# Como vimos no gráfico o maior preço médio é do gênero Clássico. Porém a melhor avaliação de todos os gênero está para o "negócios". Com isso, não necessariamente o gênero com maior preço médio é o que tem melhores avaliações
# H2. **VERDADEIRO** O Gênero de Negócios tem o melhor rating de todos os gêneros
# No gráfico acima conseguimos observar que o gênero "Negócios" (Business) é o que tem melhores avaliações, tendo notas 5 estrelas e uma grande maioria de notas de Três estrelas
| Webscraping Rocket Books .ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] Collapsed="false"
# # News Classification App
# + [markdown] Collapsed="false"
# References:
#
# * https://www.w3schools.com/colors/colors_picker.asp
# * https://stackoverflow.com/questions/47949173/deploy-a-python-app-to-heroku-using-conda-environments-instead-of-virtualenv
# + [markdown] Collapsed="false"
# When deploying, remember to change Bs4 `html5lib` to `html.parser`.
# + Collapsed="false"
import pickle
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import punkt
from nltk.corpus.reader import wordnet
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
import requests
from bs4 import BeautifulSoup
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import dash_renderer
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
import re
# + [markdown] Collapsed="false"
# ## 1. Importing inputs
# + [markdown] Collapsed="false"
# ### 1.1. Trained Model
# + [markdown] Collapsed="false"
# The best performing model is the SVM. We'll use it in the app.
# + Collapsed="false"
path_models = "C:/Users/migue/Data Science/Master Data Science/KSCHOOL/9. TFM/0. Latest News Classifier/04. Model Training/Models/"
# SVM
path_svm = path_models + 'best_svc.pickle'
with open(path_svm, 'rb') as data:
svc_model = pickle.load(data)
# + [markdown] Collapsed="false"
# ### 1.2. TF-IDF object
# + Collapsed="false"
path_tfidf = "C:/Users/migue/Data Science/Master Data Science/KSCHOOL/9. TFM/0. Latest News Classifier/03. Feature Engineering/Pickles/tfidf.pickle"
with open(path_tfidf, 'rb') as data:
tfidf = pickle.load(data)
# + [markdown] Collapsed="false"
# ### 1.3. Category mapping dictionary
# + Collapsed="false"
category_codes = {
'business': 0,
'entertainment': 1,
'politics': 2,
'sport': 3,
'tech': 4,
'other':5
}
# + [markdown] Collapsed="false"
# ## 2. Definition of functions
# + [markdown] Collapsed="false"
# ### 2.1. Web Scraping Functions
# + Collapsed="false"
# El Pais
def get_news_elpais():
# url definition
url = "https://elpais.com/elpais/inenglish.html"
# Request
r1 = requests.get(url)
r1.status_code
# We'll save in coverpage the cover page content
coverpage = r1.content
# Soup creation
soup1 = BeautifulSoup(coverpage, 'html5lib')
# News identification
coverpage_news = soup1.find_all('h2', class_='articulo-titulo')
len(coverpage_news)
# We have to delete elements such as albums and other things
coverpage_news = [x for x in coverpage_news if "inenglish" in str(x)]
number_of_articles = 5
# Empty lists for content, links and titles
news_contents = []
list_links = []
list_titles = []
for n in np.arange(0, number_of_articles):
# Getting the link of the article
link = coverpage_news[n].find('a')['href']
list_links.append(link)
# Getting the title
title = coverpage_news[n].find('a').get_text()
list_titles.append(title)
# Reading the content (it is divided in paragraphs)
article = requests.get(link)
article_content = article.content
soup_article = BeautifulSoup(article_content, 'html5lib')
body = soup_article.find_all('div', class_='articulo-cuerpo')
x = body[0].find_all('p')
# Unifying the paragraphs
list_paragraphs = []
for p in np.arange(0, len(x)):
paragraph = x[p].get_text()
list_paragraphs.append(paragraph)
final_article = " ".join(list_paragraphs)
news_contents.append(final_article)
# df_features
df_features = pd.DataFrame(
{'Content': news_contents
})
# df_show_info
df_show_info = pd.DataFrame(
{'Article Title': list_titles,
'Article Link': list_links,
'Newspaper': 'El Pais English'})
return (df_features, df_show_info)
# The Guardian
def get_news_theguardian():
# url definition
url = "https://www.theguardian.com/uk"
# Request
r1 = requests.get(url)
r1.status_code
# We'll save in coverpage the cover page content
coverpage = r1.content
# Soup creation
soup1 = BeautifulSoup(coverpage, 'html5lib')
# News identification
coverpage_news = soup1.find_all('h3', class_='fc-item__title')
len(coverpage_news)
# We have to delete elements such as albums and other things
coverpage_news = [x for x in coverpage_news if "live" not in str(x)]
coverpage_news = [x for x in coverpage_news if "commentisfree" not in str(x)]
coverpage_news = [x for x in coverpage_news if "ng-interactive" not in str(x)]
number_of_articles = 5
# Empty lists for content, links and titles
news_contents = []
list_links = []
list_titles = []
for n in np.arange(0, number_of_articles):
# Getting the link of the article
link = coverpage_news[n].find('a')['href']
list_links.append(link)
# Getting the title
title = coverpage_news[n].find('a').get_text()
list_titles.append(title)
# Reading the content (it is divided in paragraphs)
article = requests.get(link)
article_content = article.content
soup_article = BeautifulSoup(article_content, 'html5lib')
body = soup_article.find_all('div', class_='content__article-body from-content-api js-article__body')
x = body[0].find_all('p')
# Unifying the paragraphs
list_paragraphs = []
for p in np.arange(0, len(x)):
paragraph = x[p].get_text()
list_paragraphs.append(paragraph)
final_article = " ".join(list_paragraphs)
news_contents.append(final_article)
# df_features
df_features = pd.DataFrame(
{'Content': news_contents
})
# df_show_info
df_show_info = pd.DataFrame(
{'Article Title': list_titles,
'Article Link': list_links,
'Newspaper': 'The Guardian'})
return (df_features, df_show_info)
# Sky News
def get_news_skynews():
# url definition
url = "https://news.sky.com/us"
# Request
r1 = requests.get(url)
# We'll save in coverpage the cover page content
coverpage = r1.content
# Soup creation
soup1 = BeautifulSoup(coverpage, 'html5lib')
# News identification
coverpage_news = soup1.find_all('h3', class_="sdc-site-tile__headline")
number_of_articles = 5
# Empty lists for content, links and titles
news_contents = []
list_links = []
list_titles = []
for n in np.arange(0, number_of_articles):
# Getting the link of the article
link = "https://news.sky.com" + coverpage_news[n].find('a', class_='sdc-site-tile__headline-link')['href']
list_links.append(link)
# Getting the title
title = coverpage_news[n].find('a').find('span').get_text()
list_titles.append(title)
# Reading the content (it is divided in paragraphs)
article = requests.get(link)
article_content = article.content
soup_article = BeautifulSoup(article_content, 'html5lib')
body = soup_article.find_all('div', class_='sdc-article-body sdc-article-body--lead')
x = body[0].find_all('p')
# Unifying the paragraphs
list_paragraphs = []
for p in np.arange(0, len(x)):
paragraph = x[p].get_text()
list_paragraphs.append(paragraph)
final_article = " ".join(list_paragraphs)
news_contents.append(final_article)
# df_features
df_features = pd.DataFrame(
{'Content': news_contents
})
# df_show_info
df_show_info = pd.DataFrame(
{'Article Title': list_titles,
'Article Link': list_links,
'Newspaper': 'Sky News'})
return (df_features, df_show_info)
# + [markdown] Collapsed="false"
# ### 2.2. Feature Engineering Functions
# + Collapsed="false"
punctuation_signs = list("?:!.,;")
stop_words = list(stopwords.words('english'))
def create_features_from_df(df):
df['Content_Parsed_1'] = df['Content'].str.replace("\r", " ")
df['Content_Parsed_1'] = df['Content_Parsed_1'].str.replace("\n", " ")
df['Content_Parsed_1'] = df['Content_Parsed_1'].str.replace(" ", " ")
df['Content_Parsed_1'] = df['Content_Parsed_1'].str.replace('"', '')
df['Content_Parsed_2'] = df['Content_Parsed_1'].str.lower()
df['Content_Parsed_3'] = df['Content_Parsed_2']
for punct_sign in punctuation_signs:
df['Content_Parsed_3'] = df['Content_Parsed_3'].str.replace(punct_sign, '')
df['Content_Parsed_4'] = df['Content_Parsed_3'].str.replace("'s", "")
wordnet_lemmatizer = WordNetLemmatizer()
nrows = len(df)
lemmatized_text_list = []
for row in range(0, nrows):
# Create an empty list containing lemmatized words
lemmatized_list = []
# Save the text and its words into an object
text = df.loc[row]['Content_Parsed_4']
text_words = text.split(" ")
# Iterate through every word to lemmatize
for word in text_words:
lemmatized_list.append(wordnet_lemmatizer.lemmatize(word, pos="v"))
# Join the list
lemmatized_text = " ".join(lemmatized_list)
# Append to the list containing the texts
lemmatized_text_list.append(lemmatized_text)
df['Content_Parsed_5'] = lemmatized_text_list
df['Content_Parsed_6'] = df['Content_Parsed_5']
for stop_word in stop_words:
regex_stopword = r"\b" + stop_word + r"\b"
df['Content_Parsed_6'] = df['Content_Parsed_6'].str.replace(regex_stopword, '')
df = df['Content_Parsed_6']
df = df.rename(columns={'Content_Parsed_6': 'Content_Parsed'})
# TF-IDF
features = tfidf.transform(df).toarray()
return features
# + Collapsed="false"
def get_category_name(category_id):
for category, id_ in category_codes.items():
if id_ == category_id:
return category
# + [markdown] Collapsed="false"
# ### 2.3. Prediction Functions
# + Collapsed="false"
def predict_from_features(features):
# Obtain the highest probability of the predictions for each article
predictions_proba = svc_model.predict_proba(features).max(axis=1)
# Predict using the input model
predictions_pre = svc_model.predict(features)
# Replace prediction with 6 if associated cond. probability less than threshold
predictions = []
for prob, cat in zip(predictions_proba, predictions_pre):
if prob > .65:
predictions.append(cat)
else:
predictions.append(5)
# Return result
categories = [get_category_name(x) for x in predictions]
return categories
# + Collapsed="false"
def complete_df(df, categories):
df['Prediction'] = categories
return df
# + [markdown] Collapsed="false"
# Finally, the whole process can be written in these 4 lines of code:
# + [markdown] Collapsed="false"
# ```python
# # Get the scraped dataframes
# df_features, df_show_info = get_news_elpais()
#
# # Create features
# features = create_features_from_df(df_features)
#
# # Predict
# predictions = predict_from_features(features)
#
# # Put into dataset
# df = complete_df(df_show_info, predictions)
# ```
# + [markdown] Collapsed="false"
# ## 3. Dash App
# + Collapsed="false"
# Stylesheet
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# Colors
colors = {
'background': '#ECECEC',
'text': '#696969',
'titles': '#599ACF',
'blocks': '#F7F7F7',
'graph_background': '#F7F7F7',
'banner': '#C3DCF2'
}
# Markdown text
markdown_text1 = '''
This application gathers the latest news from the newspapers **El Pais**, **The Guardian** and **Sky News**, predicts their category between **Politics**, **Business**, **Entertainment**, **Sport**, **Tech** and **Other** and then shows a summary.
The scraped news are converted into a numeric feature vector with *TF-IDF vectorization*. Then, a *Support Vector Classifier* is applied to predict each category.
This app is meant for didactic purposes.
Please enter which newspapers would you like to scrape news off and press the **Scrape** button.
'''
markdown_text2 = '''
Created by <NAME>. Visit my webpage at [mfz.es](https://www.mfz.es/) and the [github repo](https://github.com/miguelfzafra/Latest-News-Classifier).
*Disclaimer: this app is not under periodic maintenance. A live web-scraping process is carried out every time you run the app, so there may be some crashes due to the failing status of some requests.*
'''
app.layout = html.Div(style={'backgroundColor':colors['background']}, children=[
# Space before title
html.H1(children=' ',
style={'padding': '10px'}
),
# Title
html.Div(
[
html.H3(children='News Classification App',
style={"margin-bottom": "0px"}
),
html.H6(children='A Machine Learning based app')
],
style={
'textAlign': 'center',
'color': colors['text'],
#'padding': '0px',
'backgroundColor': colors['background']
},
className='banner',
),
# Space after title
html.H1(children=' ',
style={'padding': '1px'}),
# Text boxes
html.Div(
[
html.Div(
[
html.H6(children='What does this app do?',
style={'color':colors['titles']}),
html.Div(
[dcc.Markdown(children=markdown_text1),],
style={'font-size': '12px',
'color': colors['text']}),
html.Div(
[
dcc.Dropdown(
options=[
{'label': 'El Pais English', 'value': 'EPE'},
{'label': 'The Guardian', 'value': 'THG'},
{'label': 'Sky News', 'value': 'SKN'}
],
value=['EPE'],
multi=True,
id='checklist'),
],
style={'font-size': '12px',
'margin-top': '25px'}),
html.Div([
html.Button('Scrape',
id='submit',
type='submit',
style={'color': colors['blocks'],
'background-color': colors['titles'],
'border': 'None'})],
style={'textAlign': 'center',
'padding': '20px',
"margin-bottom": "0px",
'color': colors['titles']}),
dcc.Loading(id="loading-1", children=[html.Div(id="loading-output-1")], type="circle"),
html.Hr(),
html.H6(children='Headlines',
style={'color': colors['titles']}),
# Headlines
html.A(id="textarea1a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea1b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea2a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea2b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea3a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea3b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea4a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea4b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea5a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea5b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea6a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea6b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea7a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea7b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea8a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea8b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea9a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea9b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea10a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea10b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea11a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea11b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea12a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea12b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea13a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea13b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea14a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea14b", style={'color': colors['text'], 'font-size': '11px'}),
html.A(id="textarea15a", target="_blank", style={'font-size': '12px'}),
html.P(id="textarea15b", style={'color': colors['text'], 'font-size': '11px'})
],
style={'backgroundColor': colors['blocks'],
'padding': '20px',
'border-radius': '5px',
'box-shadow': '1px 1px 1px #9D9D9D'},
className='one-half column'),
html.Div(
[
html.H6("Graphic summary",
style={'color': colors['titles']}),
html.Div([
dcc.Graph(id='graph1', style={'height': '300px'})
],
style={'backgroundColor': colors['blocks'],
'padding': '20px'}
),
html.Div([
dcc.Graph(id='graph2', style={'height': '300px'})
],
style={'backgroundColor': colors['blocks'],
'padding': '20px'}
)
],
style={'backgroundColor': colors['blocks'],
'padding': '20px',
'border-radius': '5px',
'box-shadow': '1px 1px 1px #9D9D9D'},
className='one-half column')
],
className="row flex-display",
style={'padding': '20px',
'margin-bottom': '0px'}
),
# Space
html.H1(id='space2', children=' '),
# Final paragraph
html.Div(
[dcc.Markdown(children=markdown_text2),],
style={'font-size': '12px',
'color': colors['text']}),
# Hidden div inside the app that stores the intermediate value
html.Div(id='intermediate-value', style={'display': 'none'})
])
@app.callback(
[
Output('intermediate-value', 'children'),
Output('loading-1', 'children')
],
[Input('submit', 'n_clicks')],
[State('checklist', 'value')])
def scrape_and_predict(n_clicks, values):
df_features = pd.DataFrame()
df_show_info = pd.DataFrame()
if 'EPE' in values:
# Get the scraped dataframes
df_features = df_features.append(get_news_elpais()[0])
df_show_info = df_show_info.append(get_news_elpais()[1])
if 'THG' in values:
df_features = df_features.append(get_news_theguardian()[0])
df_show_info = df_show_info.append(get_news_theguardian()[1])
if 'SKN' in values:
df_features = df_features.append(get_news_skynews()[0])
df_show_info = df_show_info.append(get_news_skynews()[1])
df_features = df_features.reset_index().drop('index', axis=1)
# Create features
features = create_features_from_df(df_features)
# Predict
predictions = predict_from_features(features)
# Put into dataset
df = complete_df(df_show_info, predictions)
# df.to_csv('Tableau Teaser/df_tableau.csv', sep='^') # export to csv to work out an example in Tableau
return df.to_json(date_format='iso', orient='split'), ' '
@app.callback(
Output('graph1', 'figure'),
[Input('intermediate-value', 'children')])
def update_barchart(jsonified_df):
df = pd.read_json(jsonified_df, orient='split')
# Create a summary df
df_sum = df.groupby(['Newspaper', 'Prediction']).count()['Article Title']
# Create x and y arrays for the bar plot for every newspaper
if 'El Pais English' in df_sum.index:
df_sum_epe = df_sum['El Pais English']
x_epe = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y_epe = [[df_sum_epe['politics'] if 'politics' in df_sum_epe.index else 0][0],
[df_sum_epe['business'] if 'business' in df_sum_epe.index else 0][0],
[df_sum_epe['entertainment'] if 'entertainment' in df_sum_epe.index else 0][0],
[df_sum_epe['sport'] if 'sport' in df_sum_epe.index else 0][0],
[df_sum_epe['tech'] if 'tech' in df_sum_epe.index else 0][0],
[df_sum_epe['other'] if 'other' in df_sum_epe.index else 0][0]]
else:
x_epe = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y_epe = [0,0,0,0,0,0]
if 'The Guardian' in df_sum.index:
df_sum_thg = df_sum['The Guardian']
x_thg = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y_thg = [[df_sum_thg['politics'] if 'politics' in df_sum_thg.index else 0][0],
[df_sum_thg['business'] if 'business' in df_sum_thg.index else 0][0],
[df_sum_thg['entertainment'] if 'entertainment' in df_sum_thg.index else 0][0],
[df_sum_thg['sport'] if 'sport' in df_sum_thg.index else 0][0],
[df_sum_thg['tech'] if 'tech' in df_sum_thg.index else 0][0],
[df_sum_thg['other'] if 'other' in df_sum_thg.index else 0][0]]
else:
x_thg = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y_thg = [0,0,0,0,0,0]
if 'Sky News' in df_sum.index:
df_sum_skn = df_sum['Sky News']
x_skn = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y_skn = [[df_sum_skn['politics'] if 'politics' in df_sum_skn.index else 0][0],
[df_sum_skn['business'] if 'business' in df_sum_skn.index else 0][0],
[df_sum_skn['entertainment'] if 'entertainment' in df_sum_skn.index else 0][0],
[df_sum_skn['sport'] if 'sport' in df_sum_skn.index else 0][0],
[df_sum_skn['tech'] if 'tech' in df_sum_skn.index else 0][0],
[df_sum_skn['other'] if 'other' in df_sum_skn.index else 0][0]]
else:
x_skn = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y_skn = [0,0,0,0,0,0]
# Create plotly figure
figure = {
'data': [
{'x': x_epe, 'y':y_epe, 'type': 'bar', 'name': 'El Pais', 'marker': {'color': 'rgb(62, 137, 195)'}},
{'x': x_thg, 'y':y_thg, 'type': 'bar', 'name': 'The Guardian', 'marker': {'color': 'rgb(167, 203, 232)'}},
{'x': x_skn, 'y':y_skn, 'type': 'bar', 'name': 'Sky News', 'marker': {'color': 'rgb(197, 223, 242)'}}
],
'layout': {
'title': 'Number of news articles by newspaper',
'plot_bgcolor': colors['graph_background'],
'paper_bgcolor': colors['graph_background'],
'font': {
'color': colors['text'],
'size': '10'
},
'barmode': 'stack'
}
}
return figure
@app.callback(
Output('graph2', 'figure'),
[Input('intermediate-value', 'children')])
def update_piechart(jsonified_df):
df = pd.read_json(jsonified_df, orient='split')
# Create a summary df
df_sum = df['Prediction'].value_counts()
# Create x and y arrays for the bar plot
x = ['Politics', 'Business', 'Entertainment', 'Sport', 'Tech', 'Other']
y = [[df_sum['politics'] if 'politics' in df_sum.index else 0][0],
[df_sum['business'] if 'business' in df_sum.index else 0][0],
[df_sum['entertainment'] if 'entertainment' in df_sum.index else 0][0],
[df_sum['sport'] if 'sport' in df_sum.index else 0][0],
[df_sum['tech'] if 'tech' in df_sum.index else 0][0],
[df_sum['other'] if 'other' in df_sum.index else 0][0]]
# Create plotly figure
figure = {
'data': [
{'values': y,
'labels': x,
'type': 'pie',
'hole': .4,
'name': '% of news articles',
'marker': {'colors': ['rgb(62, 137, 195)',
'rgb(167, 203, 232)',
'rgb(197, 223, 242)',
'rgb(51, 113, 159)',
'rgb(64, 111, 146)',
'rgb(31, 84, 132)']},
}
],
'layout': {
'title': 'News articles by newspaper',
'plot_bgcolor': colors['graph_background'],
'paper_bgcolor': colors['graph_background'],
'font': {
'color': colors['text'],
'size': '10'
}
}
}
return figure
@app.callback(
[
Output('textarea1a', 'href'),
Output('textarea1a', 'children'),
Output('textarea1b', 'children'),
Output('textarea2a', 'href'),
Output('textarea2a', 'children'),
Output('textarea2b', 'children'),
Output('textarea3a', 'href'),
Output('textarea3a', 'children'),
Output('textarea3b', 'children'),
Output('textarea4a', 'href'),
Output('textarea4a', 'children'),
Output('textarea4b', 'children'),
Output('textarea5a', 'href'),
Output('textarea5a', 'children'),
Output('textarea5b', 'children'),
Output('textarea6a', 'href'),
Output('textarea6a', 'children'),
Output('textarea6b', 'children'),
Output('textarea7a', 'href'),
Output('textarea7a', 'children'),
Output('textarea7b', 'children'),
Output('textarea8a', 'href'),
Output('textarea8a', 'children'),
Output('textarea8b', 'children'),
Output('textarea9a', 'href'),
Output('textarea9a', 'children'),
Output('textarea9b', 'children'),
Output('textarea10a', 'href'),
Output('textarea10a', 'children'),
Output('textarea10b', 'children'),
Output('textarea11a', 'href'),
Output('textarea11a', 'children'),
Output('textarea11b', 'children'),
Output('textarea12a', 'href'),
Output('textarea12a', 'children'),
Output('textarea12b', 'children'),
Output('textarea13a', 'href'),
Output('textarea13a', 'children'),
Output('textarea13b', 'children'),
Output('textarea14a', 'href'),
Output('textarea14a', 'children'),
Output('textarea14b', 'children'),
Output('textarea15a', 'href'),
Output('textarea15a', 'children'),
Output('textarea15b', 'children')
],
[Input('intermediate-value', 'children')])
def update_textarea1(jsonified_df):
df = pd.read_json(jsonified_df, orient='split')
texts = []
links = []
preds_newsp = []
for article in range(len(df)):
texts.append(df.iloc[article]['Article Title'])
links.append(df.iloc[article]['Article Link'])
preds_newsp.append((df.iloc[article]['Prediction'].capitalize()) + ', ' + (df.iloc[article]['Newspaper']))
while (len(texts) < 16):
texts.append(None)
links.append(None)
preds_newsp.append(None)
return \
links[0], texts[0], preds_newsp[0],\
links[1], texts[1], preds_newsp[1],\
links[2], texts[2], preds_newsp[2],\
links[3], texts[3], preds_newsp[3],\
links[4], texts[4], preds_newsp[4],\
links[5], texts[5], preds_newsp[5],\
links[6], texts[6], preds_newsp[6],\
links[7], texts[7], preds_newsp[7],\
links[8], texts[8], preds_newsp[8],\
links[9], texts[9], preds_newsp[9],\
links[10], texts[10], preds_newsp[10],\
links[11], texts[11], preds_newsp[11],\
links[12], texts[12], preds_newsp[12],\
links[13], texts[13], preds_newsp[13],\
links[14], texts[14], preds_newsp[14]
# Loading CSS
app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})
app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/brPBPO.css"})
# + Collapsed="false"
app.run_server(debug=False)
| 10.-App-Creation-v2/21b. News Classification App V2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Fractales de Newton
#
# Es posible generar un gran número a partir del método de Newton. En este cuaderno se presenta un espacio virtual que permite visualizar los diferentes fractales que se pueden generar a partir de la aplicación del método de Newton.
#
# El fractal de Newton es una maravillosa creación que se basa en la aplicación del método de Newton para la resolución de sistemas de ecuaciones no lineales, en este caso sobre el plano complejo. El algoritmo es eficiente para encontrar aproximaciones de los ceros o raíces de una función a partir de un punto dado. No obstante, algunos puntos no convergen rapidamente hacia ninguna raíz y luego de muchas iteraciones no producen un resultado. Dichos puntos serán representados en la imagen con el color blanco.
#
# Cada color representa una raíz y los diferentes tonos del mismo color representan la velocidad siendo la más brillante la que más rapido converge.
import newton as nw
# Veamos ahora algunos ejemplos de estos fractales. Daremos inicio con el de la función $f(z)=z^3-1$
nw.fractal(fn="z**3-1")
# Ahora veremos el de la función $f(z)=z^4+1$, que expone 4 raices.
nw.fractal(fn="z**4+1")
# Siguiendo la secuencia lógica, veremos ahora la función $f(z)=z^5-1$
nw.fractal(fn="z**5-1",xa=-2,xb=2,ya=-2,yb=2)
# Finalmente, pondremos una función menos tradicional para ver que patrones se pueden observar. Esta es la función $f(z)=z^3-3^z$
nw.fractal(fn="z**3-3**z")
# Ahora invitamos a nuestros visitantes a escribir la función que deseen e interactuar con la herramienta, es necesario tener paciencia y esperar un bonito resultado.
nw.custom_fractal()
| newton.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Temperature estimation from KBr $T_{1}$
# The temperature estimation is based on the paper from Thurber and Tycko.\
# *<NAME>.; <NAME>. Measurement of Sample Temperatures under Magic-Angle Spinning from the Chemical Shift and Spin-Lattice Relaxation Rate of 79Br in KBr Powder. J. Magn. Reson. 2009, 196 (1), 84–87. https://doi.org/10.1016/j.jmr.2008.09.019.*
# +
import numpy as np
import plotly.express as px
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx], idx
# -
# The function finds the nearest member and index of the array corresponding to the value supplied.\
# The idea is to send the $T_{1}$ value and the function returns the index from the array corresponding to the closest member of that value.
temp = np.linspace(20,298,4000)
y0=0.0145*np.ones(np.size(temp));
y1=5330*(temp ** -2);
y2=1.42e7*(temp ** -4);
y3=2.48e9*(temp ** -6);
y=y0+y1+y2+y3;
fig = px.line(x=temp, y=y, labels={'x':'Temperature', 'y':'$T_1$'})
fig.show()
# Now the code asks you for the measured $T_1$ and returns you the nearest temperature.
# +
t1 = float(input("Enter the measured T1 in s : "))
k, l=find_nearest(y, t1)
print("The temperature corresponding to " + str(t1) + " s is " + str("%.2f" %temp[l]) + ' K')
# -
| tempfromKBrt1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import scipy
from scipy import misc
import glob
from PIL import Image
import matplotlib.pyplot as plt
from keras import layers
from keras.layers import (Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten,
Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D)
from keras.models import Model, load_model
from keras.preprocessing import image
from keras.utils import layer_utils
import pydot
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from keras.optimizers import Adam
from keras.initializers import glorot_uniform
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from pydub import AudioSegment
import shutil
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import numpy as np
# +
import os
import numpy, scipy, matplotlib.pyplot as plt, IPython.display as ipd
import librosa, librosa.display
import numpy as np
import math
os.chdir('/home/student/Downloads/new_violin_viola/classical/viola/combined_train')
x1=[]
y_train=[]
mfcc_list_mean = []
mfcc_list_std = []
freqViolin = []
freqViola = []
for f_name in os.listdir('/home/student/Downloads/new_violin_viola/classical/viola/combined_train'):
if f_name.endswith('.mp3') or f_name.endswith('.wav'):
print(f_name)
#temp = x/x.max() #normalization
#S = librosa.feature.melspectrogram(temp, sr=sr, n_mels=128) # 128 mel bands
#mfcc = librosa.feature.mfcc(S=librosa.power_to_db(S), n_mfcc=13)
#tempList = list(np.mean(mfcc,1))
#tempList1 = list(np.std(mfcc,1))
y, sr = librosa.load(f_name)
#mel = librosa.feature.melspectrogram(y=y,sr=sr)
X = librosa.stft(y)
S = librosa.amplitude_to_db(X, ref=np.max)
plt. clf()
fig = plt.figure(figsize=(8.0, 10.0)) #for full size graph download
librosa.display.specshow(S, y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.savefig(f'/home/student/Downloads/new_violin_viola_dl/classical/train_combined/viola/{f_name[:-4]}.png')
os.chdir('/home/student/Downloads/new_violin_viola/classical/violin/combined_train')
for f_name in os.listdir('/home/student/Downloads/new_violin_viola/classical/violin/combined_train'):
if f_name.endswith('.mp3') or f_name.endswith('.wav'):
print(f_name)
y, sr = librosa.load(f_name)
#mel = librosa.feature.melspectrogram(y=y,sr=sr)
X = librosa.stft(y)
S = librosa.amplitude_to_db(X, ref=np.max)
plt. clf()
fig = plt.figure(figsize=(8.0, 10.0)) #for full size graph download
librosa.display.specshow(S, y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.savefig(f'/home/student/Downloads/new_violin_viola_dl/classical/train_combined/violin/{f_name[:-4]}.png')
# +
os.chdir('/home/student/Downloads/new_violin_viola/classical/viola/combined_test')
for f_name in os.listdir('/home/student/Downloads/new_violin_viola/classical/viola/combined_test'):
if f_name.endswith('.mp3') or f_name.endswith('.wav'):
print(f_name)
#temp = x/x.max() #normalization
#S = librosa.feature.melspectrogram(temp, sr=sr, n_mels=128) # 128 mel bands
#mfcc = librosa.feature.mfcc(S=librosa.power_to_db(S), n_mfcc=13)
#tempList = list(np.mean(mfcc,1))
#tempList1 = list(np.std(mfcc,1))
y, sr = librosa.load(f_name)
#mel = librosa.feature.melspectrogram(y=y,sr=sr)
X = librosa.stft(y)
S = librosa.amplitude_to_db(X, ref=np.max)
plt. clf()
fig = plt.figure(figsize=(8.0, 10.0)) #for full size graph download
librosa.display.specshow(S, y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.savefig(f'/home/student/Downloads/new_violin_viola_dl/classical/test_combined/viola/{f_name[:-4]}.png')
os.chdir('/home/student/Downloads/new_violin_viola/classical/violin/combined_test')
for f_name in os.listdir('/home/student/Downloads/new_violin_viola/classical/violin/combined_test'):
if f_name.endswith('.mp3') or f_name.endswith('.wav'):
print(f_name)
y, sr = librosa.load(f_name)
#mel = librosa.feature.melspectrogram(y=y,sr=sr)
X = librosa.stft(y)
S = librosa.amplitude_to_db(X, ref=np.max)
plt. clf()
fig = plt.figure(figsize=(8.0, 10.0)) #for full size graph download
librosa.display.specshow(S, y_axis='mel')
plt.colorbar(format='%+2.0f dB')
plt.savefig(f'/home/student/Downloads/new_violin_viola_dl/classical/test_combined/violin/{f_name[:-4]}.png')
# +
train_dir = "/home/student/Downloads/new_violin_viola_dl/classical/train_combined/"
train_data = ImageDataGenerator(rescale=1./255,validation_split=0.2)
train_generator =train_data.flow_from_directory(train_dir,target_size=(288,432),color_mode="rgba",class_mode='categorical',batch_size=2,subset='training')
validation_generator=train_data.flow_from_directory(train_dir,target_size=(288,432),color_mode="rgba",class_mode='categorical',batch_size=2,subset='validation')
testing_dir = "/home/student/Downloads/new_violin_viola_dl/classical/test_combined/"
testing_data = ImageDataGenerator(rescale=1./255)
testing_generator = testing_data.flow_from_directory(testing_dir,target_size=(288,432),color_mode='rgba',class_mode='categorical',batch_size=2)
# -
def GenreModel(input_shape = (288,432,4),classes=2):
X_input = Input(input_shape)
X = Conv2D(8,kernel_size=(3,3),strides=(1,1))(X_input)
X = BatchNormalization(axis=3)(X)
X = Activation('relu')(X)
X = MaxPooling2D((2,2))(X)
X = Conv2D(16,kernel_size=(3,3),strides = (1,1))(X)
X = BatchNormalization(axis=3)(X)
X = Activation('relu')(X)
X = MaxPooling2D((2,2))(X)
X = Conv2D(32,kernel_size=(3,3),strides = (1,1))(X)
X = BatchNormalization(axis=3)(X)
X = Activation('relu')(X)
X = MaxPooling2D((2,2))(X)
X = Conv2D(64,kernel_size=(3,3),strides=(1,1))(X)
X = BatchNormalization(axis=-1)(X)
X = Activation('relu')(X)
X = MaxPooling2D((2,2))(X)
X = Conv2D(128,kernel_size=(3,3),strides=(1,1))(X)
X = BatchNormalization(axis=-1)(X)
X = Activation('relu')(X)
X = MaxPooling2D((2,2))(X)
X = Flatten()(X)
X = Dense(classes, activation='softmax', name='fc' + str(classes))(X)
model = Model(inputs=X_input,outputs=X,name='GenreModel')
return model
# +
import keras.backend as K
def recall_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def f1_m(y_true, y_pred):
precision = precision_m(y_true, y_pred)
recall = recall_m(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
def get_f1(y_true, y_pred): #taken from old keras source code
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
recall = true_positives / (possible_positives + K.epsilon())
f1_val = 2*(precision*recall)/(precision+recall+K.epsilon())
return f1_val
model = GenreModel(input_shape=(288,432,4),classes=2)
opt = Adam(learning_rate=0.0015)
model.compile(optimizer = opt,loss='categorical_crossentropy',metrics=['accuracy', 'mae'])
history = model.fit_generator(train_generator,epochs=30,validation_data=validation_generator)
# -
model.evaluate(testing_generator)
| cnn_combined_classical.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# # Introduction to Software Testing
#
# Before we get to the central parts of the book, let us introduce essential concepts of software testing. Why is it necessary to test software at all? How does one test software? How can one tell whether a test has been successful? How does one know if one has tested enough? In this chapter, let us recall the most important concepts, and at the same time get acquainted with Python and interactive notebooks.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## Simple Testing
#
# Let's start with a simple example. Your co-worker has been asked to implement a square root function $\sqrt{x}$. (Let's assume for a moment that the environment does not already have one.) After studying the [Newton–Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method), she comes up with the following Python code, claiming that, in fact, this `my_sqrt()` function computes square roots.
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def my_sqrt(x):
"""Computes the square root of x, using the Newton–Raphson method"""
approx = None
guess = x / 2
while approx != guess:
approx = guess
guess = (approx + x / approx) / 2
return approx
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Your job is now to find out whether this function actually does what it claims to do.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "notes"}
# ### Understanding Python Programs
#
# If you're new to Python, you might first have to understand what the above code does. We very much recommend the [Python tutorial](https://docs.python.org/3/tutorial/) to get an idea on how Python works. The most important things for you to understand the above code are these three:
#
# 1. Python structures programs through _indentation_, so the function and `while` bodies are defined by being indented;
# 2. Python is _dynamically typed_, meaning that the type of variables like `x`, `approx`, or `guess` is determined at run-time.
# 3. Most of Python's syntactic features are inspired by other common languages, such as control structures (`while`, `if`), assignments (`=`), or comparisons (`==`, `!=`, `<`).
#
# With that, you can already understand what the above code does: Starting with a `guess` of `x / 2`, it computes better and better approximations in `approx` until the value of `approx` no longer changes. This is the value that finally is returned.
# -
# ### Running a Function
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# To find out whether `my_sqrt()` works correctly, we can *test* it with a few values. For `x = 4`, for instance, it produces the correct value:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
my_sqrt(4)
# + [markdown] slideshow={"slide_type": "fragment"}
# The upper part above `my_sqrt(4)` (a so-called _cell_) is an input to the Python interpreter, which by default _evaluates_ it. The lower part (`2.0`) is its output. We can see that `my_sqrt(4)` produces the correct value.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# The same holds for `x = 2.0`, apparently, too:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
my_sqrt(2)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Interacting with Notebooks
#
# If you are reading this in the interactive notebook, you can try out `my_sqrt()` with other values as well. Click on one of the above cells with invocations of `my_sqrt()` and change the value – say, to `my_sqrt(1)`. Press `Shift+Enter` (or click on the play symbol) to execute it and see the result. If you get an error message, go to the above cell with the definition of `my_sqrt()` and execute this first. You can also run _all_ cells at once; see the Notebook menu for details. (You can actually also change the text by clicking on it, and corect mistaks such as in this sentence.)
# + [markdown] slideshow={"slide_type": "subslide"}
# Executing a single cell does not execute other cells, so if your cell builds on a definition in another cell that you have not executed yet, you will get an error. You can select `Run all cells above` from the menu to ensure all definitions are set.
# + [markdown] slideshow={"slide_type": "subslide"}
# Also keep in mind that, unless overwritten, all definitions are kept across executions. Occasionally, it thus helps to _restart the kernel_ (i.e. start the Python interpreter from scratch) to get rid of older, superfluous definitions.
# -
# ### Debugging a Function
# To see how `my_sqrt()` operates, a simple strategy is to insert `print()` statements in critical places. You can, for instance, log the value of `approx`, to see how each loop iteration gets closer to the actual value:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def my_sqrt_with_log(x):
"""Computes the square root of x, using the Newton–Raphson method"""
approx = None
guess = x / 2
while approx != guess:
print("approx =", approx) # <-- New
approx = guess
guess = (approx + x / approx) / 2
return approx
# -
my_sqrt_with_log(9)
# Interactive notebooks also allow to launch an interactive *debugger* – insert a "magic line" `%%debug` at the top of a cell and see what happens. Unfortunately, interactive debuggers interfere with our dynamic analysis techniques, so we mostly use logging and assertions for debugging.
# ### Checking a Function
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Let's get back to testing. We can read and run the code, but are the above values of `my_sqrt(2)` actually correct? We can easily verify by exploiting that $\sqrt{x}$ squared again has to be $x$, or in other words $\sqrt{x} \times \sqrt{x} = x$. Let's take a look:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
my_sqrt(2) * my_sqrt(2)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Okay, we do have some rounding error, but otherwise, this seems just fine.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# What we have done now is that we have _tested_ the above program: We have _executed_ it on a given input and _checked_ its result whether it is correct or not. Such a test is the bare minimum of quality assurance before a program goes into production.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## Automating Test Execution
#
# So far, we have tested the above program _manually_, that is, running it by hand and checking its results by hand. This is a very flexible way of testing, but in the long run, it is rather inefficient:
#
# 1. Manually, you can only check a very limited number of executions and their results
# 2. After any change to the program, you have to repeat the testing process
#
# This is why it is very useful to _automate_ tests. One simple way of doing so is to let the computer first do the computation, and then have it check the results.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# For instance, this piece of code automatically tests whether $\sqrt{4} = 2$ holds:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
result = my_sqrt(4)
expected_result = 2.0
if result == expected_result:
print("Test passed")
else:
print("Test failed")
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# The nice thing about this test is that we can run it again and again, thus ensuring that at least the square root of 4 is computed correctly. But there are still a number of issues, though:
#
# 1. We need _five lines of code_ for a single test
# 2. We do not care for rounding errors
# 3. We only check a single input (and a single result)
#
# Let us address these issues one by one. First, let's make the test a bit more compact. Almost all programming languages do have a means to automatically check whether a condition holds, and stop execution if it does not. This is called an _assertion_, and it is immensely useful for testing.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# In Python, the `assert` statement takes a condition, and if the condition is true, nothing happens. (If everything works as it should, you should not be bothered.) If the condition evaluates to false, though, `assert` raises an exception, indicating that a test just failed.
#
# In our example, we can use `assert` to easily check whether `my_sqrt()` yields the expected result as above:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
assert my_sqrt(4) == 2
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# As you execute this line of code, nothing happens: We just have shown (or asserted) that our implementation indeed produces $\sqrt{4} = 2$.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Remember, though, that floating-point computations may induce rounding errors. So we cannot simply compare two floating-point values with equality; rather, we would ensure that the absolute difference between them stays below a certain threshold value, typically denoted as $\epsilon$ or ``epsilon``. This is how we can do it:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
EPSILON = 1e-8
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
assert abs(my_sqrt(4) - 2) < EPSILON
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# We can also introduce a special function for this purpose, and now do more tests for concrete values:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def assertEquals(x, y, epsilon=1e-8):
assert abs(x - y) < epsilon
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
assertEquals(my_sqrt(4), 2)
assertEquals(my_sqrt(9), 3)
assertEquals(my_sqrt(100), 10)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Seems to work, right? If we know the expected results of a computation, we can use such assertions again and again to ensure our program works correctly.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## Generating Tests
#
# Remember that the property $\sqrt{x} \times \sqrt{x} = x$ universally holds? We can also explicitly test this with a few values:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
assertEquals(my_sqrt(2) * my_sqrt(2), 2)
assertEquals(my_sqrt(3) * my_sqrt(3), 3)
assertEquals(my_sqrt(42.11) * my_sqrt(42.11), 42.11)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Still seems to work, right? Most importantly, though, $\sqrt{x} \times \sqrt{x} = x$ is something we can very easily test for thousands of values:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
for n in range(1, 1000):
assertEquals(my_sqrt(n) * my_sqrt(n), n)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# How much time does it take to test `my_sqrt()` with 100 values? Let's see.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# We use our own [`Timer` module](Timer.ipynb) to measure elapsed time. To be able to use `Timer`, we first import our own utility module, which allows us to import other notebooks.
# + slideshow={"slide_type": "skip"}
import fuzzingbook_utils
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
from Timer import Timer
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
with Timer() as t:
for n in range(1, 10000):
assertEquals(my_sqrt(n) * my_sqrt(n), n)
print(t.elapsed_time())
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# 10,000 values take about a hundredth of a second, so a single execution of `my_sqrt()` takes 1/1000000 second, or about 1 microseconds.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Let's repeat this with 10,000 values picked at random. The Python `random.random()` function returns a random value between 0.0 and 1.0:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
import random
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
with Timer() as t:
for i in range(10000):
x = 1 + random.random() * 1000000
assertEquals(my_sqrt(x) * my_sqrt(x), x)
print(t.elapsed_time())
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Within a second, we have now tested 10,000 random values, and each time, the square root was actually computed correctly. We can repeat this test with every single change to `my_sqrt()`, each time reinforcing our confidence that `my_sqrt()` works as it should. Note, though, that while a random function is _unbiased_ in producing random values, it is unlikely to generate special values that drastically alter program behavior. We will discuss this later below.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## Run-Time Verification
#
# Instead of writing and running tests for `my_sqrt()`, we can also go and _integrate the check right into the implementation._ This way, _each and every_ invocation of `my_sqrt()` will be automatically checked.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Such an _automatic run-time check_ is very easy to implement:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def my_sqrt_checked(x):
root = my_sqrt(x)
assertEquals(root * root, x)
return root
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Now, whenever we compute a root with `my_sqrt_checked()`$\dots$
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
my_sqrt_checked(2.0)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# we already know that the result is correct, and will so for every new successful computation.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Automatic run-time checks, as above, assume two things, though:
#
# * One has to be able to _formulate_ such run-time checks. Having concrete values to check against should always be possible, but formulating desired properties in an abstract fashion can be very complex. In practice, you need to decide which properties are most crucial, and design appropriate checks for them. Plus, run-time checks may depend not only on local properties, but on several properties of the program state, which all have to be identified.
#
# * One has to be able to _afford_ such run-time checks. In the case of `my_sqrt()`, the check is not very expensive; but if we have to check, say, a large data structure even after a simple operation, the cost of the check may soon be prohibitive. In practice, run-time checks will typically be disabled during production, trading reliability for efficiency. On the other hand, a comprehensive suite of run-time checks is a great way to find errors and quickly debug them; you need to decide how many such capabilities you would still want during production.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## System Input vs Function Input
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# At this point, we may make `my_sqrt()` available to other programmers, who may then embed it in their code. At some point, it will have to process input that comes from _third parties_, i.e. is not under control by the programmer.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# Let us simulate this *system input* by assuming a _program_ `sqrt_program()` whose input is a string under third-party control:
# -
def sqrt_program(arg):
x = int(arg)
print('The root of', x, 'is', my_sqrt(x))
# We assume that `sqrt_program` is a program which accepts system input from the command line, as in
#
# ```shell
# $ sqrt_program 4
# 2
# ```
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# We can easily invoke `sqrt_program()` with some system input:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
sqrt_program("4")
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# What's the problem? Well, the problem is that we do not check external inputs for validity. Try invoking `sqrt_program(-1)`, for instance. What happens?
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Indeed, if you invoke `my_sqrt()` with a negative number, it enters an infinite loop. For technical reasons, we cannot have infinite loops in this chapter (unless we'd want the code to run forever); so we use a special `with ExpectTimeOut(1)` construct to interrupt execution after one second.
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
from ExpectError import ExpectTimeout
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
with ExpectTimeout(1):
sqrt_program("-1")
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# The above message is an _error message_, indicating that something went wrong. It lists the *call stack* of functions and lines that were active at the time of the error. The line at the very bottom is the line last executed; the lines above represent function invocations – in our case, up to `my_sqrt(x)`.
#
# We don't want our code terminating with an exception. Consequently, when accepting external input, we must ensure that it is properly validated. We may write, for instance:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def sqrt_program(arg):
x = int(arg)
if x < 0:
print("Illegal Input")
else:
print('The root of', x, 'is', my_sqrt(x))
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# and then we can be sure that `my_sqrt()` is only invoked according to its specification.
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
sqrt_program("-1")
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# But wait! What happens if `sqrt_program()` is not invoked with a number? Then we would try to convert a non-number string, which would also result in a runtime error:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
from ExpectError import ExpectError
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
with ExpectError():
sqrt_program("xyzzy")
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Here's a version which also checks for bad inputs:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def sqrt_program(arg):
try:
x = float(arg)
except ValueError:
print("Illegal Input")
else:
if x < 0:
print("Illegal Number")
else:
print('The root of', x, 'is', my_sqrt(x))
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
sqrt_program("4")
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
sqrt_program("-1")
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
sqrt_program("xyzzy")
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# We have now seen that at the system level, the program must be able to handle any kind of input gracefully without ever entering an uncontrolled state. This, of course, is a burden for programmers, who must struggle to make their programs robust for all circumstances. This burden, however, becomes a _benefit_ when generating software tests: If a program can handle any kind of input (possibly with well-defined error messages), we can also _send it any kind of input_. When calling a function with generated values, though, we have to _know_ its precise preconditions.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## The Limits of Testing
#
# Despite best efforts in testing, keep in mind that you are always checking functionality for a _finite_ set of inputs. Thus, there may always be _untested_ inputs for which the function may still fail.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# In the case of `my_sqrt()`, for instance, computing $\sqrt{0}$ results in a division by zero:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
with ExpectError():
root = my_sqrt(0)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# In our tests so far, we have not checked this condition, meaning that a program which builds on $\sqrt{0} = 0$ will surprisingly fail. But even if we had set up our random generator to produce inputs in the range of 0–1000000 rather than 1–1000000, the chances of it producing a zero value by chance would still have been one in a million. If the behavior of a function is radically different for few individual values, plain random testing has few chances to produce these.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# We can, of course, fix the function accordingly, documenting the accepted values for `x` and handling the special case `x = 0`:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
def my_sqrt_fixed(x):
assert 0 <= x
if x == 0:
return 0
return my_sqrt(x)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
# With this, we can now correctly compute $\sqrt{0} = 0$:
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
assert my_sqrt_fixed(0) == 0
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Illegal values now result in an exception:
#
# + button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "fragment"}
with ExpectError():
root = my_sqrt_fixed(-1)
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# Still, we have to remember that while extensive testing may give us a high confidence into the correctness of a program, it does not provide a guarantee that all future executions will be correct. Even run-time verification, which checks every result, can only guarantee that _if_ it produces a result, the result will be correct; but there is no guarantee that future executions may not lead to a failing check. As I am writing this, I _believe_ that `my_sqrt_fixed(x)` is a correct implementation of $\sqrt{x}$, but I cannot be 100% certain.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# With the Newton-Raphson method, we may still have a good chance of actually _proving_ that the implementation is correct: The implementation is simple, the math is well-understood. Alas, this is only the case for few domains. If we do not want to go into full-fledged correctness proofs, our best chance with testing is to
#
# 1. Test the program on several, well-chosen inputs; and
# 2. Check results extensively and automatically.
#
# This is what we do in the remainder of this course: Devise techniques that help us to thoroughly test a program, as well as techniques that help us checking its state for correctness. Enjoy!
# + [markdown] run_control={} slideshow={"slide_type": "slide"}
# ## Lessons Learned
#
# * The aim of testing is to execute a program such that we find bugs.
# * Test execution, test generation, and checking test results can be automated.
# * Testing is _incomplete_; it provides no 100% guarantee that the code is free of errors.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "skip"}
# ## Next Steps
#
# From here, you can move on how to
#
# * [use _fuzzing_ to test programs with random inputs](Fuzzer.ipynb)
#
# Enjoy the read!
# -
# ## Background
# There is a large number of works on software testing and analysis. For this book, we are happy to recommend "Software Testing and Analysis" \cite{Pezze2008} as an introduction to the field; its strong technical focus very well fits our methodology. Other important must-reads with a comprehensive approach to software testing, including psychology and organization, include "The Art of Software Testing" \cite{Myers2004} as well as "Software Testing Techniques" \cite{Beizer1990}.
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "slide"}
# ## Exercises
# + [markdown] button=false new_sheet=false run_control={"read_only": false} slideshow={"slide_type": "subslide"}
# ### Exercise 1: Testing Shellsort
#
# Consider the following implementation of a [Shellsort](https://en.wikipedia.org/wiki/Shellsort) function, taking a list of elements and (presumably) sorting it.
# + slideshow={"slide_type": "subslide"}
def shellsort(elems):
sorted_elems = elems.copy()
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
for i in range(gap, len(sorted_elems)):
temp = sorted_elems[i]
j = i
while j >= gap and sorted_elems[j - gap] > temp:
sorted_elems[j] = sorted_elems[j - gap]
j -= gap
sorted_elems[j] = temp
return sorted_elems
# + [markdown] slideshow={"slide_type": "fragment"}
# A first test indicates that `shellsort()` might actually work:
# + slideshow={"slide_type": "subslide"}
shellsort([3, 2, 1])
# + [markdown] slideshow={"slide_type": "fragment"}
# The implementation uses a _list_ as argument `elems` (which it copies into `sorted_elems`) as well as for the fixed list `gaps`. Lists work like _arrays_ in other languages:
# + slideshow={"slide_type": "fragment"}
a = [5, 6, 99, 7]
print("First element:", a[0], "length:", len(a))
# + [markdown] slideshow={"slide_type": "fragment"}
# The `range()` function returns an iterable list of elements. It is often used in conjunction with `for` loops, as in the above implementation.
# + slideshow={"slide_type": "subslide"}
for x in range(1, 5):
print(x)
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Part 1: Manual Test Cases
# + [markdown] slideshow={"slide_type": "fragment"}
# Your job is now to thoroughly test `shellsort()` with a variety of inputs.
# + [markdown] slideshow={"slide_type": "fragment"} solution2="hidden" solution2_first=true
# First, set up `assert` statements with a number of manually written test cases. Select your test cases such that extreme cases are covered. Use `==` to compare two lists.
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# **Solution.** Here are a few selected test cases:
# + cell_style="split" slideshow={"slide_type": "skip"} solution2="hidden"
# Standard lists
assert shellsort([3, 2, 1]) == [1, 2, 3]
assert shellsort([1, 2, 3, 4]) == [1, 2, 3, 4]
assert shellsort([6, 5]) == [5, 6]
# + cell_style="split" slideshow={"slide_type": "skip"} solution2="hidden"
# Check for duplicates
assert shellsort([2, 2, 1]) == [1, 2, 2]
# + cell_style="split" slideshow={"slide_type": "skip"} solution2="hidden"
# Empty list
assert shellsort([]) == []
# + [markdown] slideshow={"slide_type": "subslide"}
# #### Part 2: Random Inputs
# + [markdown] slideshow={"slide_type": "fragment"}
# Second, create random lists as arguments to `shellsort()`. Make use of the following helper predicates to check whether the result is (a) sorted, and (b) a permutation of the original.
# + slideshow={"slide_type": "fragment"}
def is_sorted(elems):
return all(elems[i] <= elems[i + 1] for i in range(len(elems) - 1))
# + slideshow={"slide_type": "fragment"}
is_sorted([3, 5, 9])
# + slideshow={"slide_type": "fragment"}
def is_permutation(a, b):
return len(a) == len(b) and all(a.count(elem) == b.count(elem) for elem in a)
# + slideshow={"slide_type": "fragment"}
is_permutation([3, 2, 1], [1, 3, 2])
# + [markdown] slideshow={"slide_type": "subslide"} solution2="hidden" solution2_first=true
# Start with a random list generator, using `[]` as the empty list and `elems.append(x)` to append an element `x` to the list `elems`. Use the above helper functions to assess the results. Generate and test 1,000 lists.
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# **Solution.** Here's a simple random list generator:
# + slideshow={"slide_type": "skip"} solution2="hidden"
def random_list():
length = random.randint(1, 10)
elems = []
for i in range(length):
elems.append(random.randint(0, 100))
return elems
# + slideshow={"slide_type": "skip"} solution2="hidden"
random_list()
# + slideshow={"slide_type": "skip"} solution2="hidden"
elems = random_list()
print(elems)
# + slideshow={"slide_type": "skip"} solution2="hidden"
sorted_elems = shellsort(elems)
print(sorted_elems)
# + slideshow={"slide_type": "skip"} solution2="hidden"
assert is_sorted(sorted_elems) and is_permutation(sorted_elems, elems)
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# Here's the test for 1,000 lists:
# + slideshow={"slide_type": "skip"} solution2="hidden"
for i in range(1000):
elems = random_list()
sorted_elems = shellsort(elems)
assert is_sorted(sorted_elems) and is_permutation(sorted_elems, elems)
# + [markdown] slideshow={"slide_type": "subslide"}
# ### Exercise 2: Quadratic Solver
# + [markdown] slideshow={"slide_type": "fragment"}
# Given an equation $ax^2 + bx + c = 0$, we want to find solutions for $x$ given the values of $a$, $b$, and $c$. The following code is supposed to do this, using the equation $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
# + slideshow={"slide_type": "fragment"}
def quadratic_solver(a, b, c):
q = b * b - 4 * a * c
solution_1 = (-b + my_sqrt_fixed(q)) / (2 * a)
solution_2 = (-b - my_sqrt_fixed(q)) / (2 * a)
return (solution_1, solution_2)
# + slideshow={"slide_type": "fragment"}
quadratic_solver(3, 4, 1)
# + [markdown] slideshow={"slide_type": "subslide"}
# The above implementation is incomplete, though. You can trigger
#
# 1. a division by zero; and
# 2. violate the precondition of `my_sqrt_fixed()`.
#
# How does one do that, and how can one prevent this?
# + [markdown] slideshow={"slide_type": "subslide"} solution2="hidden" solution2_first=true
# #### Part 1: Find bug-triggering inputs
#
# For each of the two cases above, identify values for `a`, `b`, `c` that trigger the bug.
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# **Solution**. Here are two inputs that trigger the bugs:
# + slideshow={"slide_type": "skip"} solution2="hidden"
with ExpectError():
print(quadratic_solver(3, 2, 1))
# + slideshow={"slide_type": "skip"} solution2="hidden"
with ExpectError():
print(quadratic_solver(0, 0, 1))
# + [markdown] slideshow={"slide_type": "subslide"} solution2="hidden" solution2_first=true
# #### Part 2: Fix the problem
#
# Extend the code appropriately such that the cases are handled. Return `None` for nonexistent values.
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# **Solution.** Here is an appropriate extension of `quadratic_solver()` that takes care of all the corner cases:
# + slideshow={"slide_type": "skip"} solution2="hidden"
def quadratic_solver_fixed(a, b, c):
if a == 0:
if b == 0:
if c == 0:
# Actually, any value of x
return (0, None)
else:
# No value of x can satisfy c = 0
return (None, None)
else:
return (-c / b, None)
q = b * b - 4 * a * c
if q < 0:
return (None, None)
if q == 0:
solution = -b / 2 * a
return (solution, None)
solution_1 = (-b + my_sqrt_fixed(q)) / (2 * a)
solution_2 = (-b - my_sqrt_fixed(q)) / (2 * a)
return (solution_1, solution_2)
# + slideshow={"slide_type": "skip"} solution2="hidden"
with ExpectError():
print(quadratic_solver_fixed(3, 2, 1))
# + slideshow={"slide_type": "skip"} solution2="hidden"
with ExpectError():
print(quadratic_solver_fixed(0, 0, 1))
# + [markdown] slideshow={"slide_type": "subslide"} solution2="hidden" solution2_first=true
# #### Part 3: Odds and Ends
#
# What are the chances of discovering these conditions with random inputs? Assuming one can do a billion tests per second, how long would one have to wait on average until a bug gets triggered?
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# **Solution.** Consider the code above. If we choose the full range of 32-bit integers for `a`, `b`, and `c`, then the first condition alone, both `a` and `b` being zero, has a chance of $p = 1 / (2^{32} * 2^{32})$; that is, one in 18.4 quintillions:
# + slideshow={"slide_type": "skip"} solution2="hidden"
combinations = 2 ** 32 * 2 ** 32
combinations
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# If we can do a billion tests per second, how many years would we have to wait?
# + slideshow={"slide_type": "skip"} solution2="hidden"
tests_per_second = 1000000000
seconds_per_year = 60 * 60 * 24 * 365.25
tests_per_year = tests_per_second * seconds_per_year
combinations / tests_per_year
# + [markdown] slideshow={"slide_type": "skip"} solution2="hidden"
# We see that on average, we'd have to wait for 584 years. Clearly, pure random choices are not sufficient as sole testing strategy.
| notebooks/Intro_Testing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline
# -
def calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos):
mesozoo = zz_rate_mesozoo_winterconc * np.ones(365)
for i in range(365):
for j in range(3):
mesozoo[i] += (zz_rate_mesozoo_sumpeakval[j] *
np.exp(-(i-zz_rate_mesozoo_sumpeakpos[j])**2/zz_rate_mesozoo_sumpeakwid[j]**2))
mesozoo[i] += (zz_rate_mesozoo_sumpeakval[j] *
np.exp(-(i-zz_rate_mesozoo_sumpeakpos[j]+365)**2/zz_rate_mesozoo_sumpeakwid[j]**2))
mesozoo[i] += (zz_rate_mesozoo_sumpeakval[j] *
np.exp(-(i-zz_rate_mesozoo_sumpeakpos[j]-365)**2/zz_rate_mesozoo_sumpeakwid[j]**2))
return mesozoo
# SOG
zz_rate_mesozoo_winterconc = 0.073 # uM N mesozooplankton background concentration
zz_rate_mesozoo_sumpeakval = 0.525, 0.152, 0.0318 # uM N magnitude of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakwid = 53.8, 51.6, 14.60 # year-days widths of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakpos = 112.0, 229.0, 316.0 # year-day times of mesozooplankton summer concentration peaks
mesozoo_SOG = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
# Base (201905)
zz_rate_mesozoo_winterconc = 0.38 # uM N mesozooplankton background concentration
zz_rate_mesozoo_sumpeakval = 0.55, 0.55, 0.36 # uM N magnitude of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakwid = 40.0, 70.00, 43.00 # year-days widths of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakpos = 130.0, 206.0, 290.0 # year-day times of mesozooplankton summer concentration peaks
mesozoo_base = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
# Base2 (201812)
zz_rate_mesozoo_winterconc = 0.41 # uM N mesozooplankton background concentration
zz_rate_mesozoo_sumpeakval = 0.53, 0.57, 0.35 # uM N magnitude of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakwid = 40.0, 65.00, 44.00 # year-days widths of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakpos = 135.0, 208.0, 296.0 # year-day times of mesozooplankton summer concentration peaks
mesozoo_base2 = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
# New, later and lower
zz_rate_mesozoo_winterconc = 0.41 # uM N mesozooplankton background concentration
zz_rate_mesozoo_sumpeakval = 0.50, 0.57, 0.35 # uM N magnitude of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakwid = 40.0, 65.00, 44.00 # year-days widths of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakpos = 140.0, 208.0, 296.0 # year-day times of mesozooplankton summer concentration peaks
mesozoo_new = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
# T1
zz_rate_mesozoo_winterconc = 0.44 # uM N mesozooplankton background concentration
zz_rate_mesozoo_sumpeakval = 0.50, 0.52, 0.30 # uM N magnitude of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakwid = 35.0, 65.00, 44.00 # year-days widths of mesozooplankton summer concentration peaks
zz_rate_mesozoo_sumpeakpos = 138.0, 208.0, 296.0 # year-day times of mesozooplankton summer concentration peaks
mesozoo_T1 = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
# T4
zz_rate_mesozoo_winterconc = (0.3*3 - 0.38*2)
zz_rate_mesozoo_sumpeakval = 0.6*3-0.55*2, 0.63*3-0.55*2, 0.42*3-0.36*2
zz_rate_mesozoo_sumpeakwid = 40.0, 70.00, 43.00
zz_rate_mesozoo_sumpeakpos = 130.0, 206.0, 290.0
mesozoo_T4 = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
print (zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval)
# T2
zz_rate_mesozoo_winterconc = 0.3 # uM N mesozooplankton background concentration
zz_rate_mesozoo_sumpeakval = 0.5, 0.63, .4
zz_rate_mesozoo_sumpeakwid = 43.0, 70.00, 43.00
zz_rate_mesozoo_sumpeakpos = 138.000, 206.000, 290.00
mesozoo_T2 = calc_mesozoo(zz_rate_mesozoo_winterconc, zz_rate_mesozoo_sumpeakval, zz_rate_mesozoo_sumpeakwid,
zz_rate_mesozoo_sumpeakpos)
plt.plot(mesozoo_base[0:60], label='201905');
plt.plot(mesozoo_base2[0:60], label='201812');
plt.plot(mesozoo_SOG[0:60], label='SOG');
plt.plot(mesozoo_new[0:60], label='new');
plt.plot(mesozoo_T1[0:60], label='T1');
plt.legend();
it0, ite = 40, 120
plt.plot(range(it0, ite), mesozoo_base[it0:ite], label='201905');
plt.plot(range(it0, ite), mesozoo_base2[it0:ite], label='201812');
#plt.plot(range(it0, ite), mesozoo_SOG[it0:ite], label='SOG');
plt.plot(range(it0, ite), mesozoo_new[it0:ite], label='New');
#plt.plot(range(it0, ite), mesozoo_T1[it0:ite], label='T1');
plt.legend();
it0, ite = -90, -1
rit0, rite = 365-90, 365-1
plt.plot(range(rit0, rite), mesozoo_base[it0:ite], label='201905');
plt.plot(range(rit0, rite), mesozoo_base2[it0:ite], label='201812');
#plt.plot(range(rit0, rite), mesozoo_SOG[it0:ite], label='SOG');
plt.plot(range(rit0, rite), mesozoo_new[it0:ite], label='new');
plt.legend();
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
#ax.plot(range(-365, 0), mesozoo_SOG, color="maroon");
ax.plot(range(-365, 0), mesozoo_base, color="blue");
ax.plot(range(-365, 0), mesozoo_base2, color="purple");
ax.plot(range(-365, 0), mesozoo_new, color="darkgreen");
#ax.plot(mesozoo_SOG, label='SOG', color="maroon");
ax.plot(mesozoo_base, label='201905', color="blue");
ax.plot(mesozoo_base2, label='201812', color="purple");
ax.plot(mesozoo_new, label='new', color="darkgreen");
ax.set_xlabel('Year Day')
ax.set_ylabel('Mesozooplankton')
ax.axvspan(-90, 181, alpha=0.5, color='grey')
ax.axvspan(68, 68, color='k')
ax.axvspan(87, 87, color='k')
ax.axvspan(104, 104, color='k')
ax.legend();
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(range(0, 365), np.cumsum(mesozoo_base), color="blue");
ax.plot(range(0, 365), np.cumsum(mesozoo_base2), color="purple");
ax.plot(range(0, 365), np.cumsum(mesozoo_new), color="darkgreen");
ax.set_xlim(50, 100);
ax.set_ylim(20, 50);
# ## Mesozooplankton Levels
fig, ax = plt.subplots(1, 1, figsize=(15, 5))
ax.plot(mesozoo_base-mesozoo_T1, label='T1', color="purple");
ax.plot(mesozoo_base-mesozoo_T2, label='T2', color="darkgreen");
ax.plot(mesozoo_base-mesozoo_T3, label='T3', color="tab:cyan");
ax.plot(mesozoo_base-mesozoo_T4, label='T4', color="tab:orange");
ax.set_xlabel('Year Day')
ax.set_ylabel('Mesozooplankton')
ax.axvspan(-90, 181, alpha=0.5, color='grey')
ax.axvspan(68, 68, color='k')
ax.axvspan(87, 87, color='k')
ax.axvspan(104, 104, color='k')
ax.set_xlim(0, 110)
#ax.set_ylim(0.25, 0.85)
ax.grid()
ax.legend();
x = np.arange(0.2, 2, 0.1)
plt.plot(x, 86400*1.37e-5*0.14*(x-0.2)/(1 + (x-0.2)))
plt.plot(x, 86400*1.37e-5*0.26*(x-0.2)/(1 + (x-0.2)))
plt.plot(x, 86400*1.37e-5*0.30*(x-0.2)/(1 + (x-0.2)))
plt.plot(x, 86400*1.37e-5*0.38*(x-0.2)/(1 + (x-0.2)))
plt.plot(x, 0.06e-5*x*86400)
x = np.arange(0.2, 2, 0.1)
plt.plot(x, 86400*1.37e-5*0.14*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)
plt.plot(x, 86400*1.37e-5*0.26*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)
plt.plot(x, 86400*1.37e-5*0.30*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)
plt.plot(x, 86400*1.37e-5*0.38*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)
x = np.arange(0.2, 1, 0.05)
plt.plot(x, (86400*1.37e-5*0.14*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)/(
86400*1.37e-5*0.38*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400))
plt.plot(x, (86400*1.37e-5*0.26*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)/(
86400*1.37e-5*0.38*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400))
plt.plot(x, (86400*1.37e-5*0.30*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400)/(
86400*1.37e-5*0.38*(x-0.2)/(1 + (x-0.2))+0.06e-5*x*86400))
| notebooks/Tuning/MesoZooplanktonCurves.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import pandas as pd
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.utils.data import DataLoader, Dataset
from sklearn.preprocessing import MinMaxScaler
# -
location = pd.read_csv("metaData_taxistandsID_name_GPSlocation.csv")
df = pd.read_csv('train.csv')
df['LENGTH'] = df['POLYLINE'].apply(lambda x: len(json.loads(x)))
df = df[df['LENGTH'] > 8]
sample = df[df.MISSING_DATA==False].sample(n=10000).copy(deep=True)
coordinates = [item for trajectory in list(sample['POLYLINE'].apply(lambda x: json.loads(x))) for item in trajectory]
coordinates = np.array(coordinates)
scaler = MinMaxScaler()
scaler.fit(coordinates)
class CustomDataset(Dataset):
def __init__(self, X_data, y_data):
self.x = X_data
self.y = y_data
self.n_samples = len(y_data)
def __getitem__(self, idx):
data = self.x[idx], self.y[idx]
return data
def __len__(self):
return self.n_samples
# +
def convert_data(trajectory):
trajectory = np.array(json.loads(trajectory))
trajectory = scaler.transform(trajectory)
length = trajectory.shape[0]
data = []
label = []
for i in range(8, length):
data.append(trajectory[i-8:i])
label.append(trajectory[i])
data = np.stack(data, axis=0)
label = np.stack(label, axis=0)
return data, label
def prepare_data(data):
results = list(data['POLYLINE'].apply(lambda x: convert_data(x)))
X, y = list(zip(*results))
X = np.concatenate(X, axis=0)
y = np.concatenate(y, axis=0)
X = torch.from_numpy(X).float()
y = torch.from_numpy(y).float()
return X, y
# -
(train_X, train_y), (valid_X, valid_y), (test_X, test_y) = prepare_data(sample[:7000]), prepare_data(sample[7000:8000]), prepare_data(sample[8000:10000])
# +
train_set = CustomDataset(train_X, train_y)
valid_set = CustomDataset(valid_X, valid_y)
test_set = CustomDataset(test_X, test_y)
train_loader = DataLoader(train_set, batch_size=1000, shuffle=True, num_workers=4)
valid_loader = DataLoader(valid_set, batch_size=1000, shuffle=True, num_workers=4)
test_loader = DataLoader(test_set, batch_size=1, shuffle=True, num_workers=1)
# -
class Model(nn.Module):
def __init__(self, input_size, output_size, hidden_size, num_layers=2, dropout=0.2):
super(Model, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.in2lstm1 = nn.Linear(input_size, hidden_size)
self.lstm1 = nn.LSTM(hidden_size, hidden_size, num_layers=num_layers, bidirectional=False, batch_first=True, dropout=dropout)
self.in2lstm2 = nn.Linear(input_size, hidden_size)
self.lstm2 = nn.LSTM(hidden_size, hidden_size, num_layers=num_layers, bidirectional=False, batch_first=True, dropout=dropout)
self.fc0 = nn.Linear(hidden_size, hidden_size*2)
self.fc1 = nn.Linear(hidden_size*2, int(hidden_size/2))
self.fc2 = nn.Linear(int(hidden_size/2), output_size)
self.tanh = nn.Tanh()
def forward(self, x):
lstm_out1, _ = self.lstm1(self.in2lstm1(x))
lstm_out2, _ = self.lstm2(self.in2lstm2(x))
out = self.tanh(self.fc0(lstm_out1 + lstm_out2))
out = self.tanh(self.fc1(out))
output = self.fc2(out)[:, -1]
return output
# +
INPUT_SIZE=2
OUTPUT_SIZE=2
HIDDEN_SIZE=128
NUM_LAYERS = 2
LEARNING_RATE = 0.0005
N_EPOCHS = 100
BATCH_SIZE = train_loader.batch_size
model = Model(INPUT_SIZE, OUTPUT_SIZE, HIDDEN_SIZE, NUM_LAYERS)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
for epoch in range(1, N_EPOCHS+1):
train_loss_cache = []
valid_loss_cache = []
train_loss = 0
valid_loss = 0
for X, y in train_loader:
optimizer.zero_grad()
prediction = model(X)
loss = criterion(prediction, y)
loss.backward()
optimizer.step()
train_loss += loss.item()
with torch.no_grad():
for X, y in valid_loader:
prediction = model(X)
loss = criterion(prediction, y)
valid_loss += loss.item()
train_loss = train_loss/BATCH_SIZE
valid_loss = valid_loss/BATCH_SIZE
train_loss_cache.append(train_loss)
valid_loss_cache.append(valid_loss)
print(f'Epoch: {epoch}, Train Loss: {train_loss/BATCH_SIZE}, Valid Loss: {valid_loss/BATCH_SIZE}')
# -
| pkdd-15-predict-taxi-service-trajectory-i/Trajectory_Prediction.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] tags=[] cell_id="f6475667-d496-4f67-8380-db3880b9af5d" deepnote_cell_type="markdown"
# # Policy Gradient Reinforcement Learning
# + [markdown] tags=[] cell_id="00001-8cc7d3cd-040c-46e6-9a31-51aed6e12738" deepnote_cell_type="markdown"
# ## General Overview
#
# This notebook demonstrates a simple but general implementation of policy gradient reinforcement learning (for discrete actions).
#
# The code is split into:
#
# PolicyGradient -- a class that implements the learning algorithm itself
# and will make use of an 'agent' and an 'environment' that
# are defined elsewhere. This is general and can be used for
# any kind of (discrete-action) reinforcement learning task.
#
# QubitEnvironment -- a class that implements the environment for
# a specific task (see below). The interface to this
# class (i.e. the methods) is general and can also be
# used for other tasks.
#
# ...plus code that sets up the agent as a network and code that actually runs the training and visualizes the results.
#
# Two noteworthy aspects here are: the use of batches (i.e. many trajectories can be processed in parallel, adding an extra dimension to every array, like states and actions and rewards) and the function ‘sample’ that selects a random action given a set of probabilities (provided by the policy). The latter is a bit involved since we try to deal with batches.
#
# ## Physics Scenario
#
# The particular scenario we consider here is inspired by quantum physics. Consider a spin and represent it by a single unit vector (the so-called Bloch vector). Imagine this vector starts out pointing in some (possibly random) direction, and our goal is to implement a series of rotations such that in the end the vector aligns as closely as possible with some target direction.
#
# Assume that only two different rotations can be applied (e.g. a rotation around the x-axis by some angle phi_x and another rotation around the z-axis, by some angle phi_z). Can the agent find a strategy that rotates a random initial vector in a fixed number of steps into the desired direction?
#
# The state is given by the current unit vector (Bloch vector) and there are only two actions (a=0,1) corresponding to the two possible rotations. The reward is supplied only at the final time and is essentially the scalar product between the Bloch vector at the final time and the target vector.
#
# (C) 2022 <NAME> and <NAME>, Theory Division at the Max Planck Institute for the Science of Light. MIT License.
# + deepnote_to_be_reexecuted=false execution_millis=7430 execution_start=1642883763935 source_hash="1ab5ea93" tags=[] cell_id="00002-b20a4b4e-1cc5-40f2-96b6-8e2eb3397591" deepnote_cell_type="code"
import numpy as np
import tensorflow as tf
import tensorflow.keras as tfk
from tqdm import trange
import matplotlib.pyplot as plt
# + [markdown] tags=[] cell_id="00003-16ecb1e5-9244-4ca7-9f3e-1cec0dd995a7" deepnote_cell_type="markdown"
# ## Brief reminder of policy gradient reinforcement learning, illustrated for this example
#
# state s = qubit state (pure)
#
# s = Bloch vector = (n_x,n_y,n_z) where n = <Psi|sigma_vector|Psi>
#
# Note the *observed* state, passed to the agent, is a 4D vector, where the last entry is the current time step index. This allows the agent to react differently at the beginning of the trajectory and later.
#
#
# Actions
#
# actions = rotations of the qubit around two possible axes, and for each axis a fixed angle
#
#
# Policy
#
# policy = pi(a|s) = action probabilities
#
# Reward and return
#
# reward = (only final reward) = |<Psi(T)|Psi_target>| = 0.5*(1+ n * n_target)
#
# return R = cumulative rewards = final reward
#
#
# Policy gradient method 'REINFORCE', in one line
#
# (parametrize policy, e.g. neural network)
#
# d theta = eta sum_t E[ R * (d/dtheta) ln pi_theta(a_t|s_t) ]
#
# method: run trajectories, record s_0,a_0,s_1,...,s_T and R,
# then apply this d theta update
#
#
# + [markdown] cell_id="3fca46fe-f477-4322-92d1-760c0f13d12d" tags=[] deepnote_cell_type="markdown"
# ## The policy gradient RL learner class
# + [markdown] cell_id="88186328-1b61-4272-9a03-45784182ba03" tags=[] deepnote_cell_type="markdown"
# This is the general code that could be re-used for any other kind of scenario.
# + deepnote_to_be_reexecuted=false execution_millis=6 execution_start=1642884763630 source_hash="1203bde6" tags=[] cell_id="00004-de157fb1-e761-4e3f-8127-d1a1019d855b" deepnote_cell_type="code"
def sample(probs):
"""
A function that, given probability distributions probs
(of shape [batchsize,bins]) for discrete events, samples
from these distributions. It returns an integer array of shape [batchsize]
which contains the random integer numbers that are distributed
according to probs. That is, result[j] is distributed according to probs[j,:].
"""
# get cumulative distribution for each sample:
prob_cumsum=np.cumsum(probs,axis=-1)
# pick a random number between 0 and 1 for each sample:
random_number=np.random.uniform(size=probs.shape[:-1])
# return the selected index for each sample:
return np.argmax(random_number[...,None]<prob_cumsum,axis=-1)
class SimplePolicyGradient:
def __init__(self,batchsize,num_steps,agent,environment,learning_rate=1e-3):
"""
Set up a policy gradient reinforcement learner that can process
batches of states and actions in parallel.
batchsize:
The batchsize.
num_steps:
Number of time steps in a trajectory.
agent:
One has to be able to call agent(state), which acts on a batch
of states of shape [batchsize,...], where ... is defined by environment.
Returns a set of action probabilities, shape [batchsize,num_actions].
This could simply be a keras Model with the right input dimensions (defined
by the environment) and the right number of output neurons for the
desired number of actions, using softmax (compatible with environment).
Besides being able to act on a state and return the policy, it also
has to supply agent.trainable_variables (this will automatically be the
case for any keras model).
environment:
Has to implement env.prepare_initial_state(batchsize),
env.provide_observed_state(), and env.perform_action(action,time_step,num_steps).
env.provide_observed_state() returns the current observed state (a batch), while
perform_action returns the reward (batch of rewards) after performing action.
"""
self.batchsize=batchsize
self.num_steps=num_steps
self.agent=agent
self.environment=environment
self.learning_rate = learning_rate
self.return_history = []
self.optimizer=tfk.optimizers.Adam(learning_rate=self.learning_rate)
def run_trajectory(self):
"""
Run a single trajectory and update self.return_R and
self.state_history and self.action_history.
"""
self.environment.prepare_initial_state(self.batchsize)
self.return_R=np.zeros([self.batchsize])
for time_step in range(self.num_steps):
state=self.environment.provide_observed_state()
action_probabilities=self.agent(state) # shape [batchsize,num_actions]
action=sample(action_probabilities) # shape [batchsize]
reward=self.environment.perform_action(action,time_step,num_steps)
self.return_R += reward
if time_step==0:
self.state_history = np.zeros([self.num_steps]+list(state.shape))
self.action_history = np.zeros([self.num_steps, self.batchsize],dtype='int')
self.state_history[time_step,...]=state
self.action_history[time_step,:]=action
def update_policy_gradient(self):
"""
Call this after having run a trajectory. This uses the
cumulative reward that was recorded, together with the
history of states and actions, to update the policy of the agent.
"""
idx=np.arange(self.batchsize)
for time_step in range(self.num_steps):
with tf.GradientTape() as tape:
# now calculate R * ln pi(a_t|s_t), within the gradient tape
# evaluate policy probabilities at this time step (a full batch of prob. distributions)
action_probs = agent(self.state_history[time_step,...])
# now fill an array of the same shape, inserting the return R at only
# the slot of the action that was actually performed, for each sample in the batch:
selected_actions=np.zeros(action_probs.shape)
selected_actions[idx,self.action_history[time_step,:]]=-self.return_R
# Now, for the loss, calculate - R * ln pi(a_t|s_t) for the
# selected actions, averaged over the batch!
# Note: We used the - sign above because the loss will be *minimized*.
# Note: this is really a categorical cross-entropy, except we multiplied with R for
# each sample!
loss = tf.reduce_mean(selected_actions * tf.math.log(action_probs))
# get the gradient that is needed for policy gradient
grads = tape.gradient(loss, agent.trainable_variables)
# applying the gradient immediately involves a certain approximation,
# namely the policy will now already have changed a bit when we go to
# evaluate it in the next time step. Nevertheless, this keeps things
# simple. Should not matter too much if learning rate is small enough.
self.optimizer.apply_gradients(zip(grads,agent.trainable_variables))
def train(self,train_steps):
for step in trange(train_steps):
self.run_trajectory()
self.update_policy_gradient()
self.return_history.append(np.mean(self.return_R))
# + [markdown] cell_id="e207db08-ac4d-46b9-92b7-c07922113829" tags=[] deepnote_cell_type="markdown"
# ## The physics environment (a qubit)
# + deepnote_to_be_reexecuted=false source_hash="9e4be6c5" execution_start=1642884894418 execution_millis=26 cell_id="00005-df8c8a2f-4090-4025-8e1b-c106b2a265b7" deepnote_cell_type="code"
def rotation_matrix(rot_axis, rot_angle):
'''
Rotation matrix about the axis x,y,z (rot_axis=0,1,2) for
angle rot_angle (in radians)
'''
rot_matrix = np.zeros([3,3])
rot_matrix[rot_axis,rot_axis] = 1
rot_matrix[(rot_axis+1)%3,(rot_axis+1)%3] = np.cos(rot_angle)
rot_matrix[(rot_axis+1)%3,(rot_axis+2)%3] = -np.sin(rot_angle)
rot_matrix[(rot_axis+2)%3,(rot_axis+1)%3] = np.sin(rot_angle)
rot_matrix[(rot_axis+2)%3,(rot_axis+2)%3] = np.cos(rot_angle)
return rot_matrix
class QubitEnvironment:
"""
All the call interfaces here are general, except for the init method
(and of course except for the 'overlap' method).
"""
def __init__(self,action_matrix,target_state,num_actions,state_dimension,
reward_all=False):
"""
Set up parameters of the environment.
"""
self.action_matrix = action_matrix
self.num_actions = num_actions
self.state_dimension = state_dimension
self.reward_all = reward_all
self.target_state = target_state
def prepare_initial_state(self,batchsize):
"""
Prepare internally the state at the starting point of
a trajectory (actually, a batch of states, given by batchsize).
"""
# last dimension in the state corresponds to the Bloch vector = (n_x,n_y,n_z)
self.state = np.random.randn(batchsize,self.state_dimension)
self.state = self.state/(np.linalg.norm(self.state, axis=-1)[:,None])
self.current_time_step=0
self.batchsize=batchsize
def provide_observed_state(self):
"""
Return the current observed state, to be given to the agent. (actually, a batch of states, of
some shape [batchsize,...]).
"""
observed_state=np.zeros([self.batchsize,self.state_dimension+1])
# now include the time index in the state that is observed by the agent:
observed_state[:,:-1]=self.state
observed_state[:,-1]=self.current_time_step
return observed_state
def perform_action(self,action,time_step,num_steps):
"""
Perform actions 'action' (shape: [batchsize]) in parallel
on a batch, updating the internal state, and return an array
of rewards (shape: [batchsize]).
time_step: current time step (0 will be first)
num_step: maximum number of time_steps (time_step == num_steps-1 will indicate last)
Here the actions refer to the application of different rotations,
which are provided as matrices when setting up the environment.
"""
self.current_time_step = time_step
self.state = np.matmul(self.action_matrix[action],self.state[...,None])[...,0]
if self.reward_all: # reward is evaluated at all the time steps
return self.overlap(self.state,self.target_state)
else: # reward is evaluated only at the final time step
if time_step==num_steps-1:
return self.overlap(self.state,self.target_state)
else:
return 0
def overlap(self,state,target_state):
'''
Evaluate the overlap of the state and the target state.
Overlap = 0.5*(1+ n * n_target)
state is of the shape [:,state_dimension]
target_state is of the shape [state_dimension]
'''
dot_product = np.sum(state*target_state[None,:], axis=-1)
return 0.5*(1 + dot_product) # reward = 0.5*(1+ n * n_target)
# + [markdown] cell_id="7f9697c9-2167-4d37-bd2d-071c7122465d" tags=[] deepnote_cell_type="markdown"
# ## Some small tests for the probabilistic selection of actions
# + [markdown] cell_id="00006-e0ab1fcc-0faf-4af0-9b18-16be396958e5" deepnote_cell_type="markdown"
# Test the sample function (sampling according to given probability distribution)
# + deepnote_output_heights=[21.1875] deepnote_to_be_reexecuted=false execution_millis=17 execution_start=1642884896248 source_hash="40db8f36" tags=[] cell_id="00007-9a0adc85-09b5-4059-83d9-f6ec4c9edeb6" deepnote_cell_type="code"
# little toy example of generating numbers
# according to a given probability distribution
probs=[0.3,0.5,0.2]
probs_cum=np.cumsum(probs)
counter=np.zeros(3)
for _ in range(1000):
x=np.random.uniform()
result=np.where(x<probs_cum)[0][0]
counter[result]+=1
# print frequencies:
print("Observed:", counter/1000)
print("Expected:", probs)
# + deepnote_to_be_reexecuted=false source_hash="85dbda2f" execution_start=1642884897061 execution_millis=89 cell_id="00008-130b38b9-44f2-4f36-af21-20ea73651568" deepnote_cell_type="code"
# Checking the batch-enabled sample function that is used by us:
probs=np.array([[0.3,0.5,0.2],[0.7,0.2,0.1]]) # shape [2,3]
counter=np.zeros(probs.shape)
for _ in range(1000):
result = sample(probs)
for sample_idx in range(probs.shape[0]):
counter[sample_idx,result[sample_idx]]+=1
print("Observed:", counter/1000)
print("Expected:", probs)
# + [markdown] cell_id="00009-d5baefce-85b9-4339-a511-6bd1e69e3a28" deepnote_cell_type="markdown"
# ## Perform the training
# + [markdown] cell_id="cbd5161b-c230-45ae-9f03-ca3c7f45da9d" tags=[] deepnote_cell_type="markdown"
# ### Initialize physics (environment) properties
# + deepnote_output_heights=[59.5625] deepnote_to_be_reexecuted=false execution_millis=13 execution_start=1642884899216 source_hash="5fa6d273" tags=[] cell_id="00010-62cb494b-2143-4891-955c-63997677f0d7" deepnote_cell_type="code"
# Selecting the two rotation axes and the corresponding angles
# here you could choose different axes and angles.
rot_axis = [0,2] # rotation axis (0,1,2) -> (x,y,z) axis
rot_angle = [np.pi/8, np.pi/8] # angle of rotation about the two axes
# Obtain the action matrices (2 rotation matrices and an identity matrix)
num_actions = 3
action_matrix = np.zeros([num_actions,3,3]) # shape [num_action matrices, xyz, xyz]
action_matrix[0,...] = rotation_matrix(rot_axis=rot_axis[0], rot_angle=rot_angle[0])
action_matrix[1,...] = rotation_matrix(rot_axis=rot_axis[1], rot_angle=rot_angle[1])
action_matrix[2,...] = rotation_matrix(rot_axis=0, rot_angle=0)
state_dimension = 3 # Bloch vector's 3 dimensions
target_state = np.array([2.5,0.6,1]) # Bloch vector of the target state
target_state = target_state/np.linalg.norm(target_state) # normalization
# Environment
# reward_all=True -> return is the sum of overlaps at all the time steps
# reward_all=False -> return is the overlap at the final time step
environment = QubitEnvironment(action_matrix,target_state=target_state,
num_actions=num_actions,state_dimension=state_dimension,
reward_all=False)
# + [markdown] cell_id="f81d770f-03ad-4d09-ba1a-35b33f8c0128" tags=[] deepnote_cell_type="markdown"
# ### Initialize agent and RL policy gradient learner
# + deepnote_to_be_reexecuted=false source_hash="6c953c02" execution_start=1642884900646 execution_millis=44 cell_id="00011-de4bd498-9fe5-40b7-8bf3-cb5d8ddbfa65" deepnote_cell_type="code"
# Agent policy network
# Initialize the policy neural network that returnsthe actin probabilities: pi(a_t|s_t).
layers = [10,10] # List containing the number of neurons in each hidden layer
N_in = state_dimension+1 # number of neurons in the input layer (state_dimension + time_step)
N_out = num_actions # number of neurons in the output layer
Dense = tfk.layers.Dense
agent = tfk.Sequential([Dense(layers[0], activation='relu', input_shape=(N_in,))] +
[Dense(n, activation='relu') for n in layers[1:]] +
[Dense(N_out, activation='softmax')]
)
# Learner
batchsize = 32
num_steps = 10 # maximum number of time steps during each run
learner = SimplePolicyGradient(batchsize,num_steps,agent,environment,learning_rate=1e-3) # Define the RL policy
# + [markdown] cell_id="ef52d958-1f7d-49b5-96a4-b24424c57960" tags=[] deepnote_cell_type="markdown"
# ### The actual training
# + deepnote_to_be_reexecuted=false source_hash="56ec683e" execution_start=1642884902878 execution_millis=22005 deepnote_output_heights=[null, 386] cell_id="00012-2c616a1b-ed09-4069-b0b3-2bda8d3e9ebe" deepnote_cell_type="code"
train_steps = 200
learner.train(train_steps=train_steps) # Perform the training
# + [markdown] cell_id="00013-9a6c5086-e742-4e7a-8c62-f237905a0424" deepnote_cell_type="markdown"
# ## Visualization of the results
# + [markdown] cell_id="00014-0e5f1180-0f6f-4389-b7d5-1635a846ad85" deepnote_cell_type="markdown"
# ### Average return vs training step
# + deepnote_to_be_reexecuted=false source_hash="c46c86f1" execution_start=1642884926695 execution_millis=630 deepnote_output_heights=[605] cell_id="00015-61908603-6b91-4dc3-ab39-1d6fa2210b05" deepnote_cell_type="code"
# If reward is evaluated only at the final time step, then
# the y-axis corresponds to the overlap of the final state
# with the target state. Otherwise, the y-axis is the sum of the
# overlaps at all the time steps.
fig = plt.figure(dpi=300)
ax = plt.axes()
ax.plot(learner.return_history)
ax.set_xlabel('Training step')
ax.set_ylabel('Return')
plt.show()
# + [markdown] cell_id="00016-60167be5-b504-4b8f-8b0e-f28d5ed765fc" deepnote_cell_type="markdown"
# ### Test the network
# + deepnote_to_be_reexecuted=false source_hash="d4b9db81" execution_start=1642884931121 execution_millis=30 deepnote_output_heights=[21] cell_id="00017-e6268624-87de-456c-a9fb-9d52c0523471" deepnote_cell_type="code"
# Run a batch of initial states
learner.run_trajectory()
learner.update_policy_gradient() # just for getting access to the return R
print(np.mean(learner.return_R))
# + deepnote_to_be_reexecuted=false source_hash="1268e941" execution_start=1642884957770 execution_millis=655 deepnote_output_heights=[462, 444] cell_id="00019-5df6e315-a11f-4d09-84ee-4aa92d7533ad" deepnote_cell_type="code"
# investigate one particular case of the batch in detail
batch_idx = 14
fig, ax = plt.subplots(nrows=2, dpi=150, figsize=(8,4))
# Action operations vs time
# y=n => action=n
ax[0].bar(np.arange(num_steps), learner.action_history[:,batch_idx]+1, bottom=-1)
ax[0].set_ylim(-0.5,num_actions+0.5)
ax[0].set_xticks([])
ax[0].set_ylabel('Action index')
# Reward (overlap) vs time
overlap = environment.overlap(learner.state_history[:,batch_idx,:3], target_state)
ax[1].plot(overlap)
ax[1].set_ylim(0.0,1)
ax[1].set_xlabel('Operation step')
ax[1].set_ylabel('Overlap')
plt.subplots_adjust(hspace=0.0)
plt.show()
# + tags=[] deepnote_to_be_reexecuted=false source_hash="14813636" execution_start=1642884963788 execution_millis=1729 deepnote_output_heights=[611, 611] cell_id="00020-913435a2-5e1f-4cd1-ab27-06aca6a34ade" deepnote_cell_type="code"
# investigate the overlaps of many cases in the batch
N_cases = 10
batch_idx = np.arange(N_cases)
fig, ax = plt.subplots(nrows=N_cases, dpi=150, figsize=(8,6))
# Overlap vs time
for idx in range(N_cases):
overlap = environment.overlap(learner.state_history[:,idx,:3], target_state)
ax[idx].plot(overlap)
ax[idx].set_ylim(0.0,1)
ax[N_cases-1].set_xlabel('Time step')
ax[0].set_ylabel('Overlap')
plt.subplots_adjust(hspace=0.2)
plt.show()
# + tags=[] cell_id="00021-64f96fe1-2f39-41c5-b620-25bf17c7e761" deepnote_to_be_reexecuted=false source_hash="ae3f48eb" execution_start=1642884983925 execution_millis=4 deepnote_cell_type="code"
# This can still be improved by further training...
# + [markdown] tags=[] created_in_deepnote_cell=true deepnote_cell_type="markdown"
# <a style='text-decoration:none;line-height:16px;display:flex;color:#5B5B62;padding:10px;justify-content:end;' href='https://deepnote.com?utm_source=created-in-deepnote-cell&projectId=257edd66-166e-407b-a4a5-f8a466bff41d' target="_blank">
# <img alt='Created in deepnote.com' style='display:inline;max-height:16px;margin:0px;margin-right:7.5px;' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iODBweCIgaGVpZ2h0PSI4MHB4IiB2aWV3Qm94PSIwIDAgODAgODAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDU0LjEgKDc2NDkwKSAtIGh0dHBzOi8vc2tldGNoYXBwLmNvbSAtLT4KICAgIDx0aXRsZT5Hcm91cCAzPC90aXRsZT4KICAgIDxkZXNjPkNyZW<KEY>ZXNjPgogICAgPGcgaWQ9IkxhbmRpbmciIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJBcnRib2FyZCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEyMzUuMDAwMDAwLCAtNzkuMDAwMDAwKSI+CiAgICAgICAgICAgIDxnIGlkPSJHcm91cC0zIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMjM1LjAwMDAwMCwgNzkuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8cG9seWdvbiBpZD0iUGF0aC0yMCIgZmlsbD0iIzAyNjVCNCIgcG9pbnRzPSIyLjM3NjIzNzYyIDgwIDM4LjA0NzY2NjcgODAgNTcuODIxNzgyMiA3My44MDU3NTkyIDU3LjgyMTc4MjIgMzIuNzU5MjczOSAzOS4xNDAyMjc4IDMxLjY4MzE2ODMiPjwvcG9seWdvbj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0zNS4wMDc3MTgsODAgQzQyLjkwNjIwMDcsNzYuNDU0OTM1OCA0Ny41NjQ5MTY3LDcxLjU0MjI2NzEgNDguOTgzODY2LDY1LjI2MTk5MzkgQzUxLjExMjI4OTksNTUuODQxNTg0MiA0MS42NzcxNzk1LDQ5LjIxMjIyODQgMjUuNjIzOTg0Niw0OS4yMTIyMjg0IEMyNS40ODQ5Mjg5LDQ5LjEyNjg0NDggMjkuODI2MTI5Niw0My4yODM4MjQ4IDM4LjY0NzU4NjksMzEuNjgzMTY4MyBMNzIuODcxMjg3MSwzMi41NTQ0MjUgTDY1LjI4MDk3Myw2Ny42NzYzNDIxIEw1MS4xMTIyODk5LDc3LjM3NjE0NCBMMzUuMDA3NzE4LDgwIFoiIGlkPSJQYXRoLTIyIiBmaWxsPSIjMDAyODY4Ij48L3BhdGg+CiAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMCwzNy43MzA0NDA1IEwyNy4xMTQ1MzcsMC4yNTcxMTE0MzYgQzYyLjM3MTUxMjMsLTEuOTkwNzE3MDEgODAsMTAuNTAwMzkyNyA4MCwzNy43MzA0NDA1IEM4MCw2NC45NjA0ODgyIDY0Ljc3NjUwMzgsNzkuMDUwMzQxNCAzNC4zMjk1MTEzLDgwIEM0Ny4wNTUzNDg5LDc3LjU2NzA4MDggNTMuNDE4MjY3Nyw3MC4zMTM2MTAzIDUzLjQxODI2NzcsNTguMjM5NTg4NSBDNTMuNDE4MjY3Nyw0MC4xMjg1NTU3IDM2LjMwMzk1NDQsMzcuNzMwNDQwNSAyNS4yMjc0MTcsMzcuNzMwNDQwNSBDMTcuODQzMDU4NiwzNy43MzA0NDA1IDkuNDMzOTE5NjYsMzcuNzMwNDQwNSAwLDM3LjczMDQ0MDUgWiIgaWQ9IlBhdGgtMTkiIGZpbGw9IiMzNzkzRUYiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+' > </img>
# Created in <span style='font-weight:600;margin-left:4px;'>Deepnote</span></a>
| 2022_01_PolicyGradientRL.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# # !pip install plotly
# -
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.metrics import confusion_matrix
import sys
# %matplotlib inline
import matplotlib.pyplot as plt
import plotly.express as px
# !ls data
def genesis_train(file):
data = pd.read_csv(file)
del data['Unnamed: 32']
print('Number of datapoints in Training dataset: ',len(data))
X_train = data.iloc[:, 2:].values
y_train = data.iloc[:, 1].values
test = pd.read_csv('./data/test.csv')
del test['Unnamed: 32']
print('Number of datapoints in Testing dataset: ',len(test))
X_test = test.iloc[:, 2:].values
y_test = test.iloc[:, 1].values
labelencoder = LabelEncoder()
y_train = labelencoder.fit_transform(y_train)
y_test = labelencoder.fit_transform(y_test)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
model = Sequential()
model.add(Dense(16, activation='relu', input_dim=30))
model.add(Dropout(0.1))
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=100, epochs=5)
scores = model.evaluate(X_test, y_test)
print("Loss: ", scores[0]) #Loss
print("Accuracy: ", scores[1]) #Accuracy
#Saving Model
model.save("./output.h5")
return scores[1]
def update_train(file):
data = pd.read_csv(file)
del data['Unnamed: 32']
X_train = data.iloc[:, 2:].values
y_train = data.iloc[:, 1].values
test = pd.read_csv('./data/test.csv')
del test['Unnamed: 32']
print('Number of datapoints in Testing dataset: ',len(test))
X_test = test.iloc[:, 2:].values
y_test = test.iloc[:, 1].values
labelencoder = LabelEncoder()
y_train = labelencoder.fit_transform(y_train)
y_test = labelencoder.fit_transform(y_test)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
model = Sequential()
model.add(Dense(16, activation='relu', input_dim=30))
model.add(Dropout(0.1))
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(1, activation='sigmoid'))
model.load_weights("./output.h5")
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=100, epochs=5)
scores = model.evaluate(X_test, y_test)
print("Loss: ", scores[0]) #Loss
print("Accuracy: ", scores[1]) #Accuracy
#Saving Model
model.save("./output.h5")
return scores[1]
datasetAccuracy = {}
datasetAccuracy['Complete Dataset'] = genesis_train('./data/data.csv')
datasetAccuracy['A'] = genesis_train('./data/dataA.csv')
datasetAccuracy['B'] = genesis_train('./data/dataB.csv')
datasetAccuracy['C'] = genesis_train('./data/dataC.csv')
datasetAccuracy['D'] = genesis_train('./data/dataD.csv')
datasetAccuracy['E'] = genesis_train('./data/dataE.csv')
datasetAccuracy['F'] = genesis_train('./data/dataF.csv')
datasetAccuracy['G'] = genesis_train('./data/dataG.csv')
datasetAccuracy['H'] = genesis_train('./data/dataH.csv')
datasetAccuracy['I'] = genesis_train('./data/dataI.csv')
px.bar(pd.DataFrame.from_dict(datasetAccuracy, orient='index'))
FLAccuracy = {}
FLAccuracy['A'] = update_train('./data/dataA.csv')
FLAccuracy['B'] = update_train('./data/dataB.csv')
FLAccuracy['C'] = update_train('./data/dataC.csv')
FLAccuracy['D'] = update_train('./data/dataD.csv')
FLAccuracy['E'] = update_train('./data/dataE.csv')
FLAccuracy['F'] = update_train('./data/dataF.csv')
FLAccuracy['G'] = update_train('./data/dataG.csv')
FLAccuracy['H'] = update_train('./data/dataH.csv')
FLAccuracy['I'] = update_train('./data/dataI.csv')
px.bar(pd.DataFrame.from_dict(FLAccuracy, orient='index'))
# +
#################################################################################################################
# -
FLAccuracy
| Jupyter Simulations/2. Cancer (CSV) Classification Simulations/Centralised vs Sequential Federated Learning.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Load
# This tutorial shows how to load graphs from files in various formats and from existing collections of datasets, [NetSet](https://netset.telecom-paris.fr) and [Konect](http://konect.cc/).
# + pycharm={"is_executing": false}
from sknetwork.data import load_edge_list, load_graphml, load_netset, load_konect
# -
# ## TSV files
#
# Loading a graph from a [TSV](https://en.wikipedia.org/wiki/Tab-separated_values) file (list of edges).
graph = load_edge_list('miserables.tsv')
adjacency = graph.adjacency
names = graph.names
# Digraph
graph = load_edge_list('painters.tsv', directed=True)
adjacency = graph.adjacency
names = graph.names
# Bigraph
graph = load_edge_list('movie_actor.tsv', bipartite=True)
biadjacency = graph.biadjacency
names_row = graph.names_row
names_col = graph.names_col
# ## GraphML files
#
# Loading a graph from a [GraphML](https://en.wikipedia.org/wiki/GraphML) file.
graph = load_graphml('miserables.graphml')
adjacency = graph.adjacency
names = graph.names
# Digraph
graph = load_graphml('painters.graphml')
adjacency = graph.adjacency
names = graph.names
# ## NetSet
#
# Loading a graph from the [NetSets](https://netset.telecom-paris.fr) collection.
graph = load_netset('openflights')
adjacency = graph.adjacency
names = graph.names
# to get all fields
graph
# Digraph
graph = load_netset('wikivitals')
adjacency = graph.adjacency
names = graph.names
labels = graph.labels
# Bigraph
graph = load_netset('cinema')
biadjacency = graph.biadjacency
# ## Konect
#
# Loading a graph from the [Konect](http://konect.cc/) collection.
# +
# first check server availability!
# graph = load_konect('dolphins')
# adjacency = graph.adjacency
| docs/tutorials/data/load.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Interacting with HBase in Python (using Happybase)
# [Happybase](https://happybase.readthedocs.io/en/latest/) is a python library to interact with HBase that uses its Thrift API under the hood. [Apache Thrift](https://thrift.apache.org/) is a software framework which is used for the development of cross-language services.
# ## An Overview of HBase Structure
# It is important to first understand how data is stored in HBase. <br>HBase is a Column oriented database i.e. the table schema defines only column families and the records are sorted by row. <br>
# A table can have many column families and each column family can have many columns (if a restriction is not defined). <br>
# The data is then stored as key:value pairs in these columns. <br> <br>
# The following list of points summarize the above paragraph:
# 1. A Table in HBase is a collection of rows
# 2. A Row is a collection of Column Families
# 3. A Column Family is a collection of columns and
# 4. A Column stores data as key:value pairs
#
# The cell below shows such a structure:
# +
# A typical HBase structure:
# |Row key| Column Family 1 | Column Family 2 |
# |-------|-----------------|-----------------|
# | | col 1 | col 2 | col A | col B |
# |-------|-----------------|--------|--------|
# | row1 | alpha | beta | gama | delta |
# -
# ## Interacting in Python
# +
# check if the library is installed
# otherwise install it (pip install happybase)
import happybase
# +
# get a connection
# start the hbase by running the script ${HBASE_HOME}/bin/start-hbase.sh
# ensure that the thrift server is running
# this is done using hbase-daemon.sh start thrift
# Note that by default the thrift server runs at localhost:9090
# Hence the connection can be established as follows:
conn = happybase.Connection(host='localhost', port=9090)
# or simply as
#conn = happybase.Connection()
# -
# print all the tables present
print(conn.tables())
# ### Creating a Table
# +
# let us create a simple table named 'books' with two column famiilies named Author and Info
# create the table only if it does not exist
tables_list = conn.tables() # get the list of tables
if b'books' not in tables_list:
conn.create_table(
'books',
{'Author': dict(max_versions=2),
'Info':dict(),
}
)
# -
# ### Storing data
# First get an instance of the Table object
table = conn.table('books')
# +
# Enter data using the put() method of Table object
table.put(b'101', {b'Author:FirstName' : b'George',
b'Author:LastName' : b'Orwell'})
table.put(b'101', {b'Info:Title' : b'Animal Farm',
b'Info:Price' : b'100'})
table.put(b'102', {b'Author:FirstName' : b'George',
b'Author:LastName' : b'Orwell'})
table.put(b'102', {b'Info:Title' : b'1984',
b'Info:Price' : b'150'})
table.put(b'103', {b'Author:FirstName' : b'Albert',
b'Author:LastName' : b'Camus'})
table.put(b'103', {b'Info:Title' : b'The Fall',
b'Info:Price' : b'200'})
table.put(b'104', {b'Author:FirstName' : b'Franz',
b'Author:LastName' : b'Kafka'})
table.put(b'104', {b'Info:Title' : b'The Trial',
b'Info:Price' : b'250'})
# -
# ### Reading data
# +
# We can read the whole table using Table.scan() as follows
for key, data in table.scan():
print(key,data)
# -
# a row can be retrived using Table.row()
# for a given row key
# note that the byte objects can be decoded into strins using decode("utf-8")
row = table.row(b'102')
print("Author : {} {}".format(row[b'Author:FirstName'].decode("utf-8"), row[b'Author:LastName'].decode("utf-8")))
# Note that similar to above multiple rows of data
# can be retrieved using Table.rows()
rows = table.rows([b'101', b'103', b'104'])
for key, data in rows:
print(key, data)
# get the result as a dictionary
rows_as_dict = dict(table.rows([b'101', b'103', b'104']))
type(rows_as_dict)
print(rows_as_dict)
# access individual columns
rows_as_dict[b'101'][b'Author:FirstName']
# +
# we can also retrieve only the required columns rather than
# retrieving whole rows and filtering the output
# This improves the performance
# This is done with columns argument. For example:
rows = table.rows([b'101', b'104'], columns=[b'Author'])
for key,data in rows:
print(key, data)
# In the abvoe example note how all the columns of a column family can be retrieved
# -
| notebooks/Tutorial 1 Basic operations.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python (nflows)
# language: python
# name: nflows
# ---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import torch
import math
import astropy.coordinates as coord
import astropy.units as u
data = pd.read_csv('rgb_rc_gaia.csv')
# +
#in torch
l = torch.from_numpy(data['l'].values)
b = torch.from_numpy(data['b'].values)
dist = torch.from_numpy(data['distance'].values)
pi = torch.tensor(math.pi)
X = dist*torch.cos(l*pi/180.)*torch.cos(b*pi/180.) - coord.Galactocentric().galcen_distance.value
Y = dist*torch.sin(l*pi/180.)*torch.cos(b*pi/180.)
Z = dist*torch.sin(b*pi/180.) #+ 0.0208
# +
#in numpy
#X = data['distance']*np.cos(data['l']*np.pi/180.)*np.cos(data['b']*np.pi/180.) - coord.Galactocentric().galcen_distance.value
#Y = data['distance']*np.sin(data['l']*np.pi/180.)*np.cos(data['b']*np.pi/180.)
#Z = data['distance']*np.sin(data['b']*np.pi/180.) #+ 0.0208
# +
insample = (X < 0) & (X > -20) & (Y > -10) & (Y < 10) & (np.abs(Z) < 2)
fig, ax = plt.subplots(1,3, figsize=(15,5))
H, xe, ye = np.histogram2d(X[insample].detach().numpy(), Y[insample].detach().numpy(), bins=50)
im = ax[0].pcolormesh(xe, ye, H.T+1, norm=mpl.colors.LogNorm())
fig.colorbar(im, ax=ax[0])
ax[0].set_xlabel('X')
ax[0].set_ylabel('Y')
ax[0].set_aspect('equal')
H, xe, ye = np.histogram2d(X[insample].detach().numpy(), Z[insample].detach().numpy(), bins=50)
im = ax[1].pcolormesh(xe, ye, H.T+1, norm=mpl.colors.LogNorm())
fig.colorbar(im, ax=ax[1])
ax[1].set_xlabel('X')
ax[1].set_ylabel('Z')
ax[1].set_aspect('equal')
H, xe, ye = np.histogram2d(Y[insample].detach().numpy(), Z[insample].detach().numpy(), bins=50)
im = ax[2].pcolormesh(xe, ye, H.T+1, norm=mpl.colors.LogNorm())
fig.colorbar(im, ax=ax[2])
ax[2].set_xlabel('Y')
ax[2].set_ylabel('Z')
ax[2].set_aspect('equal')
# -
c = coord.Galactic(l=data['l'].values*u.deg, b=data['b'].values*u.deg, distance=data['distance'].values*u.kpc)
cg = c.transform_to(coord.Galactocentric)
fontsize=20
plt.plot(cg.x.value, X.detach().numpy() - cg.x.value, 'ko', markersize=3)
plt.xlim(-28, 12)
plt.ylim(-2, 2)
plt.xlabel(r'$x_{\mathrm{astropy}}$ [kpc]', fontsize=fontsize)
plt.ylabel(r'$x_{\mathrm{astropy}} - x_{\mathrm{lauren}}$ [kpc]', fontsize=fontsize)
plt.plot(cg.z.value, Z.detach().numpy() - cg.z.value, 'ko', markersize=3)
plt.xlim(-20, 20)
plt.ylim(-2, 2)
plt.xlabel(r'$z_{\mathrm{astropy}}$ [kpc]', fontsize=fontsize)
plt.ylabel(r'$z_{\mathrm{astropy}} - z_{\mathrm{lauren}}$ [kpc]', fontsize=fontsize)
plt.plot(cg.y.value, Y.detach().numpy() - cg.y.value, 'ko', markersize=3)
plt.xlim(-20, 20)
plt.ylim(-2, 2)
plt.xlabel(r'$z_{\mathrm{astropy}}$ [kpc]', fontsize=fontsize)
plt.ylabel(r'$z_{\mathrm{astropy}} - z_{\mathrm{lauren}}$ [kpc]', fontsize=fontsize)
insample = (cg.x.value < 0) & (cg.x.value > -20) & (cg.y.value > -10) & (cg.y.value < 10) & (np.abs(cg.z.value) < 2)
# +
fig, ax = plt.subplots(1,3, figsize=(15,5))
H, xe, ye = np.histogram2d(cg.x[insample].value, cg.y[insample].value, bins=50)
im = ax[0].pcolormesh(xe, ye, H.T+1, norm=mpl.colors.LogNorm())
fig.colorbar(im, ax=ax[0])
ax[0].set_xlabel('X')
ax[0].set_ylabel('Y')
ax[0].set_aspect('equal')
H, xe, ye = np.histogram2d(cg.x[insample].value, cg.z[insample].value, bins=50)
im = ax[1].pcolormesh(xe, ye, H.T+1, norm=mpl.colors.LogNorm())
fig.colorbar(im, ax=ax[1])
ax[1].set_xlabel('X')
ax[1].set_ylabel('Z')
ax[1].set_aspect('equal')
H, xe, ye = np.histogram2d(cg.y[insample].value, cg.z[insample].value, bins=50)
im = ax[2].pcolormesh(xe, ye, H.T+1, norm=mpl.colors.LogNorm())
fig.colorbar(im, ax=ax[2])
ax[2].set_xlabel('Y')
ax[2].set_ylabel('Z')
ax[2].set_aspect('equal')
# -
| rotate_coordinates.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + colab={} colab_type="code" id="6IEzg7alFSR9"
# To suppress warnings
import warnings
warnings.filterwarnings("ignore")
warnings.filterwarnings("ignore", category=DeprecationWarning)
# + colab={} colab_type="code" id="EA5jkZ5SFnWt"
# Basic Libraries for Data organization, Statistical operations and Plotting
import numpy as np
import pandas as pd
# %matplotlib inline
# For loading .arff files
from scipy.io import arff
# + colab={"base_uri": "https://localhost:8080/", "height": 224} colab_type="code" id="HCwWvo9JHoAX" outputId="0914f854-00ea-4b93-e29d-87f43b061106"
############################################################
# Loads the 5 raw .arff files into a list
def load_arff_raw_data():
N=5
return [arff.loadarff(str(i+1) + 'year.arff') for i in range(N)]
############################################################
# Loads the 5 raw .arff files into pandas dataframes
def load_dataframes():
return [pd.DataFrame(data_i_year[0]) for data_i_year in load_arff_raw_data()]
############################################################
# Set the column headers from X1 ... X64 and the class label as Y, for all the 5 dataframes.
def set_new_headers(dataframes):
cols = ['X' + str(i+1) for i in range(len(dataframes[0].columns)-1)]
cols.append('Y')
for df in dataframes:
df.columns = cols
############################################################
# dataframes is the list of pandas dataframes for the 5 year datafiles.
dataframes = load_dataframes()
# Set the new headers for the dataframes. The new headers will have the renamed set of feature (X1 to X64)
set_new_headers(dataframes)
# print the first 5 rows of a dataset 'year1'
dataframes[0].head()
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="EGRFeDBZHpsB" outputId="f2a8c2cf-1011-44ca-a254-7cb725c44904"
dataframes[0].shape
# + colab={} colab_type="code" id="D6tCTDrPH68L"
# Convert the dtypes of all the columns (other than the class label columns) to float.
def convert_columns_type_float(dfs):
for i in range(5):
index = 1
while(index<=63):
colname = dfs[i].columns[index]
col = getattr(dfs[i], colname)
dfs[i][colname] = col.astype(float)
index+=1
convert_columns_type_float(dataframes)
# + colab={} colab_type="code" id="Np7SpEWfH8ny"
# The class labels for all the dataframes are originally in object type.
# Convert them to int types
def convert_class_label_type_int(dfs):
for i in range(len(dfs)):
col = getattr(dfs[i], 'Y')
dfs[i]['Y'] = col.astype(int)
convert_class_label_type_int(dataframes)
# + colab={} colab_type="code" id="GWHfiGc9IU-4"
# To analyze the type of missing data
# !pip install missingno
import missingno as msno
# + colab={"base_uri": "https://localhost:8080/", "height": 678} colab_type="code" id="wusa-e3DJHFB" outputId="38b76b40-05e8-408a-f6e6-5b12fc48df82"
# Missing Values in the first Dataframe
msno.bar(dataframes[0],color='red',labels=True,sort="ascending")
# + colab={"base_uri": "https://localhost:8080/", "height": 685} colab_type="code" id="WkP5XkduJRgI" outputId="20fd4e49-7ecf-4cc2-8549-948d62e04f60"
# Missing Values in the second Dataframe
msno.bar(dataframes[1],color='blue',labels=True,sort="ascending")
# + colab={"base_uri": "https://localhost:8080/", "height": 685} colab_type="code" id="AxzROAB4JqQR" outputId="6fa0c3a7-fdd5-48b9-9707-a7f751304c91"
# Missing Values in the third Dataframe
msno.bar(dataframes[2],labels=True,sort="ascending")
# + colab={} colab_type="code" id="uBn27NnEZzlW"
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
# + colab={} colab_type="code" id="VZbzkY6pkmcw"
mean_imputed_df1=pd.DataFrame(imputer.fit_transform(dataframes[0]),columns=dataframes[0].columns)
# + colab={"base_uri": "https://localhost:8080/", "height": 678} colab_type="code" id="T2aMjxSDkqhy" outputId="352819af-e266-483c-ea6c-164e4454bda1"
msno.bar(mean_imputed_df1,color='red',labels=True,sort="ascending")
# + colab={"base_uri": "https://localhost:8080/", "height": 685} colab_type="code" id="7AXgpdKVkwVU" outputId="64c6ce5c-34b0-4bdf-8462-51ba4fa2df68"
# Imputation for the second Dataframe
mean_imputed_df2=pd.DataFrame(imputer.fit_transform(dataframes[1]),columns=dataframes[1].columns)
#check for missing values
msno.bar(mean_imputed_df2,color='red',labels=True,sort="ascending")
# + colab={"base_uri": "https://localhost:8080/", "height": 685} colab_type="code" id="FkbZMrDIlozp" outputId="30b7dd7d-112e-4e02-ddb3-eaf6955ae622"
# Imputation for the third Dataframe
mean_imputed_df3=pd.DataFrame(imputer.fit_transform(dataframes[2]),columns=dataframes[2].columns)
#checking missing values
msno.bar(mean_imputed_df3,color='red',labels=True,sort="ascending")
# +
#Exercise 4.04
# + colab={} colab_type="code" id="c8izWpeflwnO"
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
# + colab={} colab_type="code" id="Xk8UVJfpl0Qa"
imputer = IterativeImputer()
# + colab={} colab_type="code" id="OI9Nn8Rql17r"
iterative_imputed_df1 = pd.DataFrame(imputer.fit_transform(dataframes[0]),columns=dataframes[0].columns)
# + colab={"base_uri": "https://localhost:8080/", "height": 678} colab_type="code" id="RrwJNFVEl3cp" outputId="5cd03cdf-5459-4f1f-a34b-48f581096e3d"
msno.bar(iterative_imputed_df1,color='red',labels=True,sort="ascending")
# + colab={"base_uri": "https://localhost:8080/", "height": 685} colab_type="code" id="3sb8QS6Tl_j8" outputId="093dedcd-82b1-4130-92f5-cdecf1b5dedd"
#Creating a dataframe iterative_imputed_df2 for dataframe[1] where missing values are filled with the help of iterative imputer
iterative_imputed_df2 = pd.DataFrame(imputer.fit_transform(dataframes[1]),columns=dataframes[1].columns)
#check for the missing values in the dataframe.
msno.bar(iterative_imputed_df2,color='red',labels=True,sort="ascending")
# + colab={"base_uri": "https://localhost:8080/", "height": 685} colab_type="code" id="dAZ_-DjCmPSl" outputId="1af96669-d0a8-4cd3-cb3b-1fe3f6e84c79"
#Creating a dataframe iterative_imputed_df3 for dataframe[2] where missing values are filled with the help of iterative imputer
iterative_imputed_df3 = pd.DataFrame(imputer.fit_transform(dataframes[2]),columns=dataframes[2].columns)
#check for the missing values in the dataframe.
msno.bar(iterative_imputed_df3,color='red',labels=True,sort="ascending")
| Chapter04/Exercise4.04/Exercise4.04.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Pandas
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
from config import pw
# SQL Alchemy
from sqlalchemy import create_engine
# -
# Create Engine
engine = create_engine(f"postgresql://postgres:{pw}@localhost:5432/Employees")
connection = engine.connect()
# Query All Records in the the Database
salaries_df = pd.read_sql("SELECT * FROM salaries", connection)
# Preview the Data
salaries_df.head()
plt.hist(salaries_df["salary"], bins=20)
employees_df = pd.read_sql("""
SELECT
t.title
,AVG(s.salary) AS average_salary
FROM employees AS e
JOIN titles AS t ON e.emp_title = t.title_id
JOIN salaries AS s on e.emp_no = s.emp_no
GROUP BY t.title
ORDER BY average_salary DESC
""", connection)
employees_df
plt.barh(employees_df.title, employees_df.average_salary)
empl_df = pd.read_sql("""
SELECT
e.first_name
,e.last_name
FROM employees AS e
WHERE emp_no = 499942
""", connection)
empl_df
| EmployeeSQL/SQLIntoPandas.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Reusable Embeddings
#
# **Learning Objectives**
# 1. Learn how to use a pre-trained TF Hub text modules to generate sentence vectors
# 1. Learn how to incorporate a pre-trained TF-Hub module into a Keras model
# 1. Learn how to deploy and use a text model on CAIP
#
#
#
# ## Introduction
#
#
# In this notebook, we will implement text models to recognize the probable source (Github, Tech-Crunch, or The New-York Times) of the titles we have in the title dataset.
#
# First, we will load and pre-process the texts and labels so that they are suitable to be fed to sequential Keras models with first layer being TF-hub pre-trained modules. Thanks to this first layer, we won't need to tokenize and integerize the text before passing it to our models. The pre-trained layer will take care of that for us, and consume directly raw text. However, we will still have to one-hot-encode each of the 3 classes into a 3 dimensional basis vector.
#
# Then we will build, train and compare simple DNN models starting with different pre-trained TF-Hub layers.
# +
import os
from google.cloud import bigquery
import pandas as pd
# -
# %load_ext google.cloud.bigquery
# Replace the variable values in the cell below:
# +
PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = PROJECT
REGION = "us-central1"
os.environ['PROJECT'] = PROJECT
os.environ['BUCKET'] = BUCKET
os.environ['REGION'] = REGION
# -
# ## Create a Dataset from BigQuery
#
# Hacker news headlines are available as a BigQuery public dataset. The [dataset](https://bigquery.cloud.google.com/table/bigquery-public-data:hacker_news.stories?tab=details) contains all headlines from the sites inception in October 2006 until October 2015.
#
# Here is a sample of the dataset:
# +
# %%bigquery --project $PROJECT
SELECT
url, title, score
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
LENGTH(title) > 10
AND score > 10
AND LENGTH(url) > 0
LIMIT 10
# -
# Let's do some regular expression parsing in BigQuery to get the source of the newspaper article from the URL. For example, if the url is http://mobile.nytimes.com/...., I want to be left with <i>nytimes</i>
# +
# %%bigquery --project $PROJECT
SELECT
ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source,
COUNT(title) AS num_articles
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$')
AND LENGTH(title) > 10
GROUP BY
source
ORDER BY num_articles DESC
LIMIT 100
# -
# Now that we have good parsing of the URL to get the source, let's put together a dataset of source and titles. This will be our labeled dataset for machine learning.
# +
regex = '.*://(.[^/]+)/'
sub_query = """
SELECT
title,
ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '{0}'), '.'))[OFFSET(1)] AS source
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
REGEXP_CONTAINS(REGEXP_EXTRACT(url, '{0}'), '.com$')
AND LENGTH(title) > 10
""".format(regex)
query = """
SELECT
LOWER(REGEXP_REPLACE(title, '[^a-zA-Z0-9 $.-]', ' ')) AS title,
source
FROM
({sub_query})
WHERE (source = 'github' OR source = 'nytimes' OR source = 'techcrunch')
""".format(sub_query=sub_query)
print(query)
# -
# For ML training, we usually need to split our dataset into training and evaluation datasets (and perhaps an independent test dataset if we are going to do model or feature selection based on the evaluation dataset). AutoML however figures out on its own how to create these splits, so we won't need to do that here.
#
#
bq = bigquery.Client(project=PROJECT)
title_dataset = bq.query(query).to_dataframe()
title_dataset.head()
# AutoML for text classification requires that
# * the dataset be in csv form with
# * the first column being the texts to classify or a GCS path to the text
# * the last colum to be the text labels
#
# The dataset we pulled from BiqQuery satisfies these requirements.
print("The full dataset contains {n} titles".format(n=len(title_dataset)))
# Let's make sure we have roughly the same number of labels for each of our three labels:
title_dataset.source.value_counts()
# Finally we will save our data, which is currently in-memory, to disk.
#
# We will create a csv file containing the full dataset and another containing only 1000 articles for development.
#
# **Note:** It may take a long time to train AutoML on the full dataset, so we recommend to use the sample dataset for the purpose of learning the tool.
#
# +
DATADIR = './data/'
if not os.path.exists(DATADIR):
os.makedirs(DATADIR)
# +
FULL_DATASET_NAME = 'titles_full.csv'
FULL_DATASET_PATH = os.path.join(DATADIR, FULL_DATASET_NAME)
# Let's shuffle the data before writing it to disk.
title_dataset = title_dataset.sample(n=len(title_dataset))
title_dataset.to_csv(
FULL_DATASET_PATH, header=False, index=False, encoding='utf-8')
# -
# Now let's sample 1000 articles from the full dataset and make sure we have enough examples for each label in our sample dataset (see [here](https://cloud.google.com/natural-language/automl/docs/beginners-guide) for further details on how to prepare data for AutoML).
sample_title_dataset = title_dataset.sample(n=1000)
sample_title_dataset.source.value_counts()
# Let's write the sample datatset to disk.
# +
SAMPLE_DATASET_NAME = 'titles_sample.csv'
SAMPLE_DATASET_PATH = os.path.join(DATADIR, SAMPLE_DATASET_NAME)
sample_title_dataset.to_csv(
SAMPLE_DATASET_PATH, header=False, index=False, encoding='utf-8')
# +
import datetime
import os
import shutil
import pandas as pd
import tensorflow as tf
from tensorflow.keras.callbacks import TensorBoard, EarlyStopping
from tensorflow_hub import KerasLayer
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.utils import to_categorical
print(tf.__version__)
# -
# %matplotlib inline
# Let's start by specifying where the information about the trained models will be saved as well as where our dataset is located:
MODEL_DIR = "./text_models"
DATA_DIR = "./data"
# ## Loading the dataset
# As in the previous labs, our dataset consists of titles of articles along with the label indicating from which source these articles have been taken from (GitHub, Tech-Crunch, or the New-York Times):
# ls ./data/
# +
DATASET_NAME = "titles_full.csv"
TITLE_SAMPLE_PATH = os.path.join(DATA_DIR, DATASET_NAME)
COLUMNS = ['title', 'source']
titles_df = pd.read_csv(TITLE_SAMPLE_PATH, header=None, names=COLUMNS)
titles_df.head()
# -
# Let's look again at the number of examples per label to make sure we have a well-balanced dataset:
titles_df.source.value_counts()
# ## Preparing the labels
# In this lab, we will use pre-trained [TF-Hub embeddings modules for english](https://tfhub.dev/s?q=tf2%20embeddings%20text%20english) for the first layer of our models. One immediate
# advantage of doing so is that the TF-Hub embedding module will take care for us of processing the raw text.
# This also means that our model will be able to consume text directly instead of sequences of integers representing the words.
#
# However, as before, we still need to preprocess the labels into one-hot-encoded vectors:
CLASSES = {
'github': 0,
'nytimes': 1,
'techcrunch': 2
}
N_CLASSES = len(CLASSES)
def encode_labels(sources):
classes = [CLASSES[source] for source in sources]
one_hots = to_categorical(classes, num_classes=N_CLASSES)
return one_hots
encode_labels(titles_df.source[:4])
# ## Preparing the train/test splits
# Let's split our data into train and test splits:
# +
N_TRAIN = int(len(titles_df) * 0.95)
titles_train, sources_train = (
titles_df.title[:N_TRAIN], titles_df.source[:N_TRAIN])
titles_valid, sources_valid = (
titles_df.title[N_TRAIN:], titles_df.source[N_TRAIN:])
# -
# To be on the safe side, we verify that the train and test splits
# have roughly the same number of examples per class.
#
# Since it is the case, accuracy will be a good metric to use to measure
# the performance of our models.
sources_train.value_counts()
sources_valid.value_counts()
# Now let's create the features and labels we will feed our models with:
X_train, Y_train = titles_train.values, encode_labels(sources_train)
X_valid, Y_valid = titles_valid.values, encode_labels(sources_valid)
X_train[:3]
Y_train[:3]
# ## NNLM Model
# We will first try a word embedding pre-trained using a [Neural Probabilistic Language Model](http://www.jmlr.org/papers/volume3/bengio03a/bengio03a.pdf). TF-Hub has a 50-dimensional one called
# [nnlm-en-dim50-with-normalization](https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1), which also
# normalizes the vectors produced.
#
# ### Lab Task 1a: Import NNLM TF Hub module into `KerasLayer`
#
# Once loaded from its url, the TF-hub module can be used as a normal Keras layer in a sequential or functional model. Since we have enough data to fine-tune the parameters of the pre-trained embedding itself, we will set `trainable=True` in the `KerasLayer` that loads the pre-trained embedding:
# +
NNLM = "https://tfhub.dev/google/nnlm-en-dim50/2"
nnlm_module = KerasLayer(# TODO)
# -
# Note that this TF-Hub embedding produces a single 50-dimensional vector when passed a sentence:
# ### Lab Task 1b: Use module to encode a sentence string
nnlm_module(tf.constant([# TODO]))
# ## Swivel Model
# Then we will try a word embedding obtained using [Swivel](https://arxiv.org/abs/1602.02215), an algorithm that essentially factorizes word co-occurrence matrices to create the words embeddings.
# TF-Hub hosts the pretrained [gnews-swivel-20dim-with-oov](https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim-with-oov/1) 20-dimensional Swivel module.
#
# ### Lab Task 1c: Import Swivel TF Hub module into `KerasLayer`
# +
SWIVEL = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim-with-oov/1"
swivel_module = KerasLayer(# TODO)
# -
# Similarly as the previous pre-trained embedding, it outputs a single vector when passed a sentence:
#
# ### Lab Task 1d: Use module to encode a sentence string
swivel_module(tf.constant([# TODO]))
# ## Building the models
# Let's write a function that
#
# * takes as input an instance of a `KerasLayer` (i.e. the `swivel_module` or the `nnlm_module` we constructed above) as well as the name of the model (say `swivel` or `nnlm`)
# * returns a compiled Keras sequential model starting with this pre-trained TF-hub layer, adding one or more dense relu layers to it, and ending with a softmax layer giving the probability of each of the classes:
#
# ### Lab Task 2: Incorporate a pre-trained TF Hub module as first layer of Keras Sequential Model
def build_model(hub_module, name):
model = Sequential([
# TODO
Dense(16, activation='relu'),
Dense(N_CLASSES, activation='softmax')
], name=name)
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
# Let's also wrap the training code into a `train_and_evaluate` function that
# * takes as input the training and validation data, as well as the compiled model itself, and the `batch_size`
# * trains the compiled model for 100 epochs at most, and does early-stopping when the validation loss is no longer decreasing
# * returns an `history` object, which will help us to plot the learning curves
def train_and_evaluate(train_data, val_data, model, batch_size=5000):
X_train, Y_train = train_data
tf.random.set_seed(33)
model_dir = os.path.join(MODEL_DIR, model.name)
if tf.io.gfile.exists(model_dir):
tf.io.gfile.rmtree(model_dir)
history = model.fit(
X_train, Y_train,
epochs=100,
batch_size=batch_size,
validation_data=val_data,
callbacks=[EarlyStopping(), TensorBoard(model_dir)],
)
return history
# ## Training NNLM
data = (X_train, Y_train)
val_data = (X_valid, Y_valid)
nnlm_model = build_model(nnlm_module, 'nnlm')
nnlm_history = train_and_evaluate(data, val_data, nnlm_model)
history = nnlm_history
pd.DataFrame(history.history)[['loss', 'val_loss']].plot()
pd.DataFrame(history.history)[['accuracy', 'val_accuracy']].plot()
# ## Training Swivel
swivel_model = build_model(swivel_module, name='swivel')
swivel_history = train_and_evaluate(data, val_data, swivel_model)
history = swivel_history
pd.DataFrame(history.history)[['loss', 'val_loss']].plot()
pd.DataFrame(history.history)[['accuracy', 'val_accuracy']].plot()
# Swivel trains faster but achieves a lower validation accuracy, and requires more epochs to train on.
# ## Deploying the model
# The first step is to serialize one of our trained Keras model as a SavedModel:
# +
OUTPUT_DIR = "./savedmodels"
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
EXPORT_PATH = os.path.join(OUTPUT_DIR, 'swivel')
os.environ['EXPORT_PATH'] = EXPORT_PATH
shutil.rmtree(EXPORT_PATH, ignore_errors=True)
tf.saved_model.save(swivel_model, EXPORT_PATH)
# -
# Then we can deploy the model using the gcloud CLI as before:
# ### Lab Task 3a: Complete the following script to deploy the swivel model
# + language="bash"
#
# # TODO 5
#
# MODEL_NAME=title_model
# VERSION_NAME=swivel
#
# if [[ $(gcloud ai-platform models list --format='value(name)' | grep $MODEL_NAME) ]]; then
# echo "$MODEL_NAME already exists"
# else
# echo "Creating $MODEL_NAME"
# gcloud ai-platform models create --region=$REGION $MODEL_NAME
# fi
#
# if [[ $(gcloud ai-platform versions list --model $MODEL_NAME --format='value(name)' | grep $VERSION_NAME) ]]; then
# echo "Deleting already existing $MODEL_NAME:$VERSION_NAME ... "
# echo yes | gcloud ai-platform versions delete --model=$MODEL_NAME $VERSION_NAME
# echo "Please run this cell again if you don't see a Creating message ... "
# sleep 2
# fi
#
# echo "Creating $MODEL_NAME:$VERSION_NAME"
#
# gcloud ai-platform versions create $VERSION_NAME\
# --model=$MODEL_NAME \
# --framework=# TODO \
# --python-version=# TODO \
# --runtime-version=2.1 \
# --origin=# TODO \
# --staging-bucket=# TODO \
# --machine-type n1-standard-4 \
# --region=$REGION
# -
# Before we try our deployed model, let's inspect its signature to know what to send to the deployed API:
# !saved_model_cli show \
# --tag_set serve \
# --signature_def serving_default \
# --dir {EXPORT_PATH}
# !find {EXPORT_PATH}
# Let's go ahead and hit our model:
# ### Lab Task 3b: Create the JSON object to send a title to the API you just deployed
# (**Hint:** Look at the 'saved_model_cli show' command output above.)
# %%writefile input.json
{# TODO}
# !gcloud ai-platform predict \
# --model title_model \
# --json-instances input.json \
# --version swivel \
# --region=$REGION
# ## Bonus
# Try to beat the best model by modifying the model architecture, changing the TF-Hub embedding, and tweaking the training parameters.
# Copyright 2019 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
| training-data-analyst/courses/machine_learning/deepdive2/text_classification/labs/reusable_embeddings.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <code>import module</code>
# ##### A module is just a collection of variables defined by someone else
# <code>dir(module)</code> : See all the names of the variables
# <code>dir(module.submodule)</code> : See all the names of the variables of the variable of a module
#
# We can access these variables using dot syntax.
# (E.g. <code>math.pi</code>)
# +
import math
print("pi to 4 significant digits = {:.4}".format(math.pi))
# -
# ##### Add an alias to the imported method
# <code>import numpy as np</code>
#
# ##### Makes the module's variables directly accessible to you
# <code>from module import log, pi</code> : You can import all with <code>*</code> but you have to keep in mind that some variables of a module could coincide with the variables of other modules.
| Basics/Imports.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] colab_type="text" id="pL--_KGdYoBz"
# ##### Copyright 2019 The TensorFlow Authors.
# + cellView="form" colab={} colab_type="code" id="uBDvXpYzYnGj"
#@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.
# + [markdown] colab_type="text" id="HQzaEQuJiW_d"
# # TFRecord и tf.Example
#
# <table class="tfo-notebook-buttons" align="left">
# <td>
# <a target="_blank" href="https://www.tensorflow.org/tutorials/load_data/tfrecord"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Смотрите на TensorFlow.org</a>
# </td>
# <td>
# <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ru/tutorials/load_data/tfrecord.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Запустите в Google Colab</a>
# </td>
# <td>
# <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ru/tutorials/load_data/tfrecord.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />Изучайте код на GitHub</a>
# </td>
# <td>
# <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ru/tutorials/load_data/tfrecord.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Скачайте ноутбук</a>
# </td>
# </table>
# + [markdown] colab_type="text" id="gVN4BFQ5Dg4v"
# Note: Вся информация в этом разделе переведена с помощью русскоговорящего Tensorflow сообщества на общественных началах. Поскольку этот перевод не является официальным, мы не гарантируем что он на 100% аккуратен и соответствует [официальной документации на английском языке](https://www.tensorflow.org/?hl=en). Если у вас есть предложение как исправить этот перевод, мы будем очень рады увидеть pull request в [tensorflow/docs](https://github.com/tensorflow/docs) репозиторий GitHub. Если вы хотите помочь сделать документацию по Tensorflow лучше (сделать сам перевод или проверить перевод подготовленный кем-то другим), напишите нам на [<EMAIL> list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ru).
# + [markdown] colab_type="text" id="3pkUd_9IZCFO"
# Чтобы эффективно читать данные будет полезно сериализовать ваши данные и держать их в наборе файлов (по 100-200MB каждый) каждый из которых может быть прочитан построчно. Это особенно верно если данные передаются по сети. Также это может быть полезно для кеширования и предобработки данных.
#
# Формат TFRecord это простой формат для хранения последовательности двоичных записей.
#
# [Protocol buffers](https://developers.google.com/protocol-buffers/) это кросс-платформенная, кросс-языковая библиотека для эффективной сериализации структурированных данных.
#
# Сообщения протокола обычно определяются файлами `.proto`. Это часто простейший способ понять тип сообщения.
#
# Сообщение `tf.Example` (или protobuf) гибкий тип сообщений, который преедставляет сопоставление `{"string": value}`. Он разработан для использования с TensorFlow и используется в высокоуровневых APIs таких как [TFX](https://www.tensorflow.org/tfx/).
# + [markdown] colab_type="text" id="Ac83J0QxjhFt"
# Этот урок покажет как создавать, парсить и использовать сообщение `tf.Example`, а затем сериализовать читать и писать сообщения `tf.Example` в/из файлов `.tfrecord`.
#
# Замечание: Хотя эти структуры полезны, они необязательны. Нет необходимости конвертировать существующий код для использования TFRecords если вы не используете [`tf.data`](https://www.tensorflow.org/guide/datasets) и чтение данных все еще узкое место обучения. См. [Производительность конвейера входных данных](https://www.tensorflow.org/guide/performance/datasets) для советов по производительности датасета.
# + [markdown] colab_type="text" id="WkRreBf1eDVc"
# ## Setup
# + colab={} colab_type="code" id="Ja7sezsmnXph"
import tensorflow as tf
import numpy as np
import IPython.display as display
# + [markdown] colab_type="text" id="e5Kq88ccUWQV"
# ## `tf.Example`
# + [markdown] colab_type="text" id="VrdQHgvNijTi"
# ### Типы данных для `tf.Example`
# + [markdown] colab_type="text" id="lZw57Qrn4CTE"
# Фундаментально `tf.Example` это соответствие `{"string": tf.train.Feature}`.
#
# Вид сообщений `tf.train.Feature` допускает один из следующих трех типов (См. [файл `.proto`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto) для справки). Большинство других общих типов может быть сведено к одному из этих трех:
#
# 1. `tf.train.BytesList` (можно привести следующие типы)
#
# - `string`
# - `byte`
#
# 1. `tf.train.FloatList` (можно привести следующие типы)
#
# - `float` (`float32`)
# - `double` (`float64`)
#
# 1. `tf.train.Int64List` (можно привести следующие типы)
#
# - `bool`
# - `enum`
# - `int32`
# - `uint32`
# - `int64`
# - `uint64`
# + [markdown] colab_type="text" id="_e3g9ExathXP"
# Чтобы преобразовать стандартный тип TensorFlow в `tf.Example`-совместимый` tf.train.Feature`, вы можете использовать приведенные ниже функции. Обратите внимание, что каждая функция принимает на вход скалярное значение и возвращает `tf.train.Feature` содержащий один из трех вышеприведенных `list` типов:
# + colab={} colab_type="code" id="mbsPOUpVtYxA"
# Следующая функция может быть использована чтобы преобразовать значение в тип совместимый с
# с tf.Example.
def _bytes_feature(value):
"""Преобразует string / byte в bytes_list."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList не будет распаковывать строку из EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(value):
"""Преобразует float / double в float_list."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _int64_feature(value):
"""Преобразует bool / enum / int / uint в int64_list."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
# + [markdown] colab_type="text" id="Wst0v9O8hgzy"
# Замечание: Для простоты этот пример использует только скалярные входные данные. Простейший способ обработки нескалярных признаков - использование `tf.serialize_tensor` для конвертации тензоров в двоичнеые строки. Стоки являются скалярами в тензорфлоу. Используйте `tf.parse_tensor` для обратной конвертации двоичных сток в тензор.
# + [markdown] colab_type="text" id="vsMbkkC8xxtB"
# Ниже приведены несколько примеров того как работают эти функции. Обратите внимание на различные типы ввода и стандартизированные типы вывода. Если входной тип функции не совпадает с одним из приводимых типов указанных выше, функция вызовет исключение (например `_int64_feature(1.0)` выдаст ошибку поскольку `1.0` это значение с плавающей точкой и должно быть использовано с функцией `_float_feature`):
# + colab={} colab_type="code" id="hZzyLGr0u73y"
print(_bytes_feature(b'test_string'))
print(_bytes_feature(u'test_bytes'.encode('utf-8')))
print(_float_feature(np.exp(1)))
print(_int64_feature(True))
print(_int64_feature(1))
# + [markdown] colab_type="text" id="nj1qpfQU5qmi"
# Все proto сообщения могут быть сериализованы в двоичную строку с использованием метода `.SerializeToString`:
# + colab={} colab_type="code" id="5afZkORT5pjm"
feature = _float_feature(np.exp(1))
feature.SerializeToString()
# + [markdown] colab_type="text" id="laKnw9F3hL-W"
# ### Создание сообщения `tf.Example`
# + [markdown] colab_type="text" id="b_MEnhxchQPC"
# Допустим вы хотите создать сообщение `tf.Example` из существующих данных. На практике данные могут прийти откуда угодно, но процедура создания сообщения `tf.Example` из одного наблюдения будет той же:
#
# 1. В рамках каждого наблюдения каждое значение должно быть преобразовано в `tf.train.Feature` содержащее одно из 3 совместимых типов, с использованием одной из вышеприведенных функций.
#
# 2. Вы создаете отображение (словарь) из строки названий признаков в закодированное значение признака выполненное на шаге #1.
#
# 3. Отображение (map) созданное на шаге 2 конвертируется в [`Features` message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto#L85).
# + [markdown] colab_type="text" id="4EgFQ2uHtchc"
# В этом уроке вы создадите датасет с использованием NumPy.
#
# У этого датасета будет 4 признака:
# * булев признак, `False` или `True` с равной вероятностью
# * целочисленный признак - равномерно случайно выбранный из `[0, 5]`
# * строковый признак сгенерированный из табицы строк с использованием целочисленного признака в качестве индекса
# * признак с плавающей точкой из стандартного нормального распределения
#
# Рассмотрим выборку состающую из 10 000 независимых, одинаково распределенных наблюдений из каждого вышеприведенного распределения:
# + colab={} colab_type="code" id="CnrguFAy3YQv"
# Число наблюдений в датасете.
n_observations = int(1e4)
# Булев признак, принимающий значения False или True.
feature0 = np.random.choice([False, True], n_observations)
# Целочисленный признак, случайное число от 0 до 4.
feature1 = np.random.randint(0, 5, n_observations)
# Строковый признак
strings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])
feature2 = strings[feature1]
# Признак с плавающей точкой, из стандартного нормального распределения
feature3 = np.random.randn(n_observations)
# + [markdown] colab_type="text" id="aGrscehJr7Jd"
# Каждый из этих признаков может быть приведен к `tf.Example`-совместимому типу с использованием одного из `_bytes_feature`, `_float_feature`, `_int64_feature`. Вы можете затем создать `tf.Example`-сообщение из этих закодированных признаков:
# + colab={} colab_type="code" id="RTCS49Ij_kUw"
def serialize_example(feature0, feature1, feature2, feature3):
"""
Создает tf.Example-сообщение готовое к записи в файл.
"""
# Создает словарь отображение имен признаков в tf.Example-совместимые
# типы данных.
feature = {
'feature0': _int64_feature(feature0),
'feature1': _int64_feature(feature1),
'feature2': _bytes_feature(feature2),
'feature3': _float_feature(feature3),
}
# Создает Features message с использованием tf.train.Example.
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
return example_proto.SerializeToString()
# + [markdown] colab_type="text" id="XftzX9CN_uGT"
# Возьмем, например, одно наблюдение из датасета, `[False, 4, bytes('goat'), 0.9876]`. Вы можете создать и распечатать `tf.Example`-сообщение для этого наблюдения с использованием `create_message()`. Каждое наблюдение может быть записано в виде `Features`-сообщения как указано выше. Note that the `tf.Example`-[сообщение](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/example.proto#L88) это всего лишь обертка вокруг `Features`-сообщения:
# + colab={} colab_type="code" id="N8BtSx2RjYcb"
# Это пример наблюдения из набора данных.
example_observation = []
serialized_example = serialize_example(False, 4, b'goat', 0.9876)
serialized_example
# + [markdown] colab_type="text" id="_pbGATlG6u-4"
# Для декодирования сообщения используйте метод `tf.train.Example.FromString`.
# + colab={} colab_type="code" id="dGim-mEm6vit"
example_proto = tf.train.Example.FromString(serialized_example)
example_proto
# + [markdown] colab_type="text" id="o6qxofy89obI"
# ## Детали формата TFRecords
#
# Файл TFRecord содержит последовательность записей. Файл может быть прочитан только линейно.
#
# Каждая запись содержит строку байтов для данных плюс длину данных и CRC32C (32-bit CRC использующий полином Кастаньоли) хеши для проверки целостности.
#
# Каждая запись хранится в следующих форматах:
#
# uint64 length
# uint32 masked_crc32_of_length
# byte data[length]
# uint32 masked_crc32_of_data
#
# Записи сцеплены друг с другом и организуют файл.. CRCs
# [описаны тут](https://en.wikipedia.org/wiki/Cyclic_redundancy_check), и
# маска CRC выглядит так:
#
# masked_crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8ul
#
# Замечание: Не обязательно использовать `tf.Example` в файлах TFRecord. `tf.Example` это всего лишь метод сериализации словарей в байтовые строки. Строки текста, закодированные данные изображений, или сериализованные тензоры (с использованием `tf.io.serialize_tensor`, и
# `tf.io.parse_tensor` при загрузке). См. модуль `tf.io` для дополнительных возможностей.
# + [markdown] colab_type="text" id="y-Hjmee-fbLH"
# ## Файлы TFRecord с использованием `tf.data`
# + [markdown] colab_type="text" id="GmehkCCT81Ez"
# Модуль `tf.data` также предоставляет инструменты для чтения и записи данных в TensorFlow.
# + [markdown] colab_type="text" id="1FISEuz8ubu3"
# ### Запись файла TFRecord
#
# Простейший способ помещения данных в датасет это использование метода `from_tensor_slices`.
#
# Примененный к массиву он возвращает датасет скаляров:
# + colab={} colab_type="code" id="mXeaukvwu5_-"
tf.data.Dataset.from_tensor_slices(feature1)
# + [markdown] colab_type="text" id="f-q0VKyZvcad"
# Примененный к кортежу массивов он возвращает датасет кортежей:
# + colab={} colab_type="code" id="H5sWyu1kxnvg"
features_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))
features_dataset
# + colab={} colab_type="code" id="m1C-t71Nywze"
# Используйте `take(1)` чтобы взять только один пример из датасета.
for f0,f1,f2,f3 in features_dataset.take(1):
print(f0)
print(f1)
print(f2)
print(f3)
# + [markdown] colab_type="text" id="mhIe63awyZYd"
# Используйте метод `tf.data.Dataset.map` чтобы применить функцию к каждому элементу `Dataset`.
#
# «Функция отображения должна работать в графовом режиме TensorFlow - она должна принимать и возвращать` tf.Tensors`. Не тензорная функция, такая как `create_example`, может быть заключена в` tf.py_function`, для совместимости.
#
# Использование `tf.py_function` требует указания размерности и информации о типе, которая в противном случае недоступна:
# + colab={} colab_type="code" id="apB5KYrJzjPI"
def tf_serialize_example(f0,f1,f2,f3):
tf_string = tf.py_function(
serialize_example,
(f0,f1,f2,f3), # передайте эти аргументы в верхнюю функцию.
tf.string) # возвращаемый тип `tf.string`.
return tf.reshape(tf_string, ()) # Результатом является скаляр
# + colab={} colab_type="code" id="lHFjW4u4Npz9"
tf_serialize_example(f0,f1,f2,f3)
# + [markdown] colab_type="text" id="CrFZ9avE3HUF"
# Примените эту функцию к каждому элементу датасета:
# + colab={} colab_type="code" id="VDeqYVbW3ww9"
serialized_features_dataset = features_dataset.map(tf_serialize_example)
serialized_features_dataset
# + colab={} colab_type="code" id="DlDfuh46bRf6"
def generator():
for features in features_dataset:
yield serialize_example(*features)
# + colab={} colab_type="code" id="iv9oXKrcbhvX"
serialized_features_dataset = tf.data.Dataset.from_generator(
generator, output_types=tf.string, output_shapes=())
# + colab={} colab_type="code" id="Dqz8C4D5cIj9"
serialized_features_dataset
# + [markdown] colab_type="text" id="p6lw5VYpjZZC"
# И запишите их в файл TFRecord:
# + colab={} colab_type="code" id="vP1VgTO44UIE"
filename = 'test.tfrecord'
writer = tf.data.experimental.TFRecordWriter(filename)
writer.write(serialized_features_dataset)
# + [markdown] colab_type="text" id="6aV0GQhV8tmp"
# ### Чтение TFRecord файла
# + [markdown] colab_type="text" id="o3J5D4gcSy8N"
# Вы можете также прочитать TFRecord файл используя класс `tf.data.TFRecordDataset`.
#
# Больше информации об использовании TFRecord файлов с использованием `tf.data` может быть найдено [тут](https://www.tensorflow.org/guide/datasets#consuming_tfrecord_data)..
#
# Использование `TFRecordDataset`-ов может быть полезно для стандартизации входных данных и оптимизации производительности.
# + colab={} colab_type="code" id="6OjX6UZl-bHC"
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
# + [markdown] colab_type="text" id="6_EQ9i2E_-Fz"
# На этом этапе датасет содержит сериализованные сообщения `tf.train.Example`. При их итерации возвращаются скалярные строки тензоров.
#
# Используйте метод `.take` чтобы показать только первые 10 записей.
#
# Замечание: итерация по `tf.data.Dataset` работает только при включенном eager execution.
# + colab={} colab_type="code" id="hxVXpLz_AJlm"
for raw_record in raw_dataset.take(10):
print(repr(raw_record))
# + [markdown] colab_type="text" id="W-6oNzM4luFQ"
# Эти тензоры может распарсить используя нижеприведенную функцию. Заметьте что `feature_description` обязателен тут поскольку датасеты используют графовое исполнение и нуждаются в этом описании для построения своей размерностной и типовой сигнатуры:
# + colab={} colab_type="code" id="zQjbIR1nleiy"
# Создайте описание этих признаков
feature_description = {
'feature0': tf.io.FixedLenFeature([], tf.int64, default_value=0),
'feature1': tf.io.FixedLenFeature([], tf.int64, default_value=0),
'feature2': tf.io.FixedLenFeature([], tf.string, default_value=''),
'feature3': tf.io.FixedLenFeature([], tf.float32, default_value=0.0),
}
def _parse_function(example_proto):
# Разберите `tf.Example` proto используя вышеприведенный словарь.
return tf.io.parse_single_example(example_proto, feature_description)
# + [markdown] colab_type="text" id="gWETjUqhEQZf"
# Альтернативно, используйте `tf.parse example` чтобы распарсить весь пакет за раз. Примените эту функцию к кажому элементу датасета используя метод `tf.data.Dataset.map`:
# + colab={} colab_type="code" id="6Ob7D-zmBm1w"
parsed_dataset = raw_dataset.map(_parse_function)
parsed_dataset
# + [markdown] colab_type="text" id="sNV-XclGnOvn"
# Используйте eager execution чтобы показывать наблюдения в датасете. В этом наборе данных 10,000 наблюдений, но вы выведете только первые 10. Данные показываются как словарь признаков. Каждое наблюдение это `tf.Tensor`, и элемент `numpy`этого тензора показывает значение признака:
# + colab={} colab_type="code" id="x2LT2JCqhoD_"
for parsed_record in parsed_dataset.take(10):
print(repr(parsed_record))
# + [markdown] colab_type="text" id="Cig9EodTlDmg"
# Здесь функция `tf.parse_example` распаковывает поля `tf.Example` в стандартные тензоры.
# + [markdown] colab_type="text" id="jyg1g3gU7DNn"
# ## TFRecord файлы в Python
# + [markdown] colab_type="text" id="3FXG3miA7Kf1"
# Модуль `tf.io` также содержит чисто Python функции для чтения и записи файлов TFRecord.
# + [markdown] colab_type="text" id="CKn5uql2lAaN"
# ### Запись TFRecord файла
# + [markdown] colab_type="text" id="LNW_FA-GQWXs"
# Далее запишем эти 10 000 наблюдений в файл `test.tfrecord`. Каждое наблюдения конвертируется в `tf.Example`-сообщение и затем пишется в файл. Вы можете после проверить, что файл `test.tfrecord` был создан:
# + colab={} colab_type="code" id="MKPHzoGv7q44"
# Запишем наблюдения `tf.Example` в файл.
with tf.io.TFRecordWriter(filename) as writer:
for i in range(n_observations):
example = serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])
writer.write(example)
# + colab={} colab_type="code" id="EjdFHHJMpUUo"
# !du -sh {filename}
# + [markdown] colab_type="text" id="2osVRnYNni-E"
# ### Чтение TFRecord файла
#
# Эти сериализованные тензоры могут быть легко распарсены с использование `tf.train.Example.ParseFromString`:
# + colab={} colab_type="code" id="U3tnd3LerOtV"
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
# + colab={} colab_type="code" id="nsEAACHcnm3f"
for raw_record in raw_dataset.take(1):
example = tf.train.Example()
example.ParseFromString(raw_record.numpy())
print(example)
# + [markdown] colab_type="text" id="S0tFDrwdoj3q"
# ## Упражнение: Чтение и запись данных изображений
# + [markdown] colab_type="text" id="rjN2LFxFpcR9"
# Это пример того как читать и писать данные изображений используя TFRecords. Цель этого показать как, от начала до конца, ввести данные (в этом случае изображение) и записать данные в TFRecord файл, затем прочитать файл и показать изображение.
#
# Это будет полезно если, например, вы хотите использовать несколько моделей на одних и тех же входных данных. Вместо хранения сырых данных изображений, они могут быть предобработанны в формат TFRecords, и затем могут быть использованы во всех дальнейших обработках и моделированиях.
#
# Сперва давайте скачаем [это изображение](https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg) кота и покажем [это фото](https://upload.wikimedia.org/wikipedia/commons/f/fe/New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg) строительства моста Williamsburg, NYC.
# + [markdown] colab_type="text" id="5Lk2qrKvN0yu"
# ### Получите изображения
# + colab={} colab_type="code" id="3a0fmwg8lHdF"
cat_in_snow = tf.keras.utils.get_file('320px-Felis_catus-cat_on_snow.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg')
williamsburg_bridge = tf.keras.utils.get_file('194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/194px-New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg')
# + colab={} colab_type="code" id="7aJJh7vENeE4"
display.display(display.Image(filename=cat_in_snow))
display.display(display.HTML('Image cc-by: <a "href=https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg">Von.grzanka</a>'))
# + colab={} colab_type="code" id="KkW0uuhcXZqA"
display.display(display.Image(filename=williamsburg_bridge))
display.display(display.HTML('<a "href=https://commons.wikimedia.org/wiki/File:New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg">From Wikimedia</a>'))
# + [markdown] colab_type="text" id="VSOgJSwoN5TQ"
# ### Write the TFRecord file
# + [markdown] colab_type="text" id="Azx83ryQEU6T"
# Как и ранее закодируйте признаки как типы совместимые с `tf.Example`. Здесь хранится необработанные данные изображения в формате string, так же как и высота, ширина, глубина и произвольный признак `label`. Последнее используется когда вы пишете файл чтобы различать изображение кота и моста. Используйте `0` изображения кота, и `1` для моста:
# + colab={} colab_type="code" id="kC4TS1ZEONHr"
image_labels = {
cat_in_snow : 0,
williamsburg_bridge : 1,
}
# + colab={} colab_type="code" id="c5njMSYNEhNZ"
# Это пример использования только изображения кота.
image_string = open(cat_in_snow, 'rb').read()
label = image_labels[cat_in_snow]
# Создайте библиотеку с признаками которые могут быть релевантны.
def image_example(image_string, label):
image_shape = tf.image.decode_jpeg(image_string).shape
feature = {
'height': _int64_feature(image_shape[0]),
'width': _int64_feature(image_shape[1]),
'depth': _int64_feature(image_shape[2]),
'label': _int64_feature(label),
'image_raw': _bytes_feature(image_string),
}
return tf.train.Example(features=tf.train.Features(feature=feature))
for line in str(image_example(image_string, label)).split('\n')[:15]:
print(line)
print('...')
# + [markdown] colab_type="text" id="2G_o3O9MN0Qx"
# Заметьте что все признаки сейчас содержатся в `tf.Example`-сообщении. Далее функционализируйте вышеприведенный код и запишите пример сообщений в файл с именем `images.tfrecords`:
# + colab={} colab_type="code" id="qcw06lQCOCZU"
# Запишем файлы изображений в `images.tfrecords`.
# Сперва, преобразуем два изображения в `tf.Example`-сообщения.
# Затем запишем их в `.tfrecords` файл.
record_file = 'images.tfrecords'
with tf.io.TFRecordWriter(record_file) as writer:
for filename, label in image_labels.items():
image_string = open(filename, 'rb').read()
tf_example = image_example(image_string, label)
writer.write(tf_example.SerializeToString())
# + colab={} colab_type="code" id="yJrTe6tHPCfs"
# !du -sh {record_file}
# + [markdown] colab_type="text" id="jJSsCkZLPH6K"
# ### Чтение TFRecord файла
#
# У вас сейчас есть файл `images.tfrecords` и вы можете проитерировать записи в нем чтобы прочитать то что вы в него записали. Поскольку этот пример содержит только изображение единственное свойство которое вам нужно это необработанная строка изображения. Извлеките ее используя геттеры описанные выше, а именно `example.features.feature['image_raw'].bytes_list.value[0]`. Вы можете также использовать метки чтобы определить, которая запись является котом, и которая мостом:
# + colab={} colab_type="code" id="M6Cnfd3cTKHN"
raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')
# Создадим словарь описывающий свойства.
image_feature_description = {
'height': tf.io.FixedLenFeature([], tf.int64),
'width': tf.io.FixedLenFeature([], tf.int64),
'depth': tf.io.FixedLenFeature([], tf.int64),
'label': tf.io.FixedLenFeature([], tf.int64),
'image_raw': tf.io.FixedLenFeature([], tf.string),
}
def _parse_image_function(example_proto):
# Распарсим входной tf.Example proto используя вышесозданный словарь.
return tf.io.parse_single_example(example_proto, image_feature_description)
parsed_image_dataset = raw_image_dataset.map(_parse_image_function)
parsed_image_dataset
# + [markdown] colab_type="text" id="0PEEFPk4NEg1"
# Восстановим изображение из TFRecord файла:
# + colab={} colab_type="code" id="yZf8jOyEIjSF"
for image_features in parsed_image_dataset:
image_raw = image_features['image_raw'].numpy()
display.display(display.Image(data=image_raw))
| site/ru/tutorials/load_data/tfrecord.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python3
# ---
# # Street network figure-ground diagrams, a la <NAME>' *Great Streets*
import osmnx as ox, matplotlib.pyplot as plt
# %matplotlib inline
ox.config(log_file=True, log_console=True, use_cache=True)
dist = 805 # 1 mile in meters
places = [['sf', (37.793897, -122.402189), 'drive_service'],
['portland', (45.517309, -122.682138), 'drive_service'],
['irvine', (33.694981, -117.841375), 'drive_service'],
['rome', (41.901336, 12.471831), 'all']]
edges = []
for name, point, nt in places:
print(name, point)
G = ox.graph_from_point(point, distance=dist, distance_type='bbox', network_type=nt, truncate_by_edge=True)
G = ox.project_graph(G)
# create the bounding box in UTM zone units to limit the plot to the bounding box requested
# this is only necessary when truncate_by_edge=True to prevent display of nodes/edges that extend beyond bounding box
bbox_proj = ox.bbox_from_point(point, dist, project_utm=True, utm_crs=G.graph['crs'])
ew = []
for u, v, key, data in G.edges(keys=True, data=True):
if data['highway'] in ['footway', 'steps', 'pedestrian', 'service', 'footway', 'path', 'track']:
width = 1.5
elif data['highway'] in ['motorway']:
width = 6
else:
width = 4
ew.append(width)
fig, ax = ox.plot_graph(G, bbox=bbox_proj, fig_height=8, margin=0, node_size=0, edge_linewidth=ew,
edge_color='w', bgcolor='#333333', show=True, save=True, filename='gs_'+name)
edges.extend(G.edges(keys=True, data=True))
hwys = [data['highway'] for u, v, key, data in edges]
tags = list(set([hwy[0] if isinstance(hwy, list) else hwy for hwy in hwys]))
tags
| figure-ground.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: venv
# language: python
# name: venv
# ---
import sys
sys.path.insert(0, '../src/data')
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import bame_datastore
bame_datastore.lib
# # Causal Nex
#
# https://causalnex.readthedocs.io/en/latest/03_tutorial/03_tutorial.html
# +
from causalnex.structure.notears import from_pandas
from causalnex.plots import plot_structure, NODE_STYLE, EDGE_STYLE
from IPython.display import Image
df_raw = pd.read_csv("../data/processed/master_df.csv", index_col=0).dropna()
df_raw["bame_share"] = df_raw.Other+df_raw.Black_African_Caribbean+df_raw.Asian+df_raw.Mixed
nex_df = df_raw.copy()
nex_df.drop(columns=["Area Name", "covid_deaths_pop", "geometry","IMD_rank_std","area", "total_pop",
"White", "Mixed", "Black_African_Caribbean","Asian","Other"], inplace=True)
sm = from_pandas(nex_df, tabu_edges=[("deaths_covid", "IMD_rank_avg"),
("deaths_covid", "pop_density")])
sm.remove_edges_below_threshold(0.8)
viz = plot_structure(
sm,
graph_attributes={"scale": "0.9"},
all_node_attributes=NODE_STYLE.WEAK,
all_edge_attributes=EDGE_STYLE.WEAK)
Image(viz.draw(format='png'))
| notebooks/causal_attempt.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 09 Training - DS-CNN Model with Spectrogram
# #### Author: <NAME>
# #### Cognibit Solutions LLP
#
# Derived from https://arxiv.org/pdf/1711.07128.pdf
#
# DS-CNN Model
# +
import sys
import os
import tensorflow as tf
sys.path.append("../libs")
from classification import input_data
from classification import models
from classification import trainer
from classification import freeze
# -
# Change the data folder to use the required data folder.
# ### Flags
flags=tf.app.flags
# +
flags=tf.app.flags
#Important Directories
flags.DEFINE_string('data_dir','../data/raw','Train Data Folder')
flags.DEFINE_string('summaries_dir','../summaries','Summaries Folder')
flags.DEFINE_string('train_dir','../logs&checkpoint','Directory to write event logs and checkpoint')
flags.DEFINE_string('models_dir','../models','Models Folder')
#Task Specific Parameters
flags.DEFINE_string('wanted_words','yes,no,up,down,left,right,on,off,stop,go','Wanted Words')
flags.DEFINE_float('validation_percentage',10,'Validation Percentage')
flags.DEFINE_float('testing_percentage',10,'Testing Percentage')
flags.DEFINE_integer('sample_rate',16000,'Sample Rate')
flags.DEFINE_integer('clip_duration_ms',1000,'Clip Duration in ms')
flags.DEFINE_float('window_size_ms',20,'How long each spectogram timeslice is')
flags.DEFINE_float('window_stride_ms',10.0,'How far to move in time between frequency windows.')
flags.DEFINE_integer('dct_coefficient_count',257,'How many bins to use for the MFCC fingerprint')
flags.DEFINE_float('time_shift_ms',100.0,'Range to randomly shift the training audio by in time.')
FLAGS=flags.FLAGS
# -
# ### Variables
model_architecture='ds_cnn_spec'
start_checkpoint='../logs&checkpoint/ds_cnn_spec/ckpt-20000'
logging_interval=10
eval_step_interval=500
save_step_interval=2000
silence_percentage=10.0
unknown_percentage=12.0
background_frequency=0.8
background_volume=0.2
learning_rate='0.0005,0.0001' #Always seperated by comma, trains with each of the learning rate for the given number of iterations
train_steps='10000,20000' #Declare the training steps for which the learning rates will be used
batch_size=100
model_size_info=[6 ,276 ,10 ,4 ,2 ,1 ,276 ,3 ,3 ,2 ,2 ,276 ,3 ,3 ,1 ,1 ,276 ,3 ,3 ,1 ,1 ,276 ,3 ,3 ,1 ,1 ,276 ,3 ,3 ,1 ,1 ]
# ### Initialise the get_train_data() get_val_data() and get_test_data() Function
train_dir=os.path.join(FLAGS.data_dir,'train','audio')
model_settings = models.prepare_model_settings(
len(input_data.prepare_words_list(FLAGS.wanted_words.split(','))),
FLAGS.sample_rate, FLAGS.clip_duration_ms, FLAGS.window_size_ms,
FLAGS.window_stride_ms, FLAGS.dct_coefficient_count)
audio_processor = input_data.AudioProcessor(
train_dir, silence_percentage, unknown_percentage,
FLAGS.wanted_words.split(','), FLAGS.validation_percentage,
FLAGS.testing_percentage, model_settings,use_silence_folder=True,use_spectrogram=True)
def get_train_data(args):
sess=args
time_shift_samples = int((FLAGS.time_shift_ms * FLAGS.sample_rate) / 1000)
train_fingerprints, train_ground_truth = audio_processor.get_data(
batch_size, 0, model_settings,background_frequency,
background_volume, time_shift_samples, 'training', sess)
return train_fingerprints,train_ground_truth
sess=tf.InteractiveSession()
def get_val_data(args):
'''
Input: (sess,offset)
'''
sess,i=args
validation_fingerprints, validation_ground_truth = (
audio_processor.get_data(batch_size, i, model_settings, 0.0,
0.0, 0, 'validation', sess))
return validation_fingerprints,validation_ground_truth
def get_test_data(args):
'''
Input: (sess,offset)
'''
sess,i=args
test_fingerprints, test_ground_truth = audio_processor.get_data(
batch_size, i, model_settings, 0.0, 0.0, 0, 'testing', sess)
return test_fingerprints,test_ground_truth
# ### Training
def main(_):
sess=tf.InteractiveSession()
# Placeholders
fingerprint_size = model_settings['fingerprint_size']
label_count = model_settings['label_count']
fingerprint_input = tf.placeholder(
tf.float32, [None, fingerprint_size], name='fingerprint_input')
ground_truth_input = tf.placeholder(
tf.float32, [None, label_count], name='groundtruth_input')
set_size = audio_processor.set_size('validation')
label_count = model_settings['label_count']
# Create Model
logits, dropout_prob = models.create_model(
fingerprint_input,
model_settings,
model_architecture,
model_size_info=model_size_info,
is_training=True)
#Start Training
extra_args=(dropout_prob,label_count,batch_size,set_size)
trainer.train(sess,logits,fingerprint_input,ground_truth_input,get_train_data,
get_val_data,train_steps,learning_rate,eval_step_interval, logging_interval=logging_interval,
start_checkpoint=start_checkpoint,checkpoint_interval=save_step_interval,
model_name=model_architecture,train_dir=FLAGS.train_dir,
summaries_dir=FLAGS.summaries_dir,args=extra_args)
tf.app.run(main=main)
# ### Freeze
save_checkpoint='../logs&checkpoint/ds_cnn/ckpt-50000'
save_path=os.path.join(FLAGS.models_dir,model_architecture,'%s.pb'%os.path.basename(save_checkpoint))
freeze.freeze_graph(FLAGS,model_architecture,save_checkpoint,save_path,model_size_info=model_size_info)
save_path=os.path.join(FLAGS.models_dir,model_architecture,'%s-batched.pb'%os.path.basename(save_checkpoint))
freeze.freeze_graph(FLAGS,model_architecture,save_checkpoint,save_path,batched=True,model_size_info=model_size_info)
| documented_jupyter_notebook/09 Training - DS-CNN Spectrogram.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# +
"""
Implementation of the K-Means algorithm, while distributing the computations on a cluster.
Given a set of feature vectors, this algorithm runs the K-Means clustering algorithm starting
from a given set of centroids.
"""
import tensorflow as tf
import tensorframes as tfs
import numpy as np
def tf_compute_distances(points, start_centers):
"""
Given a set of points and some centroids, computes the distance from each point to each
centroid.
:param points: a 2d TF tensor of shape num_points x dim
:param start_centers: a numpy array of shape num_centroid x dim
:return: a TF tensor of shape num_points x num_centroids
"""
with tf.variable_scope("distances"):
# The dimensions in the problem
(num_centroids, _) = np.shape(start_centers)
# The shape of the block is extracted as a TF variable.
num_points = tf.shape(points)[0]
# The centers are embedded in the TF program.
centers = tf.constant(start_centers)
# Computation of the minimum distance. This is a standard implementation that follows
# what MLlib does.
squares = tf.reduce_sum(tf.square(points), reduction_indices=1)
center_squares = tf.reduce_sum(tf.square(centers), reduction_indices=1)
prods = tf.matmul(points, centers, transpose_b = True)
# This code simply expresses two outer products: center_squares * ones(num_points)
# and ones(num_centroids) * squares
t1a = tf.expand_dims(center_squares, 0)
t1b = tf.pack([num_points, 1])
t1 = tf.tile(t1a, t1b)
t2a = tf.expand_dims(squares, 1)
t2b = tf.pack([1, num_centroids])
t2 = tf.tile(t2a, t2b)
distances = t1 + t2 - 2 * prods
return distances
def run_one_step(dataframe, start_centers):
"""
Performs one iteration of K-Means.
This function takes a dataframe with dense feature vectors, a set of centroids, and returns
a new set of centroids along with the total distance of points to centroids.
This function calculates for each point the closest centroid and then aggregates the newly
formed clusters to find the new centroids.
This function uses Spark to distribute the aggregation amongst the node.
:param dataframe: a dataframe containing a column of features (an array of doubles)
:param start_centers: a k x m matrix with k the number of centroids and m the number of features
:return: a k x m matrix, and a positive double
"""
# The dimensions in the problem
(num_centroids, num_features) = np.shape(start_centers)
# For each feature vector, compute the nearest centroid and the distance to that centroid.
# The index of the nearest centroid is stored in the 'indexes' column.
# We also add a column of 1's that will be reduced later to count the number of elements in
# each cluster.
with tf.Graph().as_default() as g:
# The placeholder for the input: we use the block format
points = tf.placeholder(tf.double, shape=[None, num_features], name='features')
# The shape of the block is extracted as a TF variable.
num_points = tf.pack([tf.shape(points)[0]], name="num_points")
distances = tf_compute_distances(points, start_centers)
# The outputs of the program.
# The closest centroids are extracted.
indexes = tf.argmin(distances, 1, name='indexes')
# This could be done based on the indexes as well.
min_distances = tf.reduce_min(distances, 1, name='min_distances')
counts = tf.tile(tf.constant([1]), num_points, name='count')
df2 = tfs.map_blocks([indexes, counts, min_distances], dataframe)
# Perform the reduction: we regroup the point by their centroid indexes.
gb = df2.groupBy("indexes")
with tf.Graph().as_default() as g:
# Look at the documentation of tfs.aggregate for the naming conventions of the placeholders.
x_input = tfs.block(df2, "features", tf_name="features_input")
count_input = tfs.block(df2, "count", tf_name="count_input")
md_input = tfs.block(df2, "min_distances", tf_name="min_distances_input")
# Each operation is just the sum.
x = tf.reduce_sum(x_input, [0], name='features')
count = tf.reduce_sum(count_input, [0], name='count')
min_distances = tf.reduce_sum(md_input, [0], name='min_distances')
df3 = tfs.aggregate([x, count, min_distances], gb)
# Get the new centroids
df3_c = df3.collect()
# The new centroids.
new_centers = np.array([np.array(row.features) / row['count'] for row in df3_c])
total_distances = np.sum([row['min_distances'] for row in df3_c])
return (new_centers, total_distances)
def run_one_step2(dataframe, start_centers):
"""
Performs one iteration of K-Means.
This function takes a dataframe with dense feature vectors, a set of centroids, and returns
a new set of centroids along with the total distance of points to centroids.
This function calculates for each point the closest centroid and then aggregates the newly
formed clusters to find the new centroids.
This function performs most of the aggregation in TensorFlow.
:param dataframe: a dataframe containing a column of features (an array of doubles)
:param start_centers: a k x m matrix with k the number of centroids and m the number of features
:return: a k x m matrix, and a positive double
"""
# The dimensions in the problem
(num_centroids, _) = np.shape(start_centers)
# For each feature vector, compute the nearest centroid and the distance to that centroid.
# The index of the nearest centroid is stored in the 'indexes' column.
# We also add a column of 1's that will be reduced later to count the number of elements in
# each cluster.
with tf.Graph().as_default() as g:
# The placeholder for the input: we use the block format
points = tf.placeholder(tf.double, shape=[None, num_features], name='features')
# The distances
distances = tf_compute_distances(points, start_centers)
# The rest of this block performs a pre-aggregation step in TF, to limit the
# communication between TF and Spark.
# The closest centroids are extracted.
indexes = tf.argmin(distances, 1, name='indexes')
min_distances = tf.reduce_min(distances, 1, name='min_distances')
num_points = tf.pack([tf.shape(points)[0]], name="num_points")
counts = tf.tile(tf.constant([1]), num_points, name='count')
# These compute the aggregate based on the indexes.
block_points = tf.unsorted_segment_sum(points, indexes, num_centroids, name="block_points")
block_counts = tf.unsorted_segment_sum(counts, indexes, num_centroids, name="block_counts")
block_distances = tf.reduce_sum(min_distances, name="block_distances")
# One leading dimension is added to express the fact that the previous elements are just
# one row in the final dataframe.
# The final dataframe has one row per block.
agg_points = tf.expand_dims(block_points, 0, name="agg_points")
agg_counts = tf.expand_dims(block_counts, 0, name="agg_counts")
agg_distances = tf.expand_dims(block_distances, 0, name="agg_distances")
# Using trimming to drop the original data (we are just returning one row of data per
# block).
df2 = tfs.map_blocks([agg_points, agg_counts, agg_distances],
dataframe, trim=True)
# Now we simply collect and sum the elements
with tf.Graph().as_default() as g:
# Look at the documentation of tfs.aggregate for the naming conventions of the placeholders.
x_input = tf.placeholder(tf.double,
shape=[None, num_centroids, num_features],
name='agg_points_input')
count_input = tf.placeholder(tf.int32,
shape=[None, num_centroids],
name='agg_counts_input')
md_input = tf.placeholder(tf.double,
shape=[None],
name='agg_distances_input')
# Each operation is just the sum.
x = tf.reduce_sum(x_input, [0], name='agg_points')
count = tf.reduce_sum(count_input, [0], name='agg_counts')
min_distances = tf.reduce_sum(md_input, [0], name='agg_distances')
(x_, count_, total_distances) = tfs.reduce_blocks([x, count, min_distances], df2)
# The new centers
new_centers = (x_.T / (count_ + 1e-7)).T
return (new_centers, total_distances)
def kmeanstf(dataframe, init_centers, num_iters = 5, tf_aggregate = True):
"""
Runs the K-Means algorithm on a set of feature points.
This function takes a dataframe with dense feature vectors, a set of centroids, and returns
a new set of centroids along with the total distance of points to centroids.
:param dataframe: a dataframe containing a column of features (an array of doubles)
:param init_centers: the centers to start from
:param num_iters: the maximum number of iterations to run
:return: a k x m matrix, and a list of positive doubles
"""
step_fun = run_one_step2 if tf_aggregate else run_one_step
c = init_centers
d = np.Inf
ds = []
for i in range(num_iters):
(c1, d1) = step_fun(dataframe, c)
print "Step =", i, ", overall distance = ", d1
c = c1
if d == d1:
break
d = d1
ds.append(d1)
return c, ds
# Here is a an example of usage:
from pyspark.ml.clustering import KMeans, KMeansModel
from pyspark.mllib.linalg import VectorUDT, _convert_to_vector
from pyspark.sql.types import Row, StructField, StructType
import time
# Small vectors
num_features = 100
# The number of clusters
k = 10
num_points = 100000
num_iters = 10
FEATURES_COL = "features"
np.random.seed(2)
np_data = [x.tolist() for x in np.random.uniform(0.0, 1.0, size=(num_points, num_features))]
schema = StructType([StructField(FEATURES_COL, VectorUDT(), False)])
mllib_rows = [Row(_convert_to_vector(x)) for x in np_data]
mllib_df = sqlContext.createDataFrame(mllib_rows, schema).coalesce(1).cache()
df = sqlContext.createDataFrame([[r] for r in np_data]).toDF(FEATURES_COL).coalesce(1)
# For now, analysis is still required. We cache the output because we are going to perform
# multiple runs on the dataset.
df0 = tfs.analyze(df).cache()
mllib_df.count()
df0.count()
np.random.seed(2)
init_centers = np.random.randn(k, num_features)
start_centers = init_centers
dataframe = df0
ta_0 = time.time()
kmeans = KMeans().setK(k).setSeed(1).setFeaturesCol(FEATURES_COL).setInitMode(
"random").setMaxIter(num_iters)
mod = kmeans.fit(mllib_df)
ta_1 = time.time()
#(c1, d1) = run_one_step(dataframe, start_centers)
#(c2, d2) = run_one_step2(dataframe, start_centers)
tb_0 = time.time()
(centers, agg_distances) = kmeanstf(df0, init_centers, num_iters=num_iters, tf_aggregate=False)
tb_1 = time.time()
tc_0 = time.time()
(centers, agg_distances) = kmeanstf(df0, init_centers, num_iters=num_iters, tf_aggregate=True)
tc_1 = time.time()
mllib_dt = ta_1 - ta_0
tf_dt = tb_1 - tb_0
tf2_dt = tc_1 - tc_0
print "mllib:", mllib_dt, "tf+spark:",tf_dt, "tf:",tf2_dt
# -
| jupyterhub/notebooks/zz_under_construction/zz_old/TensorFlow/TensorFrames/ML/KMeans Demo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] toc="true"
# # Table of Contents
# <p>
# -
import datetime
# +
# set of objects for basic time
# +
# date, time, and date time objects
# +
# date(year, month, day) #in gregorian calendar
# -
d1 = datetime.date(2015, 1, 23)
d1
d1.strftime("%A %m/%d/%y")
d2 = datetime.date(2015, 1, 19)
d2
d1 - d2
print(d1 - d2)
(d1-d2).days # time delta objects
datetime.date.today()
# +
# time object
# -
t1 = datetime.time(1, 2) # always 24hours
t1
t2 = datetime.time(18)
t2
t1.strftime('%I:%M %p')
# +
# difference is not supported
# -
t2 - t1
# +
# relative times in a day, no date associated with it
# -
#datetime
d1 = datetime.datetime.now()
d1
d2 = datetime.datetime.now()
d2
d2 - d1
datetime.datetime.strptime('1/1/15', '%m/%d/%y') #stringparsetime
# +
# # %a (%A) abbrev (full) weekday name
# w, weekday number (0 for sun, -- 6)
# b, B abbrev (full) month name
# # %d day of month [01, 31]
# H I, 24 hour, 12 hour clock
# j day of year
# m month
# M minute
# p AM/PM
# S second
# U W week number of year U sunday, M monday as first day of week
# y Y year without/with century
# +
# tz
| notebooks/advanced/datetime.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.5.1
# language: julia
# name: julia-1.5
# ---
# # Compare sequential vs. squeezed implementations of `multiply_dimensionwise`, 2D
#
# At first, you need to run the benchmarks by executing
# ```
# julia -e benchmark_multiply_dimensionwise.jl
# ```
# Then, you can generate the plots by running this notebook.
# +
using Printf
using BSON
using PyCall
colors = pyimport("matplotlib.colors")
import PyPlot; plt = PyPlot
function plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
x = ones(length(n_nodes_in_list)) .* n_vars_list'
y = n_nodes_in_list .* ones(length(n_vars_list))'
exponent = max(
maximum(abs, round.(Int, log10.(extrema(values)), RoundUp)),
maximum(abs, round.(Int, log10.(extrema(values)), RoundDown)))
fig, ax = plt.subplots(1, 1)
plt.imshow(transpose(values),
origin="lower", extent=(n_vars_list[1]-0.5, n_vars_list[end]+0.5,
n_nodes_in_list[1]-0.5, n_nodes_in_list[end]+0.5),
cmap="seismic", norm=colors.LogNorm(vmin=10.0^(-exponent), vmax=10.0^(+exponent)),
# norm=colors.LogNorm()
)
plt.locator_params(axis="x", nbins=length(n_vars_list))
plt.locator_params(axis="y", nbins=length(n_nodes_in_list))
plt.colorbar(label=colorbar_label)
plt.axis("Image")
plt.xlabel("n_variables_total")
plt.ylabel("n_nodes_in")
plt.title(title * @sprintf("\nextrema: (%.1e, %.1e)", extrema(values)...))
fig
end
function plot_benchmarks(datafile, title=datafile)
BSON.@load datafile n_vars_list n_nodes_in_list sequential_dynamic sequential_static sequential_nexpr sequential_dynamic_prealloc sequential_static_prealloc squeezed_dynamic squeezed_static
# @assert minimum(sequential_static ./ sequential_dynamic) >= 1
# @assert minimum(sequential_static_prealloc ./ sequential_dynamic_prealloc) >= 1
@assert minimum(sequential_dynamic_prealloc ./ sequential_dynamic_prealloc) <= 1
values = sequential_static ./ sequential_dynamic; colorbar_label = "sequential_static ./ sequential_dynamic"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
values = squeezed_static ./ squeezed_dynamic; colorbar_label = "squeezed_static ./ squeezed_dynamic"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
values = squeezed_dynamic ./ sequential_dynamic; colorbar_label = "squeezed_dynamic ./ sequential_dynamic"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
values = squeezed_static ./ sequential_dynamic; colorbar_label = "squeezed_static ./ sequential_dynamic"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
values = sequential_dynamic_prealloc ./ sequential_dynamic; colorbar_label = "sequential_dynamic_prealloc ./ sequential_dynamic"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
values = squeezed_dynamic ./ sequential_dynamic_prealloc; colorbar_label = "squeezed_dynamic ./ sequential_dynamic_prealloc"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
values = squeezed_static ./ sequential_dynamic_prealloc; colorbar_label = "squeezed_static ./ sequential_dynamic_prealloc"
fig = plot_benchmarks_helper(n_vars_list, n_nodes_in_list, title, values, colorbar_label)
return nothing
end
# -
arch = "i7-8700K_"
# arch = "i7-6850K_"
# arch = "XeonGold6230_"
plot_benchmarks(arch * "2D_nVarTotal_nNodesIn.bson", "n_nodes_out = n_nodes_in")
plot_benchmarks(arch * "2D_nVarTotal_2nNodesIn.bson", "n_nodes_out = 2*n_nodes_in")
plot_benchmarks(arch * "3D_nVarTotal_nNodesIn.bson", "n_nodes_out = n_nodes_in")
plot_benchmarks(arch * "3D_nVarTotal_2nNodesIn.bson", "n_nodes_out = 2*n_nodes_in")
# # WIP: Development. DO NOT RUN THE NEXT CELL
# + active=""
# BSON.@load "2D_nVarTotal_nNodesIn_i7-8700K.bson" n_variables_total_list n_nodes_in_list sequential sequential_prealloc squeezed
# title = "n_variables_interp=n_variables_total\nn_nodes_out=n_nodes_in"
# values = squeezed ./ sequential
#
# x = ones(length(n_nodes_in_list)) .* n_variables_total_list'
# y = n_nodes_in_list .* ones(length(n_variables_total_list))'
#
# exponent = maximum(abs, round.(Int, log10.(extrema(values))))
# plt.imshow(transpose(values),
# origin="lower", extent=(n_variables_total_list[1]-0.5, n_variables_total_list[end]+0.5,
# n_nodes_in_list[1]-0.5, n_nodes_in_list[end]+0.5),
# # cmap="seismic", norm=colors.LogNorm(vmin=10.0^(-exponent), vmax=10.0^(+exponent)),
# # norm=colors.LogNorm()
# )
# plt.locator_params(axis="x", nbins=length(n_variables_total_list))
# plt.locator_params(axis="y", nbins=length(n_nodes_in_list))
# plt.colorbar(label="run time in ns (mean)")
# plt.axis("Image")
# plt.xlabel("n_variables_total")
# plt.ylabel("n_nodes_in")
# plt.title(title)
# -
| benchmark/multiply_dimensionwise/plot_benchmarks.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
from sklearn import preprocessing
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn import model_selection
from sklearn.metrics import classification_report, accuracy_score
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
import pandas as pd
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data"
name = ['id','clump_thickness','uniform_cell_size',
'uniform_cell_shape','marginal_adhesion',
'single_epithelial_size','bare_nuclei','band_chromatin',
'normal_nucleoli','mitoses','class']
df = pd.read_csv(url,names=name)
# +
#preprocessing
df.replace('?',-9999,inplace=True)
#df['bare_nuclei'] = df['bare_nuclei'].astype(np.int64)
df.drop(['id'],1,inplace=True)
print(df.axes)
print(df.shape)
# -
#data visualisation
print(df.dtypes)
print(df.describe())
#histograms
df.hist(figsize=(10,10))
plt.show()
scatter_matrix(df,figsize=(10,10))
plt.show()
# +
X = np.array(df.drop(['class'],1))
Y = np.array(df['class'])
x_train,x_test,y_train,y_test = model_selection.train_test_split(X,Y,test_size=0.2)
# +
models = []
models.append(('KNN',KNeighborsClassifier(n_neighbors=5)))
models.append(('SVM',SVC(gamma='auto')))
results = []
names = []
#evaluating the model on training data
for name, model in models:
kfold = model_selection.KFold(n_splits=10,random_state=8)
cv_results = model_selection.cross_val_score(model,x_train,y_train,cv=kfold,scoring='accuracy')
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f) "%(name,cv_results.mean(),cv_results.std())
print(msg)
# -
#train model and making prediction
for name,model in models:
model.fit(x_train,y_train)
predictions = model.predict(x_test)
print(name)
print(accuracy_score(y_test,predictions))
print(classification_report(y_test,predictions))
#not related to model just trying out stuff
clf = SVC(gamma='auto')
clf.fit(x_train,y_train)
example = np.array([[1,2,3,4,1,3,2,3,1]])
example = example.reshape(1,-1)
prediction = clf.predict(example)
print(prediction)
| Breast Cancer Detection with ML.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %matplotlib inline
import gym
import itertools
import matplotlib
import numpy as np
import sys
import tensorflow as tf
import collections
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.cliff_walking import CliffWalkingEnv
from lib import plotting
matplotlib.style.use('ggplot')
# -
env = CliffWalkingEnv()
class PolicyEstimator():
"""
Policy Function approximator.
"""
def __init__(self, learning_rate=0.01, scope="policy_estimator"):
with tf.variable_scope(scope):
self.state = tf.placeholder(tf.int32, [], "state")
self.action = tf.placeholder(dtype=tf.int32, name="action")
self.target = tf.placeholder(dtype=tf.float32, name="target")
# This is just table lookup estimator
state_one_hot = tf.one_hot(self.state, int(env.observation_space.n))
self.output_layer = tf.contrib.layers.fully_connected(
inputs=tf.expand_dims(state_one_hot, 0),
num_outputs=env.action_space.n,
activation_fn=None,
weights_initializer=tf.zeros_initializer)
self.action_probs = tf.squeeze(tf.nn.softmax(self.output_layer))
self.picked_action_prob = tf.gather(self.action_probs, self.action)
# Loss and train op
self.loss = -tf.log(self.picked_action_prob) * self.target
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.train_op = self.optimizer.minimize(
self.loss, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
return sess.run(self.action_probs, { self.state: state })
def update(self, state, target, action, sess=None):
sess = sess or tf.get_default_session()
feed_dict = { self.state: state, self.target: target, self.action: action }
_, loss = sess.run([self.train_op, self.loss], feed_dict)
return loss
class ValueEstimator():
"""
Value Function approximator.
"""
def __init__(self, learning_rate=0.1, scope="value_estimator"):
with tf.variable_scope(scope):
self.state = tf.placeholder(tf.int32, [], "state")
self.target = tf.placeholder(dtype=tf.float32, name="target")
# This is just table lookup estimator
state_one_hot = tf.one_hot(self.state, int(env.observation_space.n))
self.output_layer = tf.contrib.layers.fully_connected(
inputs=tf.expand_dims(state_one_hot, 0),
num_outputs=1,
activation_fn=None,
weights_initializer=tf.zeros_initializer)
self.value_estimate = tf.squeeze(self.output_layer)
self.loss = tf.squared_difference(self.value_estimate, self.target)
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
self.train_op = self.optimizer.minimize(
self.loss, global_step=tf.contrib.framework.get_global_step())
def predict(self, state, sess=None):
sess = sess or tf.get_default_session()
return sess.run(self.value_estimate, { self.state: state })
def update(self, state, target, sess=None):
sess = sess or tf.get_default_session()
feed_dict = { self.state: state, self.target: target }
_, loss = sess.run([self.train_op, self.loss], feed_dict)
return loss
def reinforce(env, estimator_policy, estimator_value, num_episodes, discount_factor=1.0):
"""
REINFORCE (Monte Carlo Policy Gradient) Algorithm. Optimizes the policy
function approximator using policy gradient.
Args:
env: OpenAI environment.
estimator_policy: Policy Function to be optimized
estimator_value: Value function approximator, used as a baseline
num_episodes: Number of episodes to run for
discount_factor: Time-discount factor
Returns:
An EpisodeStats object with two numpy arrays for episode_lengths and episode_rewards.
"""
# Keeps track of useful statistics
stats = plotting.EpisodeStats(
episode_lengths=np.zeros(num_episodes),
episode_rewards=np.zeros(num_episodes))
Transition = collections.namedtuple("Transition", ["state", "action", "reward", "next_state", "done"])
for i_episode in range(num_episodes):
# Reset the environment and pick the fisrst action
state = env.reset()
episode = []
# One step in the environment
for t in itertools.count():
# Take a step
action_probs = estimator_policy.predict(state)
action = np.random.choice(np.arange(len(action_probs)), p=action_probs)
next_state, reward, done, _ = env.step(action)
# Keep track of the transition
episode.append(Transition(
state=state, action=action, reward=reward, next_state=next_state, done=done))
# Update statistics
stats.episode_rewards[i_episode] += reward
stats.episode_lengths[i_episode] = t
# Print out which step we're on, useful for debugging.
print("\rStep {} @ Episode {}/{} ({})".format(
t, i_episode + 1, num_episodes, stats.episode_rewards[i_episode - 1]), end="")
# sys.stdout.flush()
if done:
break
state = next_state
# Go through the episode and make policy updates
for t, transition in enumerate(episode):
# The return after this timestep
total_return = sum(discount_factor**i * t.reward for i, t in enumerate(episode[t:]))
# Update our value estimator
estimator_value.update(transition.state, total_return)
# Calculate baseline/advantage
baseline_value = estimator_value.predict(transition.state)
advantage = total_return - baseline_value
# Update our policy estimator
estimator_policy.update(transition.state, advantage, transition.action)
return stats
# +
tf.reset_default_graph()
global_step = tf.Variable(0, name="global_step", trainable=False)
policy_estimator = PolicyEstimator()
value_estimator = ValueEstimator()
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
# Note, due to randomness in the policy the number of episodes you need to learn a good
# policy may vary. ~2000-5000 seemed to work well for me.
stats = reinforce(env, policy_estimator, value_estimator, 2000, discount_factor=1.0)
# -
plotting.plot_episode_stats(stats, smoothing_window=25)
| PolicyGradient/CliffWalk REINFORCE with Baseline Solution.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#default_exp generators
# -
# # Generators
# > Functions which generate files
#hide
from nbdev.showdoc import *
#export
from fastcore.xtras import Path
import requests
#export
def generate_settings():
"""
Guide the user for generating a proper `settings.ini` if one does not already exist in the directory
"""
if Path('settings.ini').exists():
print("settings.ini already exists, going off existing version")
return
print("No settings.ini exists, let's make one:")
f = open("settings.ini", 'w')
user_inp = {}
user_inp['[DEFAULT]\nhost'] = 'github\n'
user_inp['lib_name'] = input("Please enter the name of your library: ")
_enterprise = int(input("Is this an Enterprise Git? (0 or 1): "))
if _enterprise:
user_inp['repo_name'] = input("Please enter the repo name: ")
user_inp['company_name'] = input("Please enter the company name: ")
user_inp['user'] = input("Please enter your git username: ")
user_inp['description'] = input("Please enter a description of the project: ")
user_inp['keywords'] = input("Please enter some keywords for your project seperated by a space: ")
user_inp['author'] = input("Please enter all main authors names (seperate names with a space): ")
user_inp['author_email'] = input("Please enter a main email contact for the project: ")
user_inp['copyright'] = input("Please enter a Copyright (such as company name or your name): ")
user_inp['branch'] = input("Please enter the head branch of this project (such as master/main): ")
user_inp['version'] = input("Please enter the current version of this project: ")
user_inp['min_python'] = input("Please enter the minimum required Python for this project (such as 3.6): ")
user_inp['audience'] = 'Developers'; user_inp['language'] = 'English'
for k, v in user_inp.items(): f.write(f'{k} = {v}\n')
nbs = input("Please enter where you would like your notebooks stored? (Usually `nbs` or `.`): ")
f.write('# Set to True if you want to create a more fancy sidebar.json than the default\ncustom_sidebar = False\n')
f.write('# Add licenses and see current list in `setup.py`\nlicense = apache2\n')
f.write('# From 1-7: Planning Pre-Alpha Alpha Beta Production Mature Inactive\nstatus = 2\n')
f.write('''
# Optional. Same format as setuptools requirements
# requirements =
# Optional. Same format as setuptools console_scripts
# console_scripts =
# Optional. Same format as setuptools dependency-links
# dep_links = ''')
f.write('''
###
# You probably won't need to change anything under here,
# unless you have some special requirements
###
# Change to, e.g. "nbs", to put your notebooks in nbs dir instead of repo root
''')
f.write(f'nbs_path = {nbs}\n')
f.write('doc_path = docs\n')
f.write('# Whether to look for library notebooks recursively in the `nbs_path` dir\nrecursive = False\n')
f.write("\n\n\n# Anything shown as '%(...)s' is substituted with that setting automatically")
f.write('doc_host = https://%(user)s.github.io\n') if not _enterprise else f.write('doc_host = https://pages.github.%(company_name)s.com\n')
f.write('doc_baseurl = /%(lib_name)s/\n') if not _enterprise else f.write('doc_baseurl = /%(repo_name)s/%(lib_name)s/\n')
if not _enterprise: f.write('git_url = https://github.com/%(user)s/%(lib_name)s/tree/%(branch)s/\n')
else: f.write('git_url = https://github.%(company_name)s.com/%(repo_name)s/%(lib_name)s/tree/%(branch)s/\n')
f.write('\n\n\nlib_path = %(lib_name)s\ntitle = %(lib_name)s\n')
f.write('''
#Optional advanced parameters
#Monospace docstings: adds <pre> tags around the doc strings, preserving newlines/indentation.
#monospace_docstrings = False
#Test flags: introduce here the test flags you want to use separated by |
#tst_flags =
#Custom sidebar: customize sidebar.json yourself for advanced sidebars (False/True)
#custom_sidebar =
#Cell spacing: if you want cell blocks in code separated by more than one new line
#cell_spacing =
#Custom jekyll styles: if you want more jekyll styles than tip/important/warning, set them here
#jekyll_styles = note,warning,tip,important
''')
print("If there are any necissary requirements for the project, please add them to the requirements section")
print("If there should be any test flags, please add them to the tst_flags section")
print("settings.ini successfully generated")
#export
def generate_ci():
"""
Generates a Github action for running nbdev tests
"""
path = Path('.github/workflows')
if not path.exists(): path.mkdir(parents=True)
if (path/'nbdev.yml').exists():
print("nbdev.yml already exists, please modify the existing version")
return
f = open(path/'nbdev.yml', 'w')
f.write('''
name: nbdev CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-python@v1
with:
python-version: '3.6'
architecture: 'x64'
- name: Install the library
run: |
pip install nbdev jupyter
pip install -e .
- name: Read all notebooks
run: |
nbdev_read_nbs
- name: Check if all notebooks are cleaned
run: |
echo "Check we are starting with clean git checkout"
if [ -n "$(git status -uno -s)" ]; then echo "git status is not clean"; false; fi
echo "Trying to strip out notebooks"
nbdev_clean_nbs
echo "Check that strip out was unnecessary"
git status -s # display the status to see which nbs need cleaning up
if [ -n "$(git status -uno -s)" ]; then echo -e "!!! Detected unstripped out notebooks\n!!!Remember to run nbdev_install_git_hooks"; false; fi
- name: Check if there is no diff library/notebooks
run: |
if [ -n "$(nbdev_diff_nbs)" ]; then echo -e "!!! Detected difference between the notebooks and the library"; false; fi
- name: Run tests
run: |
nbdev_test_nbs''')
#export
def generate_doc_foundations():
"""
Grabs the needed files for documentation from [nbdev_template](https://github.com/fastai/nbdev_template)
"""
_base_url = 'https://raw.githubusercontent.com/fastai/nbdev/master/docs'
_urls = {
'Gemfile':f'{_base_url}/Gemfile',
'Gemfile.lock': f'{_base_url}/Gemfile.lock',
'feed.xml': f'{_base_url}/feed.xml',
'sitemap.xml': f'{_base_url}/sitemap.xml',
'.gitignore': f'{_base_url}/.gitignore' # Specific gitignore
}
print("Initializing documentation foundation...")
base_path = Path('docs')
base_path.mkdir(exist_ok=True)
for fname, url in _urls.items():
r = requests.get(url)
with open(base_path/fname, 'w') as f:
f.write(r.text)
# This function goes and grabs the latest updated version of `Gemfile`, `Gemfile.lock`, `feed.xml`, and `sitemap.xml`. These are all needed to initially build the documentation
#export
def generate_setup():
"""
Grabs the original setup.py file from [nbdev_template](https://github.com/fastai/nbdev_template)
"""
r = requests.get('https://raw.githubusercontent.com/fastai/nbdev/master/setup.py')
with open('setup.py', 'w') as f: f.write(r.text)
# # Export -
#hide
from nbdev.export import notebook2script
notebook2script()
| 01_generators.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#read csv
import unicodecsv
def read_csv(filename):
with open(filename,'rb') as fhand:
reader = unicodecsv.DictReader(fhand)
return list(reader)
enrollments = read_csv('enrollments.csv')
# print(enrollments[0])
# print(daily_engagements[0])
# print(project_submissions[0])
# -
daily_engagement = read_csv('daily_engagement.csv')
project_submissions = read_csv('project_submissions.csv')
# + pycharm={"name": "#%%\n"}
#functions to clean datatype from csv
from datetime import datetime as dt
def parse_date(date):
if date == '':
return None
else:
return dt.strptime(date, '%Y-%m-%d')
def convert_to_int(number):
if number == '':
return None
else:
return int(number)
# + pycharm={"name": "#%%\n"}
for enrollment in enrollments:
# account_key can be left alone
enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])
enrollment['days_to_cancel'] = convert_to_int(enrollment['days_to_cancel'])
enrollment['is_canceled'] = enrollment['is_canceled'] == 'True'
enrollment['is_udacity'] = enrollment['is_udacity'] == 'True'
enrollment['join_date'] = parse_date(enrollment['join_date'])
enrollments[0]
print(len(enrollments))
# + pycharm={"name": "#%%\n"}
for engagement in daily_engagement:
engagement['utc_date'] = parse_date(engagement['utc_date'])
engagement['num_courses_visited'] = int(float(engagement['num_courses_visited']))
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
engagement['lessons_completed'] = int(float(engagement['lessons_completed']))
engagement['projects_completed'] = int(float(engagement['projects_completed']))
daily_engagement[0]
#print(len(daily_engagement))
# + pycharm={"name": "#%%\n"}
for submission in project_submissions:
submission['creation_date'] = parse_date(submission['creation_date'])
submission['completion_date'] = parse_date(submission['completion_date'] )
project_submissions[0]
print(len(project_submissions))
# + pycharm={"name": "#%%\n"}
#to find out unique enrolled students as there are multiple rows with same account key
uni_enrolled_students = set()
for enrollment in enrollments:
uni_enrolled_students.add(enrollment['account_key'])
print(len(uni_enrolled_students))
# + pycharm={"name": "#%%\n"}
uni_engaged_students = set()
for engagement in daily_engagement:
uni_engaged_students.add(engagement['account_key'])
print(len(uni_engaged_students))
# + pycharm={"name": "#%%\n"}
count = 0
for enrollment in enrollments:
student = enrollment['account_key']
if student not in uni_engaged_students and enrollment['days_to_cancel'] != 0:
count +=1
#print(enrollment)
print(count)
# + pycharm={"name": "#%%\n"}
# code to find the udacity test accounts
test_accounts = set()
for enrollment in enrollments:
if enrollment['is_udacity']:
test_accounts.add(enrollment['account_key'])
#print(test_accounts)
print(len(test_accounts))
# + pycharm={"name": "#%%\n"}
# code to remove the udacity test accounts from all the records
def remove_udacity_data(data):
non_udacity_data = []
for data_point in data:
if 'acct' in data_point and data_point['acct'] not in test_accounts:
non_udacity_data.append(data_point)
elif 'account_key' in data_point and data_point['account_key'] not in test_accounts:
non_udacity_data.append(data_point)
return non_udacity_data
non_udacity_enrollments = remove_udacity_data(enrollments)
print(len(non_udacity_enrollments))
non_udacity_engagement = remove_udacity_data(daily_engagement)
#print(len(non_udacity_engagement))
non_udacity_submission = remove_udacity_data(project_submissions)
#print(len(non_udacity_submission))
# + pycharm={"name": "#%%\n"}
# code to find all the paid students
paid_students = dict()
for enrollment in non_udacity_enrollments:
if not enrollment['is_canceled'] or enrollment['days_to_cancel'] > 7:
account_key = enrollment['account_key']
enrollment_date = enrollment['join_date']
if account_key not in paid_students or \
enrollment_date > paid_students[account_key]: #this condition only adds most recent enrollment date for students that have enrolled twice
paid_students[account_key] = enrollment_date
#print(paid_students)
print(len(paid_students))
# +
# function to find all the trial students
def within_one_week(join_date, engagement_date):
time_delta = engagement_date - join_date
return time_delta.days < 7 and time_delta.days >= 0
# +
# function to remove all the trial students
def remove_trial_students(data):
new_data = []
for data_point in data:
if data_point['account_key'] in paid_students:
new_data.append(data_point)
return new_data
#print(len(paid_engagement_in_first_week))
# -
paid_udacity_enrollments = remove_trial_students(non_udacity_enrollments)
print(len(paid_udacity_enrollments))
paid_udacity_engagement = remove_trial_students(non_udacity_engagement)
print(len(paid_udacity_engagement))
paid_udacity_submission = remove_trial_students(non_udacity_submission)
print(len(paid_udacity_submission))
for engagement_record in paid_udacity_engagement:
if engagement_record['num_courses_visited'] > 0:
engagement_record['has_visited'] = 1
else:
engagement_record['has_visited'] = 0
# +
paid_engagement_in_first_week = []
for engagement_record in paid_udacity_engagement:
account_key = engagement_record['account_key']
join_date = paid_students[account_key]
engagement_record_date = engagement_record['utc_date']
if within_one_week(join_date,engagement_record_date):
paid_engagement_in_first_week.append(engagement_record)
print(len(paid_engagement_in_first_week))
# +
#### what - average mins spent in a classroom
#### approach - divide engagement records into groups where each group represents engagement records for a particular student
#### how - dictionary mapping between student key : list of engagement record
from collections import defaultdict
def group_data(data, key_name):
grouped_data = defaultdict(list)
for data_point in data:
account_key = data_point[key_name]
grouped_data[account_key].append(data_point)
return grouped_data
engagement_by_account = group_data(paid_engagement_in_first_week, 'account_key')
# +
def sum_grouped_items(grouped_data, field_name):
summed_data = {}
for key, data_points in grouped_data.items():
total = 0
for data_point in data_points:
total += data_point[field_name]
summed_data[key] = total
return summed_data
total_minutes_by_account = sum_grouped_items(engagement_by_account,'total_minutes_visited')
total_lessons_completed = sum_grouped_items(engagement_by_account, 'lessons_completed')
#print(total_minutes_by_account)
# -
import seaborn as sns
# +
#### list conversion is not needed in python 2 because the returned type is probably a list but in python 3 it is an
#### object hence a conversion is needed.
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def describe_data(data):
print('Mean:', np.mean(data))
print('Standard Deviation:',np.std(data))
print('Minimum:',np.min(data))
print('Maximum:',np.max(data))
plt.hist(data)
#total_mins = list(total_minutes_by_account.values())
#describe_data(total_mins)
# +
####this code finds the student whose minutes are maximum and greater than the total of the mins
student_with_max_minutes = None
max_mins = 0
for student, total_mins in total_minutes_by_account.items():
if total_mins > max_mins:
max_mins = total_mins
student_with_max_minutes = student
max_mins
# -
for engagement_record in paid_engagement_in_first_week:
if engagement_record['account_key'] == student_with_max_minutes:
print(engagement_record)
lessons_completed = list(total_lessons_completed.values())
describe_data(lessons_completed)
num_of_days_visited = sum_grouped_items(engagement_by_account,'has_visited')
describe_data(list(num_of_days_visited.values()))
# +
subway_project_lesson_keys = ['746169184', '3176718735']
#passed_students = list()
passed_subway_project = set()
#passing_engagement = []
for submission in paid_udacity_submission:
project = submission['lesson_key']
rating = submission['assigned_rating']
if project in subway_project_lesson_keys and (rating == 'PASSED' or rating == 'DISTINCTION'):
passed_subway_project.add(submission['account_key'])
print(len(passed_subway_project))
# +
passing_engagement = []
non_passing_engagement = []
for engagement in paid_engagement_in_first_week:
if engagement['account_key'] in passed_subway_project:
passing_engagement.append(engagement)
else:
non_passing_engagement.append(engagement)
len(passing_engagement)
len(non_passing_engagement)
# -
#for engagement_record in passing_engagement:
# print(engagement_record)
print(passing_engagement[10])
# +
#comparison between passing engagement and non-passing engagement
passing_engagement_group = group_data(passing_engagement,'account_key')
total_mins_for_passed_students = sum_grouped_items(passing_engagement_group,'total_minutes_visited')
print('Passing engagement total mins:')
describe_data(list(total_mins_for_passed_students.values()))
# -
non_passing_engagement_group = group_data(non_passing_engagement,'account_key')
total_mins_for_non_passed_students = sum_grouped_items(non_passing_engagement_group,'total_minutes_visited')
print('Non passing engagement total mins:')
describe_data(list(total_mins_for_non_passed_students.values()))
# +
total_lessons_completed_by_passed_students = sum_grouped_items(passing_engagement_group,'lessons_completed')
print('Passing engagement lessons:')
plt.hist(list(total_lessons_completed_by_passed_students.values()), bins = 20)
#describe_data(list(total_lessons_completed_by_passed_students.values()))
# +
import seaborn as sns
total_days_visited_by_passed_students = sum_grouped_items(passing_engagement_group,'has_visited')
print('Passing engagement days visited:')
plt.hist(list(total_days_visited_by_passed_students.values()),bins =8)
plt.xlabel('Number of days')
# -
non_passing_engagement_group = group_data(non_passing_engagement,'account_key')
total_lessons_completed_by_non_passed_students = sum_grouped_items(non_passing_engagement_group,'lessons_completed')
print('Non passing engagement lessons:')
describe_data(list(total_lessons_completed_by_non_passed_students.values()))
non_passing_engagement_group = group_data(non_passing_engagement,'account_key')
total_days_visited_by_non_passed_students = sum_grouped_items(non_passing_engagement_group,'has_visited')
print('Non passing engagement days visited:')
describe_data(list(total_days_visited_by_non_passed_students.values()))
| Lesson_1/csv_practice.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="B8RfLxsnMl_s"
# *It's custom ResNet trained demonstration purpose, not for accuracy.
# Dataset used is cats_vs_dogs dataset from tensorflow_dataset with **ImageDataGenerator** for data augmentation*
#
# ---
#
#
# + [markdown] id="WJFItf1FQFF7"
# ### **1. Importing Libraries**
#
#
#
#
# + id="uT5CUoUogPlA"
import tensorflow as tf
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Input, GlobalMaxPooling2D, add, ReLU
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.image import resize_with_pad, decode_jpeg, convert_image_dtype, decode_png
import tensorflow_datasets as tfds
import pandas as pd
import numpy as np
from tensorflow.keras import Model
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from PIL import Image
from tqdm.notebook import tqdm
import os
# %matplotlib inline
# + [markdown] id="7P1M6AcOQjjE"
# ### **2. Loading & Processing Data**
#
#
#
#
# + [markdown] id="vBNrLBE83NEv"
# ##### **Loading Data**
# + id="EcQDkjdEeQwR"
(train_ds, val_ds, test_ds), info = tfds.load(
'cats_vs_dogs',
split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],
with_info=True,
as_supervised=True)
# + [markdown] id="FqeID02aCn66"
# ###### **Note ->**
#
# Well, it is unhealthy to convert them into DataFrame that require quit memory. I did because I was trying to do some DataFrame transformation which was costlier than I thought.
# + id="-uBvOMzZqEAT"
train_ds = tfds.as_dataframe(train_ds, info)
val_ds = tfds.as_dataframe(val_ds, info)
test_ds = tfds.as_dataframe(test_ds, info)
# + id="5w5w8woc8vl0" colab={"base_uri": "https://localhost:8080/"} outputId="b7964b83-4a2c-4fb9-89d3-fbbbe36c5640"
info
# + colab={"base_uri": "https://localhost:8080/"} id="nMm74HB3GZ2y" outputId="adc83005-c7c5-4f0c-c7aa-8b2c69eef857"
train_ds.columns
# + id="KnAmtdA-wIMP"
## Function to save images
def pad_image(img, dest):
img = Image.fromarray(img) ## Opening Image File
img_size = img.size
target_size = max(img_size)
ratio = 1.0
new_size = tuple([int(x*ratio) for x in img_size])
img2 = img.resize(new_size, Image.ANTIALIAS)
new_img = Image.new("RGB", (target_size, target_size))
new_img.paste(img, ((target_size-new_size[0])//2,
(target_size-new_size[1])//2))
new_img.save(dest)
img.close()
img2.close()
new_img.close()
# + id="W7RORSpapE1m"
def pad_image2(img):
img = Image.fromarray(img) ## Opening Image File
img_size = img.size
target_size = max(img_size)
ratio = 1.0
new_size = tuple([int(x*ratio) for x in img_size])
img2 = img.resize(new_size, Image.ANTIALIAS)
new_img = Image.new("RGB", (target_size, target_size))
new_img.paste(img, ((target_size-new_size[0])//2,
(target_size-new_size[1])//2))
image = np.asarray(new_img, dtype=np.uint8)
#new_img.save(dest)
img.close()
img2.close()
new_img.close()
return image
# + colab={"base_uri": "https://localhost:8080/", "height": 287} id="lJNpk6cFeU4L" outputId="28b88828-f6bd-43d8-fac1-e728c0f69751"
s = train_ds.image[1]
s = pad_image2(s)
plt.imshow(s)
# + id="wFguh9s05YON"
## importand paths
train_dir = 'train/'
test_dir = 'test/'
val_dir = 'val/'
# + id="Dh-P7Ti3E8sD"
## Train image padding
if os.path.isdir(train_dir +'dog')!=True:
os.makedirs(train_dir +'dog')
if os.path.isdir(train_dir +'cat')!=True:
os.makedirs(train_dir +'cat')
for i, img in enumerate(train_ds.image):
new_name = 'train' + str(i) + '.jpg'
if train_ds.label[i]==1:
save_dir = train_dir +'cat/' + new_name
else:
save_dir = train_dir +'dog/' + new_name
pad_image(img, save_dir)
# + id="Ciqn4QYZ6eLl"
## Test image padding
if os.path.isdir(test_dir +'dog')!=True:
os.makedirs(test_dir +'dog')
if os.path.isdir(test_dir +'cat')!=True:
os.makedirs(test_dir +'cat')
for i, img in enumerate(test_ds.image):
new_name = 'test' + str(i) + '.jpg'
if test_ds.label[i]==1:
save_dir = test_dir +'cat/' + new_name
else:
save_dir = test_dir +'dog/' + new_name
pad_image(img, save_dir)
# + id="ZmTlnX-u6eAB"
## Vallidation image padding
if os.path.isdir(val_dir +'dog')!=True:
os.makedirs(val_dir +'dog')
if os.path.isdir(val_dir +'cat')!=True:
os.makedirs(val_dir +'cat')
for i, img in enumerate(val_ds.image):
new_name = 'val' + str(i) + '.jpg'
if val_ds.label[i]==1:
save_dir = val_dir +'cat/' + new_name
else:
save_dir = val_dir +'dog/' + new_name
pad_image(img, save_dir)
# + id="4NexH_VC_QUL"
# + [markdown] id="cwx8pyNIiDxy"
# #### **Data Augmentation**
#
#
#
#
# + id="MU2FnjdbziLU"
def normalization(img):
#img = np.asarray(img, dtype=np.uint8)
img = img/255.0
return img
# + id="J4a62J2nI5w-"
batch_size = 32
shape = (224, 224, 3)
training_steps = int(18610/batch_size)
testing_steps = int(2326/batch_size)
path = '/content/drive/MyDrive/Colab Notebooks/Model/cats_v_dogs.h5'
# + id="RPmm1qjIF1G5"
datagen = ImageDataGenerator(zoom_range = 0.1,
height_shift_range = 0.1,
width_shift_range = 0.1,
horizontal_flip=True,
preprocessing_function=normalization)
# + id="9Y9avJUQR5YR"
testgen = ImageDataGenerator(preprocessing_function=normalization)
# + id="3PAbxoZVYMC-" colab={"base_uri": "https://localhost:8080/"} outputId="9d8e5bb5-753c-497d-eff7-a1457bcebcf3"
train_ds = datagen.flow_from_directory('/content/train', target_size=(224, 224), batch_size=batch_size, shuffle=True)
test_ds = datagen.flow_from_directory('/content/test', target_size=(224, 224), batch_size=batch_size, shuffle=True)
val_ds = testgen.flow_from_directory('/content/val', target_size=(224, 224), batch_size=2326, shuffle=True)
# + [markdown] id="9a8WiBJYvH5O"
# ## **3. Creating Model**
# + [markdown] id="4NmlhIBQtPy7"
# ##### **Creating Residual block**
# + id="fXqH5p9JtPBZ"
def residual_block(x, feature_map, filter=(3,3) , _strides=(1,1), _neural_shortcut=False):
shortcut = x
x = Conv2D(feature_map, filter, strides=_strides, activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = Conv2D(feature_map, filter, strides=_strides, activation='relu', padding='same')(x)
x = BatchNormalization()(x)
# _neural_shortcut used directly when the input and output are of the same dimensions
if _neural_shortcut:
shortcut = Conv2D(feature_map, filter, strides=_strides, activation='relu', padding='same')(shortcut)
shortcut = BatchNormalization()(shortcut)
x = add([shortcut, x])
x = ReLU()(x)
return x
# + id="lDQ1SH_DCv5t"
# Build the model using the functional API
i = Input(shape)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(i)
x = BatchNormalization()(x)
x = residual_block(x, 32, filter=(3,3) , _strides=(1,1), _network_shortcut=False)
#x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
#x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = residual_block(x,64, filter=(3,3) , _strides=(1,1), _network_shortcut=False)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D((2, 2))(x)
x = Flatten()(x)
x = Dropout(0.2)(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.2)(x)
x = Dense(2, activation='softmax')(x)
model = Model(i, x)
# + id="uYX32wv46PUZ" colab={"base_uri": "https://localhost:8080/"} outputId="779215ec-6c52-4280-d682-e7f6996b3126"
model.compile()
model.summary()
# + [markdown] id="fak0KjtASMdd"
# ### **4. Optimizer and loss Function**
# + id="VboMfD9BoLcm"
# + id="tv2EtPA2j6nn"
loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True)
Optimiser = tf.keras.optimizers.Adam()
# + [markdown] id="dJDUJLAXSoZn"
# ### **5. Metrics For Loss and Acuracy**
# + id="_ZV_OLFelKHN"
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.BinaryAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name="test_loss")
test_accuracy = tf.keras.metrics.BinaryAccuracy(name='test_accuracy')
# + [markdown] id="Gk8eJelPTHA3"
# ### **6. Function for training and Testing**
# + id="tcbvePZavERI"
@tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
prediction = model(images, training=True)
loss = loss_object(labels,prediction)
gradient = tape.gradient(loss, model.trainable_variables)
Optimiser.apply_gradients(zip(gradient, model.trainable_variables))
train_loss(loss)
train_accuracy(labels, prediction)
# + id="UHkF3irCnJ4e"
@tf.function
def test_step(images, labels):
prediction = model(images, training = False)
t_loss = loss_object(labels, prediction)
test_loss(t_loss)
test_accuracy(labels, prediction)
# + [markdown] id="aroHrgIrTYSN"
# ### **7. Training Model**
# + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["473e8c9b52bf4defa7fad12f61aa56a8", "03a6c0e724484605937f6f50fd8bc1bd", "4afac732248b4155a93ca0e1568df5ac", "d3ac89e3ae0c4883a621e2be267a74b5", "f002d7de019047e2b316b7dd6eabb75f", "<KEY>", "fad49d4f708744ecbc0a2940050e6f17", "<KEY>", "e28c7af8634b481fa1e20330b8a24f5a", "ca0353951e1643989cb396cec9f32e8e", "3ae1b4019b9241789e40439ec3d3add3", "0ec43b1a4084482ebc9ce097274446cc", "c14db7a463054e1495dce763bf4d787e", "<KEY>", "95809e4c95c54029b0f085dfb3543884", "c45c2bb5064343579fa0dddade3addf6", "40257f8089f84246a1b4b9e213e9cce5", "95e76e8dc580456690a9d1e47ee039b3", "<KEY>", "<KEY>", "1625378d54264db6b463275860c9451e", "662458b5c4374a9da76d2bb0530338ae", "f4ac4126c4dc4f48ba86d6579ecfce24", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "bea8a0fca8c14164b0a6e7009338e841", "<KEY>", "a1fe4f83350c4c33a57b8106856483c6", "<KEY>", "8d26d7f6d92048e486dad2374b1d7237", "2e8e39f071fe4f06a135b9386d24999d", "b1e9fac67276413a98c9295319a6b189", "<KEY>", "03f3dbb5e18f4d6e860a77a66ff9fe98", "<KEY>", "05ff5ac12d8f4859904e19eded3d3117", "<KEY>", "598df7c2a1f94e36b77202e50f3dfa67", "<KEY>", "e375be1ffaf64203a364f34f15d18e74", "cf596e58574045ed8ae703180330072d", "d84385e5d638405aab3e7d741bed2084", "dd316af4ad5a416cbe1b5ce04ba07eff", "<KEY>", "<KEY>", "4662ee37f4c54407ac3576a5bb6045ff", "<KEY>", "81c0607017df463fa01baa8da85bb538", "ff08f3c9227a4ce2a58bcb8f4765c73e", "774bf0ecc5cc46e7bdd98837ea4453b8", "70c9f94e9cc34ee1977cc6cebeac729a", "d1603b9adf2245b5aa473ba141aafa7d", "<KEY>", "6ca1ac116ee4462a919ca234401940cb", "8907cec8ab7345e1b060156b15c0dd0a", "b527e34f13b644e1a7fe0b501d0a84d1", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "1b8f574adb3945b8ae4f3feee166b81a", "<KEY>", "<KEY>", "<KEY>", "81406bc630974ffdac41273475a46f6e", "<KEY>", "7e43e884b29e4235be81a8db2518e8f9", "61b7a2e1285443f08d020653ab271342", "50660aef733744049c59253f97ada63d", "<KEY>", "<KEY>", "1caefca33e3d43c98123b5a51f568f56", "44e68c420798439484f13866efd1ab09", "<KEY>", "547dbce481ef40f898879ab6908c69f6", "0663d2f92a48456986017661fd49544f", "e3d04b9d7bc44870a02d6e7cef23c4e0", "0ad2334cdba14e9a8aca117456db10af", "65340dee8a77447da973d20f029d274b", "311c3f342a1b4c5dac8e2c1ce8547dba", "e4117df7db744de799f827683e076b5c", "6ba11773b1154a4588ca17fbf1704500", "<KEY>", "e32ccba927104912b4e40da81b99719c", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "91b6f859a7d04b34a8cdc1410bade2b2", "<KEY>", "5813856f205c4a388670b4e27cee9a47", "<KEY>", "<KEY>", "<KEY>", "496a3b98e18f4c668831537d38a8a965", "771b139d50944f1f81f5c63354adbc63", "0a9a7ddd63674247b81ebbb5775deb75", "1eb100ab85334e0bbac47c74cfb85bde", "<KEY>", "<KEY>", "<KEY>", "42875aebed4d4f9aaa6ed7612001f417", "<KEY>", "f0ecaf297bf64535abe8481b3101197b", "a865f27ec0fc48908d7f0a26853d6bac", "<KEY>", "ca201c5f93034dfca00f517832aa70db", "<KEY>", "<KEY>", "6c60da0481a4426bafa32786f89eade1", "<KEY>", "91d2023ae9cf4d1e889efd165de76e3f", "<KEY>", "58fd1f7b1eaf4344a297ac8a58773c80", "<KEY>", "<KEY>", "acc316ffcd30480fab0a6445703775d7", "c696a641adec47c9b3ade7ff3a4ea226", "<KEY>", "94336efd3a4c43ef84a544fe8bbb7135", "4a29e4710a444750b79e739260bc8aad", "<KEY>", "f27cea2410a94e83ba9f23ac78956487", "97bbda215a8645878c597ad725ebd118", "a26b1eb396b74f4ca067d1d0f259f113", "<KEY>", "<KEY>", "36e45bbe9e5d43b987f5dbf1eef80ec8", "a15c86c3d8754369aa23f35f3a331902", "<KEY>", "b7eace2bf80e4607849af9a5b9ab0742", "2a3d0cf597644aa4a8c23dac55ea9668", "<KEY>", "1591dfde5ff944ed9641fee4bbc6e72d", "<KEY>", "8c6ae833db1943fdbf06a769f0eceb96", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "0d4cb093ecee4e0bac1a2845be1eda68", "b219c10f936f46a6ba4de453333671b2", "35adb3a20c59451ca9a824b432b50e28", "<KEY>", "<KEY>", "edac37272a6b48789e03a1c9238ba00c", "fe763142c5ef400f99262331cad8c31c", "6d40257673e14c8eb49676ff3d0d0999", "f83a7a8d8e644d46b9a0dec934ded077", "8655039cd6774e6fa237cfa20606886d", "c4a167656d8a488c8974c114058ddaf8", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "74d1a40ca276419da061e239056f34ff", "65d7c99c168e44a5b64f3b875e42cce3", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "edfb0d0bd7784c0d96f87e9f0a7220b2", "0bb2250942b84db2bfeec527e3c535e4", "<KEY>", "ed096d9f54ea4e9c9ea3639a5307e874", "<KEY>", "f75db1aa78724f078e64d0b53622e551", "<KEY>", "005c071acc784aaba0879015a2006a3d", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "e8a1a22cbd42408c9afa8db1a28ef3a0", "9826ce3e68d34f28b78d5f79a3eaf9c0", "f959e7743426483087fe5aae63158d6b", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "59fd97ec842e441bace9789314caf453", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "9b7efae75d7e4b62ab92e49ee60a919a", "<KEY>", "7c2899938109441793a3bd34d943156f", "514e6b189bec420c8d12951365fe9371", "849e35befd414b31a2fcf361a54468b0", "<KEY>", "0806982c81094ce28c27a5976c04f32f", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "447bbdbec7264694af13748c746e11e1", "<KEY>", "5b997a78f0a842379623a739509711f4", "c6f0bef5430049c3a1c0a588c9672765", "e07b0ac3796e4e7691002de081117996", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "b4f4ac6b98c64e03be522b001e417f15", "<KEY>", "<KEY>", "3f4cc418245d4612a5d8cc531ea69cb2", "<KEY>", "<KEY>", "3729fcbe3e72490b97632a9dcf65eef0", "<KEY>", "9d2b613bb994478ba4b80e5551f02964", "<KEY>", "f613812568a340ef8240b5524ea7c147", "<KEY>", "36d2aef21f8d4badb12692aa27d2ef6c", "ef4b3e2b7143423e899251b889653786", "<KEY>", "<KEY>", "7882bbe2930041eea2e18cf5205f4a95", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "8b3d51494a604c76a949d541d8b8aae5", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "afa5cae986314a429dcf942cabd1d806", "319959f3a48d44a7a69bb0a2f50c123c", "005810d9db98495c940beeda5d95b116", "34ce1237cebf4195915b9cad581a5db1", "ea1b69ed1f374820869222269269191f", "9a19853da2424f4295024cc84484e35a", "<KEY>", "<KEY>", "1b8ecfd6b9d1411faf60e584c0922fe9", "<KEY>", "daf77ded9d1e4afca5e59a9ca163379f", "<KEY>", "52d2d9ace1da4e9793a720a11eb58197", "a68cdda3455c45008dab352203a06842", "<KEY>", "67062757b6e04c4093df94c7982a1c40", "a6ec3bd1d2c041d3a8cde74defe31ce8", "d3633c43e4b849c4a98b7d044adefab4", "323f7016d7614aa3964f4f78bbaded18", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "3de411e0cbb641e09c613ce2d9f18a1d", "f0ab3824db3f4a929161660c73a4be90", "<KEY>", "1145d856e43d414a843b6bee8cb0edd6", "<KEY>", "be3dd09331e64cc9b8ba020cb1263ea9", "e56af0f1436d47388e9d4507343fc022", "9d2558127b4443ebab3277f664e2739e", "2ff9533057154291a067d1daeac38ad8", "be5d8edd97a040578096a239b7263923", "ba63d3fd776843b397c1a76c027edfdc", "c6f8e3320e5d42a481d2ad48edc7f519", "<KEY>", "e500063ad8194e4eb3f9e3a64d428d79", "<KEY>", "7104c2ac36eb41d8b02e1d86b7a8455c", "<KEY>", "<KEY>", "<KEY>", "5311e1831dd64f558f86b890eaa0eed8", "424ee944f3fe484f8182ffea4031bab9", "4f18a698344749fa86cd6d4040259a18", "6591feb91e62491292bef211f7a9c3b4", "cb08926d5e184728addd2df5621f974e"]} id="rx6KtgRvngNN" outputId="c0bdc242-1a00-47b0-b688-665bb07098c4"
EPOCHS = 36
Train_LOSS = []
TRain_Accuracy = []
Test_LOSS = []
Test_Accuracy = []
for epoch in range(EPOCHS):
train_loss.reset_states()
train_accuracy.reset_states()
test_loss.reset_states()
test_accuracy.reset_states()
print(f'Epoch : {epoch+1}')
count = 0 # variable to keep tab how much data steps of training
desc = "EPOCHS {:0>4d}".format(epoch+1)
for images, labels in tqdm(train_ds, total=training_steps, desc=desc):
if count < training_steps:
train_step(images, labels)
count+=1
else:
break
test_count = 0
for test_images, test_labels in test_ds:
if test_count < testing_steps :
test_step(test_images, test_labels)
test_count +=1
else:
break
print(
f'Loss: {train_loss.result()}, '
f'Accuracy: {train_accuracy.result()*100}, '
f'Test Loss: {test_loss.result()}, '
f'Test Accuracy: {test_accuracy.result()*100}'
)
Train_LOSS.append(train_loss.result())
TRain_Accuracy.append(train_accuracy.result()*100)
Test_LOSS.append(test_loss.result())
Test_Accuracy.append(test_accuracy.result()*100)
### Implementing CallBack
if epoch==0:
min_Loss = test_loss.result()
min_Accuracy = test_accuracy.result()*100
elif (min_Loss>test_loss.result()):
if (min_Accuracy <= test_accuracy.result()*100) :
min_Loss = test_loss.result()
min_Accuracy = ( test_accuracy.result()*100)
print(f"Saving Best Model {epoch+1}")
model.save_weights(path) # Saving Model To drive
# + [markdown] id="GGsV0OJwZB1H"
# ### **8. Ploting Loss and Accuracy Per Iteration**
# + id="A84-OC64WdJ3" colab={"base_uri": "https://localhost:8080/", "height": 299} outputId="b0c1c1a3-3b0d-4efe-a92d-dfd5455ec1de"
# Plot loss per iteration
plt.plot(Train_LOSS, label='loss')
plt.plot(Test_LOSS, label='val_loss')
plt.title('Plot loss per iteration')
plt.legend()
# + id="6DD26kXBYnwh" colab={"base_uri": "https://localhost:8080/", "height": 299} outputId="3fca9fd8-9f76-465d-ab06-2594dd8e96cc"
# Plot Accuracy per iteration
plt.plot(TRain_Accuracy, label='loss')
plt.plot(Test_Accuracy, label='val_loss')
plt.title('Plot Accuracy per iteration')
plt.legend()
# + [markdown] id="A3qso3V3AV6d"
# ## 9. Evoluting model
# + id="DuQMe4iCLpys"
model.load_weights('/content/drive/MyDrive/Colab Notebooks/Model/cats_v_dogs.h5')
# + id="ntTNiHdJ_zY0"
for images, labels in val_ds:
prediction = model.predict(images)
break
# + id="LEMnw30rRCsb"
def accuracy(prediction, labels):
corect =0
for i in range(len(prediction)):
pred = prediction[i]
labe = labels[i]
if pred[0]>pred[1] and labe[0]>labe[1]:
corect+=1
elif pred[0]<pred[1] and labe[0]<labe[1]:
corect+=1
return (corect/len(prediction))*100
# + colab={"base_uri": "https://localhost:8080/"} id="i4QltEiZTQGH" outputId="85f2b534-4bad-4773-e68e-8cf82f4c372f"
print(accuracy(prediction, labels))
| CustomResnet_2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] papermill={"duration": 0.015704, "end_time": "2021-09-13T20:16:11.385653", "exception": false, "start_time": "2021-09-13T20:16:11.369949", "status": "completed"} tags=[]
# # Introduction
#
# In this micro-course, you'll learn all about **[pandas](https://pandas.pydata.org)**, the most popular Python library for data analysis.
#
# Along the way, you'll complete several hands-on exercises with real-world data. We recommend that you work on the exercises while reading the corresponding tutorials.
#
# **To start the first exercise, please click [here](https://www.kaggle.com/kernels/fork/587970).**
#
# In this tutorial, you will learn how to create your own data, along with how to work with data that already exists.
#
# # Getting started
#
# To use pandas, you'll typically start with the following line of code.
# + papermill={"duration": 0.026952, "end_time": "2021-09-13T20:16:11.427889", "exception": false, "start_time": "2021-09-13T20:16:11.400937", "status": "completed"} tags=[]
import pandas as pd
# + [markdown] papermill={"duration": 0.013219, "end_time": "2021-09-13T20:16:11.454985", "exception": false, "start_time": "2021-09-13T20:16:11.441766", "status": "completed"} tags=[]
# # Creating data
#
# There are two core objects in pandas: the **DataFrame** and the **Series**.
#
# ### DataFrame
#
# A DataFrame is a table. It contains an array of individual *entries*, each of which has a certain *value*. Each entry corresponds to a row (or *record*) and a *column*.
#
# For example, consider the following simple DataFrame:
# + papermill={"duration": 0.036299, "end_time": "2021-09-13T20:16:11.504893", "exception": false, "start_time": "2021-09-13T20:16:11.468594", "status": "completed"} tags=[]
pd.DataFrame({'Yes': [50, 21], 'No': [131, 2]})
# + [markdown] papermill={"duration": 0.014729, "end_time": "2021-09-13T20:16:11.534046", "exception": false, "start_time": "2021-09-13T20:16:11.519317", "status": "completed"} tags=[]
# In this example, the "0, No" entry has the value of 131. The "0, Yes" entry has a value of 50, and so on.
#
# DataFrame entries are not limited to integers. For instance, here's a DataFrame whose values are strings:
# + papermill={"duration": 0.025706, "end_time": "2021-09-13T20:16:11.574602", "exception": false, "start_time": "2021-09-13T20:16:11.548896", "status": "completed"} tags=[]
pd.DataFrame({'Bob': ['I liked it.', 'It was awful.'], 'Sue': ['Pretty good.', 'Bland.']})
# + [markdown] papermill={"duration": 0.016773, "end_time": "2021-09-13T20:16:11.607675", "exception": false, "start_time": "2021-09-13T20:16:11.590902", "status": "completed"} tags=[]
# We are using the `pd.DataFrame()` constructor to generate these DataFrame objects. The syntax for declaring a new one is a dictionary whose keys are the column names (`Bob` and `Sue` in this example), and whose values are a list of entries. This is the standard way of constructing a new DataFrame, and the one you are most likely to encounter.
# + [markdown] papermill={"duration": 0.015073, "end_time": "2021-09-13T20:16:11.643683", "exception": false, "start_time": "2021-09-13T20:16:11.628610", "status": "completed"} tags=[]
# The dictionary-list constructor assigns values to the *column labels*, but just uses an ascending count from 0 (0, 1, 2, 3, ...) for the *row labels*. Sometimes this is OK, but oftentimes we will want to assign these labels ourselves.
#
# The list of row labels used in a DataFrame is known as an **Index**. We can assign values to it by using an `index` parameter in our constructor:
# + papermill={"duration": 0.028552, "end_time": "2021-09-13T20:16:11.692274", "exception": false, "start_time": "2021-09-13T20:16:11.663722", "status": "completed"} tags=[]
pd.DataFrame({'Bob': ['I liked it.', 'It was awful.'],
'Sue': ['Pretty good.', 'Bland.']},
index=['Product A', 'Product B'])
# + [markdown] papermill={"duration": 0.0162, "end_time": "2021-09-13T20:16:11.723595", "exception": false, "start_time": "2021-09-13T20:16:11.707395", "status": "completed"} tags=[]
# ### Series
#
# A Series, by contrast, is a sequence of data values. If a DataFrame is a table, a Series is a list. And in fact you can create one with nothing more than a list:
# + papermill={"duration": 0.024798, "end_time": "2021-09-13T20:16:11.763771", "exception": false, "start_time": "2021-09-13T20:16:11.738973", "status": "completed"} tags=[]
pd.Series([1, 2, 3, 4, 5])
# + [markdown] papermill={"duration": 0.015665, "end_time": "2021-09-13T20:16:11.795324", "exception": false, "start_time": "2021-09-13T20:16:11.779659", "status": "completed"} tags=[]
# A Series is, in essence, a single column of a DataFrame. So you can assign column values to the Series the same way as before, using an `index` parameter. However, a Series does not have a column name, it only has one overall `name`:
# + papermill={"duration": 0.026622, "end_time": "2021-09-13T20:16:11.837890", "exception": false, "start_time": "2021-09-13T20:16:11.811268", "status": "completed"} tags=[]
pd.Series([30, 35, 40], index=['2015 Sales', '2016 Sales', '2017 Sales'], name='Product A')
# + [markdown] papermill={"duration": 0.019324, "end_time": "2021-09-13T20:16:11.874495", "exception": false, "start_time": "2021-09-13T20:16:11.855171", "status": "completed"} tags=[]
# The Series and the DataFrame are intimately related. It's helpful to think of a DataFrame as actually being just a bunch of Series "glued together". We'll see more of this in the next section of this tutorial.
# + [markdown] papermill={"duration": 0.016407, "end_time": "2021-09-13T20:16:11.910220", "exception": false, "start_time": "2021-09-13T20:16:11.893813", "status": "completed"} tags=[]
# # Reading data files
#
# Being able to create a DataFrame or Series by hand is handy. But, most of the time, we won't actually be creating our own data by hand. Instead, we'll be working with data that already exists.
#
# Data can be stored in any of a number of different forms and formats. By far the most basic of these is the humble CSV file. When you open a CSV file you get something that looks like this:
#
# ```
# Product A,Product B,Product C,
# 30,21,9,
# 35,34,1,
# 41,11,11
# ```
#
# So a CSV file is a table of values separated by commas. Hence the name: "Comma-Separated Values", or CSV.
#
# Let's now set aside our toy datasets and see what a real dataset looks like when we read it into a DataFrame. We'll use the `pd.read_csv()` function to read the data into a DataFrame. This goes thusly:
# + papermill={"duration": 1.796263, "end_time": "2021-09-13T20:16:13.722895", "exception": false, "start_time": "2021-09-13T20:16:11.926632", "status": "completed"} tags=[]
wine_reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv")
# + [markdown] papermill={"duration": 0.016653, "end_time": "2021-09-13T20:16:13.757008", "exception": false, "start_time": "2021-09-13T20:16:13.740355", "status": "completed"} tags=[]
# We can use the `shape` attribute to check how large the resulting DataFrame is:
# + papermill={"duration": 0.024223, "end_time": "2021-09-13T20:16:13.797689", "exception": false, "start_time": "2021-09-13T20:16:13.773466", "status": "completed"} tags=[]
wine_reviews.shape
# + [markdown] papermill={"duration": 0.01627, "end_time": "2021-09-13T20:16:13.830774", "exception": false, "start_time": "2021-09-13T20:16:13.814504", "status": "completed"} tags=[]
# So our new DataFrame has 130,000 records split across 14 different columns. That's almost 2 million entries!
#
# We can examine the contents of the resultant DataFrame using the `head()` command, which grabs the first five rows:
# + papermill={"duration": 0.039421, "end_time": "2021-09-13T20:16:13.886810", "exception": false, "start_time": "2021-09-13T20:16:13.847389", "status": "completed"} tags=[]
wine_reviews.head()
# + [markdown] papermill={"duration": 0.017445, "end_time": "2021-09-13T20:16:13.921815", "exception": false, "start_time": "2021-09-13T20:16:13.904370", "status": "completed"} tags=[]
# The `pd.read_csv()` function is well-endowed, with over 30 optional parameters you can specify. For example, you can see in this dataset that the CSV file has a built-in index, which pandas did not pick up on automatically. To make pandas use that column for the index (instead of creating a new one from scratch), we can specify an `index_col`.
# + papermill={"duration": 1.072494, "end_time": "2021-09-13T20:16:15.012446", "exception": false, "start_time": "2021-09-13T20:16:13.939952", "status": "completed"} tags=[]
wine_reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
wine_reviews.head()
# + [markdown] papermill={"duration": 0.017822, "end_time": "2021-09-13T20:16:15.048425", "exception": false, "start_time": "2021-09-13T20:16:15.030603", "status": "completed"} tags=[]
# # Your turn
#
# If you haven't started the exercise, you can **[get started here](https://www.kaggle.com/kernels/fork/587970)**.
| course/Pandas/creating-reading-and-writing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Create a Word Document
# Let's imagine in this hypothetical situation, a client sends the billing group a note saying that the client is undergoing a review of their legal fees and needs the supplied document completed for each invoice of theirs for the next 12 months. You could handle that in a number of ways, but since you're getting so good at Python you wonder - can I do that? Let's take a look.
#
# See the file in this folder called `client_supplied_LegalFeesSheet`. This is what the client wants and it must be in that form. We'll take a copy and mark it up filling it in with data from 3E.
import os
import sys
import pyodbc
elite_db_server = os.environ['ELITE_PROD_HOST']
elite_db = os.environ['ELITE_PROD_DB']
elite_user = os.environ['ELITE_RO_NAME']
elite_pass = os.environ['ELITE_RO_PASS']
cursor.close()
conn_str = (f'DRIVER={{FreeTDS}};SERVER={elite_db_server};'
f'PORT=1433;DATABASE={elite_db};UID={elite_user};'
f'PWD={<PASSWORD>};TDS_Version=8.0;ClientCharset=UTF-8')
conn_3e = pyodbc.connect(conn_str)
# We look at the data they are requesting and build some sql statements to get the data. Depending on how you use 3E, these may be altered slightly for your situation.
#
# The first two sections `Matter` and `This Invoice` we can do with a simple query.
sql_invoice = """
select
InvMaster.InvNumber,
InvMaster.InvDate,
InvMaster.OrgFee,
isnull(InvMaster.OrgSCo,0) + isnull(InvMaster.OrgHCo,0) 'OrgCosts',
InvMaster.OrgTax,
Matter.Number,
Matter.DisplayName,
Matter.OpenDate
from ProfMaster
join InvMaster on InvMaster.InvIndex = ProfMaster.InvMaster
join Matter on Matter.MattIndex = ProfMaster.LeadMatter
where InvMaster.InvNumber = ?
"""
invoice_number = '2019123456' # enter an invoice number
cursor = conn_3e.cursor()
invoice_results = cursor.execute(sql_invoice, (invoice_number,))
# Before we go too far, in the [Interacting with SQL](Interacting%20with%20SQL.ipynb) notebook I mentioned converting the results to a dictionary. Let's use such a function here.
def results_to_dict(results):
columns = [column[0] for column in results.description]
records = []
for row in results.fetchall():
records.append(dict(zip(columns, row)))
return records
invoice_detail = results_to_dict(invoice_results)
invoice_detail
# Great, now lets get that little summary of timekeepers.
sql_fee_summary = """
select
Title.Description 'Title',
timekeeper.BillName,
sum(ProfDetail.PresHrs) 'SumPresHours',
ProfDetail.PresRate
from ProfMaster
join ProfDetail on ProfDetail.ProfMaster = ProfMaster.ProfIndex
join ProfDetailTime on ProfDetail.ProfDetailID = ProfDetailTime.ProfDetailTimeID
join Timekeeper on ProfDetail.PresTimekeeper = Timekeeper.TkprIndex
join TkprDate on TkprDate.TimekeeperLkUp = Timekeeper.TkprIndex
and ProfDetail.WorkDate between TkprDate.NxStartDate and TkprDate.NxEndDate
join Title on Title.Code = TkprDate.Title
join BaseAppSetup TitleBase on TitleBase.BaseAppSetupID = Title.TitleID
where ProfDetail.IsDisplay = 1
and ProfMaster.InvNumber = ?
group by TitleBase.SortString, Title.Description, Timekeeper.BillName, ProfDetail.PresRate
order by TitleBase.SortString, sum(ProfDetail.PresHrs)*ProfDetail.PresRate desc """
cursor = conn_3e.cursor()
fee_summary_results = cursor.execute(sql_fee_summary, (invoice_number,))
fee_summary_details = results_to_dict(fee_summary_results)
fee_summary_details
# Okay, so now, like in the earlier Notebooks we need to install a library to help us out. This time it is called `docxtmp`. Take a look at the [documentation](https://docxtpl.readthedocs.io/en/latest/) for an indepth look at this little libary.
#
# We're going to take the form given to us by the client and mark it up so it will work for us. See that marked up version as `LegalFeesSheet.docx`.
# !{sys.executable} -m pip install docxtpl
# +
from docxtpl import DocxTemplate
doc = DocxTemplate("LegalFeesSheet.docx")
context = {'invoice':invoice_detail[0],
'fees': fee_summary_details, }
doc.render(context)
doc.save("generated_LegalFeesSheet.docx")
# -
# Now, if you look in your folder where you are saving these notebooks, there should be a `generated_LegalFeesSheet.docx` file with results.
#
# ## Conclusion
# In this Notebook, we've set up a connection to our Elite database server, run some SQL queries and output the results to a Word Document (docx).
#
# -30-
| Create a Word Document.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## <small>
# Copyright (c) 2017-21 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# </small>
#
#
#
# # Deep Learning: A Visual Approach
# ## by <NAME>, https://glassner.com
# ### Order: https://nostarch.com/deep-learning-visual-approach
# ### GitHub: https://github.com/blueberrymusic
# ------
#
# ### What's in this notebook
#
# This notebook is provided as a “behind-the-scenes” look at code used to make some of the figures in this chapter. It is cleaned up a bit from the original code that I hacked together, and is only lightly commented. I wrote the code to be easy to interpret and understand, even for those who are new to Python. I tried never to be clever or even more efficient at the cost of being harder to understand. The code is in Python3, using the versions of libraries as of April 2021.
#
# This notebook may contain additional code to create models and images not in the book. That material is included here to demonstrate additional techniques.
#
# Note that I've included the output cells in this saved notebook, but Jupyter doesn't save the variables or data that were used to generate them. To recreate any cell's output, evaluate all the cells from the start up to that cell. A convenient way to experiment is to first choose "Restart & Run All" from the Kernel menu, so that everything's been defined and is up to date. Then you can experiment using the variables, data, functions, and other stuff defined in this notebook.
# ## Chapter 2: Essential Statistics
#
# Miscellaneous figures for Chapter 2
# +
# %matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import math
import seaborn as sns ; sns.set()
# +
# Make a File_Helper for saving and loading files.
save_files = False
import os, sys, inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.dirname(current_dir)) # path to parent dir
from DLBasics_Utilities import File_Helper
file_helper = File_Helper(save_files)
# -
matplotlib.rcParams['axes.titlesize'] = 14
matplotlib.rcParams['axes.labelsize'] = 14
matplotlib.rcParams['axes.labelpad'] = 8
matplotlib.rcParams['xtick.labelsize'] = 14
matplotlib.rcParams['ytick.labelsize'] = 14
# Show the number of different types of vehicles on the lot
fig = plt.figure(figsize=(6,4))
car_names = ['Sedan', 'Pickup', 'Minivan', 'SUV', 'Wagon']
heights = [113, 245, 327, 83, 181]
xp = range(len(car_names))
plt.bar(xp, heights, align='center')
plt.xticks(xp, car_names)
plt.yticks([0, 100, 200, 300],[0, 100, 200, 300])
plt.xlabel('Variety of Car')
plt.ylabel('Number of cars')
plt.title('Available Cars')
file_helper.save_figure('car-bars')
plt.show()
# scale the vehicle probabilities so they add to 1
fig = plt.figure(figsize=(6,4))
car_names = ['Sedan', 'Pickup', 'Minivan', 'SUV', 'Wagon']
heights = [113, 245, 327, 83, 181]
heights = heights/np.sum(heights)
xp = range(len(car_names))
plt.bar(xp, heights, align='center')
plt.xticks(xp, car_names)
plt.yticks([0, .33, .66, 1],[0, '1/3', '2/3', 1])
plt.xlabel('Variety of Car')
plt.ylabel('Probability of Choosing This Type')
plt.title('Available Cars As Probability Distribution')
file_helper.save_figure('car-bars-normalized')
plt.show()
# +
# draw a nice continuous distribution
def continuous_dist(x):
v1 = 0.7 * np.exp(0.6 * -np.power(8*(x-0.25), 2))
v2 = 1.3 * np.exp(1.0 * -np.power(6*(x-0.8), 2))
return v1+v2
xs = np.linspace(0, 1, 130)
ys = [continuous_dist(x) for x in xs]
# Thanks <NAME> for pointing out I didn't correctly
# normalize the curve in the original version of this notebook.
box_width = xs[1]-xs[0] # the width of one box
total_area = box_width * np.sum(ys) # the sum of the areas of all the boxes
normalized_ys = ys / total_area
plt.plot(xs, normalized_ys, lw=2)
plt.xlabel('Amount of oil in the car')
plt.ylabel('Probability density of amount of oil')
file_helper.save_figure('continuous-pdf')
plt.show()
# +
# Draw the graph for a uniform distribution [0,1]
plt_blue = '#4d74ae' # matplotlib default blue
plt.plot([-1.5, -0.05],[0,0], c=plt_blue)
plt.scatter([0],[0], s=130, facecolors='none', edgecolors=plt_blue, lw=2)
plt.scatter([0],[1], s=130, c=plt_blue)
plt.plot([0,1],[1,1], c=plt_blue)
plt.scatter([1],[1], s=130, c=plt_blue)
plt.scatter([1],[0], s=130, facecolors='none', edgecolors=plt_blue, lw=2)
plt.plot([1.05, 1.5],[0,0], c=plt_blue)
plt.xlim(-1.5, 1.5)
plt.ylim(-.1, 1.1)
file_helper.save_figure('uniform-box-distribution')
plt.show()
# -
# Height of a Gaussian (mu, sigma-squared) at x
def gaussian(x, mu, sigma2):
s2 = 2*sigma2
f = 1/math.sqrt(math.pi * s2)
g = np.power((x-mu), 2)/s2
return f * np.exp(-g)
# +
# Show a bunch of different Gaussians
xs = np.linspace(-3, 3, 200)
mu_list = [0, 1, -1, -1]
sigma_list = [0.3, 0.3, 0.15, 1.4] # really sigma^2
plt.figure(figsize=(8,5))
subplot_num = 1
for mu, sigma in zip(mu_list, sigma_list):
plt.subplot(2, 2, subplot_num)
ys = [gaussian(x, mu, sigma) for x in xs]
plt.plot(xs, ys, lw=2)
plt.ylim(-0.1, 1.1)
plt.title('ABCD'[subplot_num-1])
subplot_num += 1
plt.tight_layout()
file_helper.save_figure('gaussians')
plt.show()
# +
# Show points randomly drawn from the Gaussians above
file_helper.save_figures = True
np.random.seed(45)
xs = np.linspace(-3, 3, 200)
mu_list = [0, 1, -1, -1]
sigma_list = [0.3, 0.3, 0.15, 1.4]
plt.figure(figsize=(8,5))
subplot_num = 1
num_samples = 50
for mu, sigma in zip(mu_list, sigma_list):
plt.subplot(2, 2, subplot_num)
ys = [gaussian(x, mu, sigma) for x in xs]
plt.plot(xs, ys, lw=2)
drawn_samples = np.random.normal(loc=mu, scale=math.sqrt(sigma), size=num_samples)
plt.scatter(drawn_samples, np.random.uniform(-.05, .05, len(drawn_samples)), c='red', s=30)
plt.ylim(-0.1, 1.1)
plt.xlim(-3, 3)
plt.title('ABCD'[subplot_num-1])
subplot_num += 1
plt.tight_layout()
file_helper.save_figure('gaussians-with-samples')
plt.show()
# +
# Show means of the Gaussians above
xs = np.linspace(-3, 3, 200)
mu_list = [0, 1, -1, -1]
sigma_list = [0.3, 0.3, 0.15, 1.4]
plt.figure(figsize=(8,5))
subplot_num = 1
for mu, sigma in zip(mu_list, sigma_list):
plt.subplot(2, 2, subplot_num)
ys = [gaussian(x, mu, sigma) for x in xs]
plt.plot(xs, ys, lw=2)
plt.plot([mu, mu],[0,gaussian(mu, mu, sigma)], lw=2, color='#E84F69')
plt.ylim(-0.1, 1.1)
plt.title('ABCD'[subplot_num-1])
subplot_num += 1
plt.tight_layout()
file_helper.save_figure('gaussians-with-means')
plt.show()
# +
# Show standard deviations
xs = np.linspace(-3, 3, 200)
mu_list = [0, 1, -1, -1]
sigma_list = [0.3, 0.3, 0.15, 1.4]
plt.figure(figsize=(8,5))
subplot_num = 1
for mu, sigma in zip(mu_list, sigma_list):
plt.subplot(2, 2, subplot_num)
ys = [gaussian(x, mu, sigma) for x in xs]
plt.plot(xs, ys, lw=2)
plt.plot([mu, mu],[0,gaussian(mu, mu, sigma)], color='#E84F69', lw=2, zorder=10)
plt.plot([mu-sigma,mu-sigma],[0,gaussian(mu-sigma, mu, sigma)], lw=2, color='#386F40')
plt.plot([mu+sigma,mu+sigma],[0,gaussian(mu+sigma, mu, sigma)], lw=2, color='#386F40')
fill_xs = np.linspace(mu-sigma, mu+sigma, 50)
fill_ys = [gaussian(x, mu, sigma) for x in fill_xs]
ax = plt.gca()
ax.fill_between(fill_xs, 0, fill_ys, facecolor='#386F40', alpha=0.5, zorder=20)
plt.ylim(-0.1, 1.1)
plt.title('ABCD'[subplot_num-1])
subplot_num += 1
plt.tight_layout()
file_helper.save_figure('gaussians-with-stddevs')
plt.show()
# +
# Show 1, 2, and 3 standard deviations
xs = np.linspace(-3, 3, 200)
mu = 0
sigma = 0.5
ys = [gaussian(x, mu, sigma) for x in xs]
fig = plt.figure()
ax = plt.gca()
plt.plot(xs, ys, lw=2)
plt.plot([mu, mu],[0,gaussian(mu, mu, sigma)], lw=2, color='#E84F69', zorder=20)
for steps in [1, 2, 3]:
sigma_n = steps * sigma
plt.plot([mu-sigma_n,mu-sigma_n],[0,gaussian(mu-sigma_n, mu, sigma)], lw=2, color='#222222', zorder=20)
plt.plot([mu+sigma_n,mu+sigma_n],[0,gaussian(mu+sigma_n, mu, sigma)], lw=2, color='#222222', zorder=20)
fill_xs = np.linspace(mu-sigma_n, mu+sigma_n, 50)
fill_ys = [gaussian(x, mu, sigma) for x in fill_xs]
ax.fill_between(fill_xs, 0, fill_ys, facecolor='#386F40', alpha=0.5, zorder=10)
# On my system thsese sigma characters come out ugly, so replace them in Illustrator
plt.ylim(-0.1, 1.1)
plt.xticks([-3*sigma,-2*sigma,-sigma,0,sigma,2*sigma,3*sigma],
['3 $\sigma$','2 $\sigma$', '$\sigma$', 0, '$\sigma$', '2 $\sigma$', '3 $\sigma$'])
file_helper.save_figure('gaussian-multi-stddevs')
plt.show()
# +
# Bernoulli distribution
fig = plt.figure(figsize=(7,4))
plt.subplot(1, 2, 1)
barlist = plt.bar([0,1],[.5,.5], align='center')
barlist[0].set_color('#ae844d')
plt.xticks([0,1],['Heads','Tails'])
plt.yticks([0,.5,1],[0,.5,1])
plt.ylim(0, 1)
plt.xlabel('Outcome')
plt.ylabel('Probability')
plt.title('A Fair Coin')
plt.subplot(1, 2, 2)
barlist = plt.bar([0,1],[.3,.7], align='center')
barlist[0].set_color('#ae844d')
plt.xticks([0,1],['Heads','Tails'])
plt.yticks([0,.5,1],[0,.5,1])
plt.ylim(0, 1)
plt.xlabel('Outcome')
plt.ylabel('Probability')
plt.title('An Unfair Coin')
plt.tight_layout()
file_helper.save_figure('bernoulli')
plt.show()
# +
# Show the histograms for bootstrapping discussion
def get_population(num_elements, low, high):
population = []
for i in range(num_elements):
element = int(np.random.uniform(low, high))
population.append(element)
return population
def get_sample_set(population, num_elements):
sample_set = np.random.choice(a=population, size=num_elements, replace=False)
return sample_set
def get_bootstrap(sample_set, num_elements):
bootstrap = np.random.choice(a=sample_set, size=num_elements, replace=True)
return bootstrap
def do_bootstraps(population_size, population_range, sample_set_size, bootstrap_size, num_boostraps):
np.random.seed(42)
population = get_population(population_size, 0, population_range)
sample_set = get_sample_set(population, sample_set_size)
bootstrap_list = []
for i in range(num_boostraps):
bootstrap = get_bootstrap(sample_set, bootstrap_size)
bootstrap_list.append(bootstrap)
population_mean = np.mean(population)
sample_set_mean = np.mean(sample_set)
bootstrap_means = [np.mean(bootstrap) for bootstrap in bootstrap_list]
n, bins, hpatches = plt.hist(bootstrap_means, 50, color='#FFC07A')
plt.plot([sample_set_mean, sample_set_mean], [0, max(n)], color='#00638C', lw=4)
plt.plot([population_mean, population_mean], [0, max(n)], color='#BD3A50', lw=4)
plt.title('Histogram of Bootstrap Means')
plt.xlabel('Mean value of bootstrap')
plt.ylabel('Number of bootstraps')
file_helper.save_figure('bootstrap-histogram')
plt.show()
n, bins, hpatches = plt.hist(bootstrap_means, 50, color='#FFC07A')
plt.plot([sample_set_mean, sample_set_mean], [0, max(n)], color='#00638C', lw=4)
plt.plot([population_mean, population_mean], [0, max(n)], color='#BD3A50', lw=4)
confidence = 0.8
gap = (1-confidence)/2
sorted_bootstrap_means = sorted(bootstrap_means)
low_index = int(gap * len(sorted_bootstrap_means))
high_index = int((1-gap) * len(sorted_bootstrap_means))
low_value = sorted_bootstrap_means[low_index]
high_value = sorted_bootstrap_means[high_index]
rect_left = low_value
rect_bottom = 0
rect_width = high_value-low_value
rect_height = max(n)
currentAxis = plt.gca()
conf_rect = patches.Rectangle((rect_left, rect_bottom),
rect_width, rect_height, facecolor="yellow",
alpha=0.25, lw=2)
currentAxis.add_patch(conf_rect)
plt.title('Histogram of Bootstrap Means with Confidence of '+str(int(100*confidence))+'%')
plt.xlabel('Mean value of bootstrap')
plt.ylabel('Number of bootstraps')
file_helper.save_figure('bootstrap-histogram-confidence')
plt.show()
do_bootstraps(population_size=5000, population_range=1000,
sample_set_size=500, bootstrap_size=20, num_boostraps=1000)
# +
# Data for the Anscombe quartet
Anscombe = [
[
[10.0, 8.04], [8.0, 6.95], [13.0, 7.58], [9.0, 8.81], [11.0, 8.33],
[14.0, 9.96], [6.0, 7.24], [4.0, 4.26], [12.0, 10.84], [7.0, 4.82], [5.0, 5.68]
],[
[10.0, 9.14], [8.0, 8.14], [13.0, 8.74], [9.0, 8.77], [11.0, 9.26],
[14.0, 8.10], [6.0, 6.13], [4.0, 3.10], [12.0, 9.13], [7.0, 7.26], [5.0, 4.74]
],[
[10.0, 7.46], [8.0, 6.77], [13.0, 12.74], [9.0, 7.11], [11.0, 7.81],
[14.0, 8.84], [6.0, 6.08], [4.0, 5.39], [12.0, 8.15], [7.0, 6.42], [5.0, 5.73]
],[
[8.0, 6.58], [8.0, 5.76], [8.0, 7.71], [8.0, 8.84], [8.0, 8.47],
[8.0, 7.04], [8.0, 5.25], [19.0, 12.50], [8.0, 5.56], [8.0, 7.91], [8.0, 6.89]
]
]
Anscombe_clrs = ['#730046', '#FFCD30', '#E88E34', '#C93F0F']
Anscombe_markers = ['o', '^', 's', 'D']
# -
# print statistics for the Anscombe quartet
for dataset in range(4):
xs = [v[0] for v in Anscombe[dataset]]
ys = [v[1] for v in Anscombe[dataset]]
xmean = np.mean(xs)
xstd = np.std(xs)
ymean = np.mean(ys)
ystd = np.std(ys)
corr = np.corrcoef(xs, ys)
line = np.polyfit(xs, ys, 1)
print("---- quartet ",dataset)
print("xmean= %3.2f x stddev= %3.2f" % (xmean, xstd))
print("ymean= %3.2f y stddev= %3.2f" % (ymean, ystd))
print("correlation x and y = %3.2f" % corr[0][1])
print("best line slope %3.2f and intercept %3.2f" % (line[0], line[1]))
# +
# show the Anscombe quartet
fig = plt.figure(figsize=(12,8))
for dataset in range(4):
xs = [v[0] for v in Anscombe[dataset]]
ys = [v[1] for v in Anscombe[dataset]]
plt.subplot(2, 2, dataset+1)
plt.scatter(xs, ys, s=120, marker=Anscombe_markers[dataset], c=Anscombe_clrs[dataset])
line = np.polyfit(xs, ys, 1)
plt.plot([4,20],[(4*line[0])+line[1], (20*line[0])+line[1]])
plt.xlim(2, 22)
plt.ylim(4, 14)
file_helper.save_figure('anscombe-quartet')
plt.show()
# +
# show all four dataset in the Anscombe quartet
for dataset in range(4):
xs = [v[0] for v in Anscombe[dataset]]
ys = [v[1] for v in Anscombe[dataset]]
plt.scatter(xs, ys, s=120, marker=Anscombe_markers[dataset], c=Anscombe_clrs[dataset])
line = np.polyfit(xs, ys, 1)
plt.plot([4,20],[(4*line[0])+line[1], (20*line[0])+line[1]])
plt.xlim(2, 22)
plt.ylim(4, 14)
file_helper.save_figure('anscombe-quartet-superimposed')
plt.show()
# -
| Notebooks/Chapter02-EssentialStatistics/Chapter-02-Statistics.ipynb |
// ---
// jupyter:
// jupytext:
// text_representation:
// extension: .cpp
// format_name: light
// format_version: '1.5'
// jupytext_version: 1.14.4
// kernelspec:
// display_name: C++14
// language: C++14
// name: xeus-cling-cpp14
// ---
// + deletable=false editable=false nbgrader={"checksum": "57e648c5f13c45c665ce2af6e221b7e7", "grade": false, "grade_id": "cell-9783944a2d477680", "locked": true, "schema_version": 1, "solution": false}
#include <iostream>
// + deletable=false editable=false nbgrader={"checksum": "cac11986b9ae586fdf49ea08a8d4a250", "grade": false, "grade_id": "cell-784db4648f7e4753", "locked": true, "schema_version": 1, "solution": false}
using namespace std;
// + deletable=false editable=false nbgrader={"checksum": "00834ae57e950bd47ace251ea3085e7e", "grade": false, "grade_id": "cell-537b715dc2dffb7e", "locked": true, "schema_version": 1, "solution": false}
cout << "Hello World" << endl;
// + deletable=false nbgrader={"checksum": "f02edb0e9c5fd56ef0caa5953e4ec650", "grade": true, "grade_id": "cell-91d68551d51b9f38", "locked": false, "points": 5, "schema_version": 1, "solution": true}
/* your code here,
If there are compile errors or uncaught exceptions, you may not get credit */
return -1;
// -
| release/Test-1/Hello World.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# **1**.
#
# Rewrite the following code using map, filter and reduce.
xs = []
for x in range(10):
if x % 3:
xs.append(x**3)
sum(xs)
xs
from functools import reduce
reduce(lambda a, b: a+b,
map(lambda x: x**3,
filter(lambda x: x % 3, range(10))))
# **2**.
#
# Euclid's algorithm to find the greatest common divisor (GCD) of two numbers $a$ and $b$:
#
# If b is 0 then the GCD is a, otherwise the GCD is the GCD of $b$ and $a \mod b$. Implement the `gcd` function and use it to find the least common multiple of 741 and 91.
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def lcm(a, b):
return a * b // gcd(a, b)
lcm(741, 91)
# **3**.
#
# The Fibonacci sequence is 1,1,2,3,5,8,13,.... where each number is the sum of the two preceding it.
#
# - Write a recursive function to calculate the nth Fibonacci number
# - Write a decorator (i.e. not using `lru_cache` or similar) that caches previously seen values and apply it to the Fibonacci function.
# - Add a print statement to see how many function calls are made for $n=10$ for the plain and decorated versions
def fib_(n):
"""Recursive Fibonacci."""
print(f'fib({n})', end=', ')
if n == 1:
return 1
elif n == 2:
return 1
else:
return fib_(n-1) + fib_(n-2)
def cache(f):
store = {}
def g(n):
if n not in store:
store[n] = f(n)
return store[n]
return g
@cache
def fib(n):
"""Recursive Fibonacci."""
print(f'fib({n})', end=', ')
if n == 1:
return 1
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
fib_(10)
fib(10)
# **4**.
#
# Write a function that flattens an arbitrarily nested list. For this exercise, you can assume that it will always be a nested list that is given.
#
# Hint: use `yield` recursively.
def flat(xs):
for x in xs:
if isinstance(x, list):
yield from flat(x)
else:
yield x
xs = [1,[2,3],[4,[5,[6]]]]
list(flat(xs))
| notebooks/solutions/S06_Exercises_Solutions.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from scipy import stats
import matplotlib.pyplot as plt
# %matplotlib inline
import pandas as pd
import numpy as np
# ### A/B тестирование
# В этом задании вы познакомитесь с A/B тестированием и примените полученные знания по статистике.
#
# Рассмотрим A/B тестирование на примере сайта. У сайта есть два дизайна - старый и новый, и мы хотим оценить, насколько новый дизайн лучше старого. Для этого пользователи сайта случайным образом разделяются на контрольную и тестовую группы. Контрольной группе показывается старая версия сайта, тестовой группе - измененная версия. Оценить изменение можно несколькими способами, самый простой - оценить конверсию. Конверсия - доля пользователей, совершивших заранее определенное действие(например подписка, нажатие на кнопку, заполнение формы).
# ### Описание данных
# Для начала нужно загрузить данные из файла `a_b_testing.csv` при помощи функции `read_csv` из библиотеки `pandas`. В данном случае 1 - была совершена подписка на сайт, 0 - подписки не было. A - контрольная группа, B - тестовая группа.
# Далее нужно выполнить следующие пункты, описание выходного формата содержится внутри каждого задания.
# ### Доверительный интервал
# В видео про доверительный интервал мы рассмотрели, как можно аппроксимировать биномиальное распределение нормальным. В некоторых случаях параметры нормального распределения можно вывести математически и ниже мы рассмотрим как.
# Представим количество пользователей как случайную величину из биномиального распределения с параметрами `n` - количество пользователей и `p` - вероятность конверсии или как сумму `n` независимых бросаний монетки. Определим следующую случайную величину:
#
# $$Y = X_{1} + X_{2} + \dots + X_{n} , \, $$
# где случайная величина $X_{i}$ имеет распределение Бернулли. Для случайной величины $Y$ математическое ожидание и дисперсия равны:
#
# $$\mu = np, \, \sigma^{2} = np\cdot(1 - p)$$
#
# Далее применяя центральную предельную теорему(случайные величины $X_{i}$ распределены независимо и размер выборки большой), получаем что
#
# $$Y \sim \mathcal{N}(np \, np\cdot(1 - p))\$$
#
# Мы перешли от биномиального распределения к нормальному. Следующий шаг - стандартизация нормального распределения:
#
# $$Z = \frac{Y - np}{\sqrt{np\cdot(1-p)}} \sim \mathcal{N}(0, \, 1) $$
#
# Преобразуем выражение выше:
#
# $$Z = \frac{Y - np}{\sqrt{np\cdot(1-p)}} = \frac{\frac{Y}{n} - p}{\sqrt{\frac{p(1-p)}{n}}} \sim \mathcal{N}(0, \, 1) $$
# Так как среднее значение по выборке - это наблюдаемый процент конверсии, то доверительный интервал будет выглядеть следующим образом:
# $${P}\left(p - z_{1-\frac{\alpha}{2}} \sqrt{\frac{p(1-p)}{n}} \le \mu \le p + z_{1-\frac{\alpha}{2}}\sqrt{\frac{p(1-p)}{n}}\right) = 1-\alpha$$
# ### ЗАДАНИЕ
# Найдите доверительный интервал для средней конверсии пользователей из контрольной выборки с уровнем значимости 95%. Округлите левую и правую границу с точностью до двух знаков после запятой. Запишите значения левой и правой границ через запятую, сохраняя приведенный порядок, в переменную `answer1`, которая будет являтся строкой.
# #### РЕШЕНИЕ
# ### Задача A/B тестирования
# Рассмотрим независимые выборки $X$ и $Y$ для которых есть $\mu_x$ и $\mu_y$, определяющие среднее значение распределения.
#
# Рассматривается следующая гипотеза:
# $$
# H_0: \mu_x = \mu_y
# $$
# против альтернативы:
#
# $$
# H_1: \mu_x \ne \mu_y.
# $$
# Если гипотеза $H_0$ отвергается, то показатель действительно поменялся.
# Также можно тест можно записать и другим способом:
# $$
# H_0: \mu_x \le \mu_y
# $$
#
# против альтернативы:
#
# $$
# H_1: \mu_x > \mu_y
# $$
# ### Задание по статистике Стьюдента
# Найдите значение статистики Стьюдента в предположении независимости выборок по формуле:
# $$
# T(X, Y) = \frac{\bar{X} - \bar{Y}}{\sqrt{\frac{s_x^2}{n} + \frac{s_y^2}{m}}}
# $$
#
# где `n` - размер контрольной выборки, `m` - размер тестовой выборки.
# Ответ запишите в переменную `answer2` с точностью до двух знаков после запятой.
# ### РЕШЕНИЕ
# ### Статистика Стьюдента из библиотеки Scipy
# Найдите p-value для статистики Стьюдента, используя функцию `stats.ttest_ind`.
# ### РЕШЕНИЕ
from scipy.stats import ttest_ind
# Дополнительная проверка: значение статистики Стьюдента, посчитанная двумя способами, должны совпадать.
# Ответ запишите в переменную `answer3` с точностью до 2 знака после запятой
| statistics/statistics.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# +
import pandas as pd
#使用pandas,读取数据文件。
data = pd.read_csv('../datasets/white_wine/white_wine_quality.csv', sep=';')
#从数据中拆分出特征与目标值。
X = data[data.columns[:-1]]
y = data[data.columns[-1]]
# +
from sklearn.model_selection import train_test_split
#拆分训练集和测试集。
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=2022)
# +
from sklearn.preprocessing import StandardScaler
#初始化数据标准化处理器。
ss = StandardScaler()
#标准化训练数据特征。
X_train = ss.fit_transform(X_train)
#标准化测试数据特征。
X_test = ss.transform(X_test)
# +
from sklearn.linear_model import SGDRegressor
#初始化随机梯度回归器模型。
sgdr = SGDRegressor()
#使用训练数据,训练随机梯度回归器模型。
sgdr.fit(X_train, y_train)
#使用训练好的回归模型,依据测试数据的特征,进行数值回归。
y_predict = sgdr.predict(X_test)
# +
from sklearn.metrics import mean_squared_error
#评估回归器的误差。
print ('Scikit-learn的随机梯度回归器在white_wine测试集上的均方误差为:%.4f。' %mean_squared_error(y_test, y_predict))
# -
| Chapter_5/Section_5.3.2.2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Implementing the Partial Convolution Layer
# One of the pillars of the paper is the partial convolution layer, which we'll have to implement in Keras. We'll base the new layer off the current Convolution2D layer already in Keras, and then introduce the mask, so that in our PConv2D layer a tuple of (img, mask) is passed, and a tuple of (conv_img, conv_mask) is returned
# +
import os
from copy import deepcopy
import cv2
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from keras.layers import Input, Dense, ZeroPadding2D
from keras.models import Model
# Change to root path
if os.path.basename(os.getcwd()) != 'PConv-Keras':
os.chdir('..')
# Import modules from libs/ directory
from libs.pconv_layer import PConv2D
from libs.util import MaskGenerator
# %matplotlib inline
# %load_ext autoreload
# %autoreload 2
# -
??PConv2D
# # Testing
#
# ## Load Data
# Just loading a sample image and randomly generated mask on top.
# +
# Load image
img = cv2.imread('./data/sample_image.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
shape = img.shape
print(f"Shape of image is: {shape}")
# Instantiate mask generator
mask_generator = MaskGenerator(shape[0], shape[1], 3, rand_seed=42)
# Load mask
mask = mask_generator.sample()
# Image + mask
masked_img = deepcopy(img)
masked_img[mask==0] = 255
# Show side by side
_, axes = plt.subplots(1, 3, figsize=(20, 5))
axes[0].imshow(img)
axes[1].imshow(mask*255)
axes[2].imshow(masked_img)
plt.show()
# -
# ## Implement Model
# Next we implement a simple model with several subsequent PConv layers, while saving all the outputs (for validation that the layer does what we expect it to)
# +
from libs.pconv_layer import PConv2D
# Input images and masks
input_img = Input(shape=(shape[0], shape[1], shape[2],))
input_mask = Input(shape=(shape[0], shape[1], shape[2],))
output_img, output_mask1 = PConv2D(8, kernel_size=(7,7), strides=(2,2))([input_img, input_mask])
output_img, output_mask2 = PConv2D(16, kernel_size=(5,5), strides=(2,2))([output_img, output_mask1])
output_img, output_mask3 = PConv2D(32, kernel_size=(5,5), strides=(2,2))([output_img, output_mask2])
output_img, output_mask4 = PConv2D(64, kernel_size=(3,3), strides=(2,2))([output_img, output_mask3])
output_img, output_mask5 = PConv2D(64, kernel_size=(3,3), strides=(2,2))([output_img, output_mask4])
output_img, output_mask6 = PConv2D(64, kernel_size=(3,3), strides=(2,2))([output_img, output_mask5])
output_img, output_mask7 = PConv2D(64, kernel_size=(3,3), strides=(2,2))([output_img, output_mask6])
output_img, output_mask8 = PConv2D(64, kernel_size=(3,3), strides=(2,2))([output_img, output_mask7])
# Create model
model = Model(
inputs=[input_img, input_mask],
outputs=[
output_img, output_mask1, output_mask2,
output_mask3, output_mask4, output_mask5,
output_mask6, output_mask7, output_mask8
])
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
# Show summary of the model
model.summary()
# -
# ## Check mask layer updates
# +
formatted_img = np.expand_dims(masked_img, 0) / 255
formatted_mask = np.expand_dims(mask, 0)
print(f"Original Mask Shape: {formatted_mask.shape} - Max value in mask: {np.max(formatted_mask)}")
output_img, o1, o2, o3, o4, o5, o6, o7, o8 = model.predict([formatted_img, formatted_mask])
# -
_, axes = plt.subplots(2, 4, figsize=(20, 10))
axes[0][0].imshow(o1[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[0][1].imshow(o2[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[0][2].imshow(o3[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[0][3].imshow(o4[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[1][0].imshow(o5[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[1][1].imshow(o6[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[1][2].imshow(o7[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[1][3].imshow(o8[0, :,:, 0], cmap = 'gray', vmin=0, vmax=1)
axes[0][0].set_title(f"Shape: {o1.shape}")
axes[0][1].set_title(f"Shape: {o2.shape}")
axes[0][2].set_title(f"Shape: {o3.shape}")
axes[0][3].set_title(f"Shape: {o4.shape}")
axes[1][0].set_title(f"Shape: {o5.shape}")
axes[1][1].set_title(f"Shape: {o6.shape}")
axes[1][2].set_title(f"Shape: {o7.shape}")
axes[1][3].set_title(f"Shape: {o8.shape}")
plt.show()
# This looks exactly like it's supposed to - the further down we do in the network, the less significant the masking gets.
| notebooks/Step2 - Partial Convolution Layer.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # "Building தமிழ் language tokenizer"
# > "In this notebook I try to build sentencepiece tokenizers for தமிழ் language with data extracted from wiki dump"
# - toc: false
# - branch: master
# - badges: true
# - comments: true
# - categories: [nlp, language-model, தமிழ்]
# - hide: false
# You can find the blog post regarding extraction [here](https://mani2106.github.io/Blog-Posts/data-cleaning/language-model/2020/04/14/wiki-data-extraction.html) and kaggle notebook with output [here](https://www.kaggle.com/manimaranp/tamil-wiki-data-extraction)
# # Import required libraries
# + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5"
from pathlib import Path
import sentencepiece as spm
import pandas as pd
# + [markdown] _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a"
# # Read data from csv
# -
lang_data = pd.read_csv('../input/tamil-wiki-data-extraction/filtered_data.csv.tar.gz', index_col=[0])
lang_data.head()
lang_data.info()
# # Setup paths
# +
# Initialize directories
OUTPUT_DIR = Path('/kaggle/working')
TEXTS_DIR = OUTPUT_DIR/'texts'
TOK_DIR = OUTPUT_DIR/'tokenizer'
# Create directories
TOK_DIR.mkdir()
TEXTS_DIR.mkdir()
# -
# # Prepare texts
# We can pass a list of files as a comma seperated string according to [documentation](https://github.com/google/sentencepiece#train-sentencepiece-model), So we can store each article in a text file and pass the names in a comma seperated string.
# +
# Save all article texts in seperate files
for t in lang_data.itertuples():
file_name = Path(TEXTS_DIR/f'text_{t.Index}.txt')
file_name.touch()
with file_name.open('w') as f:
f.write(t.text)
# -
# Check files in directory
len([t for t in TEXTS_DIR.iterdir()]), lang_data.shape[0]
# All the files have been converted to texts
# # Train sentencepiece model
# Let's make a comma seperated string of filenames
files = ','.join([str(t) for t in TEXTS_DIR.iterdir()])
files[:100]
# We must find the right `vocab_size` for the tokenizer, that can be done only by testing the tokenizer after building onw
for v in 8000, 16000, 20000, 30000:
api_str = f"""--input={files} --vocab_size={v} --model_type=unigram --character_coverage=0.9995 --model_prefix={str(TOK_DIR)}/tok_{v}_size --max_sentence_length=20000"""
print("Training with vocab set as:", v)
spm.SentencePieceTrainer.train(api_str)
# ## Cleanup
# !rm -rf /kaggle/working/texts/
# Let's test the models in another notebook, you can find the outputs in this kaggle [notebook](https://www.kaggle.com/manimaranp/building-a-tokenizer-for-tamil-with-sentencepiece)
| _notebooks/2020-04-14-building-a-tokenizer-for-tamil-with-sentencepiece.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# # Welcome to BME 590: Machine Learning in Imaging
#
#
# + [markdown] slideshow={"slide_type": "subslide"}
# ## People
#
# <img src="https://bme.duke.edu/sites/bme.duke.edu/files/u12/xhorstmeyer_200x200px.jpg.pagespeed.ic.SLWkDogtxs.webp" alt="<NAME>" width="100"/>
# <NAME> - <EMAIL> | Office location: CIEMAS 2569
# Office hours: Wednesdays 3:00pm-4:30pm | Thursdays 10:00am-11:30pm
# + [markdown] slideshow={"slide_type": "subslide"}
# <img src="https://scholars.duke.edu/file/i8074692/image_8074692.jpg" alt="<NAME>" width="100"/>
# <NAME> - <EMAIL>
# + [markdown] slideshow={"slide_type": "subslide"}
# <img src="https://avatars0.githubusercontent.com/u/5455421?s=460&v=4" alt="<NAME>" width="100"/>
# <NAME> - <EMAIL>
# + [markdown] slideshow={"slide_type": "slide"}
# # Resources
#
# ### [Class Github](https://github.com/Ouwen/BME-590-Medical-Imaging)
# - This is where homeworks scaffolds and session notes will be stored
#
# ### [Slack](https://deepimaging.slack.com)
# - This is where you can ask questions have discussion
# + [markdown] slideshow={"slide_type": "slide"}
# # Homeworks: 40%
#
# ### Homework submissions will be through a google forms link provided in the homework scaffold
# - You'll include your netid, name, and email
# - Programming Assignments will be saved on github and submitted as a link on Google Forms.
# - Pen and Paper Assignments will be submitted through a file attachement on Google Forms.
#
# + [markdown] slideshow={"slide_type": "slide"}
# # Session 0: Outline
# - Going Over [Survey](https://docs.google.com/presentation/d/1jzY5i1LLoeaaW9IGgxgcP67h4rmWk3g-7PekASodTGI/edit#slide=id.p) Results
# + [markdown] slideshow={"slide_type": "subslide"}
# - What are Juypter Notebooks:
# - Bash Shell
# - Python
# - Markdown
# + [markdown] slideshow={"slide_type": "subslide"}
# - Instances
# - Local Instances
# - Cloud Instances (GCP)
# - Docker (maybe)
#
# - Using github
# + [markdown] slideshow={"slide_type": "subslide"}
# # Homework
# - Submission for homework 0.5 is here: https://goo.gl/forms/NS5tp08lcq6OjNst1
# - Run a GCP instance with a juypter notebook running. Screenshot it and submit the image.
# - Clone the class github, submit a juypter notebook introducing yourself
# + [markdown] slideshow={"slide_type": "slide"}
# # Jupyter Notebooks
#
# Jupyter is a program to organize code and experiments. These notebooks are saved as `.ipyn` files (interactive python notebook)
# - Jupyter is run from the shell, we will review the bash shell
# - file system
# - `ls`, `cd`, `mkdir`, `cp`, `rm`, `cat`
# - permissions
# - `sudo`
# - network
# - `curl`
# - installed
# - `screen`: example `screen -S my_screen`
# - `python3`
# - `jupyter`: example `jupyter notebook`
# - `gsutil`: installing `curl https://sdk.cloud.google.com | bash`
# - `ssh`
# - It runs `IPython` which is a superset of `python`.
# - Compiles Markdown
# + slideshow={"slide_type": "subslide"}
print('Hello World')
# + slideshow={"slide_type": "subslide"}
# This will list all files in the directory just like shell
# !ls
# + [markdown] slideshow={"slide_type": "subslide"}
# # This is markdown
# ## It is a really
# ### Simple
# #### Text editor
# ##### Very popular on the web, stackoverflow uses it, github uses it.
# Check out this: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet
#
#
# ```python
# for i in range(10):
# print(i)
# ```
# + [markdown] slideshow={"slide_type": "slide"}
# # Run your own Juypter Instance
#
# # First install python: https://www.python.org/downloads/
#
# # Then install jupyter
# ```bash
# python3 -m pip install --upgrade pip
# python3 -m pip install jupyter
# ```
#
# # Run the Jupyter Notebook Locally
# ```bash
# jupyter notebook
# ```
# + [markdown] slideshow={"slide_type": "slide"}
# # Juypter Notebook with Google Cloud
#
# Credits: https://google.secure.force.com/GCPEDU?cid=L5coc3IsY%2BAzvZwfHGS3tFSvTz4wQXc8TQs7ZOvU%2BJh3lwMo8veKfLd0VG4G2XZa
#
# Follow along to setup your cloud instance
# + [markdown] slideshow={"slide_type": "slide"}
# # Github
#
# Great way to manage code
# - Cloning: `git clone <http repo>`
# - Forking: Just like `git clone`, but your account owns it (feature of github)
# - File Tracking:
# `git diff [filename or directory]`
# `git add [filename or directory]`
# `git commit -m "my notes"`
#
#
# Issue Tagging with @[username]
| session/session_0/Session 0.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from csv import reader
import numpy as np
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
from plotly.offline import init_notebook_mode, iplot
from plotly.graph_objs import Scatter, Layout, Figure
init_notebook_mode(connected=True)
# -
ls = []
with open("/home/local/saska/Documents/fastt/vecs.txt") as inp:
rd = reader(inp, delimiter=" ")
for l in rd:
if len(l) == 102:
ls.append((l[0], np.asarray(l[1:-1], dtype=np.float32)))
model = TSNE(n_components=2, verbose=2)
x2d = model.fit_transform([x[1] for x in ls])
# +
data = Scatter(x=[x[0] for x in x2d], y=[y[1] for y in x2d], text=[t[0] for t in ls], mode='markers')
layout = Layout(hovermode='closest')
fig = Figure(data=[data], layout=layout)
iplot(fig)
# -
| word2vec/plotter.ipynb |
// ---
// jupyter:
// jupytext:
// text_representation:
// extension: .fs
// format_name: light
// format_version: '1.5'
// jupytext_version: 1.14.4
// kernelspec:
// display_name: .NET (F#)
// language: F#
// name: .net-fsharp
// ---
// <a id="Contents"></a>
// # The Reasoning Engine for Interaction Networks (RE:IN)
//
// This notebook illustrates how to carry out analysis using the RE:IN tool. The working example will follow the results presented in [Dunn, Martello & Yordanov et al. (2014)](#https://science.sciencemag.org/content/344/6188/1156)
//
// * [Load Packages and Modules](#Packages)
// * [The Initial ABN](#InitialABN): Defining an Abstract Boolean Network and constraints (specifications).
// * [Check Satisfiability and Enumerate Consistent Network Models](#FindingSolutions): Quickly test whether the constraints can be satisfied by at least one network model. Enumerate some number of concrete networks consistent with the constraints.
// * [Find Required / Disallowed Interactions](#FindRequiredInteractions): Identify whether any possible interactions are present in all or none of the consistent concrete networks.
// * [Find Minimal Models](#FindMinimal): Identify the smallest networks that satisfy the constraints.
// * [Formulate Predictions](#Predictions): Test genetic perturbations on all consistent networks.
// <a id="Packages"></a>
// ### Load Packages and Modules
#load @"../REInteractiveAPI/ReLoad.fsx"
open ReasoningEngine
// <a id="InitialABN"></a>
// ### The Initial ABN
//
// Here we load an Abstract Boolean Network together with 23 experimental specifications, as described in [Dunn et al. (2014)](#https://science.sciencemag.org/content/344/6188/1156).
//
// The possible interactions in this specific ABN (dashed arrows) were selected by examining the Pearson correlation of all pairs of components across our experimental data, and including those with a threshold of at least 0.792.
//
// The colour of the nodes provides some information about what is contained in the specifications.
//
// Black: This component is knocked out in at least one specification
//
// <font color="green">Green</font>: This component has forced expression in at least one specification
//
// <font color="blue">Blue</font>: This component is knocked out in at least one specification, and has forced expression in at least one specification
//
// The colour of the arrows indicates positive regulation (black) and <font color="red">negative</font> regulation (<font color="red">red</font>).
//
// [back to contents](#Contents)
let model792 = ReinAPI.LoadFile ".\Science2014\Pearson792With23SpecificationsLegacy.rein"
model792 |> ReinAPI.DrawBespokeNetworkWithSizeSVG 400.0
// Below we can examine the specifications. These are grouped by their specification tag (e.g. #ExperimentEight), and are listed alphabetically. Each column illustrates how the behaviour of each component was specified at the indicated trajectory step.
//
// For example, in the ExperimentEight trajectory, the transcription factor Esrrb is defined to be OFF at step 0, but ON at steps 18 and 19.
//
// - <font color="blue">Blue</font>: ON
// - White: OFF
// - <font color="grey">Grey</font>: Not specified. (Note that input signals LIF, CH, and PD will remain in their initial state due to self-activation.)
// - FE(component name): Forced expression
// - KO(component name): Knockout
model792 |> ReinAPI.DrawObservations
// <a id="FindingSolutions"></a>
// ### Check Satisfiability
//
// We check that the set of constraints (specifications) are satisfiable by verifying that solutions can be found.
//
// [back to contents](#Contents)
ReinAPI.CheckAndPrint model792
// We can look at some of the concrete network models that are consistent with the constraints. For an ABN of the size we are exploring, it is likely that the number of consistent concrete networks is very large. Our previous investigations support this, and so we illustrate here how you can enumerate 15 network models.
//
// Each column corresponds to an individual model. A red box indicates that the negative interaction is present in the model, while a green box indicates that the positive interaction is present. Grey indicates that the interaction is absent in that model.
let solutions = ReinAPI.Enumerate 15 model792
solutions |> ReinAPI.DrawSummary
// We can plot individual solutions to visualise them as a network.
solutions.[0] |> ReinAPI.DrawBespokeNetworkWithSizeSVG 400.0
// We can also examine how individual networks satisfy the imposed constraints. Below, we select the first concrete model and visualise the trajectory of each component, for each experiment.
// +
//solutions.[0].solution.Value |> TrajVis.PlotTrajectories |> Array.map display
// -
// <a id="FindRequiredInteractions"></a>
// ### Find Required / Disallowed Interactions
//
// Now that we know that there are network models that are consistent with the constraints, we can identify whether any of the possible interactions appear in **every** consistent model, and can therefore be described as required, or whether any never appear, and can therefore be described as disallowed.
//
// We re-draw the model with the updated set of interactions, and also show a table of these below. These are what we would expect, as we recapitulate the 11 required interactions published in Science, but we benefit now from having the set of disallowed interactions, which we didn't publish.
//
// [back to contents](#Contents)
let model792cABN, required792, disallowed792 = model792 |> ReinAPI.IdentifyInteractions
DrawInteractions required792 disallowed792
// The cABN is visualised below, where the required interactions are now shown as definite, and the disallowed interactions have been removed.
model792cABN |> ReinAPI.DrawBespokeNetworkWithSizeSVG 400.0
// <a id="FindMinimal"></a>
// ### Find Minimal Models
//
// It may be that you are interested in the simplest concrete network that is consistent with the imposed constraints. We can identify those networks with the fewest interactions using the functionality below.
//
// [back to contents](#Contents)
model792
|> ReinAPI.FindMinimalModels
|> ReinAPI.DrawSummary
// <a id="Predictions"></a>
// ### Formulate Predictions
//
// Now that we have identified a set of concrete networks that are consistent with the imposed constraints, which are based on previous experimental results, it is of interest to test whether these networks predict a consistent response to perturbations that do not appear in the set of constraints. For example, do these networks predict whether an ESC will remain pluripotent or commit to differentiation in the presence of a specific single genetic knockdown?
//
// To formulate predictions, we encode the test hypothesis as an additional constraint and test for satisfiability. We also encode the null of the hypothesis and test this separately.
//
// For example, below we test whether or not expression of Oct4 and Sox2 can be sustained in the presence of Klf4 single knockdown.
//
// [back to contents](#Contents)
ReinAPI.CheckMultipleFiles ".\Science2014\SingleKnockdowns"
// These results show that none of the concrete models in the cABN are consistent with the null specification - that Oct4 and Sox2 expression cannot be sustained under Klf4 SKD. Given that the initial hypothesis constraint is satisfiable, we can conclude that ALL concrete models support the hypothesis.
//
// We therefore would say that the cABN predicts that pluripotency will be sustained under Klf4 SKD.
| Examples/REINDotNetInteractive.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import tensorflow as tf
import pandas as pd
import html
import re
import string
from fncbaseline.utils import dataset, generate_test_splits, score
from nltk.corpus import stopwords
from gensim.summarization import summarize
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from fncbaseline.utils import dataset, generate_test_splits, score
from fncbaseline import feature_engineering
from nltk.corpus import stopwords
from gensim.summarization import summarize
from nltk.corpus import stopwords
import html
import re
from nltk import sent_tokenize
import nltk.data
from nltk.tokenize import word_tokenize
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
# -
# Load the dataset
train_dataset = dataset.DataSet()
test_dataset = dataset.DataSet('test')
def preprocess(text):
text = html.unescape(text)
text = text.replace("\\n"," ")
#text = text.replace("\"","")
text = text.replace("_NEG","")
text = text.replace("_NEGFIRST", "")
#text = re.sub(r"#", "", text)
text = re.sub(r"\*", "", text)
#text = re.sub(r"\'s", "", text)
text = re.sub(r"\'m", " am", text)
text = re.sub(r"\'ve", " have", text)
text = re.sub(r"n\'t", " not", text)
text = re.sub(r"\'re", " are", text)
text = re.sub(r"\'d", " would", text)
text = re.sub(r"\'ll", " will", text)
#text = re.sub(r",", "", text)
#text = re.sub(r"!", " !", text)
#text = re.sub(r"\(", "", text)
#text = re.sub(r"\)", "", text)
#text = re.sub(r"\?", " ?", text)
#text = re.sub(r'[^\x00-\x7F]',' ', text)
#text = re.sub(r'[^\w\s]',' ',text)
#text = re.sub("\d+", " ", text)
text = re.sub(r"\s{2,}", " ", text)
#text = text.rstrip(',|.|;|:|\'|\"')
#text = text.strip('\'|\"|" "')
#text=text.lstrip('" "')
text=text.replace('..', '. ')
text=text.replace('--', '. ')
text = text.replace('\n','. ')
return text
# +
data=dict()
for s in test_dataset.articles:
a=list()
text=test_dataset.articles[s]
text=text.replace('”', '')
text=text.replace('“', '')
text=text.replace('"', '')
text=text.replace('..', '. ')
text=text.replace('--', '. ')
text = text.replace('\n','. ')
text=preprocess(text)
sents=tokenizer.tokenize(text)
if(len(sents)==1):
sents=sents[0].split('.')
for st in sents:
st=preprocess(st)
newsents=tokenizer.tokenize(st)
for nst in newsents:
if(len(nst)>1):
splits=nst.split(' ')
if(len(splits)>85):
a.append(' '.join(splits[:int(len(splits)/2)]))
a.append(' '.join(splits[int(len(splits)/2):]))
else:
a.append(nst)
data[s]=(a)
for s in train_dataset.articles:
a=list()
text=train_dataset.articles[s]
text=text.replace('”', '')
text=text.replace('“', '')
text=text.replace('"', '')
text=text.replace('..', '. ')
text=text.replace('--', '. ')
text = text.replace('\n','. ')
text=preprocess(text)
sents=tokenizer.tokenize(text)
if(len(sents)==1):
sents=sents[0].split('.')
for st in sents:
st=preprocess(st)
newsents=tokenizer.tokenize(st)
for nst in newsents:
if(len(nst)>1):
splits=nst.split(' ')
if(len(splits)>85):
a.append(' '.join(splits[:int(len(splits)/2)]))
a.append(' '.join(splits[int(len(splits)/2):]))
else:
a.append(nst)
data[s]=a
# -
with open('/home/kamal/OpenNMT-py/data/scr-body-articles.txt','w') as out:
for s in data:
out.write(' '.join(data[s]))
out.write('\n')
# +
# Returns (3,num_words,1024)
from allennlp.commands.elmo import ElmoEmbedder
from allennlp.modules.elmo import Elmo, batch_to_ids
options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json"
weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5"
elmo = ElmoEmbedder(options_file, weight_file)
# -
elmo_body = dict()
counter = 0
for art in data:
embeddings = elmo.embed_sentences(data[art])
temp = np.zeros(1024)
for x in data[art]:
emb = next(embeddings)
emb = np.mean(np.mean(emb,axis = 0),axis = 0)
temp = temp+emb
elmo_body[art] = temp/len(data[art])
if counter%200 ==0:
print (counter)
counter+=1
np.save('elmo_body.npy',elmo_body)
| Deep Neural Models/Elmo-Body-Copy1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import re
import numpy as np
import pandas as pd
from pprint import pprint
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
import pickle
# -
lda_model=pickle.loads(open('LDA_Model', 'rb').read())
from gensim.parsing.preprocessing import STOPWORDS
import nltk
from nltk.stem import WordNetLemmatizer
def preprocess(text):
return [w for w in gensim.utils.simple_preprocess(text) if w not in STOPWORDS and len(w)>3]
def lemmatize(text):
return [WordNetLemmatizer().lemmatize(w) for w in text]
# +
def format_topics_sentences(ldamodel, corpus, texts):
# Init output
sent_topics_df = pd.DataFrame()
# Get main topic in each document
for i, row_list in enumerate(ldamodel[corpus]):
row = row_list[0] if ldamodel.per_word_topics else row_list
# print(row)
row = sorted(row, key=lambda x: (x[1]), reverse=True)
# Get the Dominant topic, Perc Contribution and Keywords for each document
for j, (topic_num, prop_topic) in enumerate(row):
if j == 0: # => dominant topic
wp = ldamodel.show_topic(topic_num)
topic_keywords = ", ".join([word for word, prop in wp])
sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True)
else:
break
sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']
# Add original text to the end of the output
contents = pd.Series(texts)
sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)
return(sent_topics_df)
#df_topic_sents_keywords = format_topics_sentences(ldamodel=lda_model_tfidf, corpus=bow, texts=preproc_doc)
# Format
#df_dominant_topic = df_topic_sents_keywords.reset_index()
#df_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text']
#df_dominant_topic.head(10)
# +
def generate_tags(s):
preproc_doc = []
preproc_doc.append(lemmatize(preprocess(s)))
dwords = gensim.corpora.Dictionary(preproc_doc)
bow = [dwords.doc2bow(s) for s in preproc_doc]
df_topic_sents_keywords = format_topics_sentences(ldamodel=lda_model, corpus=bow, texts=preproc_doc)
df_dominant_topic = df_topic_sents_keywords.reset_index()
df_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text']
return df_dominant_topic.loc[0,'Keywords']
# -
| Tag_Generator.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python3
# ---
# # Ch `02`: Concept `04`
# ## Session logging
# Define an op on a tensor. Here's an example:
# +
import tensorflow as tf
x = tf.constant([[1, 2]])
neg_op = tf.negative(x)
# -
# Now let's use a session with a special argument passed in.
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
result = sess.run(neg_op)
print(result)
# Try this from a terminal. Jupyter notebooks won't show the logging info.
| Chapter 2 Basics/Chapter_2_Section_4_Session_Logging.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.9.7 ('base')
# language: python
# name: python3
# ---
# # Web Scraper
# ## Imports
# +
import pandas as pd
import numpy as np
from requests import get
import json
from bs4 import BeautifulSoup
import time
# -
# ## World Surf League Scores
#
# I'm going to focus on the Pipeline Masters first. It is the marquee event of the Championship Tour and is run every year (**verify**).
# ### Get HTML soup and review
# Starting URLs
pipe_2008_url = "https://www.worldsurfleague.com/events/2008/mct/75/billabong-pipeline-masters?roundId=5"
res = get(pipe_2008_url)
soup = BeautifulSoup(res.content)
soup.find('li', class_='carousel-item is-selected').find('span', class_='carousel-item-title-wrap')['data-short-title']
soup.find_all("div", class_="all-waves all-waves-grid")[0].find_all(
"span", class_="score"
)[3].text
len(soup.find_all("div", class_="all-waves all-waves-grid"))
soup.find_all("span", class_="athlete-name")[0].find_parent('div', class_='bd new-heat-bd').find_previous_sibling().find('span', class_='new-heat-hd-name').text
athletes = soup.find_all("span", class_="athlete-name")
soup.find('span', class_='carousel-item-title').text
class_ = 'carousel-item is-selected'
soup.find_all("span", class_="athlete-name")[0].text
soup.find_all("span", class_="new-heat-hd-name")[0].text
len(soup.find_all("span", class_="athlete-name"))
# ### Round 1
# Starting URLs
pipe_2008_url = "https://www.worldsurfleague.com/events/2008/mct/75/billabong-pipeline-masters?roundId=3"
res = get(pipe_2008_url)
soup = BeautifulSoup(res.content)
athletes = soup.find_all("span", class_="athlete-name")
scores = soup.find_all("div", class_="all-waves all-waves-grid")
# +
round_1 = []
for i in range(len(athletes)):
athlete_scores = {}
athlete_scores["name"] = soup.find_all("span", class_="athlete-name")[i].text
athlete_scores["scores"] = []
for b in range(len(scores[i].find_all("span", class_="score"))):
try:
athlete_scores["scores"].append(
float(scores[i].find_all("span", class_="score")[b].text)
)
except:
continue
round_1.append(athlete_scores)
round_1
# -
# ### Generalize for all rounds
# +
roundids = {
3: "round_1",
4: "round_2",
5: "round_3",
6: "round_4",
7: "quarter",
52: "semi",
77: "final",
} # roundIds do not follow a strict logical order
event_name = "2008 Pipeline"
data = []
for roundid, round_name in roundids.items():
url = f"https://www.worldsurfleague.com/events/2008/mct/75/billabong-pipeline-masters?roundId={roundid}"
res = get(url)
soup = BeautifulSoup(res.content)
athletes = soup.find_all("span", class_="athlete-name")
scores = soup.find_all("div", class_="all-waves all-waves-grid")
for i in range(len(athletes)):
athlete_scores = {}
athlete_scores["event"] = event_name
athlete_scores["round"] = round_name
athlete_scores["name"] = soup.find_all("span", class_="athlete-name")[i].text
athlete_scores["scores"] = []
for b in range(len(scores[i].find_all("span", class_="score"))):
try:
athlete_scores["scores"].append(
float(scores[i].find_all("span", class_="score")[b].text)
)
except:
continue
data.append(athlete_scores)
time.sleep(3)
# -
pd.DataFrame(data)
# ### Generalize to a function for all events
events = [
{
"name": "2008 Gold Coast",
"url": "https://www.worldsurfleague.com/events/2008/mct/4/quiksilver-pro-gold-coast?roundId=",
"rounds": {
16: "round_1",
36: "round_2",
20: "round_3",
42: "round_4",
48: "quarter",
69: "semi",
71: "final",
},
},
{
"name": "2008 Bells Beach",
"url": "https://www.worldsurfleague.com/events/2008/mct/8/rip-curl-pro-bells-beach?roundId=",
"rounds": {
31: "round_1",
10: "round_2",
50: "round_3",
56: "round_4",
60: "quarter",
64: "semi",
68: "final",
},
},
{
"name": "2008 Teahupoo",
"url": "https://www.worldsurfleague.com/events/2008/mct/20/billabong-pro-teahupoo?roundId=",
"rounds": {
8: "round_1",
35: "round_2",
30: "round_3",
43: "round_4",
51: "quarter",
65: "semi",
66: "final",
},
},
{
"name": "2008 Fiji",
"url": "https://www.worldsurfleague.com/events/2008/mct/24/globe-pro-fiji?roundId=",
"rounds": {
13: "round_1",
37: "round_2",
18: "round_3",
49: "round_4",
58: "quarter",
57: "semi",
74: "final",
},
},
{
"name": "2008 J-Bay",
"url": "https://www.worldsurfleague.com/events/2008/mct/31/billabong-pro-j-bay?roundId=",
"rounds": {
22: "round_1",
15: "round_2",
25: "round_3",
53: "round_4",
59: "quarter",
63: "semi",
72: "final",
},
},
{
"name": "2008 Bali",
"url": "https://www.worldsurfleague.com/events/2008/mct/37/rip-curl-pro-search-bali?roundId=",
"rounds": {
12: "round_1",
28: "round_2",
40: "round_3",
62: "round_4",
61: "quarter",
75: "semi",
76: "final",
},
},
{
"name": "2008 Trestles",
"url": "https://www.worldsurfleague.com/events/2008/mct/48/boost-mobile-pro?roundId=",
"rounds": {
26: "round_1",
11: "round_2",
19: "round_3",
24: "round_4",
32: "quarter",
55: "semi",
54: "final",
},
},
{
"name": "2008 France",
"url": "https://www.worldsurfleague.com/events/2008/mct/54/quiksilver-pro-france?roundId=",
"rounds": {
33: "round_1",
14: "round_2",
29: "round_3",
39: "round_4",
38: "quarter",
45: "semi",
46: "final",
},
},
{
"name": "2008 Mundaka",
"url": "https://www.worldsurfleague.com/events/2008/mct/55/billabong-pro-mundaka?roundId=",
"rounds": {
1: "round_1",
34: "round_2",
2: "round_3",
47: "round_4",
41: "quarter",
44: "semi",
73: "final",
},
},
{
"name": "2008 Santa Catarina",
"url": "https://www.worldsurfleague.com/events/2008/mct/66/hang-loose-santa-catarina-pro?roundId=",
"rounds": {
21: "round_1",
17: "round_2",
23: "round_3",
9: "round_4",
27: "quarter",
70: "semi",
67: "final",
},
},
{
"name": "2008 Pipeline",
"url": "https://www.worldsurfleague.com/events/2008/mct/75/billabong-pipeline-masters?roundId=",
"rounds": {
3: "round_1",
4: "round_2",
5: "round_3",
6: "round_4",
7: "quarter",
52: "semi",
77: "final",
},
},
{
"name": "2009 Gold Coast",
"url": "https://www.worldsurfleague.com/events/2009/mct/83/quiksilver-pro-gold-coast?roundId=",
"rounds": {
88: "round_1",
104: "round_2",
91: "round_3",
117: "round_4",
10048: "quarter",
118: "semi",
130: "final",
},
},
{
"name": "2009 Bells Beach",
"url": "https://www.worldsurfleague.com/events/2009/mct/91/rip-curl-pro-bells-beach?roundId=",
"rounds": {
94: "round_1",
106: "round_2",
105: "round_3",
108: "quarter",
141: "semi",
140: "final",
},
},
{
"name": "2009 Teahupoo",
"url": "https://www.worldsurfleague.com/events/2009/mct/95/billabong-pro-teahupoo?roundId=",
"rounds": {
82: "round_1",
81: "round_2",
101: "round_3",
102: "quarter",
99: "semi",
121: "final",
},
},
{
"name": "2009 <NAME>",
"url": "https://www.worldsurfleague.com/events/2009/mct/99/hang-loose-santa-catarina-pro?roundId=",
"rounds": {
92: "round_1",
80: "round_2",
97: "round_3",
107: "round_4",
112: "quarter",
128: "semi",
129: "final",
},
},
{
"name": "2009 J-Bay",
"url": "https://www.worldsurfleague.com/events/2009/mct/104/billabong-pro-j-bay?roundId=",
"rounds": {
89: "round_1",
109: "round_2",
116: "round_3",
137: "quarter",
138: "semi",
139: "final",
},
},
{
"name": "2009 Trestles",
"url": "https://www.worldsurfleague.com/events/2009/mct/116/hurley-pro-trestles?roundId=",
"rounds": {
84: "round_1",
103: "round_2",
79: "round_3",
86: "round_4",
95: "quarter",
132: "semi",
136: "final",
},
},
]
def get_scores(event_dict=events):
"""Takes a dict of World Surf League Events, URLs and roundIds and scrapes the scores"""
data = []
for event in events:
event_name = event["name"]
url = event["url"]
for roundid, round_name in event["rounds"].items():
req_url = url + str(roundid)
print(req_url)
res = get(req_url)
soup = BeautifulSoup(res.content)
athletes = soup.find_all("span", class_="athlete-name")
scores = soup.find_all("div", class_="all-waves all-waves-grid")
for i in range(len(athletes)):
athlete_scores = {}
athlete_scores["event"] = event_name
athlete_scores["round"] = round_name
# athlete_scores['heat'] = i
athlete_scores["name"] = athletes[i].text
athlete_scores["scores"] = []
per_wave_scores = scores[i].find_all("span", class_="score")
for b in range(len(per_wave_scores)):
try:
athlete_scores["scores"].append(float(per_wave_scores[b].text))
except:
continue
data.append(athlete_scores)
time.sleep(10)
return pd.DataFrame(data)
data = get_scores(event_dict=events)
data.to_csv('./data/scores.csv', index=False)
data
# ### Generalize for all years, all events per year
#
# Use a for loop to check every roundid, can be slow but hard coding event info in a dict seems like unnecessary work.
#
# If this gets too messy I can go back to hard coding.
yearly_urls = []
for year in range(2008, 2020):
yearly_urls.append(f'https://www.worldsurfleague.com/events/{year}/mct?all=1')
res = get(yearly_urls[0])
soup = BeautifulSoup(res.content)
for i in range(11):
print(soup.find_all("a", class_="event-schedule-details__event-name")[i]['href'])
soup.find_all("a", class_="event-schedule-details__event-name")[0].text
# Create a url for each year that shows the events page of the mens world tour
for year in range(2008, 2020):
year_url = f"https://www.worldsurfleague.com/events/{year}/mct?all=1"
data = []
# Get html content for each year
result = get(year_url)
soup = BeautifulSoup(result.content)
# Get a list of event info for each event in that year
event_info = soup.find_all("a", class_="event-schedule-details__event-name")
# Cycle through events and get their URLs
for event in event_info:
url = event["href"]
# Cycle through roundId numbers and try to get scores.
# This is difficult because roundIds do not appear to be ordered in any way
for i in range(20_000):
try:
# Append roundId integer to try
res = get(f'{url}?roundId={i}')
print(f'Got roundId: {i} for {event.text}')
# Get html soup
event_soup = BeautifulSoup(res.content)
#Get list of athlete names
athletes = event_soup.find_all("span", class_="athlete-name")
# Get list of scores lists
scores = event_soup.find_all("div", class_="all-waves all-waves-grid")
# Go through athletes
for i in range(len(athletes)):
# Create dict to save scores
athlete_scores = {}
# Save event name
# athlete_scores["event"] = event_name
# Save round name
# athlete_scores["round"] = round_name
# Save heat number
# athlete_scores['heat'] = i
# Athlete name
athlete_scores["name"] = athletes[i].text
# Empty list for athletes scores in that heat
athlete_scores["scores"] = []
# Scores list
per_wave_scores = scores[i].find_all("span", class_="score")
# Append scores
for b in range(len(per_wave_scores)):
try:
athlete_scores["scores"].append(float(per_wave_scores[b].text))
except:
continue
# Add to data list
data.append(athlete_scores)
# Timeout
time.sleep(2)
except:
time.sleep(2)
continue
# Save yearly csvs
pd.DataFrame(data).to_csv(f'./data/{year}.csv')
# ### Selenium
# get_scores function retrieves scores from event sites, selenium then clicks the button to cllect scores from previous rounds of the same event.
def get_scores(page_html, event_name):
data = []
# Get html soup
event_soup = BeautifulSoup(page_html)
# Get list of athlete names
athletes = event_soup.find_all("span", class_="athlete-name")
# Get list of scores lists
scores = event_soup.find_all("div", class_="all-waves all-waves-grid")
# Go through athletes
for i in range(len(athletes)):
# Create dict to save scores
athlete_scores = {}
# Save event name
athlete_scores["event"] = event_name
# Save round name
athlete_scores["round"] = event_soup.find(
"li", class_="carousel-item is-selected"
).find("span", class_="carousel-item-title-wrap")["data-short-title"]
# Save heat number
athlete_scores["heat"] = (
athletes[i]
.find_parent("div", class_="bd new-heat-bd")
.find_previous_sibling()
.find("span", class_="new-heat-hd-name")
.text
)
# Athlete name
athlete_scores["name"] = athletes[i].text
# Empty list for athletes scores in that heat
athlete_scores["scores"] = []
# Scores list
per_wave_scores = scores[i].find_all("span", class_="score")
# Append scores
for b in range(len(per_wave_scores)):
try:
athlete_scores["scores"].append(float(per_wave_scores[b].text))
except:
continue
# Add to data list
data.append(athlete_scores)
return data
# +
from selenium import webdriver
from selenium.webdriver.common.by import By
op = webdriver.ChromeOptions()
op.add_argument('headless')
driver = webdriver.Chrome(options=op)
driver.implicitly_wait(10)
for year in range(2008, 2020):
year_url = f"https://www.worldsurfleague.com/events/{year}/mct?all=1"
data = []
# Get html content for each year
result = get(year_url)
soup = BeautifulSoup(result.content)
# Get a list of event info for each event in that year
event_info = soup.find_all("a", class_="event-schedule-details__event-name")
# Cycle through events and get their URLs
for event in event_info:
print(event.text)
# Get event url
url = event["href"]
# Point driver to event url
driver.get(url)
# Click privacy banner
try:
element = driver.find_element(By.ID, 'onetrust-accept-btn-handler')
driver.execute_script("arguments[0].click();", element)
except:
pass
# Get initial scores
data = get_scores(driver.page_source, event_name=event.text)
# Flickity button for previous round
flickity = driver.find_element(By.CLASS_NAME, 'flickity-button-icon')
while flickity:
flickity.click()
time.sleep(2)
data.append(get_scores(driver.page_source, event_name=event.text))
print(data)
#Save scores to csv
# pd.DataFrame(data).to_csv(f'./data/{event.text}_scores.csv', index=False)
# time.sleep(2)
# driver.get('https://www.worldsurfleague.com/events/2008/mct/4/quiksilver-pro-gold-coast')
# # driver.find_element(By.ID, 'onetrust-accept-btn-handler').click()
# # Get html soup
# event_soup = BeautifulSoup(driver.page_source)
# #Get list of athlete names
# athletes = event_soup.find_all("span", class_="athlete-name")
# athletes
# driver.find_element(By.CLASS_NAME, 'flickity-button-icon').click()
# event_soup = BeautifulSoup(driver.page_source)
# #Get list of athlete names
# athletes = event_soup.find_all("span", class_="athlete-name")
# athletes
# # driver.find_element(By.CLASS_NAME, 'flickity-button-icon')
# # driver.page_source
# +
driver.get('https://www.worldsurfleague.com/events/2008/mct/4/quiksilver-pro-gold-coast')
# driver.find_element(By.ID, 'onetrust-accept-btn-handler').click()
element = driver.find_element(By.ID, 'onetrust-accept-btn-handler')
driver.execute_script("arguments[0].click();", element)
# Get html soup
event_soup = BeautifulSoup(driver.page_source)
#Get list of athlete names
athletes = event_soup.find_all("span", class_="athlete-name")
athletes
driver.find_element(By.CLASS_NAME, 'flickity-button-icon').click()
event_soup = BeautifulSoup(driver.page_source)
#Get list of athlete names
athletes = event_soup.find_all("span", class_="athlete-name")
athletes
# driver.find_element(By.CLASS_NAME, 'flickity-button-icon')
# driver.page_source
# +
driver.find_element(By.CLASS_NAME, 'flickity-button-icon').click()
time.sleep(2)
event_soup = BeautifulSoup(driver.page_source)
#Get list of athlete names
athletes = event_soup.find_all("span", class_="athlete-name")
athletes
# -
for year in range(2008, 2020):
year_url = f"https://www.worldsurfleague.com/events/{year}/mct?all=1"
data = []
# Get html content for each year
result = get(year_url)
soup = BeautifulSoup(result.content)
# Get a list of event info for each event in that year
event_info = soup.find_all("a", class_="event-schedule-details__event-name")
# Cycle through events and get their URLs
for event in event_info:
# Get event url
url = event["href"]
# Get initial scores
data = get_scores(url)
| scratch/scraper.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Federated PyTorch TinyImageNet Tutorial
# ## Using low-level Python API
# # Long-Living entities update
#
# * We now may have director running on another machine.
# * We use Federation API to communicate with Director.
# * Federation object should hold a Director's client (for user service)
# * Keeping in mind that several API instances may be connacted to one Director.
#
#
# * We do not think for now how we start a Director.
# * But it knows the data shape and target shape for the DataScience problem in the Federation.
# * Director holds the list of connected envoys, we do not need to specify it anymore.
# * Director and Envoys are responsible for encrypting connections, we do not need to worry about certs.
#
#
# * Yet we MUST have a cert to communicate to the Director.
# * We MUST know the FQDN of a Director.
# * Director communicates data and target shape to the Federation interface object.
#
#
# * Experiment API may use this info to construct a dummy dataset and a `shard descriptor` stub.
# !pip install torchvision==0.8.1
# ## Connect to the Federation
# +
# Create a federation
from openfl.interface.interactive_api.federation import Federation
# please use the same identificator that was used in signed certificate
client_id = 'api'
cert_dir = 'cert'
director_node_fqdn = 'localhost'
# 1) Run with API layer - Director mTLS
# If the user wants to enable mTLS their must provide CA root chain, and signed key pair to the federation interface
# cert_chain = f'{cert_dir}/root_ca.crt'
# api_certificate = f'{cert_dir}/{client_id}.crt'
# api_private_key = f'{cert_dir}/{client_id}.key'
# federation = Federation(client_id=client_id, director_node_fqdn=director_node_fqdn, director_port='50051',
# cert_chain=cert_chain, api_cert=api_certificate, api_private_key=api_private_key)
# --------------------------------------------------------------------------------------------------------------------
# 2) Run with TLS disabled (trusted environment)
# Federation can also determine local fqdn automatically
federation = Federation(client_id=client_id, director_node_fqdn=director_node_fqdn, director_port='50051', tls=False)
# -
federation.target_shape
shard_registry = federation.get_shard_registry()
shard_registry
# First, request a dummy_shard_desc that holds information about the federated dataset
dummy_shard_desc = federation.get_dummy_shard_descriptor(size=10)
sample, target = dummy_shard_desc[0]
# ## Creating a FL experiment using Interactive API
from openfl.interface.interactive_api.experiment import TaskInterface, DataInterface, ModelInterface, FLExperiment
# ### Register dataset
# +
import torchvision
from torchvision import transforms as T
normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
augmentation = T.RandomApply(
[T.RandomHorizontalFlip(),
T.RandomRotation(10),
T.RandomResizedCrop(64)],
p=.8
)
training_transform = T.Compose(
[T.Lambda(lambda x: x.convert("RGB")),
augmentation,
T.ToTensor(),
normalize]
)
valid_transform = T.Compose(
[T.Lambda(lambda x: x.convert("RGB")),
T.ToTensor(),
normalize]
)
# +
from torch.utils.data import Dataset
class TransformedDataset(Dataset):
"""Image Person ReID Dataset."""
def __init__(self, dataset, transform=None, target_transform=None):
"""Initialize Dataset."""
self.dataset = dataset
self.transform = transform
self.target_transform = target_transform
def __len__(self):
"""Length of dataset."""
return len(self.dataset)
def __getitem__(self, index):
img, label = self.dataset[index]
label = self.target_transform(label) if self.target_transform else label
img = self.transform(img) if self.transform else img
return img, label
# -
class TinyImageNetDataset(DataInterface):
def __init__(self, **kwargs):
self.kwargs = kwargs
@property
def shard_descriptor(self):
return self._shard_descriptor
@shard_descriptor.setter
def shard_descriptor(self, shard_descriptor):
"""
Describe per-collaborator procedures or sharding.
This method will be called during a collaborator initialization.
Local shard_descriptor will be set by Envoy.
"""
self._shard_descriptor = shard_descriptor
self.train_set = TransformedDataset(
self._shard_descriptor.get_dataset('train'),
transform=training_transform
)
self.valid_set = TransformedDataset(
self._shard_descriptor.get_dataset('val'),
transform=valid_transform
)
def get_train_loader(self, **kwargs):
"""
Output of this method will be provided to tasks with optimizer in contract
"""
return DataLoader(
self.train_set, num_workers=8, batch_size=self.kwargs['train_bs'], shuffle=True
)
def get_valid_loader(self, **kwargs):
"""
Output of this method will be provided to tasks without optimizer in contract
"""
return DataLoader(self.valid_set, num_workers=8, batch_size=self.kwargs['valid_bs'])
def get_train_data_size(self):
"""
Information for aggregation
"""
return len(self.train_set)
def get_valid_data_size(self):
"""
Information for aggregation
"""
return len(self.valid_set)
fed_dataset = TinyImageNetDataset(train_bs=64, valid_bs=64)
# ### Describe the model and optimizer
# +
import os
import glob
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# +
"""
MobileNetV2 model
"""
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.model = torchvision.models.mobilenet_v2(pretrained=True)
self.model.requires_grad_(False)
self.model.classifier[1] = torch.nn.Linear(in_features=1280, \
out_features=200, bias=True)
def forward(self, x):
x = self.model.forward(x)
return x
model_net = Net()
# +
params_to_update = []
for param in model_net.parameters():
if param.requires_grad == True:
params_to_update.append(param)
optimizer_adam = optim.Adam(params_to_update, lr=1e-4)
def cross_entropy(output, target):
"""Binary cross-entropy metric
"""
return F.cross_entropy(input=output,target=target)
# -
# ### Register model
# +
from copy import deepcopy
framework_adapter = 'openfl.plugins.frameworks_adapters.pytorch_adapter.FrameworkAdapterPlugin'
model_interface = ModelInterface(model=model_net, optimizer=optimizer_adam, framework_plugin=framework_adapter)
# Save the initial model state
initial_model = deepcopy(model_net)
# -
# ## Define and register FL tasks
# +
task_interface = TaskInterface()
import torch
import tqdm
# The Interactive API supports registering functions definied in main module or imported.
def function_defined_in_notebook(some_parameter):
print(f'Also I accept a parameter and it is {some_parameter}')
# Task interface currently supports only standalone functions.
@task_interface.add_kwargs(**{'some_parameter': 42})
@task_interface.register_fl_task(model='net_model', data_loader='train_loader', \
device='device', optimizer='optimizer')
def train(net_model, train_loader, optimizer, device, loss_fn=cross_entropy, some_parameter=None):
device = torch.device('cuda')
if not torch.cuda.is_available():
device = 'cpu'
function_defined_in_notebook(some_parameter)
train_loader = tqdm.tqdm(train_loader, desc="train")
net_model.train()
net_model.to(device)
losses = []
for data, target in train_loader:
data, target = torch.tensor(data).to(device), torch.tensor(
target).to(device)
optimizer.zero_grad()
output = net_model(data)
loss = loss_fn(output=output, target=target)
loss.backward()
optimizer.step()
losses.append(loss.detach().cpu().numpy())
return {'train_loss': np.mean(losses),}
@task_interface.register_fl_task(model='net_model', data_loader='val_loader', device='device')
def validate(net_model, val_loader, device):
device = torch.device('cuda')
net_model.eval()
net_model.to(device)
val_loader = tqdm.tqdm(val_loader, desc="validate")
val_score = 0
total_samples = 0
with torch.no_grad():
for data, target in val_loader:
samples = target.shape[0]
total_samples += samples
data, target = torch.tensor(data).to(device), \
torch.tensor(target).to(device, dtype=torch.int64)
output = net_model(data)
pred = output.argmax(dim=1,keepdim=True)
val_score += pred.eq(target).sum().cpu().numpy()
return {'acc': val_score / total_samples,}
# -
# ## Time to start a federated learning experiment
# create an experimnet in federation
experiment_name = 'tinyimagenet_test_experiment'
fl_experiment = FLExperiment(federation=federation, experiment_name=experiment_name)
# The following command zips the workspace and python requirements to be transfered to collaborator nodes
fl_experiment.start(
model_provider=model_interface,
task_keeper=task_interface,
data_loader=fed_dataset,
rounds_to_train=5,
opt_treatment='CONTINUE_GLOBAL'
)
# + pycharm={"name": "#%%\n"}
# If user want to stop IPython session, then reconnect and check how experiment is going
# fl_experiment.restore_experiment_state(model_interface)
fl_experiment.stream_metrics(tensorboard_logs=False)
| openfl-tutorials/interactive_api/PyTorch_TinyImageNet/workspace/pytorch_tinyimagenet.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Modifying Toolbar Tools
# +
import warnings
import numpy as np
import holoviews as hv
from bokeh.models import HoverTool
from holoext.xbokeh import Mod
warnings.filterwarnings('ignore') # bokeh deprecation warnings
hv.extension('bokeh')
# +
x = np.array([8, 4, 2, 1])
y = np.array([2, 4, 5, 9])
bar = hv.Bars((x, y))
# -
# ### Hide toolbar
Mod(toolbar_location=None).apply(bar)
# ### Change toolbar location
Mod(toolbar_location='west').apply(bar) # user forgiving parser for location
# ### Add the default HoloView's tools and additional ones
Mod(tools=['default', 'hover', 'zoom_in']).apply(bar)
# ### Select specific tools delimited by comma
Mod(tools='save,xwheel_zoom, ywheel_zoom, hover').apply(bar)
# ### Input your customized tools with the default
hover_tool = HoverTool(tooltips=[('X value', '@x'),
('Y value', '@y')])
Mod(tools=['default', hover_tool]).apply(bar)
# ### Have hover tool but hide it in toolbar
Mod(show_hover=False).apply(bar)
# ### Hide Bokeh logo in toolbar
Mod(logo=False).apply(bar)
| docs/examples/modifying_toolbar_tools.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Clean Irish text
#
# > "...preserving some punctuation, for silence alignment"
#
# - toc: false
# - branch: master
# - hidden: true
# - categories: [irish, cleaning, alignment]
# +
def _ga_lc_word(text):
if text[0:1] in "nt" and text[1:2] in "AÁEÉIÍOÓUÚ":
return text[0:1] + "-" + text[1:].lower()
else:
return text.lower()
def ga_lower(text):
words = [_ga_lc_word(word) for word in text.split()]
return " ".join(words)
# -
test = "Cuairt an tAthair"
assert ga_lower(test) == "cuairt an t-athair"
import re
def clean_text(text):
# keep only word-internal apostrophes
text = re.sub("^'+", "", text)
text = re.sub("[']+$", "", text)
text = text.replace("' ", " ").replace(" '", " ")
text = text.replace("’", "'")
text = re.sub("[‘“”\"\(\)\[\]\{\}]", "", text)
# keep punctuation that can correspond to silence
text = re.sub("([,;\.!?])", " \\1", text)
# leave spaced hyphens, which also can be silences, except at EOS
text = re.sub(" \-$", "", text)
return ga_lower(text)
test = "'cuairt (an) “tAthair”''"
assert clean_text(test) == "cuairt an t-athair"
test = "'cuairt, (an) “tAthair”!"
assert clean_text(test) == "cuairt , an t-athair !"
test = "'cuairt, (an) “tAthair”! -"
assert clean_text(test) == "cuairt , an t-athair !"
# Actually using it.
from pathlib import Path
OUT = Path("<SNIP>")
SRC = Path("<SNIP>")
for filename in SRC.glob("*.txt"):
base = filename.stem
wav = OUT / f"{base}.wav"
if wav.is_file():
out = OUT / f"{base}.txt"
with open(out, "w") as outf, open(filename) as inf:
text = inf.read()
clean = clean_text(text)
outf.write(clean)
| _notebooks/2012-12-06-clean-irish-for-mfa-with-silences.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: R
# language: R
# name: ir
# ---
# # Statistics review 10: Further nonparametric methods
#
# R code accompanying [paper](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC420045/pdf/cc2836.pdf)
#
# ## Key learning points
#
# - Nonparametric methods for testing differences between more than two groups or treatments
suppressPackageStartupMessages(library(tidyverse))
options(repr.plot.width=4, repr.plot.height=3)
# ## Kruskal–Wallis test
#
# Nonparametric alternative to one-way analysis of variance.
# ### Manual calculation
ct <- c(7,1,2,6,11,8)
m <- c(4,7,16,11,21)
ns <- c(20,25,13,9,14,11)
# +
icu <- c(rep("ct", length(ct)), rep("m", length(m)), rep("ns", length(ns)))
days <- c(ct, m, ns)
df <- data.frame(icu=icu, days=days)
# -
head(df)
ggplot(df, aes(x=icu, y=days)) + geom_boxplot()
df1 <- df %>% mutate(rank=rank(days))
head(df1)
df2 <- df1 %>% group_by(icu) %>% summarize(r = sum(rank), n=n())
df2
# +
N <- dim(df1)[1]
T <- (12/(N*(N+1)))*sum((df2$r^2/df2$n)) - 3*(N+1)
# -
round(T, 2)
df <- dim(df2)[1]- 1
df
round(1 - pchisq(T, df), 4)
# ### Using built in function
kruskal.test(days ~ icu, data=df1)
# ### Dunn test for multiple comparisons
suppressPackageStartupMessages(library(FSA))
dunnTest(df1$days, df1$icu)
# ### Ad-hoc comparisons with Wilcoxon
pairwise.wilcox.test(df1$days, df1$icu, p.adjust.method = "holm")
# ## The Jonckheere–Terpstra test
#
# For comparisons where the treatment group is ordinal.
#
# We re-use the same data set, assuming that the ICU ordering is ct, m, ns.
# ### Using a package
head(df1)
df1$icu <- factor(df1$icu, levels=c("ct", "m","ns"))
str(df1)
library(clinfun)
jonckheere.test(df1$days, as.numeric(df1$icu), nperm=10000)
df1$days
as.numeric(df1$icu)
# ## The Friedman Test
#
# Extension of the sign test for matched pairs and is used when the data arise from more than two related samples. The Friedman test is the non-parametric alternative to the one-way ANOVA with repeated measures. Used as a two-way ANOVA with a completely balanced design.
# +
A <- c(6,9,10,14,11)
B <- c(9,16,14,14,16)
C <- c(10,16,22,40,17)
D <- c(16,32,67,19,60)
df3 <- data.frame(Patient = 1:5, A=A, B=B, C=C, D=D)
# -
df3.rank <- t(apply(df3[,2:5], 1, rank))
df3.rank <- data.frame(df3.rank)
df3.rank
df4 <- df3.rank %>% summarise_each("sum")
df4
# +
k <- dim(df3.rank)[2]
b <- dim(df3.rank)[1]
T <- (12/(b*k*(k+1)))*sum(df4^2) - 3*b*(k+1)
# -
T
round(1 - pchisq(T, k-1), 4)
df3
df5 <- df3 %>% gather(treatment, score, A:D)
head(df5)
str(df5)
# #### First way to call Friedman test
friedman.test(score ~ treatment | Patient, data=df5)
# #### Second way to call Friedman test
friedman.test(df5$score, df5$treatment, df5$Patient)
head(chickwts)
# ## Exercise
# **1**. Practice using the non-parametric tests on the `chickwts` data set.
| SR10_Further_nonparametric_methods.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <img src="../../img/logo-bdc.png" align="right" width="64" />
#
# # <span style="color:#336699">Calculating Image Difference on images obtained through STAC</span>
# <hr style="border:2px solid #0077b9;">
# If you haven't installed the [STAC client for Python](https://github.com/brazil-data-cube/stac.py), install it with `pip`:
# + id="J7bdIfKUd9Z_" outputId="989d243c-73dd-4d5d-b96f-c41d077ac6b7"
# !pip install stac.py
# -
# For more information on [STAC client for Python](https://github.com/brazil-data-cube/stac.py), see the introductory Jupyter Notebook about the [SpatioTemporal Asset Catalog (STAC)](./stac-introduction.ipynb).
# # 1. Load the following Libraries
# <hr style="border:1px solid #0077b9;">
# + id="jsqlxkurd9aF"
import numpy
import rasterio
import stac
from math import floor, ceil
from matplotlib import pyplot as plt
from pyproj import Proj
from rasterio.windows import Window
def longlat2window(lon, lat, dataset):
"""
Args:
lon (tuple): Tuple of min and max lon
lat (tuple): Tuple of min and max lat
dataset: Rasterio dataset
Returns:
rasterio.windows.Window
"""
p = Proj(dataset.crs)
t = dataset.transform
xmin, ymin = p(lon[0], lat[0])
xmax, ymax = p(lon[1], lat[1])
col_min, row_min = ~t * (xmin, ymin)
col_max, row_max = ~t * (xmax, ymax)
return Window.from_slices(rows=(floor(row_max), ceil(row_min)),
cols=(floor(col_min), ceil(col_max)))
# -
# # 2. Set the service and search for images
# <hr style="border:1px solid #0077b9;">
# + id="3hBZpY3Sd9aO"
st = stac.STAC('https://brazildatacube.dpi.inpe.br/stac/', access_token='<PASSWORD>')
# -
my_search = st.search({'collections':['CB4_64_16D_STK-1'],
'bbox':'-46.62597656250001,-13.19716452328198,-45.03570556640626,-12.297068292853805',
'datetime':'2018-08-01/2019-02-28',
'limit':30})
my_search
nir_band_info = my_search['features'][0]['properties']['eo:bands'][3]
nir_band_info
first_date_nir_url = my_search['features'][1]['assets']['BAND16']['href']
first_date_nir_url
last_date_nir_url = my_search['features'][13]['assets']['BAND16']['href']
last_date_nir_url
# +
w = -45.90
n = -12.6
e = -45.40
s = -12.90
with rasterio.open(first_date_nir_url) as dataset:
first_date_nir = dataset.read(1, window = longlat2window((w,e), (s,n), dataset))
plt.imshow(first_date_nir, cmap='gray')
plt.show()
# -
with rasterio.open(last_date_nir_url) as dataset:
last_date_nir = dataset.read(1, window = longlat2window((w,e), (s,n), dataset))
plt.imshow(last_date_nir, cmap='gray')
plt.show()
# # 3. Calculate image difference
# <hr style="border:1px solid #0077b9;">
nir_difference = last_date_nir - first_date_nir
nir_difference
plt.imshow(nir_difference, cmap='jet')
| Python/stac/stac-image-difference.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import gym, importlib, sys, warnings, IPython
import tensorflow as tf
import itertools
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# # %autosave 240
warnings.filterwarnings("ignore")
print(tf.__version__)
# -
# ## Cartpole Benchmark Setup
sys.path.append('../../embodied_arch/')
import embodied_AC as em
from embodied_misc import ActionPolicyNetwork, ValueNetwork, SensoriumNetworkTemplate
importlib.reload(em)
actor = lambda s: ActionPolicyNetwork(s, hSeq=(3,), gamma_reg=1.)
value = lambda s: ValueNetwork(s, hSeq=(3,), gamma_reg=1.)
sensor = lambda st, out_dim: SensoriumNetworkTemplate(st, hSeq=(8,), out_dim=out_dim, gamma_reg=5.)
# +
tf.reset_default_graph()
env = gym.make('CartPole-v0')
env.seed(1) # reproducible
cpac = em.EmbodiedAgentAC(
name="cp-emb-ac-v0", env_=env,
space_size = (4,1),latentDim=20,
alpha_p=10., alpha_v=50.,
actorNN=actor, sensorium=sensor
)
print(cpac, cpac.s_size, cpac.a_size)
# +
saver = tf.train.Saver(max_to_keep=1) #n_epochs = 1000
sess = tf.InteractiveSession()
cpac.init_graph(sess)
num_episodes = 100
n_epochs = 751
# -
## Verify step + play set up
state = cpac.env.reset()
print(state, cpac.act(state, sess))
cpac.env.step(cpac.act(state, sess))
cpac.play(sess)
len(cpac.episode_buffer)
# ## Baseline
print('Baselining untrained pnet...')
uplen0 = []
for k in range(num_episodes):
cpac.play(sess)
uplen0.append(cpac.last_total_return)
if k%20 == 0: print("\rEpisode {}/{}".format(k, num_episodes),end="")
base_perf = np.mean(uplen0)
print("\nCartpole stays up for an average of {} steps".format(base_perf))
# ## Train
obs = []
for ct in range(750):
cpac.play(sess)
tmp = cpac.pretrainV(sess)
obs.append(tmp)
print('\r\tIteration {}: Value loss({})'.format(ct, tmp), end="")
plt.plot(obs)
# Train pnet on cartpole episodes
print('Training...')
saver = tf.train.Saver(max_to_keep=1)
hist = cpac.work(sess, saver, num_epochs=n_epochs)
# ## Test
# Test pnet!
print('Testing...')
uplen = []
for k in range(num_episodes):
cpac.play(sess)
uplen.append(cpac.last_total_return)
if k%20 == 0: print("\rEpisode {}/{}".format(k, num_episodes),end="")
trained_perf = np.mean(uplen)
print("\nCartpole stays up for an average of {} steps compared to baseline {} steps".format(trained_perf, base_perf) )
# ## Evaluate
fig, axs = plt.subplots(2, 1, sharex=True)
sns.boxplot(uplen0, ax = axs[0])
axs[0].set_title('Baseline Episode Lengths')
sns.boxplot(uplen, ax = axs[1])
axs[1].set_title('Trained Episode Lengths')
buf = []
last_total_return, d, s = 0, False, cpac.env.reset()
while (len(buf) < 1000) and not d:
a_t = cpac.act(s, sess)
s1, r, d, *rest = cpac.env.step(a_t)
cpac.env.render()
buf.append([s, a_t, float(r), s1])
last_total_return += float(r)
s = s1
print("\r\tEpisode Length", len(buf), end="")
# +
# sess.close()
| embodied_arch/unit-tests/test_Emb-Cartpole-AC.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Adversarial attacks on Neural Networks
# This notebook has 6 parts, the last two parts are optionnal and added content :
# - Presentation of Attacks on Neural Networks
# - Implementation of basic attacks (hands-on)
# - Some theory and concepts to explain those basic attacks
# - Explaination and Hands-on on black-box attacks and transferability
# - Some words about Defense mechanisms
# - A fun fact
#
# All the links in the notebook are added in plain text at the end of the notebook in order of apparition. The papers used as source are also linked multiple time in the notebook. Some solution to the exercices and examples are given and loadable from the solutions folder.
# Please follow the notebook (and especially the cells) in the order as some content generated are saved and reused throughout the notebook.
#
# Some trainings and tests may take some time (at most 10-15min on the cell), and since I did not have the patience to implement a version for the Colab GPU, there is no escape for those. But they are not that long, and I would highly recommend you to *continue on the following exercises and theory during the computation* as there is a lot to read and do !
# (If it takes really too long, advancing in the notebook you will find cells for saving and loading the models and examples : a version is already available with my own tries in the folders, and you can directly load them to escape the long training and generation of examples, but that's not fun...)
#
# PS : Enjoy the work, all the sources and the cool-looking panda :3
# ## 1 - Attacks on Neural Networks (presentation)
# Deep learning models are spreading in applications in the industry and public sectors. In some recent examples we are looking at Convolutional Neural Networks for [self-driving cars](https://blogs.nvidia.com/blog/2019/05/07/self-driving-cars-make-decisions/)\[1\], with the capacity to recognize signs and lights, or in [medical image analysis](https://www.researchgate.net/publication/319535615_Medical_Image_Analysis_using_Convolutional_Neural_Networks_A_Review)\[2\] for detecting diseases such as cancer, or [human face recognition](https://www.researchgate.net/publication/3796546_Human_face_recognition_using_neural_networks)\[3\].
# Consequently, Deep Neural Networks become also critical in such systems, and industrials are looking for guarantees and not simple magical black-boxes... You may have found a lot of internship proposals on the subject of Neural Network security whether on the quality of the result, or even on the secrecy of the industry that uses it ! In other words, the development of deep learning applications is limited today because of its low interpretability : we don't know what the model will do and have no guarantees.
#
# But for today we are going to discuss a simple security matter about Neural Networks, which is about the quality of the results. Imagine for a second a self-driving car with such embedded DNN, and imagine for a second that someone outside can modify slightly the images sent to the NN, what would happen ?
# An attacker would try to make the image of a red light look like green for the NN, causing an accident. Is it possible ?
# Indeed it is, and it's actually quite easy in some situations. But more formally we are going to talk about (and simulate) an attack consisting of modifying as slightly as possible an image so that a Neural Network will wrongly classify it. Let's put it in forms :
# <div class="alert alert-warning">
# We consider a classification task with data $x \in [0, 1]^d$ and labels $y_{true} \in Z_k$ sampled from a distribution D. We identify a model with an hypothesis $h$ from a space $H$. On input $x$, the model outputs k
# class scores $h(x) \in \mathbb{R}$ . The loss function used to train the model, e.g., cross-entropy, is $L(h(x), y)$.
#
# We chose a target model $h \in H$ and an input $(x, y_{true})$. The goal is to find an *adversarial example* $x^{ADV}$ such that $x^{ADV}$ is **close** to x and yet is misclassified by the model. For this case we limit our adversarial examples in the space of $l_{\infty}$ adversaries, such that given a *budget* $\epsilon$, $\parallel x^{ADV} -x \parallel _{\infty} \le \epsilon$.
# </div>
# This type of adversarial attack is only one type of attack and example, so you can imagine the vastness of the problem to tackle for industrials.
# Now let's talk more precisely on the types of attacks : the objective is to find an *adversarial example* close to the original image. In order to do that, we start from the original image and we try to go in the direction of wrong classification. And you see it coming : for some attacks it's just a type of *gradient descent*. The attacks only tries to maximize the loss function around the original image. Yeah that's less impresive !
#
# But let me show you a basic example of the results :
# <img src="img/pandas.png">
# from [Explaining and harnessing adversarial examples, <NAME> & al.](https://arxiv.org/pdf/1412.6572.pdf)\[4\]
# Not bad eh?
#
# See, there are different types of attacks :
# - *White-box attacks* which have access to the model's parameters, vs. *black-box attacks* which don't know anything about the model they are attacking (except maybe about the dataset).
# - *Non-targeted attacks* try to make a misclassification by the model, whereas *Targeted attacks* make a misclassification to a specific target class (red light to green light for instance).
# - And finally *One-shot attacks* only require one step of computation to create an adversarial example, but you can also find *iterative* approaches, which are supposedly better, but we'll see about that...
# <div class="alert alert-info">
# Without further do, let's stop <b>talking</b> and do some <b>hackin'</b> !
# </div>
# ## 2 - Basic attacks (hands-on)
# Let's start by coding basic attacks.
# For now we will use as a target a simple convolutional model from the [pytorch examples](https://github.com/pytorch/examples/blob/master/mnist/main.py)\[5\] as a NN to attack, on the MNIST dataset.
# ### MNIST
#
# For this part and for the rest on the notebook, all the examples will be applied to the MNIST dataset which you already know.
# %matplotlib inline
import itertools
import math
import time
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
import matplotlib.pyplot as plt
from IPython import display
from torch.autograd import Variable
# +
# set batch_size
batch_size = 128
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5]) ])
train_dataset = torchvision.datasets.MNIST(root='data/', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = torchvision.datasets.MNIST(root='data/', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=True) # batch_size of 1 for adversarial attack
train_iterator = iter(train_loader)
# +
num_test_samples = 16 # number of digits to plot
# create figure for plotting
size_figure_grid = int(math.sqrt(num_test_samples))
fig, ax = plt.subplots(size_figure_grid, size_figure_grid, figsize=(6, 6))
for i, j in itertools.product(range(size_figure_grid), range(size_figure_grid)):
ax[i,j].get_xaxis().set_visible(False)
ax[i,j].get_yaxis().set_visible(False)
# load a batch of training data
images, labels = next(train_iterator)
# show a subpart of it
for k in range(num_test_samples):
i = k//4
j = k%4
ax[i,j].cla()
ax[i,j].imshow(images[k,:].data.cpu().numpy().reshape(28, 28), cmap='Greys')
display.clear_output(wait=True)
# -
# Simple CNN network from https://github.com/pytorch/examples/blob/master/mnist/main.py \[5\]
# +
# CNN
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import pickle
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
def train(model, train_loader, optimizer, epoch, log_interval):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test(model, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
# +
lr = 0.01
epochs = 5
log_interval = 100
model = Net()
optimizer = optim.SGD(model.parameters(), lr=lr)
for epoch in range(1, epochs + 1):
train(model, train_loader, optimizer, epoch, log_interval)
test(model, test_loader)
# -
# Let's save it in the `models` folder for later use. We store the entire model with all its parameters using `torch.save`, and we can later retrieve the entire model for another training if we want with `torch.load`.
model_file = "models/CNN_model"
torch.save(model, model_file)
# Now we will look into the most basic and famous attacking methods. Remember, those methods are optimization functions assimilable to gradient descent and which try to maximize the loss of the NN starting from one classified image.
# ### Fast Gradient Sign Method
#
# This method create a image-wide perturbation in the direction of the gradient of the loss function. It is a *single-step*, *non-targeted* attack with $\epsilon$ budget regulating the distance from initial image.
#
# $$x_{ADV} = x + \epsilon . sign(\nabla_{x}J(x, y_{true}))$$
# FGSM
def fgsm_attack(data, epsilon, model, target):
# Set requires_grad attribute of tensor. Important for Attack
data.requires_grad = True
# Forward pass the data through the model
output = model(data)
# Calculate the loss (same loss as for training)
loss = F.nll_loss(output, target)
# Zero all existing gradients
model.zero_grad()
# Calculate gradients of model in backward pass
loss.backward()
# Collect datagrad
data_grad = data.grad.data
# Collect the element-wise sign of the data gradient
sign_data_grad = data_grad.sign()
perturbed_image = data + epsilon * sign_data_grad
# Adding clipping to maintain [0,1] range
perturbed_image = torch.clamp(perturbed_image, 0, 1)
return perturbed_image
# +
epsilon = 0.05
scorer = torch.nn.Softmax(dim=1)
test_image, test_target = next(iter(test_loader))
output = model(test_image)
init_pred = output.max(1, keepdim=True)[1][0][0]
with torch.no_grad():
scores = scorer(output)
plt.figure()
plt.imshow(test_image.data.cpu().numpy().reshape(28, 28), cmap='Greys')
plt.title(f"Initial prediction: {init_pred}, True label: {test_target[0]}, Score: {scores[0][init_pred] * 100}%")
perturbed_data = fgsm_attack(test_image, epsilon, model, test_target)
output = model(perturbed_data)
final_pred = output.max(1, keepdim=True)[1][0][0]
with torch.no_grad():
scores = scorer(output)
plt.figure()
plt.imshow(perturbed_data.data.cpu().numpy().reshape(28, 28), cmap='Greys')
plt.title(f"Final prediction: {final_pred}, Score: {scores[0][final_pred] * 100}%")
plt.show()
# -
# ### Targeted - FGSM
#
# This method is pretty similar to the basic Fast Gradient Sign Method, except this version is *targeted*, meaning it wants to create an image that the model will classify as a specific class.
#
# $$x_{ADV} = x - \epsilon . sign(\nabla_{x}J(x, y_{target}))$$
# If you don't know what target class you should use, try to put the least likely class, $y_{target}=arg min(h(x))$. This is what we call the Single-Step Least-Likely Class Method (Step-LL) by [Adversarial Examples in the Physical World, Kurackin & al.](https://arxiv.org/abs/1607.02533)\[6\].
# <div class="alert alert-success">
# <h3>Now it's your turn !</h3>
# Implement this method, and the following, using the formulas. Mind all the parameters in input of the methods !
# </div>
# # %load solutions/tfgsm_attack.py
def t_fgsm_attack(image, espilon, model, false_target):
# code HERE
return image
# ### Iterative - FGSM
#
# This method is the iterative version of Fast Gradient Sign Method. Remember that we are constrained in the distance to the original image, we therefor have to limit the size of the iterative steps with the parameter $ \alpha = \epsilon/T$.
#
# $$x^{ADV}_0 = x, \space x^{ADV}_{t+1} = x^{ADV}_{t} + \alpha . sign(\nabla_{x}J(x^{ADV}_t, y_{true}))$$
# # %load solutions/ifgsm_attack.py
def i_fgsm_attack(image, espilon, T, model, target):
# code HERE
return image
# ### A randomized single-step attack
#
# This method is not famous, but as we will see later on, it has some intresting properties with the random step. It is however a *single-step* attack inspired by the FGSM. $\epsilon$ is our budget and $\alpha \le \epsilon$ is our random step.
#
# First we make a random step : $x' = x + \alpha . sign(\mathcal{N}(\boldsymbol{O}^d, \boldsymbol{I}^d))$
#
# And then we have simply : $x^{ADV} = x' + (\epsilon-\alpha) . sign(\nabla_{x'}J(x', y_{true}))$.
#
# Some people may argue that this is a *two*-steps attack, but don't mess with my nerves.
# As I'm very kind, I already implemented this one for you. You're welcome.
# R-FGSM
def r_fgsm_attack(data, epsilon, alpha, model, target):
new_data = data + alpha * torch.Tensor(np.random.normal(0, 1, size=(1, 1, 28, 28)))
#new_data = torch.clamp(new_data, 0, 1)
new_data.requires_grad = True
output = model(new_data)
loss = F.nll_loss(output, target)
model.zero_grad()
loss.backward()
data_grad = new_data.grad.data
sign_data_grad = data_grad.sign()
perturbed_image = new_data + (epsilon - alpha) * sign_data_grad
perturbed_image = torch.clamp(perturbed_image, 0, 1)
return perturbed_image
# +
epsilon = 0.05
alpha = 0.02
scorer = torch.nn.Softmax(dim=1)
test_image, test_target = next(iter(test_loader))
output = model(test_image)
init_pred = output.max(1, keepdim=True)[1][0][0]
with torch.no_grad():
scores = scorer(output)
plt.figure()
plt.imshow(test_image.data.cpu().numpy().reshape(28, 28), cmap='Greys')
plt.title(f"Initial prediction: {init_pred}, True label: {test_target[0]}, Score: {scores[0][init_pred] * 100}%")
perturbed_data = r_fgsm_attack(test_image, epsilon, alpha, model, test_target)
output = model(perturbed_data)
final_pred = output.max(1, keepdim=True)[1][0][0]
with torch.no_grad():
scores = scorer(output)
plt.figure()
plt.imshow(perturbed_data.data.cpu().numpy().reshape(28, 28), cmap='Greys')
plt.title(f"Final prediction: {final_pred}, Score: {scores[0][final_pred] * 100}%")
plt.show()
# -
# ### Test on our model
#
# We test the previous methods with this testing function which goes through all test dataset (but skip poorly classified images). It computes for each a perturbed image with the method chosen and return some of the adversarial examples generated and the accuracy on this new images. You can increase the number of adversarial examples in output by increasing the `size_limit` parameter, as we will later do.
# Test on NN
def test_attack( model, test_loader, epsilon, size_limit=5 ):
# Accuracy counter
correct = 0
adv_examples = []
# Loop over all examples in test set
for data, target in test_loader:
# Forward pass the data through the model
output = model(data)
init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
# If the initial prediction is wrong, dont bother attacking, just move on
if init_pred.item() != target.item():
continue
# Call FGSM Attack
perturbed_data = fgsm_attack(data, epsilon, model, target)
# Re-classify the perturbed image
output = model(perturbed_data)
# Check for success
final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
if final_pred.item() == target.item():
correct += 1
# Special case for saving 0 epsilon examples
if (epsilon == 0) and (len(adv_examples) < size_limit):
adv_ex = perturbed_data.data.cpu().numpy()
org = data.data.cpu().numpy()
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex, org) )
else:
# Save some adv examples for visualization later
if len(adv_examples) < size_limit:
adv_ex = perturbed_data.data.cpu().numpy()
org = data.data.cpu().numpy()
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex, org) )
# Calculate final accuracy for this epsilon
final_acc = correct/float(len(test_loader))
print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
# Return the accuracy and an adversarial example
return final_acc, adv_examples
# +
# load the model from saved ones
model = torch.load(model_file)
accuracies = []
examples = []
epsilons = [0.05, 0.1, 0.2, 0.3, 0.5]
# Run test for each epsilon
for eps in epsilons:
acc, ex = test_attack(model, test_loader, eps)
accuracies.append(acc)
examples.append(ex)
# -
# Let's save some examples in a pickle file for later use, since it takes a while to compute.
# +
# Create and export 200 adversarial examples for later with epsilon=0.05
model = torch.load(model_file)
acc, ex = test_attack(model, test_loader, 0.05, size_limit=200)
with open('data/pickle/cnn_adv_examples', 'wb') as file:
pickle.dump(ex, file)
# -
# We can also plot few of the adversarial examples generated to see the effect of the perturbations, and the impact of epsilon.
# Plot several examples of adversarial samples at each epsilon
cnt = 0
plt.figure(figsize=(8,10))
for i in range(len(epsilons)):
for j in range(len(examples[i])):
cnt += 1
plt.subplot(len(epsilons),len(examples[0]),cnt)
plt.xticks([], [])
plt.yticks([], [])
if j == 0:
plt.ylabel("Eps: {}".format(epsilons[i]), fontsize=14)
orig,adv,ex,org_data = examples[i][j]
plt.title("{} -> {}".format(orig, adv))
plt.imshow(ex[0][0], cmap="gray")
plt.tight_layout()
plt.show()
# <div class="alert alert-success">
# <h3>Now it's your turn !</h3>
# Try and modify the <b>test_attack</b> function to test another method that you implemented. Make sure to give all the paramenters needed by the method in the <b>test_attack</b> function, and also in the main cell.
# </div>
# For another, more complex approach to attack using momentum, refer to [Boosting Adversarial Attacks with Momentum, Y.Dong & al.](https://arxiv.org/pdf/1710.06081.pdf)\[7\].
# <div class="alert alert-info">
# As we can see in this test, we can easily affect the accuracy of the trained model, and the greater epsilon is, the more effective are the attacks.
# However the perturbations are quite visible for some examples, moreover the model was not trained for long (only 5 epochs). We are far from the wonderful example given with the panda. But, I would recommend you after this notebook to try to improve the training of the model for 20 epochs or more, and give a try to the iterative-FGSM attack to see how good this attack can perform in more real cases.
#
# The attacks presented here have obviously some limitations, that we will see in the Defenses part, yet the performance of those attacks is still surprising. Let's try to understand why it works so well.
# </div>
# ## 3 - Why does it work ? (theory-ish)
# We know that the given attacks try to look around an original image to find adversarial examples. Let's try to understand why a small perturbation like what we create with those attacks would have such an impact on the output of the NN.
# This theory is not formally developed in the sources found, but they give a sense of what is happening, or at least interpretations. However those interpretations may also be false intuitions.
# Generally speaking a neural network is simply a highly nonlinear function, from a black box point of view. And the output layer represents a conditional distribution of the label considering the input (and the training of the model). But since we don't want the model to overfit, and to only recognize the training set, we want the model to *generalize* its analysis on the entire space of possible images. For instance we don't want him to only recognize a perfect circle in the center of the image but also a less rounded circle slightly moved from the center.
#
# We want our model to recognize an infinite space (or very dense space) by giving him only a limited number of examples for training. This is like analyzing $\mathbb{R}$ when you only give him $\mathbb{N}$ as training. Therefor the model should generalize information, even in non-local region of the input space (regions that does not contains training examples in their vicinity).
# Moreover, we want the model to *locally* generalize the information, so that a slight modification of the image doesn't change the classification. We can call that **smoothness** : imperceptibly tiny perturbations of a given image should not change the underlying class. But we saw with the previous attacks that this is not always the case.
# <div class="alert alert-warning">
# Since the neural network is highly nonlinear, the input-to-ouput mapping of the model is fairly discontinuous, and the output space around all points is actually not "smooth". We can find adversarial examples close to every point of the input space. In other words, adversarial examples represent low-probability images but which are dense in the input space.
#
# The ouput space around the original image is not smooth, and to find a different output near the original image we are looking for increased loss (because the loss supposedly translate the distance to correct label). Therefor, intuitively, this means that the loss around training images is not smooth, and the more we increase the loss, the more we have a chance that the output is effectively of a different (wrong) class.
# </div>
#
# If $\mathbb{N}$ are the training images, $\mathbb{Q}$ the space of correctly classified images, then irrationnals are the adversarial examples. They have a low probability of appearing, but they are dense in the space of images. That's why it is ineficient to try to create randomly those adversarial examples, but this is actually what we do for usual training by adding transormation of the space for more robustness of the model. We now know that this is not an efficient defense method, and we will look at more advanced defense mechanisms later on.
# #### Limits of direct attacks
# As we said all the attacks we saw until now are focused on Gradient Descent near the original image. However, as we will see in the Defense mechanisms, this type of attack can be defeated.
# Since they use a gradient approximation, the model can naturally have (or learn to have) a non-smooth loss gradient around each points, so that the approximation of the gradient by those linear methods fail.
#
# [Tamèr & al.](https://arxiv.org/pdf/1705.07204.pdf) \[8\] are giving a great view of this, and how it can be used, in the paper *Ensemble adversarial training : attacks and defenses*. Here is an image of this paper to illustrate this.
# <img src="img/gradient-masking.png">
# This is called the Gradient masking effect : the Loss gradient around the original image have local maxima in different directions, that prevent single-step attacks to find the right direction for increasing the loss.
#
# And this increasing the loss does not necessarily mean having a different class, the model can actually learn to create Loss small maxima around training point that do not translate in class change (for instance it could change the scores to increase the loss but keep the argmax the same).
#
# This type of defense is less efficient against the iterative attack, which is less sensible to that non-smoothness, but can still be trapped in those local loss maxima.
#
# Remember the R-FGSM attack, with the random step at the beginning ? This is exactly the objective of this random step : get outside of this non-smoothness learnt by the model.
#
# We will see more about that in the Defenses part.
# ## 4 - About transfers of attacks (mixed)
# What we saw until now was actually pretty simple : we attack a model by doing a gradient descent to increase the loss function. But what if we don't have access to the model ?
#
# <div class="alert alert-info">
# We can find, for any trained model, adversarial examples with the attacks we developped earlier. But it gets better than this : the adversarial examples we created on a model are actually really robusts, they work on other models as well !
# More dramatically, you can even attack model that were trained on a completely different training subset !
# </div>
#
# This is called *black-box attack*, and reprensents the event I described at the beginning of someone attacking a self-driving car.
# One major problem about deep learning as I said earlier is the low interpretability of the model. After training we can hardly see what each unit represent or has learnt, and even guarantee what the model will recognize or not.
# The study of interpretability of Neural Network is an entirely different and complex subject, so I will not formally present it here. But if you want to get a closer look, I will suggest to start from [Visualizing and Understanding Convolutional Networks, <NAME> & <NAME>](https://arxiv.org/abs/1311.2901) \[9\].
# If we are not going to put formal concepts on interpretability, we still are going to use the intuition that we get from this field of study. Especially, we want to understand why adversarial examples generated from a model would work on another.
#
# Intuitively we think that a model in training is learning to recognize information in the image (for the MNIST example), so that specific layers or units (we don't know which one) are responsible for recognizing a specific feature in the image, and other layers for different features, etc. Therefor we would think that the parameters of the model after training contain some meaning, with the capacity to recognize information.
#
# If we take a layer, the output vector should give a vector representation of a feature. The direction of the ouput vector should include the meaning of what the unit has learnt, what we call the *semantic*. In other words, we would think that the last layer forms a distinguished basis of the space that is particurlarly suitable to extract semantic information. You could get a better sense of this into [this small explanation](https://www.quora.com/What-does-it-mean-that-Neural-Networks-Disentangle-variation-factors-across-coordinates) \[10\].
# <div class="alert alert-warning">
# To justify this idea we can look for images that maximize the activation value of a specific feature (an output vector), the result images have supposedly in common the feature that the unit is recognizing, and the ouput vector (the direction) we used would be identify as this specific feature in the output space.
#
# Formally we look for $x' = arg_{x \in I} max(<\phi(x)|e_i>)$ , where $\phi(x)$ is the layer we consider, and $e_i$ the natural basis vector associated with the i-th hidden unit, and I a set of images from the data distribution that the network was not trained on. The direction $e_i$ intuitively contains the information learnt by the layer, and the x' images found that nearly maximize this projection should share high-level similarities that the layer has recognized.
#
# However in [Intriguing properties of neural networks](https://arxiv.org/pdf/1312.6199.pdf) \[11\], I.Goodfellow & al. show that the maximization of a random projection of the ouput is semantically indistinguishable from the maximization of the ouput projected on the natural basis vector associated with the unit.
# Meaning that $x' = arg_{x \in I} max(<\phi(x)|v>)$ , where v is a random direction, give the same type of images that share high-level similarities (features). Therefor the direction of the layer doesn't hold the information learnt and our intuition was false.
#
# In other words, the ouput space is not better than a random projection for inspecting the properties of the layer, this suggests that the bulk of semantic information is not included in the individual units, but in the space of activations (the images).
# </div>
# This explains why adversarial examples are somewhat transferable to other models that were trained on the same or close training set, because the set actually contains this type of hidden information, and the models are just a translation of it in some way.
# #### Difference between models
# Let's test this transfer of attack between two models that share the same training set. Let's train another simple fully connected model from [here](https://towardsdatascience.com/training-neural-network-from-scratch-using-pytorch-in-just-7-cells-e6e904070a1d) \[12\].
input_size = 784
hidden_layers = [128,64]
output_size = 10
model = nn.Sequential(
nn.Linear(input_size, hidden_layers[0]),
nn.ReLU(),
nn.Linear(hidden_layers[0], hidden_layers[1]),
nn.ReLU(),
nn.Linear(hidden_layers[1], output_size),
nn.LogSoftmax(dim=1)
)
criterion = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr=0.003)
epochs = 8
for e in range(epochs):
running_loss = 0
for batch_idx, (data, target) in enumerate(train_loader):
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
e, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test_fc(model, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data = data.view(data.shape[0], -1)
output = model(data)
test_loss += criterion(output, target).item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
test_fc(model, test_loader)
# Save it for later
model_2_file = "models/Fully_connected_model"
torch.save(model, model_2_file)
# #### Test of transfer
# Now we will try to transfer some adversarial examples generated with the CNN model to the Fully Connected model, and see what are their performance.
# +
# test black-box attacks
cnn = torch.load(model_file)
simple_model = torch.load(model_2_file)
with open('data/pickle/cnn_adv_examples', 'rb') as file:
cnn_adv_examples = pickle.load(file)
"""
For each example we have the original class, the modified prediction, the adversarial image generated, and the original image.
We will see for the 200 adversarial images from the CNN if they also trick the GAN into misprediction.
"""
def transfer_attack(model, adv_examples, is_fc=True):
model.eval()
correct = 0
adversarial = 0
modified = 0
with torch.no_grad():
for org, mod, adv, data in adv_examples:
if is_fc:
# Convert numpy saved data into Tensor
data = torch.from_numpy(data)
adv = torch.from_numpy(adv)
# Convert the data format for the simple model (784 in input)
data = data.view(data.shape[0], -1)
adv = adv.view(data.shape[0], -1)
if not is_fc:
data = torch.from_numpy(data.reshape(1, 1, 28, 28))
adv = torch.from_numpy(adv.reshape(1, 1, 28, 28))
output = model(data)
first_pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += first_pred.eq(org).item()
output = model(adv)
mod_pred = output.argmax(dim=1, keepdim=True)
adversarial += mod_pred.eq(org).item()
modified += mod_pred.ne(first_pred).item()
print(f"Adversarial examples {len(adv_examples)}: \n{100. * correct / len(adv_examples)}% accuracy on originals \n{100. * adversarial / len(adv_examples)}% accuracy on adversarials \n-> {100. * modified / len(adv_examples)}% of adversarials led to misclassification")
transfer_attack(simple_model, cnn_adv_examples, True)
# -
# You see that even if the adversarial examples where generated using gradient descent on our Convolutional Network, a third of them successfully attacked our other fully connected model.
# To go deeper into the strenght of those adversarial examples, we could apply this test to a complete test set composed of already misclassified images and adversarial examples generated from the CNN on the simple model. We would know what is the impact on the overall accuracy of the simple model.
# <div class="alert alert-success">
# <h2>Your turn !</h2>
# Generate adversarial examples for the simple model using the <b>test_attack</b> method from the beginning by completing the following cell.
# Then test the effectiveness of those adversarial examples on our first CNN. (Remember to save the adversarial examples in a different file for reuse as it take long to generate).
# </div>
# # %load solutions/test_attack_bis.py
# Test attack on the simple model
def test_attack_bis( model, test_loader, epsilon, size_limit=5 ):
correct = 0
adv_examples = []
for data, target in test_loader:
# Modify the format of data so that the simple model can read it
# Code HERE
output = model(data)
init_pred = output.max(1, keepdim=True)[1]
if init_pred.item() != target.item():
continue
# Call FGSM Attack or another attack
perturbed_data = fgsm_attack(data, epsilon, model, target)
output = model(perturbed_data)
final_pred = output.max(1, keepdim=True)[1]
if final_pred.item() == target.item():
correct += 1
if (epsilon == 0) and (len(adv_examples) < size_limit):
adv_ex = perturbed_data.data.cpu().numpy()
org = data.data.cpu().numpy()
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex, org) )
else:
if len(adv_examples) < size_limit:
adv_ex = perturbed_data.data.cpu().numpy()
org = data.data.cpu().numpy()
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex, org) )
final_acc = correct/float(len(test_loader))
print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
return final_acc, adv_examples
# +
# # %load solutions/fc_adversarial_examples.py
# Generate adversarial examples for the FC model
# Save some of them in a file
filename = 'data/pickle/fc_adv_examples'
# Code HERE
# +
# # %load solutions/transfer_fc_attacks.py
# Load FC adversarial examples and test them on the CNN
# Code HERE
# -
# Which model is more robust to the attacks ?
# #### Difference between training sets
# <div class="alert alert-info">
# We could also try a black box attack between two models trained on different training sets from the MNIST example. But since it takes a while to train our two models, and we don't want to get confused with the names, we will not do it here. However if you have some time after the notebook, you can try here to train those models and transfer adversarial examples from one to the other !
# </div>
# ## 5 - (Optionnal) Defenses
# Now that we know how main attacks work, we want and try to defend our models to those attacks.
# We present here some defense mechanisms described by [Tramèr & al.](https://arxiv.org/pdf/1705.07204.pdf)\[8\].
# We already some methods to make NN models more robust via training : using manipulations on the training set such as transformations. However, as we explained earlier in the 3rd part, those methods are similar to randomly or uniformly creating adversarial examples that are inefficients. They are in particular not effective against the type of white-box attacks we saw today.
#
# Yet the models can actually learn to defend themselves against those white-box attacks, by adding adversarial examples in the mix of the training set. In order to ameliorate this *adversarial training*, the percentage of those adversarial examples in the training set, and the time at which those adversarial examples are generated may vary. In their work [Goodfellow & al.](https://arxiv.org/pdf/1312.6199.pdf)\[11\] suggests that the best option is to generate adversarial examples at each step and mix them with the training set in a stable proportion.
# The theory behind adversarial training is actually fascinating, I highly recommend to take a look at [the paper from Tramèr & al.](https://arxiv.org/pdf/1705.07204.pdf)\[8\].
# For instance, the adversarial training enables the model to train no on the adversarial examples, but actually make the attack itself perform worse overall !
#
# This is in particular due to the limits of attacks, that we presented shortly in the *Why it works* section.
# <div class="alert alert-warning">
# To make it more formal : we take the notation from Tramèr & al.
# $$h^{*} = argmin_{h \in H} \mathbb{E}_{(x, y_{true} \sim D)}[max_{\| x^{ADV}-x\|_{\infty} \le \epsilon} L(h(x^{ADV}), y_{true})]$$
# </div>
# The ideally trained model $h^*$ is the model that minimizes the risk of adversarial examples, i.e. minimizes in mean the loss of generated adversarial examples.
# You there are two optimization problems, quite like the GAN : the attack is generating adversarial examples that maximize the loss around the original images from D (the training set for instance), and the model is learning to minimize the mean of this created loss. This may remind you of the GAN with the Generator creating adverarial fake images, and the discriminator trying to discern which is which.
# However, Tramèr & al. point out that by using standard attacks like single-step FGSMs we do not sufficiently approach the maximization problem inside the bracket, meaning the attack is far from the maximum of loss we could create around the images. Therefor the adversarial training is less effective and even reach a degenerate solution of this optimization problem.
#
# To tackle this limitation, they propose an ensemble adversarial training, using the black-box transferability of adversarial examples instead of generating them directly on the model. This ensemble training method (ensemble because it uses different models for generation of adversarial examples) is better in the sens that the model has no effect on the strength of the attack : it cannot limit the attack with unsmooth gradient anymore, since the attacks are generated on other static models. Moreover this method supposedly train the model against black-box attacks (or at least it trains it better than usual adversarial training).
#
# They formulate a theorem that state this capacity of the trained model to resist to future black-box attacks if the new adversary A∗ is not “much stronger” than the adversaries used for training.
# As you can see this is not much convincing for an industrial who wishes for guarantees. Not only we cannot guarantee the robustness of the model to black-box attacks, but this just for the $l_{\infty}$ bounded adversarial examples ! They are a lot of other classes of adversaries. By reducing the dimension (for example for the MNIST problem with lower dimension than other ImageNet-scale tasks) we can reach some kind of guarantees, but still limited to the adversaries met in training, whereas for higher dimensions the guarantees seem out of reach.
# There are other type of defense mechanisms like high-level Denoiser methods based on DUNET, which try to dimish the amplification of the perturbation throughout the layers of the model. They are different types of Denoiser, a small description is given in [this article on medium.com](https://medium.com/onfido-tech/adversarial-attacks-and-defences-for-convolutional-neural-networks-66915ece52e7) \[13\], and you can find an implementation of such denoiser on this [GitHub repository](https://github.com/lfz/Guided-Denoise) \[14\].
#
# [Goodfellow & al.](https://arxiv.org/pdf/1312.6199.pdf) \[11\] present a spectral analysis of the stability of model accross layers, which can be used to give bounds to the adversarial examples' perturbations effects.
# In conclusion there is still a lot of work to do in the subject of attacks and defenses mechanisms, as well as formal guarantees and interpretability of neural networks.
# ## 6 - Infinity War 2 (fun-fact)
# With all this attack and defense mechanisms, we are entering a similar research on cybersecurity world, where people are trying to attack the best defenses, and defend against the best attacks.
#
# The most famous attacks and defenses are all presented in the [NISP Competition of 2017](https://www.kaggle.com/google-brain/nips17-adversarial-learning-final-results) \[15\], which is cited by almost the ressources I gave in this notebook. This competition establishes a ranking of best attacks and defenses. Have a look, you can event try and complete this notebook by implementing them (the boosted attack with momentum for instance is just at your reach !).
# ## Sources
# I hope you had fun with this notebook hacking some simple model of Neural Network, and that you understood some of the principles behind attacks and defenses.
#
# Here is the list of all the links and ressources of this notebook in order of appearance !
# \[1\] https://blogs.nvidia.com/blog/2019/05/07/self-driving-cars-make-decisions/
#
# \[2\] https://www.researchgate.net/publication/319535615_Medical_Image_Analysis_using_Convolutional_Neural_Networks_A_Review
#
# \[3\] https://www.researchgate.net/publication/3796546_Human_face_recognition_using_neural_networks
#
# \[4\] [Explaining and harnessing adversarial examples, <NAME> & al.](https://arxiv.org/pdf/1412.6572.pdf)
#
# \[5\] [PyTorch examples for MNIST](https://github.com/pytorch/examples/blob/master/mnist/main.py)
#
# \[6\] [Adversarial Examples in the Physical World, Kurackin & al.](https://arxiv.org/abs/1607.02533)
#
# \[7\] [Boosting Adversarial Attacks with Momentum, Y.Dong & al.](https://arxiv.org/pdf/1710.06081.pdf)
#
# \[8\] [Ensemble adversarial training : attacks and defenses, Tamèr & al.](https://arxiv.org/pdf/1705.07204.pdf)
#
# \[9\] [Visualizing and Understanding Convolutional Networks, <NAME> & <NAME>](https://arxiv.org/abs/1311.2901)
#
# \[10\] [Small explanation on semantic information extraction by NN](https://www.quora.com/What-does-it-mean-that-Neural-Networks-Disentangle-variation-factors-across-coordinates)
#
# \[11\] [Intriguing properties of neural networks, I.Goodfellow & al.](https://arxiv.org/pdf/1312.6199.pdf) the main source for the notebook
#
# \[12\] [A simple fully connected network for MNIST](https://towardsdatascience.com/training-neural-network-from-scratch-using-pytorch-in-just-7-cells-e6e904070a1d)
#
# \[13\] [Medium article on Adversarial attacks and Defences](https://medium.com/onfido-tech/adversarial-attacks-and-defences-for-convolutional-neural-networks-66915ece52e7)
#
# \[14\] [GitHub repository of a High-level Denoiser](https://github.com/lfz/Guided-Denoise)
#
# \[15\] [The NISP Competition of 2017](https://www.kaggle.com/google-brain/nips17-adversarial-learning-final-results)
| Adversarial_attacks_on_NN.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 0.4.5
# language: julia
# name: julia-0.4
# ---
# # ADVI scratchpad
# Let's start with a simple model:
#
# $$
# \begin{align}
# n &\sim \mathrm{Normal}(\mu, \sigma^2) \\
# \mu &\sim \mathrm{Gamma}(2, 1) \\
# \sigma &\sim \mathrm{Gamma}(1, 2)
# \end{align}
# $$
# ## Generate fake data
using Distributions
using ForwardDiff
using VinDsl
srand(12587);
N = 5000
a, b, c, d = 2, 1, 1, 2
λ = Gamma(a, b)
ϕ = Gamma(d, c)
μ = rand(λ)
σ = rand(ϕ)
n = rand(Normal(μ, σ), N);
using PyPlot
plt[:hist](n);
# ## Build the ELBO
constrain_positive(x) = exp(x)
unconstrain_positive(x) = log(x)
post_pars(d::Distribution) = (p = length(d); Int(p * (p + 3)/2))
vars = [λ, ϕ]
nvars = length(vars)
npars = sum(map(post_pars, vars))
x = rand(npars)
function ELBO(x)
# make posterior distributions
d_λ = Normal(x[1], exp(x[2]))
d_ϕ = Normal(x[3], exp(x[4]))
# scaled unconstrained parameters
ζ_λ = rand(d_λ)
ζ_ϕ = rand(d_ϕ)
# constrained parameters
λ = constrain_positive(ζ_λ)
ϕ = constrain_positive(ζ_ϕ)
# jacobian
jac = ForwardDiff.jacobian(constrain_positive)
# make ELBO
L = sum(map(H, [d_λ, d_ϕ]))
L += logpdf(Gamma(a, b), λ)
L += logpdf(Gamma(d, c), ϕ)
L += sum(logpdf(Normal(λ, ϕ), n))
L += logdet(jac([ζ_λ]))
L += logdet(jac([ζ_ϕ]))
end
# + active=""
# Pseudocode of ELBO:
#
# L = 0
#
# ---- first pass: sample pts from posterior ---
# for s in sampling statements:
# switch dim(s):
# scalar: d_s = Normal(x[i], exp(x[i + 1]))
# update i counter
# vector: d_s = MvNormal(x[length(s)], Sigma)
# # need way to make MvNormal from Chol L:
# # U = Base.LinAlg.Cholesky(UpperTriangular(x[flat]), :U)
# # Sigma = PDMat(U)
# # or can overload MvNormal(mu::Vector{T}, L::LowerTriangular{S})
#
# xi = rand(d_s)
#
# sampled_var_name = constrain(xi, sampled_dist)
# # (e.g., y ~ Gamma ==> y = constrain(xi, Gamma)
# # constrain(xi, Gamma) = constrain_positive(xi)
# # in reality, if v ~ p_1 and y ~ p_2(v, w)
# # need to ensure v is in the intersection of the support of p_1 and the
# # valid parameter range of p_2
# # or just pick one and throw if it doesn't make sense
# # for now, just use RHS distribution; eventually, figure out support
#
# ---- comput H and logdet(J)
# L += H(d_s)
# L += logdet(jacobian(constrain mapping(xi))
#
# ---- other code inside macro that defines nonrandom variables ----
#
# ---- second pass: estimate E[log p] ----
# for s in sampling statements:
# # sampling statement LHS ~ RHS
# L += sum(logpdf(RHS, LHS))
#
# return L
#
# -
ELBO(x)
x0 = randn(npars)
∇L = ForwardDiff.gradient(ELBO)
ELBO(x)
eps = 0.1
decay = 0.9
x = x0
avg_sq_grad = nothing
elbo = Float64[]
for idx in 1:200
gg = ∇L(x)
if avg_sq_grad != nothing
avg_sq_grad = avg_sq_grad * decay + gg.^2 * (1 - decay)
else
avg_sq_grad = gg.^2
end
x += eps * gg ./ (sqrt(avg_sq_grad) + 1e-8)
L = ELBO(x)
display(L)
push!(elbo, L)
end
plot(elbo)
plt[:ylim](-2e4, -9000)
∇L(x)
x
exp(x[1]), exp(x[3])
μ, σ
| test/ADVI_scratch.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Encoding of categorical variables
#
# In this notebook, we will present typical ways of dealing with
# **categorical variables** by encoding them, namely **ordinal encoding** and
# **one-hot encoding**.
# Let's first load the entire adult dataset containing both numerical and
# categorical data.
# +
import pandas as pd
adult_census = pd.read_csv("../datasets/adult-census.csv")
# drop the duplicated column `"education-num"` as stated in the first notebook
adult_census = adult_census.drop(columns="education-num")
target_name = "class"
target = adult_census[target_name]
data = adult_census.drop(columns=[target_name])
# -
# <div class="admonition caution alert alert-warning">
# <p class="first admonition-title" style="font-weight: bold;">Caution!</p>
# <p class="last">Here and later, we use the name <tt class="docutils literal">data</tt> and <tt class="docutils literal">target</tt> to be explicit. In
# scikit-learn documentation, <tt class="docutils literal">data</tt> is commonly named <tt class="docutils literal">X</tt> and <tt class="docutils literal">target</tt> is
# commonly called <tt class="docutils literal">y</tt>.</p>
# </div>
#
# ## Identify categorical variables
#
# As we saw in the previous section, a numerical variable is a
# quantity represented by a real or integer number. These variables can be
# naturally handled by machine learning algorithms that are typically composed
# of a sequence of arithmetic instructions such as additions and
# multiplications.
#
# In contrast, categorical variables have discrete values, typically
# represented by string labels (but not only) taken from a finite list of
# possible choices. For instance, the variable `native-country` in our dataset
# is a categorical variable because it encodes the data using a finite list of
# possible countries (along with the `?` symbol when this information is
# missing):
data["native-country"].value_counts().sort_index()
# How can we easily recognize categorical columns among the dataset? Part of
# the answer lies in the columns' data type:
data.dtypes
# If we look at the `"native-country"` column, we observe its data type is
# `object`, meaning it contains string values.
#
# ## Select features based on their data type
#
# In the previous notebook, we manually defined the numerical columns. We could
# do a similar approach. Instead, we will use the scikit-learn helper function
# `make_column_selector`, which allows us to select columns based on
# their data type. We will illustrate how to use this helper.
# +
from sklearn.compose import make_column_selector as selector
categorical_columns_selector = selector(dtype_include=object)
categorical_columns = categorical_columns_selector(data)
categorical_columns
# -
# Here, we created the selector by passing the data type to include; we then
# passed the input dataset to the selector object, which returned a list of
# column names that have the requested data type. We can now filter out the
# unwanted columns:
data_categorical = data[categorical_columns]
data_categorical.head()
print(f"The dataset is composed of {data_categorical.shape[1]} features")
# In the remainder of this section, we will present different strategies to
# encode categorical data into numerical data which can be used by a
# machine-learning algorithm.
# ## Encoding ordinal categories
#
# The most intuitive strategy is to encode each category with a different
# number. The `OrdinalEncoder` will transform the data in such manner.
# We will start by encoding a single column to understand how the encoding
# works.
# +
from sklearn.preprocessing import OrdinalEncoder
education_column = data_categorical[["education"]]
encoder = OrdinalEncoder()
education_encoded = encoder.fit_transform(education_column)
education_encoded
# -
# We see that each category in `"education"` has been replaced by a numeric
# value. We could check the mapping between the categories and the numerical
# values by checking the fitted attribute `categories_`.
encoder.categories_
# Now, we can check the encoding applied on all categorical features.
data_encoded = encoder.fit_transform(data_categorical)
data_encoded[:5]
encoder.categories_
print(
f"The dataset encoded contains {data_encoded.shape[1]} features")
# We see that the categories have been encoded for each feature (column)
# independently. We also note that the number of features before and after the
# encoding is the same.
#
# However, be careful when applying this encoding strategy:
# using this integer representation leads downstream predictive models
# to assume that the values are ordered (0 < 1 < 2 < 3... for instance).
#
# By default, `OrdinalEncoder` uses a lexicographical strategy to map string
# category labels to integers. This strategy is arbitrary and often
# meaningless. For instance, suppose the dataset has a categorical variable
# named `"size"` with categories such as "S", "M", "L", "XL". We would like the
# integer representation to respect the meaning of the sizes by mapping them to
# increasing integers such as `0, 1, 2, 3`.
# However, the lexicographical strategy used by default would map the labels
# "S", "M", "L", "XL" to 2, 1, 0, 3, by following the alphabetical order.
#
# The `OrdinalEncoder` class accepts a `categories` constructor argument to
# pass categories in the expected ordering explicitly.
#
# If a categorical variable does not carry any meaningful order information
# then this encoding might be misleading to downstream statistical models and
# you might consider using one-hot encoding instead (see below).
#
# <div class="admonition important alert alert-info">
# <p class="first admonition-title" style="font-weight: bold;">Important</p>
# <p class="last">Note however that the impact of violating this ordering assumption is really
# dependent on the downstream models. For instance, linear models will be
# impacted by misordered categories while decision trees model will not be.</p>
# </div>
#
# ## Encoding nominal categories (without assuming any order)
#
# `OneHotEncoder` is an alternative encoder that prevents the downstream
# models to make a false assumption about the ordering of categories. For a
# given feature, it will create as many new columns as there are possible
# categories. For a given sample, the value of the column corresponding to the
# category will be set to `1` while all the columns of the other categories
# will be set to `0`.
#
# We will start by encoding a single feature (e.g. `"education"`) to illustrate
# how the encoding works.
# +
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False)
education_encoded = encoder.fit_transform(education_column)
education_encoded
# [markdown]
# ```{note}
# `sparse=False` is used in the `OneHotEncoder` for didactic purposes, namely
# easier visualisation of the data.
#
# sparse matrices are efficient data structures when most of your matrix
# elements are zero. They won't be covered in details in this course. If you
# want more details about them, you can look at
# [this](https://scipy-lectures.org/advanced/scipy_sparse/introduction.html#why-sparse-matrices).
# ```
# -
# We see that encoding a single feature will give a NumPy array full of zeros
# and ones. We can get a better understanding using the associated feature
# names resulting from the transformation.
feature_names = encoder.get_feature_names(input_features=["education"])
education_encoded = pd.DataFrame(education_encoded, columns=feature_names)
education_encoded
# As we can see, each category (unique value) became a column; the encoding
# returned, for each sample, a 1 to specify which category it belongs to.
#
# Let's apply this encoding on the full dataset.
print(
f"The dataset is composed of {data_categorical.shape[1]} features")
data_categorical.head()
data_encoded = encoder.fit_transform(data_categorical)
data_encoded[:5]
print(
f"The encoded dataset contains {data_encoded.shape[1]} features")
# Let's wrap this NumPy array in a dataframe with informative column names as
# provided by the encoder object:
columns_encoded = encoder.get_feature_names(data_categorical.columns)
pd.DataFrame(data_encoded, columns=columns_encoded).head()
# Look at how the "workclass" variable of the 3 first records has been encoded
# and compare this to the original string representation.
#
# The number of features after the encoding is more than 10 times larger than
# in the original data because some variables such as `occupation` and
# `native-country` have many possible categories.
#
# ## Evaluate our predictive pipeline
#
# We can now integrate this encoder inside a machine learning pipeline like we
# did with numerical data: let's train a linear classifier on the encoded data
# and check the statistical performance of this machine learning pipeline using
# cross-validation.
#
# Before we create the pipeline, we have to linger on the `native-country`.
# Let's recall some statistics regarding this column.
data["native-country"].value_counts()
# We see that the `Holand-Netherlands` category is occurring rarely. This will
# be a problem during cross-validation: if the sample ends up in the test set
# during splitting then the classifier would not have seen the category during
# training and will not be able to encode it.
#
# In scikit-learn, there are two solutions to bypass this issue:
#
# * list all the possible categories and provide it to the encoder via the
# keyword argument `categories`;
# * use the parameter `handle_unknown`.
#
# Here, we will use the latter solution for simplicity.
# <div class="admonition tip alert alert-warning">
# <p class="first admonition-title" style="font-weight: bold;">Tip</p>
# <p class="last">Be aware the <tt class="docutils literal">OrdinalEncoder</tt> exposes as well a parameter
# <tt class="docutils literal">handle_unknown</tt>. It can be set to <tt class="docutils literal">use_encoded_value</tt> and by setting
# <tt class="docutils literal">unknown_value</tt> to handle rare categories.</p>
# </div>
# We can now create our machine learning pipeline.
# +
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
model = make_pipeline(
OneHotEncoder(handle_unknown="ignore"), LogisticRegression(max_iter=500)
)
# -
# <div class="admonition note alert alert-info">
# <p class="first admonition-title" style="font-weight: bold;">Note</p>
# <p class="last">Here, we need to increase the maximum number of iterations to obtain a fully
# converged <tt class="docutils literal">LogisticRegression</tt> and silence a <tt class="docutils literal">ConvergenceWarning</tt>. Contrary
# to the numerical features, the one-hot encoded categorical features are all
# on the same scale (values are 0 or 1), so they would not benefit from
# scaling. In this case, increasing <tt class="docutils literal">max_iter</tt> is the right thing to do.</p>
# </div>
# Finally, we can check the model's statistical performance only using the
# categorical columns.
from sklearn.model_selection import cross_validate
cv_results = cross_validate(model, data_categorical, target)
cv_results
scores = cv_results["test_score"]
print(f"The accuracy is: {scores.mean():.3f} +/- {scores.std():.3f}")
# As you can see, this representation of the categorical variables is
# slightly more predictive of the revenue than the numerical variables
# that we used previously.
#
# In this notebook we have:
# * seen two common strategies for encoding categorical features: **ordinal
# encoding** and **one-hot encoding**;
# * used a **pipeline** to use a **one-hot encoder** before fitting a logistic
# regression.
| notebooks/03_categorical_pipeline.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
#      
#      
#      
#      
#    
# [Home Page](../../Start_Here.ipynb)
#
# [Previous Notebook](../introduction/Introductory_Notebook.ipynb)
#      
#      
#      
#      
#    
# [1](../introduction/Introductory_Notebook.ipynb)
# [2]
# [3](../spring_mass/Spring_Mass_Problem_Notebook.ipynb)
# [4](../chip_2d/Challenge_CFD_Problem_Notebook.ipynb)
#      
#      
#      
#      
# [Next Notebook](../spring_mass/Spring_Mass_Problem_Notebook.ipynb)
#
#
# # Steady State 1D Diffusion in a Composite Bar using PINNs
# This notebook give you a headstart in solving your own Partial Differential Equations (PDEs) using neural networks. Let's quickly recap the theory of PINNs before proceeding. We will embed the physics of the problem in the the neural networks and in such setting, we can use them to approximate the solution to a given differential equation and boundary condition without any training data from other solvers. More specifically, the neural network will be trained to minimize a loss function which is formed using the differential equation and the boundary conditions. If the network is able to minimize this loss then it will in effect solve the given differential equation. More information about the Physics Informed Neural Networks (PINNs) can be found in the [paper](https://www.sciencedirect.com/science/article/pii/S0021999118307125?casa_token=<KEY>) published by Raissi et al.
#
# In this notebook we will solve the steady 1 dimensional heat transfer in a composite bar. We will use NVIDIA's SimNet library to create the problem setup. You can refer to the *SimNet User Guide* for more examples on solving different types of PDEs using the SimNet library. Also, for more information about the SimNet APIs you can refer the *SimNet Source Code Documentation*.
# ### Learning Outcomes
# 1. How to use SimNet to simulate physics problems using PINNs
# 1. How to write your own PDEs and formulate the different losses
# 2. How to use the Constructive Solid Geometry (CSG) module
# 2. How to use SimNet to solve a parameterized PDEs
#
# ## Problem Description
#
# Our aim is to obtain the temperature distribution inside the bar that is made up of two materials with different thermal conductivity. The geometry and the problem specification of the problem can be seen below
#
# <img src="diffusion_bar_geometry.png" alt="Drawing" style="width: 600px;"/>
#
# The composite bar extends from $x=0$ to $x=2$. The bar has material of conductivity $D_1=10$ from $x=0$ to $x=1$ and $D_2=0.1$ from $x=1$ to $x=2$. Both the ends of the bar, $x=0$ and $x=2$ are maintained at a constant temperatures of $0$ and $100$ respectively. For simplicity of modeling, we will treat the composite bar as two separate bars, bar 1 and bar 2, whose ends are joined together. We will treat the temperatures in the bar 1 as $U_1$ and the temperature in bar 2 as $U_2$.
#
# The equations and boundary conditions governing the problem can be mathematically expressed as
#
# One dimensional diffusion of temperature in bar 1 and 2:
#
# $$
# \begin{align}
# \frac{d}{dx}\left( D_1\frac{dU_1}{dx} \right) = 0, && \text{when } 0<x<1 \\
# \frac{d}{dx}\left( D_2\frac{dU_2}{dx} \right) = 0, && \text{when } 1<x<2 \\
# \end{align}
# $$
#
# Flux and temperature continuity at interface $(x=1)$
# $$
# \begin{align}
# D_1\frac{dU_1}{dx} = D_1\frac{dU_1}{dx}, && \text{when } x=1 \\
# U_1 = U_2, && \text{when } x=1 \\
# \end{align}
# $$
#
# ## Case Setup
#
# Now that we have our problem defined, let's take a look at the code required to solve it using SimNet's PINN library. SimNet has a variety of helper functions that will help us to set up the problem with ease. It has APIs to model geometry in a parameterized fashion using the Constructive Solid Geometry (CSG) module, write-up the required equations in a user-friendly symbolic format and comes with several advanced neural network architectures to choose for more complicated problems.
#
# Now let's start the problem by importing the required libraries and packages
# +
# import SimNet library
from sympy import Symbol, Function, Number, sin, Eq, Abs, exp
import numpy as np
import tensorflow as tf
from simnet.solver import Solver
from simnet.dataset import TrainDomain, ValidationDomain, MonitorDomain
from simnet.data import Validation, Monitor
from simnet.sympy_utils.geometry_1d import Line1D
from simnet.controller import SimNetController
from simnet.node import Node
from simnet.pdes import PDES
from simnet.variables import Variables
# -
# The `Solver` class trains and evaluates the SimNet's neural network solver. The class `TrainDomain` is used to define the training data for the problem, while the other classes like `ValidationDomain`, `MonitorDomain`, etc. are used to create other data evaluations during the training.
#
# The modules like `PDES` and `sympy_utils` contain predefined differential equations and geometries respectively that one can use to define the problem. We will describe each of them in detail as we move forward in the code. For more detailed information on all the different modules present in SimNet, we recommended you to refer the *SimNet Source Code Documentation*.
#
#
# ## Creating the geometry
#
# In this problem, we will create the 1-dimensional geometry using the `Line1D` from the geometry module. The module also contains several 2d and 3d shapes like rectangle, circle, triangle, cuboids, sphere, torus, cones, tetrahedrons, etc. We will define the one dimensional line object using the two end-points. For composite bar, we will create two separate bars as defined in the problem statement
# params for domain
L1 = Line1D(0,1)
L2 = Line1D(1,2)
# Next we will define the properties for the problem which will later be used while making the equations, boundary conditions, etc. Also, for this problem, we can find the temperature at the interface analytically and we will use that as to form validation domain to compare our neural network results
# +
# defining the parameters for boundary conditions and equations of the problem
D1 = 1e1
D2 = 1e-1
Ta = 0
Tc = 100
# temperature at the interface from analytical solution
Tb = (Tc + (D1/D2)*Ta)/(1 + (D1/D2))
# -
# ## Defining the differential equations for the problem
#
# The `PDES` class allows us to write the equations symbolically in Sympy. This allows users to quickly write their equations in the most natural way possible. The Sympy equations are converted to TensorFlow expressions in the back-end and can also be printed to ensure correct implementation.
#
# SimNet also comes with several common PDEs predefined for the user to choose from. Some of the PDEs that are already available in the PDEs module are: Navier Stokes, Linear Elasticity, Advection Diffusion, Wave Equations, etc.
#
# Let's create the PDE to define the diffusion equation. We will define the equation in its most generic, transient 3-dimensional, form and then have an argument `dim` that can reduce it to lower dimensional forms.
# $$\frac{\partial T}{\partial t}= \nabla\cdot \left( D \nabla T \right) + Q$$
#
# Let's start defining the equation by inhereting from the `PDES` class. We will create the initialization method for this class that defines the equation(s) of interest. We will be defining the diffusion equation using the source(`Q`), diffusivity(`D`), symbol for diffusion(`T`). If `D` or `Q` is given as a string we will convert it to functional form. This will allow us to solve problems with spatially/temporally varying properties.
class Diffusion(PDES):
name = 'Diffusion'
def __init__(self, T='T', D='D', Q=0, dim=3, time=True):
# set params
self.T = T
self.dim = dim
self.time = time
# coordinates
x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
# time
t = Symbol('t')
# make input variables
input_variables = {'x':x,'y':y,'z':z,'t':t}
if self.dim == 1:
input_variables.pop('y')
input_variables.pop('z')
elif self.dim == 2:
input_variables.pop('z')
if not self.time:
input_variables.pop('t')
# Temperature
assert type(T) == str, "T needs to be string"
T = Function(T)(*input_variables)
# Diffusivity
if type(D) is str:
D = Function(D)(*input_variables)
elif type(D) in [float, int]:
D = Number(D)
# Source
if type(Q) is str:
Q = Function(Q)(*input_variables)
elif type(Q) in [float, int]:
Q = Number(Q)
# set equations
self.equations = Variables()
self.equations['diffusion_'+self.T] = (T.diff(t)
- (D*T.diff(x)).diff(x)
- (D*T.diff(y)).diff(y)
- (D*T.diff(z)).diff(z)
- Q)
# First we defined the input variables $x, y, z$ and $t$ with Sympy symbols. Then we defined the functions for $T$, $D$ and $Q$ that are dependent on the input variables $(x, y, z, t)$. Using these we can write out our simple equation $T_t = \nabla \cdot (D \nabla T) + Q$. We store this equation in the class by adding it to the dictionary of `equations`.
#
# Note that we moved all the terms of the PDE either to LHS or RHS. This way, while using the equations in the `TrainDomain`, we
# can assign a custom source function to the `’diffusion_T’` key instead of 0 to add more source terms to our PDE.
#
# Great! We just wrote our own PDE in SimNet! Once you have understood the process to code a simple PDE, you can easily extend the procedure for different PDEs. You can also bundle multiple PDEs together in a same file by adding new keys to the equations dictionary. Below we show the code for the interface boundary condition where we need to maintain the field (dirichlet) and flux (neumann) continuity. *(More examples of coding your own PDE can be found in the SimNet User Guide Chapter 4)*.
#
# **Note :** The field continuity condition is needed because we are solving for two different temperatures in the two bars.
class DiffusionInterface(PDES):
name = 'DiffusionInterface'
def __init__(self, T_1, T_2, D_1, D_2, dim=3, time=True):
# set params
self.T_1 = T_1
self.T_2 = T_2
self.D_1 = D_1
self.D_2 = D_2
self.dim = dim
self.time = time
# coordinates
x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
normal_x, normal_y, normal_z = Symbol('normal_x'), Symbol('normal_y'), Symbol('normal_z')
# time
t = Symbol('t')
# make input variables
input_variables = {'x':x,'y':y,'z':z,'t':t}
if self.dim == 1:
input_variables.pop('y')
input_variables.pop('z')
elif self.dim == 2:
input_variables.pop('z')
if not self.time:
input_variables.pop('t')
# variables to match the boundary conditions (example Temperature)
T_1 = Function(T_1)(*input_variables)
T_2 = Function(T_2)(*input_variables)
# set equations
self.equations = Variables()
self.equations['diffusion_interface_dirichlet_'+self.T_1+'_'+self.T_2] = T_1 - T_2
flux_1 = self.D_1 * (normal_x * T_1.diff(x) + normal_y * T_1.diff(y) + normal_z * T_1.diff(z))
flux_2 = self.D_2 * (normal_x * T_2.diff(x) + normal_y * T_2.diff(y) + normal_z * T_2.diff(z))
self.equations['diffusion_interface_neumann_'+self.T_1+'_'+self.T_2] = flux_1 - flux_2
# ## Creating Train Domain: Assigning the boundary conditions and equations to the geometry
#
# As described earlier, we need to define a training domain for training our neural network. A loss function is then constructed which is a combination of contributions from the boundary conditions and equations that a neural network must satisfy at the end of the training. These training points (BCs and equations) are defined in a class that inherits from the `TrainDomain` parent class. The boundary conditions are implemented as soft constraints. These BCs along with the equations to be solved are used to formulate a composite loss that is minimized by the network during training.
#
# $$L = L_{BC} + L_{Residual}$$
#
# **Boundary conditions:** For generating a boundary condition, we need to sample the points on the required boundary/surface of the geometry and then assign them the desired values. We will use the method `boundary_bc` to sample the points on the boundary of the geometry we already created. `boundary_bc` will sample the entire boundary of the geometry, in this case, both the endpoints of the 1d line. A particular boundary of the geometry can be sub-sampled by using a particular criterion for the boundary_bc using the criteria parameter. For example, to sample the left end of `L1`, criteria is set to `Eq(x, 0)`.
#
# The desired values for the boundary condition are listed as a dictionary in `outvar_sympy` parameter. In SimNet we define these variables as keys of this dictionary which are converted to appropriate nodes in the computational graph. For this problem, we have `'u_1':0` at $x=0$ and `'u_2':100` at $x=2$. At $x=1$, we have the interface condition `'diffusion_interface_dirichlet_u_1_u_2':0` and `'diffusion_interface_neumann_u_1_u_2':0` that we defined earlier (i.e. $U_1=U_2$ and $D_1\frac{dU_1}{dx}=D_2\frac{dU_2}{dx}$).
#
# The number of points to sample on each boundary are specified using the `batch_size_per_area` parameter. The
# actual number of points sampled is then equal to the length/area of the geometry being sampled (boundary or interior)
# times the batch_size_per_area.
#
# In this case, since we only have 1 point on the boundary, we specify the `batch_size_per_area` as 1 for all the boundaries.
#
# **Equations to solve:** The Diffusion PDE we defined is enforced on all the points in the
# interior of both the bars, `L1` and `L2`. We will use `interior_bc` method to sample points in the interior of the geometry. Again, the equations to solve are specified as a dictionary input to `outvar_sympy` parameter. These dictionaries are then used when unrolling the computational graph for training.
#
# For this problem we have the `'diffusion_u_1':0` and `'diffusion_u_2':0` for bars `L1` and `L2` respectively. The parameter `bounds`, determines the range for sampling the values for variables $x$ and $y$. The `lambda_sympy` parameter is used to determine the weights for different losses. In this problem, we weight each point equally and hence keep the variable to 1 for each key (default).
class DiffusionTrain(TrainDomain):
def __init__(self, **config):
super(DiffusionTrain, self).__init__()
# sympy variables
x = Symbol('x')
c = Symbol('c')
# right hand side (x = 2) Pt c
IC = L2.boundary_bc(outvar_sympy={'u_2': Tc},
batch_size_per_area=1,
criteria=Eq(x, 2))
self.add(IC, name="RightHandSide")
# left hand side (x = 0) Pt a
IC = L1.boundary_bc(outvar_sympy={'u_1': Ta},
batch_size_per_area=1,
criteria=Eq(x, 0))
self.add(IC, name="LeftHandSide")
# interface 1-2
IC = L1.boundary_bc(outvar_sympy={'diffusion_interface_dirichlet_u_1_u_2': 0,
'diffusion_interface_neumann_u_1_u_2': 0},
lambda_sympy={'lambda_diffusion_interface_dirichlet_u_1_u_2': 1,
'lambda_diffusion_interface_neumann_u_1_u_2': 1},
batch_size_per_area=1,
criteria=Eq(x, 1))
self.add(IC, name="Interface1n2")
# interior 1
interior = L1.interior_bc(outvar_sympy={'diffusion_u_1': 0},
lambda_sympy={'lambda_diffusion_u_1': 1},
bounds={x: (0, 1)},
batch_size_per_area=200)
self.add(interior, name="Interior1")
# interior 2
interior = L2.interior_bc(outvar_sympy={'diffusion_u_2': 0},
lambda_sympy={'lambda_diffusion_u_2': 1},
bounds={x: (1, 2)},
batch_size_per_area=200)
self.add(interior, name="Interior2")
# At this point you might be wondering where do we input the parameters of the equation, for eg. values for $D_1, D_2$, etc. Don't worry, we will discuss them while making the neural network solver. But before that, let's create the validation data to verify our simulation results against the analytical solution.
# ## Creating Validation Domain
#
# For this 1d bar problem where the conductivity is constant in each bar, the temperature varies linearly with position inside the solid. The analytical solution can then be given as:
#
# $$
# \begin{align}
# U_1 = xT_b + (1-x)T_a, && \text{when } 0 \leq x \leq 1 \\
# U_2 = (x-1)T_c + (2-x)T_b, && \text{when } 1 \leq x \leq 2 \\
# \end{align}
# $$
#
# where,
# $$
# \begin{align}
# T_a = U_1|_{x=0}, && T_c = U_2|_{x=2}, && \frac{\left(T_c + \left( D_1/D_2 \right)T_a \right)}{1+ \left( D_1/D_2 \right)}\\
# \end{align}
# $$
#
# Now let's create the validation domains. The validation domain is created by inheriting from the `ValidationDomain` parent class. We use numpy to solve for the `u_1` and `u_2` based on the analytical expressions we showed above. The dictionary of generated numpy arrays (`invar_numpy` and `outvar_numpy`)for input and output variables is used as an input to the class method `from_numpy`.
class DiffusionVal(ValidationDomain):
def __init__(self, **config):
super(DiffusionVal, self).__init__()
x = np.expand_dims(np.linspace(0, 1, 100), axis=-1)
u_1 = x*Tb + (1-x)*Ta
invar_numpy = {'x': x}
outvar_numpy = {'u_1': u_1}
val = Validation.from_numpy(invar_numpy, outvar_numpy)
self.add(val, name='Val1')
# make validation data line 2
x = np.expand_dims(np.linspace(1, 2, 100), axis=-1)
u_2 = (x-1)*Tc + (2-x)*Tb
invar_numpy = {'x': x}
outvar_numpy = {'u_2': u_2}
val = Validation.from_numpy(invar_numpy, outvar_numpy)
self.add(val, name='Val2')
# ## Creating Monitor Domain
#
# SimNet library allows you to monitor desired quantities in Tensorboard as the simulation progresses and
# assess the convergence. A `MonitorDomain` can be used to create such an feature. This a useful feature when we want
# to monitor convergence based on a quantity of interest. Examples of such quantities can be point values of variables,
# surface averages, volume averages or any other derived quantities. The variables are available as TensorFlow tensors. We can perform tensor operations available in TensorFlow to compute any desired derived quantity of our choice.
#
# In the code below, we create monitors for flux at the interface. The variable `u_1__x` represents the derivative of `u_1` in x-direction (two underscores (`__`) and the variable (`x`)). The same notation is used while handling other derivatives using the SimNet library. (eg. a neumann boundary condition of $\frac{dU_1}{dx}=0$ can be assigned as `'u_1__x':0` in the train domain for solving the same problem with a adiabatic/fixed flux boundary condition).
#
# The points to sample can be selected in a similar way as we did for specifying the Train domain. We create the monitors by inheriting from the `MonitorDoamin` parent class
class DiffusionMonitor(MonitorDomain):
def __init__(self, **config):
super(DiffusionMonitor, self).__init__()
x = Symbol('x')
# flux in U1 at x = 1
fluxU1 = Monitor(L1.sample_boundary(10, criteria=Eq(x, 1)),
{'flux_U1': lambda var: tf.reduce_mean(D1*var['u_1__x'])})
self.add(fluxU1, 'FluxU1')
# flux in U2 at x = 1
fluxU2 = Monitor(L2.sample_boundary(10, criteria=Eq(x, 1)),
{'flux_U2': lambda var: tf.reduce_mean(D2*var['u_2__x'])})
self.add(fluxU2, 'FluxU2')
# ## Creating the Neural Network Solver
#
# Now that we have the train domain and other validation and monitor domains defined, we can prepare the neural network solver and run the problem. The solver is defined by inheriting the `Solver` parent class. The `train_domain`, `val_domain`, and `monitor_domains` are assigned. The equations to be solved are specified under `self.equations`. Here, we will call the `Diffusion` and `DiffusionInterface` classes we defined earlier to include the PDEs of the problem. Now we will pass the appropriate values for the parameters like the variable name (eg. `T='u_1'`) and also specify the dimensions of the problem (1d and steady).
#
# The inputs and the outputs of the neural network are specified and the nodes of the architecture are made. The default
# network architecture is a simple fully connected multi-layer perceptron architecture with *swish* activation function. The network consists of 6 hidden layers with 512 nodes in each layer. Here we are using two separate neural networks for each variable (`u_1` and `u_2`). All these values can be modified through `update_defaults` function. Also, the different architectures in SimNet library can be used (eg. Fourier Net architecture, Radial Basis Neural Network architecture, etc. More details can be found in *SimNet User Guide*). We use the default exponential learning rate decay, set the start learning rate and decay steps and also assign the `'max_steps'` to 5000.
# Define neural network
class DiffusionSolver(Solver):
train_domain = DiffusionTrain
val_domain = DiffusionVal
monitor_domain = DiffusionMonitor
def __init__(self, **config):
super(DiffusionSolver, self).__init__(**config)
self.equations = (Diffusion(T='u_1', D=D1, dim=1, time=False).make_node()
+ Diffusion(T='u_2', D=D2, dim=1, time=False).make_node()
+ DiffusionInterface('u_1', 'u_2', D1, D2, dim=1, time=False).make_node())
diff_net_u_1 = self.arch.make_node(name='diff_net_u_1',
inputs=['x'],
outputs=['u_1'])
diff_net_u_2 = self.arch.make_node(name='diff_net_u_2',
inputs=['x'],
outputs=['u_2'])
self.nets = [diff_net_u_1, diff_net_u_2]
@classmethod
def update_defaults(cls, defaults):
defaults.update({
'network_dir': './network_checkpoint_diff',
'max_steps': 5000,
'decay_steps': 100,
'start_lr': 1e-4,
#'end_lr': 1e-6,
})
# Awesome! We have just completed the file set up for the problem using the SimNet library. We are now ready to solve the PDEs using Neural Networks!
#
# Before we can start training, we can make use of Tensorboard for visualizing the loss values and convergence of several other monitors we just created. This can be done inside the jupyter framework by selecting the directory in which the checkpoint will be stored by clicking on the small checkbox next to it. The option to launch a Tensorboard then shows up in that directory.
#
# <img src="image_tensorboard.png" alt="Drawing" style="width: 900px;"/>
#
# Also, SimNet is desinged such that it can accept command line arguments. This causes issues when the code is directly executed through the jupyter notebook. So as a workaround, we will save the code in form of a python script and execute that script inside the jupyter cell. This example is already saved for you and the code block below executes that script `diffusion_bar.py`. You are encouraged to open the script in a different window and go through the code once before executing. Also, feel free to edit the parameters of the model and see its effect on the results.
# +
import os
import sys
sys.path.append('../../source_code/diffusion_1d')
# !python ../../source_code/diffusion_1d/diffusion_bar.py
# -
# ## Visualizing the solution
#
# SimNet saves the data in .vtu and .npz format by default. The .npz arrays can be plotted to visualize the output of the simulation. The .npz files that are created are found in the `network_checkpoint*` directory.
#
# Now let's plot the temperature along the bar for the analytical and the neural network solution. A sample script to plot the results is shown below. If the training is complete, you should get the results like shown below. As we can see, our neural network solution and the analytical solution match almost exactly for this diffusion problem.
#
# <img src="image_diffusion_problem_bootcamp.png" alt="Drawing" style="width: 500px;"/>
# +
# %%capture
import sys
# !{sys.executable} -m pip install ipympl
# %matplotlib inline
import matplotlib.pyplot as plt
plt.figure()
network_dir = './network_checkpoint_diff/val_domain/results/'
u_1_pred = np.load(network_dir + 'Val1_pred.npz', allow_pickle=True)
u_2_pred = np.load(network_dir + 'Val2_pred.npz', allow_pickle=True)
u_1_pred = np.atleast_1d(u_1_pred.f.arr_0)[0]
u_2_pred = np.atleast_1d(u_2_pred.f.arr_0)[0]
plt.plot(u_1_pred['x'][:,0], u_1_pred['u_1'][:,0], '--', label='u_1_pred')
plt.plot(u_2_pred['x'][:,0], u_2_pred['u_2'][:,0], '--', label='u_2_pred')
u_1_true = np.load(network_dir + 'Val1_true.npz', allow_pickle=True)
u_2_true = np.load(network_dir + 'Val2_true.npz', allow_pickle=True)
u_1_true = np.atleast_1d(u_1_true.f.arr_0)[0]
u_2_true = np.atleast_1d(u_2_true.f.arr_0)[0]
plt.plot(u_1_true['x'][:,0], u_1_true['u_1'][:,0], label='u_1_true')
plt.plot(u_2_true['x'][:,0], u_2_true['u_2'][:,0], label='u_2_true')
plt.legend()
plt.savefig('image_diffusion_problem_bootcamp.png')
# -
from IPython.display import Image
Image(filename='image_diffusion_problem_bootcamp.png')
#
#
# # Parameterizing the PDE
#
# As we discussed in the introductory notebook, one important advantage of a PINN solver over traditional numerical methods is its ability to solve parameterized geometries and PDEs. This was initially proposed in the [paper](https://arxiv.org/abs/1906.02382) published by Sun et al. This allows us to significant computational advantage as one can now use PINNs to solve for multiple desigs/cases in a single training. Once the training is complete, it is possible to run inference on several geometry/physical parameter combinations as a post-processing step, without solving the forward problem again.
#
# To demonstrate the concept, we will train the same 1d diffusion problem, but now by parameterizing the conductivity of the first bar in the range (5, 25). Once the training is complete, we can obtain the results for any conductivity value in that range saving us the time to train multiple models.
# ## Case Setup
#
# The definition of equations remain the same for this part. Since earlier while defining the equations, we already defined the constants and coefficients of the PDE to be either numerical values or strings, this will allow us to paramterize `D1` by passing it as a string while calling the equations and making the neural network. Now let's start by creating the paramterized train domain. We will skip the parts that are common to the previous section and only discuss the changes. The complete script can be referred in `diffusion_bar_parameterized.py`
# ## Creating Train Domain
#
# Before starting out to create the train domain using the `TrainDomain` class, we will create the symbolic variable for the $D_1$ and also specify the range of variation for the variable. While the simulation runs, we will validate it against the same diffusion coefficient that we solved earlier i.e. $D_1=10$. Once the sybolic variables and the ranges are described for sampling, these parameter ranges need to be inputted to the `param_ranges` attribute of each boundary and internal sampling (`boundary_bc` and `interior_bc`)
# +
# params for domain
L1 = Line1D(0,1)
L2 = Line1D(1,2)
D1 = Symbol('D1')
D1_range = {D1: (5, 25)}
D1_validation = 1e1
D2 = 1e-1
Tc = 100
Ta = 0
Tb = (Tc + (D1/D2)*Ta)/(1 + (D1/D2))
Tb_validation = float(Tb.evalf(subs={D1: 1e1}))
class DiffusionTrain(TrainDomain):
def __init__(self, **config):
super(DiffusionTrain, self).__init__()
# sympy variables
x = Symbol('x')
c = Symbol('c')
# right hand side (x = 2) Pt c
IC = L2.boundary_bc(outvar_sympy={'u_2': Tc},
batch_size_per_area=10,
criteria=Eq(x, 2),
param_ranges=D1_range)
self.add(IC, name="RightHandSide")
# left hand side (x = 0) Pt a
IC = L1.boundary_bc(outvar_sympy={'u_1': Ta},
batch_size_per_area=10,
criteria=Eq(x, 0),
param_ranges=D1_range)
self.add(IC, name="LeftHandSide")
# interface 1-2
IC = L1.boundary_bc(outvar_sympy={'diffusion_interface_dirichlet_u_1_u_2': 0,
'diffusion_interface_neumann_u_1_u_2': 0},
lambda_sympy={'lambda_diffusion_interface_dirichlet_u_1_u_2': 1,
'lambda_diffusion_interface_neumann_u_1_u_2': 1},
batch_size_per_area=10,
criteria=Eq(x, 1),
param_ranges=D1_range)
self.add(IC, name="Interface1n2")
# interior 1
interior = L1.interior_bc(outvar_sympy={'diffusion_u_1': 0},
lambda_sympy={'lambda_diffusion_u_1': 1},
bounds={x: (0, 1)},
batch_size_per_area=400,
param_ranges=D1_range)
self.add(interior, name="Interior1")
# interior 2
interior = L2.interior_bc(outvar_sympy={'diffusion_u_2': 0},
lambda_sympy={'lambda_diffusion_u_2': 1},
bounds={x: (1, 2)},
batch_size_per_area=400,
param_ranges=D1_range)
self.add(interior, name="Interior2")
# -
# ## Creating Validation and Monitor Domains
#
# The process to create these domains is again similar to the previous section. For validation data, we need to create an additional key for the string `'D1'` in the `invar_numpy`. The value for this string can be in the range we specified earlier and which we would like to validate against. It is possible to create multiple validations if required, eg. different $D_1$ values. For monitor domain, similar to `interior_bc` and `boundary_bc` in the train domain, we will supply the paramter ranges for monitoring in the `param_ranges` attribute of the `sample_boundary` method.
# +
class DiffusionVal(ValidationDomain):
def __init__(self, **config):
super(DiffusionVal, self).__init__()
# make validation data line 1
x = np.expand_dims(np.linspace(0, 1, 100), axis=-1)
D1 = np.zeros_like(x) + D1_validation # For creating D1 input array
u_1 = x*Tb_validation + (1-x)*Ta
invar_numpy = {'x': x} # Set the invars for the required D1
invar_numpy.update({'D1': np.full_like(invar_numpy['x'], D1_validation)})
outvar_numpy = {'u_1': u_1}
val = Validation.from_numpy(invar_numpy, outvar_numpy)
self.add(val, name='Val1')
# make validation data line 2
x = np.expand_dims(np.linspace(1, 2, 100), axis=-1)
u_2 = (x-1)*Tc + (2-x)*Tb_validation
invar_numpy = {'x': x} # Set the invars for the required D1
invar_numpy.update({'D1': np.full_like(invar_numpy['x'], D1_validation)})
outvar_numpy = {'u_2': u_2}
val = Validation.from_numpy(invar_numpy, outvar_numpy)
self.add(val, name='Val2')
class DiffusionMonitor(MonitorDomain):
def __init__(self, **config):
super(DiffusionMonitor, self).__init__()
x = Symbol('x')
# flux in U1 at x = 1
fluxU1 = Monitor(L1.sample_boundary(10, criteria=Eq(x, 1), param_ranges={D1: D1_validation}), # Set the parameter range for the required D1
{'flux_U1': lambda var: tf.reduce_mean(D1_validation*var['u_1__x'])})
self.add(fluxU1, 'FluxU1')
# flux in U2 at x = 1
fluxU2 = Monitor(L2.sample_boundary(10, criteria=Eq(x, 1), param_ranges={D1: D1_validation}), # Set the parameter range for the required D1
{'flux_U2': lambda var: tf.reduce_mean(D2*var['u_2__x'])})
self.add(fluxU2, 'FluxU2')
# -
# ## Creating the Neural Network Solver
#
# Once all the parameterized domain definitions are completed, for training the parameterized model, we will have the symbolic parameters we defined earlier as inputs to both the neural networks in `diff_net_u_1` and `diff_net_u_2` viz. `'D1'` along with the usual x coordinate. The outputs remain the same as what we would have for any other non-parameterized simulation.
# Define neural network
class DiffusionSolver(Solver):
train_domain = DiffusionTrain
val_domain = DiffusionVal
monitor_domain = DiffusionMonitor
def __init__(self, **config):
super(DiffusionSolver, self).__init__(**config)
self.equations = (Diffusion(T='u_1', D='D1', dim=1, time=False).make_node() # Symbolic input to the equation
+ Diffusion(T='u_2', D=D2, dim=1, time=False).make_node()
+ DiffusionInterface('u_1', 'u_2', 'D1', D2, dim=1, time=False).make_node())
diff_net_u_1 = self.arch.make_node(name='diff_net_u_1',
inputs=['x', 'D1'], # Add the parameters to the network
outputs=['u_1'])
diff_net_u_2 = self.arch.make_node(name='diff_net_u_2',
inputs=['x', 'D1'],
outputs=['u_2'])
self.nets = [diff_net_u_1, diff_net_u_2]
@classmethod # Explain This
def update_defaults(cls, defaults):
defaults.update({
'network_dir': './network_checkpoint_diff_parameterized',
'max_steps': 10000,
'decay_steps': 200,
'start_lr': 1e-4,
'layer_size': 256,
'xla': True,
})
# ## Visualizing the solution
#
# The .npz arrays can be plotted similar to previous section to visualize the output of the simulation. You can see that we get the same answer as the analytical solution. You can try to run the problem in `eval` mode by chaning the validation data and see how it performs for the other `D1` values as well. To run the model in evaluation mode (i.e. without training), you just need to add the `--run_mode=eval` flag while executing the script.
#
# <img src="image_diffusion_problem_bootcamp_parameterized.png" alt="Drawing" style="width: 500px;"/>
#
# You can see that at a fractional increase in computational time, we solved the PDE for $D_1$ ranging from (5, 25). This concept can easily be extended to more complicated problems and this ability of solving parameterized problems comes very handy during desing optimization and exploring the desing space. For more examples of solving parameterized problems, please refer to *SimNet User Guide Chapter 13*
# # Licensing
# This material is released by NVIDIA Corporation under the Creative Commons Attribution 4.0 International (CC BY 4.0)
#
#      
#      
#      
#      
#    
# [Home Page](../../Start_Here.ipynb)
#
# [Previous Notebook](../introduction/Introductory_Notebook.ipynb)
#      
#      
#      
#      
#    
# [1](../introduction/Introductory_Notebook.ipynb)
# [2]
# [3](../spring_mass/Spring_Mass_Problem_Notebook.ipynb)
# [4](../chip_2d/Challenge_CFD_Problem_Notebook.ipynb)
#      
#      
#      
#      
# [Next Notebook](../spring_mass/Spring_Mass_Problem_Notebook.ipynb)
| hpc_ai/PINN/English/python/jupyter_notebook/diffusion_1d/Diffusion_Problem_Notebook.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# ## Lookup for citations -- based on the wild examples
## All imports
import re
import os
import json
import numpy as np
import pandas as pd
from tqdm import tqdm
tqdm.pandas()
## load the file which contains the citation for which we need to perform the lookup
wild_exp_journal = pd.read_csv('./wild_examples_journal.csv')
# wild_exp_book = pd.read_csv('../wild_examples_book.csv')
wild_exp_journal.shape
# ### Extract the title of the citation and the author, if they exist - which will be used for CrossRef lookup
# +
def get_title(citation_text):
"""Get title of citation based on finding the placeholder keywords using regular expressions"""
title_res = re.findall('title\s{0,10}=\s{0,10}([^|]+)', citation_text)
if len(title_res) == 0:
if 'sports-reference' in citation_text:
return re.findall('(C|c)ite\s{0,10}sports-reference\s{0,10}|([^|]+)', citation_text)[1][1].strip()
else:
article_res = re.findall('article\s{0,10}=\s{0,10}([^|]+)', citation_text)
if len(article_res) != 0:
return article_res[0].strip()
return None
return title_res[0].strip()
wild_exp_book['title'] = wild_exp_book['citations'].progress_apply(lambda x: get_title(x))
# -
wild_exp_book.head()
wild_exp_book[~wild_exp_book['title'].notnull()].shape
def get_author(citation_text):
"""Get author based on finding the placeholder keywords using regular expressions"""
def check_first_last_res(first_res, last_res):
if len(first_res) != 0 and len(last_res) != 0:
return first_res[0].strip() + ' ' + last_res[0].strip()
if len(first_res) != 0:
return first_res[0].strip()
if len(last_res) != 0:
return last_res[0].strip()
## https://en.wikipedia.org/wiki/Template:Citation - only these keywords are available
first_res = re.findall('first\s{0,10}=\s{0,10}([^|]+)', citation_text)
last_res = re.findall('last\s{0,10}=\s{0,10}([^|]+)', citation_text)
author_res = re.findall('author\s{0,10}=\s{0,10}([^|]+)', citation_text)
author1_res = re.findall('author1\s{0,10}=\s{0,10}([^|]+)', citation_text)
first1_res = re.findall('first1\s{0,10}=\s{0,10}([^|]+)', citation_text)
last1_res = re.findall('last1\s{0,10}=\s{0,10}([^|]+)', citation_text)
if first_res or last_res:
return check_first_last_res(first_res, last_res)
elif author_res:
return author_res[0].strip()
elif author1_res:
return author1_res[0].strip()
elif first1_res or last1_res:
return check_first_last_res(first1_res, last1_res)
else:
return None
## For each citation, get the first author if it exists
wild_exp_book['first_author'] = wild_exp_book['citations'].progress_apply(lambda x: get_author(x))
wild_exp_book.head()
## Total number of citations for which their is no author
wild_exp_book[~wild_exp_book['first_author'].notnull()].shape
wild_exp_book.iloc[1]['citations']
## Fill NaN values in first author column as it is missing and can act as distraction for the lookup
wild_exp_book['first_author'].fillna(value='No author found', inplace=True)
# +
def check_whitespace_author(first_author):
"""Check if the first author column has whitespace and replace it"""
if not first_author.strip():
return 'No author found'
return first_author
wild_exp_book['first_author'] = wild_exp_book['first_author'].progress_apply(lambda x: check_whitespace_author(x))
# -
wild_exp_book.head(7)
## Saving the file for which the lookup needs to be performed
wild_exp_book.to_csv('../wild_exp_info_book.csv', index=True, index_label='index')
## Example as to how a citation might look like
wild_exp_book.iloc[0]['citations']
# ### Once lookup is done..
#
# 1. Assign filename for each index in the dataframe
# 2. For each file/metadata found, get the 3 DOIs if they exist and their corresponding scores
wild_exp_info = pd.read_csv('./wild_exp_info.csv')
print('The total examples of the wild examples: {}'.format(wild_exp_info.shape[0]))
wild_exp_info.head()
# +
def assign_metadata(index):
"""Check if the file exists for a given index"""
if os.path.exists('lookup_journal/_{}.json'.format(index)):
return '_{}.json'.format(index)
return 'Metadata does not exist'
## assigning name of the file for each citation
wild_exp_info['metadata_file'] = wild_exp_info['index'].progress_apply(lambda x: assign_metadata(x))
# -
## Number of citations for which metadata did not exist in CrossRef
## This is because some of the citations neither author and title did not exist
## or CrossRef was unable to parse the request -- due to invalid characters
print('Metadata did not exist for these many citations: {} out of {}'.format(
wild_exp_info[wild_exp_info['metadata_file'] == 'Metadata does not exist'].shape[0],
wild_exp_info.shape[0]
))
wild_exp_info.head()
def get_identifier_or_score(filename, identifier=True):
"""Return the 3 identifiers (DOIs) or confidence scores for each citation"""
column_name = 'DOI' if identifier else 'score'
if filename == 'Metadata does not exist':
return None
else:
with open('lookup_journal/{}'.format(filename)) as f:
content = json.loads(f.read())
if len(content) > 0:
if 'message' in content and content['message'] == 'No result was found in CrossRef':
return None
else:
return np.array([content[i][column_name] for i in range(len(content))])
return None
## Get the DOIs for each citation which we extracted from CrossRef
wild_exp_info['identifier'] = wild_exp_info['metadata_file'].progress_apply(
lambda x: get_identifier_or_score(x))
wild_exp_info.head()
print('Identifier does not exist for these many citations: {} out of {}'.format(
wild_exp_info[~wild_exp_info['identifier'].notnull()].shape[0], wild_exp_info.shape[0]
))
## Get the confidence scores for each citation which we extracted from CrossRef
wild_exp_info['conf_score'] = wild_exp_info['metadata_file'].progress_apply(
lambda x: get_identifier_or_score(x, identifier=False))
wild_exp_info.head()
print('Confidence scores does not exist for these many citations: {} out of {}'.format(
wild_exp_info[~wild_exp_info['conf_score'].notnull()].shape[0],
wild_exp_info.shape[0]
))
## Save the results which we got from the metadata
wild_exp_info.to_parquet('wild_exp.gzip', compression='gzip')
# ### If the file with the lookup for no confidence threshold is there.. then load it
wild_exp_journal = pd.read_parquet('wild_exp.gzip')
print('The total number of citations are: {}'.format(wild_exp_journal.shape))
threshold_score = 34.997
# +
def get_score_based_on_threshold(conf_score):
if conf_score is None:
return None
else:
res = np.array([i for i, j in enumerate(conf_score) if j > threshold_score])
if len(res) == 0:
return None
else:
return res
wild_exp_journal['updated_conf_index'] = wild_exp_journal['conf_score'].progress_apply(
lambda x: get_score_based_on_threshold(x))
# -
wild_exp_journal.head()
print('Total number of identifiers greater than the confidence score: {}'.format(
wild_exp_journal.shape[0] - wild_exp_journal[~wild_exp_journal['updated_conf_index'].notnull()].shape[0]))
print('which is a percentage: {}'.format(
wild_exp_journal[wild_exp_journal['updated_conf_index'].notnull()].shape[0] / float(wild_exp_journal.shape[0]) * 100))
# +
def get_updated_identifier(row):
if row['updated_conf_index'] is None:
return None
else:
return row['identifier'][row['updated_conf_index']]
wild_exp_journal['updated_identifier'] = wild_exp_journal.progress_apply(get_updated_identifier, axis=1)
# -
wild_exp_journal.head()
wild_exp_journal.iloc[0]
wild_exp_journal.iloc[2]
wild_exp_journal.to_parquet('wild_exp_with_confidence_score.gzip', compression='gzip')
wild_exp_journal[wild_exp_journal['updated_identifier'].notnull()]
z = wild_exp_journal[wild_exp_journal['updated_identifier'].notnull()]
all_doi_identifiers = np.concatenate(z['updated_identifier'].tolist()).ravel()
len(set(all_doi_identifiers))
len(set(z['page_title'].tolist()))
| Extractor/cite-classifications-wiki/notebooks/wild_examples_lookup_journal.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as sts
import numpy as np
file = "./database.csv"
# -
df = pd.read_csv(file, low_memory=False)
df
df.columns
# +
weather = ["FOG, RAIN, SNOW", "FOG, SNOW", "RAIN, SNOW", "FOG, RAIN", "SNOW", "FOG", "RAIN"]
df.loc[df['Precipitation']=='FOG, RAIN, SNOW','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
df.loc[df['Precipitation']=='FOG, SNOW','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
df.loc[df['Precipitation']=='RAIN, SNOW','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
df.loc[df['Precipitation']=='FOG, RAIN','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
# df.loc[df['Precipitation']=='SNOW','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
# df.loc[df['Precipitation']=='FOG','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
# df.loc[df['Precipitation']=='RAIN','Precipitation'] = 'FOG, RAIN, AND/OR SNOW'
df['Precipitation'].value_counts(ascending=False).head(20).plot(kind='barh', title='Precipitaion',)
plt.xlabel('Count')
plt.savefig("./Figures/Precipitation.png")
plt.show()
# -
df['Precipitation'].value_counts(ascending=False).head(20).plot(kind='barh')
plt.xlabel('Count')
plt.show()
# +
df['Visibility'].value_counts(ascending=False).head(20).plot(kind='barh', )
plt.xlabel('Count')
plt.savefig("./Figures/Visibility.png")
plt.show()
# +
df.groupby('Incident Year').size().plot()
plt.ylabel("Incidents Count")
plt.title("Wildlife Strikes per Year")
plt.savefig("./Figures/strikersperyear(year).png")
# +
df['Species Name'].value_counts(ascending=False).head(20).plot(kind='barh', title='Top 20 Species Involved in Aircraft Damage',)
plt.xlabel('Count')
plt.savefig("./Figures/top20species.png")
plt.show()
# -
df['Aircraft'].value_counts(ascending=False).head(20).plot(kind='barh', title='Top 20 Aircrafts Involved in Incident',)
plt.xlabel('Count')
plt.savefig("./Figures/top20aircraft.png")
plt.show()
df['Operator'].value_counts(ascending=False).head(20).plot(kind='barh', title='Operator',)
plt.tight_layout()
plt.savefig("./Figures/top20operator.png")
plt.show()
df['Warning Issued'].value_counts(ascending=False).head(20).plot(kind='pie', title='Warning Issued',)
plt.show()
df['Species Quantity'].value_counts(ascending=False).head(20).plot(kind='barh', title='Number of Birds Hit During Event',)
plt.show()
# +
df['Airport'].value_counts(ascending=False).head(20).plot(kind='barh', title='Airport',)
plt.savefig("./Figures/top20airports.png")
plt.show()
# +
df = df[df['Incident Year']!=2015]
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
days_in_month_leap = [31,29,31,30,31,30,31,31,30,31,30,31]
years = []
months = []
incidents_in_month = []
days_in_months = []
incidents_in_year = []
for year in range(1990,2015):
for month in range(1,13):
df_month = df[(df['Incident Year']==year) & (df['Incident Month']==month)]
incident_count = df_month.shape[0]
years.append(year)
months.append(month)
incidents_in_month.append(incident_count)
if year%4 == True:
days_in_months.append(days_in_month_leap[month-1])
else:
days_in_months.append(days_in_month[month-1])
df_month = df[(df['Incident Year']==year)]
incident_count = df_month.shape[0]
for i in range(0,12):
incidents_in_year.append(incident_count)
data = pd.DataFrame({
'Year': years,
'Month': months,
'incidents_in_month':incidents_in_month,
'days_in_months':days_in_months,
'incidents_in_year':incidents_in_year
}, )
data
# +
plt.plot(data.incidents_in_month)
plt.xlabel("Months since 1989")
plt.ylabel("Incidents per Month")
plt.title(("Wildlife Strikes per Month"))
plt.savefig("./Figures/strikespermonth.png")
plt.show()
# +
plt.plot(data.incidents_in_year)
plt.xlabel("Months since 1989")
plt.ylabel("Incidents per Year")
plt.title("Wildlife Strikes per Year")
plt.savefig("./Figures/strikersperyear(month).png")
plt.show()
# +
plt.plot(data.incidents_in_month/data.days_in_months)
plt.xlabel('Months since 1989')
plt.ylabel('Incidents per Day')
plt.title(('Average Incidents per Day'))
plt.savefig("./Figures/strikersperday.png")
plt.show()
# +
df.loc[df['Flight Impact']=='ENGINE SHUT DOWN','Flight Impact'] = 'ENGINE SHUTDOWN'
df['Flight Impact'].value_counts(ascending=False).plot(kind='barh', title='Top flight impacts',)
plt.xlabel('Count')
plt.savefig("./Figures/topflightimpacts.png")
plt.show()
# -
contingencyTable = pd.crosstab(df['Precipitation'],df['Flight Impact'])
print(contingencyTable)
chi2(contingencyTable)
df['Flight Impact'].dropna().value_counts()
print(88082/99465)
print(6145/99465)
print(2423/99465)
print(2352/99465)
print(463/99465)
# +
df_2 = df[['Aircraft Damage', 'Radome Strike', 'Radome Damage',
'Windshield Strike', 'Windshield Damage', 'Nose Strike', 'Nose Damage',
'Engine1 Strike', 'Engine1 Damage', 'Engine2 Strike', 'Engine2 Damage',
'Engine3 Strike', 'Engine3 Damage', 'Engine4 Strike', 'Engine4 Damage',
'Engine Ingested', 'Propeller Strike', 'Propeller Damage',
'Wing or Rotor Strike', 'Wing or Rotor Damage', 'Fuselage Strike',
'Fuselage Damage', 'Landing Gear Strike', 'Landing Gear Damage',
'Tail Strike', 'Tail Damage', 'Lights Strike', 'Lights Damage',
'Other Strike', 'Other Damage']]
df_2.dropna().head()
# -
df_2.sum()
# +
df.groupby('Incident Month').size().plot()
plt.ylabel('Incident Count')
plt.title('Month with highest incident count')
plt.savefig("./Figures/monthcount.png")
# -
| project1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # EPSchema
# # 1. Introduction
#
# This notebook explores the EnergyPlus schema using the EPSchema class in the eprun package.
# ## 2. Setup
# ### 2.1. Module Imports
from eprun import EPSchema
# ### 2.2. Filepaths
fp='Energy+.schema.epJSON'
# ## 3. Reading the schema file
# ### 3.1. Import
schema=EPSchema(fp)
schema
# ### 3.2. Viewing basic properties
type(schema)
schema.build
schema.required
schema.version
print(schema.object_type_names)
# ### 3.3. Accessing all object types
schema.get_object_types()
# ### 3.4. Accessing a single object type
schema.get_object_type('Building')
# ## 4. Reading a EPSchemaObjectType object
# ### 4.1. Creation
building=schema.get_object_type('Building')
building
type(building)
# ### 4.2. Dictionary access
list(building.keys())
dict(building)
# ### 4.2 Properties
try:
building.legacy_idd_extensibles
except KeyError as err:
print(err)
try:
building.legacy_idd_extension
except KeyError as err:
print(err)
building.legacy_idd_fields
building.name
building.pattern_properties_regexes
building.property_names
# ### 4.3. Methods
building.get_properties()
building.get_property('north_axis')
building.validate_property_name('north_axis')
try:
building.validate_property_name('bad_property_name')
except IndexError as err:
print(err)
try:
building.validate_object({})
except Exception as err:
print(err)
try:
building.validate_object({'my_building':{}}) # allowed by the object schema
except Exception as err:
print(err)
# ## 5. Exploring the object types in the schema
# ### How many object types are there?
len(schema.get_object_types())
# ### What are the unique keys in the object type dictionary?
from collections import Counter
Counter([y for x in schema.get_object_types() for y in x.keys()])
# ### How many unique pattern properties are there?
len({str(x['patternProperties']) for x in schema.get_object_types()})
# ### How many unique legacy_idds are there?
len({str(x['legacy_idd']) for x in schema.get_object_types()})
# ### What are the unique types?
Counter([x['type'] for x in schema.get_object_types()])
# ### What are the unique maxProperties?
Counter([x.get('maxProperties') for x in schema.get_object_types()])
# ### How many unique memos are there?
len({str(x['memo']) for x in schema.get_object_types() if 'memo' in x})
# ### What are the unique formats?
Counter([x.get('format') for x in schema.get_object_types()])
# ### What are the unique min_fields?
Counter([x.get('min_fields') for x in schema.get_object_types()])
# ### How many unique names are there?
len({str(x['name']) for x in schema.get_object_types() if 'name' in x})
# ### What are the unique minProperties?
Counter([x.get('minProperties') for x in schema.get_object_types()])
# ### What are the unique extensible_size?
Counter([x.get('extensible_size') for x in schema.get_object_types()])
# ### What are the unique additionalProperties?
Counter([x.get('additionalProperties') for x in schema.get_object_types()])
# ## 6. Exploring the pattern properties
# ### What are the unique keys of the pattern properties?
Counter([y for x in schema.get_object_types() for y in x['patternProperties'].keys()])
# ## 7. Exploring the legacy_idds
# ### What are the unique keys of the legacy_idds?
Counter([y for x in schema.get_object_types() for y in x['legacy_idd'].keys()])
# ### What are the types of the legacy_idd keys?
legacy_idd_keys={y for x in schema.get_object_types() for y in x['legacy_idd'].keys()}
for lik in legacy_idd_keys:
print(lik, end=' - ')
print(Counter([type(x['legacy_idd'][lik]) for x in schema.get_object_types() if lik in x['legacy_idd']]))
# ### What are the unique keys of the alphas?
Counter([y for x in schema.get_object_types() for y in x['legacy_idd'].get('alphas',{}).keys()])
# ### What are the unique types of the alphas fields?
Counter([str(type(x['legacy_idd'].get('alphas',{}).get('fields',None))) for x in schema.get_object_types()])
# ### What are the unique types of the alphas extensions?
Counter([str(type(x['legacy_idd'].get('alphas',{}).get('extensions',None))) for x in schema.get_object_types()])
# ## 8. Exploring the memos
# ### What are the unique types of the memos?
Counter([type(x['memo']) for x in schema.get_object_types() if 'memo' in x])
# ## 9. Exploring the names
Counter([str(x.get('name')) for x in schema.get_object_types()])
{str(x['name']) for x in schema.get_object_types() if 'name' in x}
print(ot)
print(ot.name)
print(ot.get_properties())
print(list(ot.keys()))
print(ot['memo'])
# ## EPSchemaProperty
from eprun import EPSchema
s=EPSchema(fp='Energy+.schema.epJSON')
ot=s.get_object_type('Building')
p=ot.get_property('north_axis')
print(type(p))
print(p.name)
print(list(p.keys()))
print(p['units'])
| docs_notebooks/EPSchema/EPSchema.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Ruby 2.4.0
# language: ruby
# name: ruby
# ---
# # first ruby notebook
#
# Running a docker in a notebook was easy thanks to
#
# ```sh
#
# docker pull kechako/jupyter-iruby
#
# docker run --name iruby -p 8888:8888 -v $PWD:/opt/notebooks kechako/jupyter-iruby
# ```
#
# Simple example
puts "Hello sailor " + Math.sin(3.14/2).to_s
# +
# Now for a simple class
# From the https://www.ruby-lang.org/en/documentation/quickstart/3/
class MegaGreeter
attr_accessor :names
# Create the object
def initialize(names = "World")
@names = names
end
# Say hi to everybody
def say_hi
if @names.nil?
puts "..."
elsif @names.respond_to?("each")
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hello #{@names}!"
end
end
# Say bye to everybody
def say_bye
if @names.nil?
puts "..."
elsif @names.respond_to?("join")
# Join the list elements with commas
puts "Goodbye #{@names.join(", ")}. Come back soon!"
else
puts "Goodbye #{@names}. Come back soon!"
end
end
end
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
# Change name to be "Zeke"
mg.names = "Zeke"
mg.say_hi
mg.say_bye
# Change the name to an array of names
mg.names = ["Albert", "Brenda", "Charles",
"Dave", "Engelbert"]
mg.say_hi
mg.say_bye
# Change to nil
mg.names = nil
mg.say_hi
mg.say_bye
# -
| First Ruby Notebook.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Stocks
#
# Overview of the stock market data.
# +
# %load_ext autoreload
# %autoreload 2
# %matplotlib inline
import os
import pandas as pd
from pandas.plotting import scatter_matrix
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import cluster
from sklearn import metrics
from sklearn import linear_model
from sklearn import svm
from sklearn import preprocessing
from scipy import stats
from mlxtend.plotting import plot_decision_regions
from ast import literal_eval
import warnings
from collections import OrderedDict
from lob_data_utils import lob, model, roc_results, gdf_pca, lob_classify, stocks
from lob_data_utils.svm_calculation import lob_svm
sns.set_style('whitegrid')
warnings.filterwarnings('ignore')
# -
data_dir = 'data/prepared'
should_savefig = True
stocks_lengths = []
for stock in stocks.all_stocks:
if stock in ['11390', '4695', '7843']:
continue
df, df_test = lob.load_prepared_data(stock, include_test=True)
mid_price_counts = df['mid_price_indicator'].value_counts()
test_mid_price_counts = df_test['mid_price_indicator'].value_counts()
df.rename(columns={'Unnamed: 0': 'datetime'}, inplace=True)
df_test.rename(columns={'Unnamed: 0' : 'datetime'}, inplace=True)
properties = {
'mean_mid_price': df['mid_price'].mean(),
'mean_spread': (df['ask_price'] - df['bid_price']).mean(),
'mid_price_indicator_ratio': mid_price_counts[1] / mid_price_counts[0],
'test_mean_mid_price': df_test['mid_price'].mean(),
'test_mid_price_indicator_ratio': test_mid_price_counts[1] / test_mid_price_counts[0],
'test_mean_spread': (df_test['ask_price'] - df_test['bid_price']).mean(),
'test_dates': (min(df_test['datetime']), max(df_test['datetime'])),
'train_dates': (min(df['datetime']), max(df['datetime'])),
'test_set_length': len(df_test),
'train_set_length': len(df),
}
stocks_lengths.append(
{'stock': stock, 'train_length': len(df), 'test_length': len(df_test), **properties})
df_stocks = pd.DataFrame(stocks_lengths)
df_stocks['diff_mean_mid_price'] = np.abs(df_stocks['mean_mid_price'] - df_stocks['test_mean_mid_price'])
df_stocks['diff_mid_price_indicator_ratio'] = np.abs(
df_stocks['mid_price_indicator_ratio'] - df_stocks['test_mid_price_indicator_ratio'])
df_stocks['diff_mean_spread'] = np.abs(df_stocks['mean_spread'] - df_stocks['test_mean_spread'])
df_stocks.describe()
axes = df_stocks.hist(figsize=(16, 8))
axes = df_stocks.plot(kind='box', subplots=True, layout=(4,4), figsize=(16, 8))
sns.heatmap(df_stocks[[c for c in df_stocks.columns if 'len' not in c]].corr(), annot=True)
df_stocks.head()
axes = scatter_matrix(
df_stocks[[c for c in df_stocks.columns if 'len' not in c and 'test' not in c and 'diff' not in c]],
figsize=(8, 8))
axes = scatter_matrix(
df_stocks[[c for c in df_stocks.columns if 'len' not in c and 'test' in c and 'diff' not in c]],
figsize=(8, 8))
df_stocks['mid_price_indicator_ratio'].plot(kind='kde')
df_stocks['test_mid_price_indicator_ratio'].plot(kind='kde')
# For most of the stocks the classes are inbalanced!
df_stocks.sort_values(by=['mid_price_indicator_ratio'], ascending=False).head(5)
df_stocks['diff_mid_price_indicator_ratio'].plot(kind='kde')
df_stocks['diff_mean_mid_price'].plot(kind='kde')
# ## Lets cluster
km = cluster.KMeans(n_clusters=3)
cols = ['mean_mid_price', 'mean_spread']
df_stocks['km'] = km.fit_predict(df_stocks[cols])
plt.scatter(x=df_stocks['mean_mid_price'], y=df_stocks['mean_spread'], c=df_stocks['km'])
plt.xlabel('Mean Mid-Price')
plt.ylabel('Mean Spread')
plt.title('Scatter plot showing clusters')
plt.tight_layout()
if should_savefig:
plt.savefig('clusters.png')
for k in [0,1,2]:
d = df_stocks[df_stocks['km'] == k]
print(k)
print(min(d['mean_mid_price']), max(d['mean_mid_price']))
print(min(d['mean_spread']), max(d['mean_spread']))
# ### Choosing stocks
#
# 3 representative stocks one from each cluster.
#
# 5 stocks per cluster.
choosen_stocks1 = df_stocks[df_stocks['km'] == 2].sort_values(
by='diff_mid_price_indicator_ratio', ascending=True).head(5)['stock'].values
choosen_stocks2 = df_stocks[df_stocks['km'] == 1].sort_values(
by='diff_mid_price_indicator_ratio', ascending=True).head(5)['stock'].values
choosen_stocks3 = df_stocks[df_stocks['km'] == 0].sort_values(
by='diff_mid_price_indicator_ratio', ascending=True).head(5)['stock'].values
choosen_stocks = np.concatenate([choosen_stocks1, choosen_stocks2, choosen_stocks3])
is_choosen = []
for i, row in df_stocks.iterrows():
if row['stock'] in choosen_stocks:
is_choosen.append(1)
else:
is_choosen.append(0)
df_stocks['is_choosen'] = is_choosen
df_stocks[['']]
# ## Overview
pd.DataFrame(choosen_stocks).to_csv('choosen_stocks.csv')
df_stocks.to_csv('stocks.csv')
df_choosen = df_stocks[df_stocks['is_choosen'] == 1]
df_choosen[['test_dates', 'train_dates', 'test_set_length', 'train_set_length', 'stock', 'km']].groupby('km').head(1)
dfs = {}
stocks = df_choosen[[
'test_dates', 'train_dates', 'test_set_length', 'train_set_length', 'stock', 'km']].groupby(
'km').head(1)['stock'].values
for stock in stocks:
df, _ = lob.load_prepared_data(stock, include_test=True)
df['spread'] = (df['bid_price'] - df['ask_price'])
df.index = pd.to_datetime(df['Unnamed: 0'].values)
dfs[stock] = df
dfs[stocks[2]]['spread'].describe()
f, ax = plt.subplots(1, 3, figsize=(16, 4))
for i in range(len(stocks)):
print(len(dfs[stocks[i]]))
dfs[stocks[i]][['mid_price']].plot(label=stocks[i], ax=ax[i])
ax[i].set_title('Mid-Price for {}'.format(stocks[i]))
ax[i].set_ylabel('Mid Price')
ax[i].set_xlabel('Date')
ax[i].legend()
plt.tight_layout()
plt.legend()
if should_savefig:
print('Saving figure')
plt.savefig('mid_price.png')
# +
f, ax = plt.subplots(1, 3, figsize=(16, 4))
from sklearn.preprocessing import MinMaxScaler
for i in range(len(stocks)):
df = dfs[stocks[i]]
df = df[df['spread'] < 20]
scaler = MinMaxScaler()
scaler.fit(df[['spread', 'mid_price']])
scaled = scaler.transform(df[['spread', 'mid_price']])
ax[i].plot(df.index, scaled[:, 0])
ax[i].plot(df.index, scaled[:, 1])
ax[i].set_title('Spread for {}'.format(stocks[i]))
ax[i].set_ylabel('Spread')
ax[i].set_xlabel('Date')
ax[i].legend()
plt.tight_layout()
plt.legend()
if should_savefig:
print('Saving figure')
plt.savefig('spread.png')
# -
f, ax = plt.subplots(1, 3, figsize=(16, 4))
for i in range(len(stocks)):
sns.distplot(dfs[stocks[i]][['mid_price']], ax=ax[i], )
ax[i].legend(['Mid Price'])
ax[i].set_title('Mid-Price distribution for {}'.format(stocks[i]))
plt.tight_layout()
if should_savefig:
plt.savefig('mid_price_distribution.png')
f, ax = plt.subplots(1, 3, figsize=(16, 4))
for i in range(len(stocks)):
sns.boxenplot(dfs[stocks[i]][['mid_price']], ax=ax[i])
ax[i].legend(['Mid Price'])
ax[i].set_title('Mid-Price distribution for {}'.format(stocks[i]))
plt.tight_layout()
if should_savefig:
plt.savefig('mid_price_box_distribution.png')
# +
f, ax = plt.subplots(1, 3, sharey=True, figsize=(16, 4))
i = 0
plt.title('Violin Plots of Queue Imbalance vs Mid Price Indicator')
for k, d in dfs.items():
sns.violinplot(y=d['queue_imbalance'], x=d['mid_price_indicator'], ax=ax[i], scale="count", split=True)
ax[i].set_title(k)
ax[i].set_ylabel('Queue Imbalance')
ax[i].set_xlabel('Mid Price Indicator')
i += 1
plt.ylabel('Queue Imbalance')
plt.xlabel('Mid Price Indicator')
plt.tight_layout()
if should_savefig:
plt.savefig('violin_plot_imb_vs_ind.png')
# +
def format_pie_(pct, allvals):
absolute = int(pct * np.sum(allvals) / 100.0)
return "{:.1f}%\n {:d} data points".format(pct, absolute)
f, ax = plt.subplots(1, 3, figsize=(12, 4), sharex=True, sharey=True)
for i in range(len(stocks)):
df = dfs[stocks[i]]
sizes = [len(df[df['mid_price_indicator'] == 0.0]), len(df[df['mid_price_indicator'] == 1.0]), ]
ax[i].pie(sizes, labels=['0', '1'], autopct=lambda pct: format_pie_(pct, sizes))
ax[i].set_title(stocks[i])
plt.tight_layout()
if should_savefig:
plt.savefig('pie_plot_mid_price_indicator.png')
# +
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4), sharey=True)
df_stocks['mean_mid_price'].hist(label='All stocks', ax=ax1, alpha=0.5)
df_choosen['mean_mid_price'].hist(label='Choosen stocks', ax=ax1, alpha=0.5)
df_stocks['mean_spread'].hist(label='All stocks', ax=ax2, alpha=0.5)
df_choosen['mean_spread'].hist(label='Choosen stocks', ax=ax2, alpha=0.5)
ax1.legend()
ax2.legend()
ax1.set_title('Distribution of mean Mid-Price')
ax2.set_title('Distribution of mean spread')
ax1.set_xlabel('Mid-Price')
ax1.set_ylabel('Number of stocks')
plt.tight_layout()
if should_savefig:
plt.savefig('choosen_stock_dist.png')
# -
| overview/stocks_overview.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('covid-cases-by-source.csv')
df.head()
df.dtypes
df['date'] = pd.to_datetime(df['Date'], format='%b %d, %Y')
df.set_index(['Code', 'date'], inplace=True)
df.sort_index(ascending=True, inplace=True)
df.index
df.drop(columns=['Johns Hopkins', 'WHO (cases)', 'Entity'], inplace=True)
df.dropna(axis=0, inplace=True)
df.head()
# #### Contruir una lista con los índices (multindex) para utilizar en el cálculo de la variación diaria
lst = list(df.index)
# + jupyter={"outputs_hidden": true}
lst
# -
# #### Probar que por medio de la lista de índices se puede extrar el valor de "ECDC (cases)"
int(df.loc[(lst[2]), 'ECDC (cases)'])
df.loc['ABW'].index
#
# #### Crear una lista de countries extrayéndolos de los índices.
# #### Probablemente no se utilice, pero el ejercicio aporta.
#
countries = list(pd.Series([lst[i][0] for i in range(len(lst))]).unique())
tst_lst = ['ABW', 'ECU']
tst_lst
# +
daylyvar = list()
#range(len(d_lst))
for c in countries:
prev_day = 0
try:
d_lst = list(df.loc[c].index)
d_min = pd.Series(d_lst).min()
print(f'{c} Min date: {d_min}', '\n')
for i in range(5):
if d_lst[i] == d_min:
var = int(df.loc[(c, d_lst[i]), 'ECDC (cases)'])
print(f'Variation: {var}')
daylyvar.append(var)
else:
prev_day = int(df.loc[(c, d_lst[y]), 'ECDC (cases)'])
var = int(df.loc[(c, d_lst[i]), 'ECDC (cases)']) - prev_day
print(f'Variation: {var}')
daylyvar.append(var)
print(f'Prev day: {prev_day}')
print(f'Dayly var: {daylyvar}', '\n')
y = i
except:
continue
# -
df.loc['ABW']
| MoreCovid.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: RevData39
# language: python
# name: rd39
# ---
# ----
# <img src="../../../files/refinitiv.png" width="20%" style="vertical-align: top;">
#
# # Data Library for Python
#
# ----
# ## Delivery - EndPoint - HistoricalPricing - Events
# This notebook demonstrates how to use the Delivery Layer of the library to retrieve HistoricalPricing events from the Refinitiv Data Platform directly using the Endpoint.
# ## Set the location of the configuration file
# For ease of use, you can set various initialization parameters of the RD Library in the **_refinitiv-data.config.json_** configuration file - as described in the Quick Start -> Sessions example.
#
# ### One config file for the tutorials
# As these tutorial Notebooks are categorised into sub-folders and to avoid the need for multiple config files, we will use the _RD_LIB_CONFIG_PATH_ environment variable to point to a single instance of the config file in the top-level ***Configuration*** folder.
#
# Before proceeding, please **ensure you have entered your credentials** into the config file in the ***Configuration*** folder.
import os
os.environ["RD_LIB_CONFIG_PATH"] = "../../../Configuration"
import refinitiv.data as rd
from refinitiv.data.delivery import endpoint_request
import datetime
import json
import pandas as pd
# ## Open the default session
#
# To open the default session ensure you have a '*refinitiv-data.config.json*' in the ***Configuration*** directory, populated with your credentials and specified a 'default' session in the config file
#
# + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"}
rd.open_session()
# -
# ## Define the endpoint request
# Basic Endpoint Request - Directly code RIC into the request
request_definition = rd.delivery.endpoint_request.Definition(
url = "/data/historical-pricing/v1/views/events/VOD.L",
# optionally limit the datapoints
query_parameters = {"count":"5"}
)
# ### OR by setting the Path Parameter
request_definition = rd.delivery.endpoint_request.Definition(
url = "/data/historical-pricing/v1/views/events/{universe}",
method = rd.delivery.endpoint_request.RequestMethod.GET,
path_parameters = {"universe": "VOD.L"}
)
# ## Send a request
response = request_definition.get_data()
# ## Display the result
# + tags=[]
response.data.raw[0]
# -
# Extract the data part of the JSON, along with column headings to populate a DataFrame
df = pd.DataFrame(response.data.raw[0]['data'], columns=[h['name']
for h in response.data.raw[0]['headers']])
df
# ## Close the session
rd.close_session()
| Tutorials/3.Delivery/3.2-Endpoint/TUT_3.2.02-EndPoint-HistoricalPricingEvents.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] cell_id="aa40ce83-83ab-492e-9c85-c754345d1f94" deepnote_cell_type="markdown" deepnote_cell_height=142.796875
# # Freelancer Scraper - search by keyword
#
# **`Goal:`** Scrape results from Freelancer.com when using a specific search query. Updated to scrape badges, skills, and certifications
# + deepnote_to_be_reexecuted=false execution_millis=11 execution_start=1647622729249 source_hash="f679a1ab" cell_id="00001-7d15b276-bcbc-4592-aeae-8d1afa1ae769" owner_user_id="90b26b03-99c4-40c0-a870-8175b99a6ae3" deepnote_cell_type="code" deepnote_cell_height=225
#Import the necessary packages needed to build the freelancer bot and navigate the pages
import re
import pandas as pd
from time import sleep
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
# + deepnote_to_be_reexecuted=false execution_millis=48 execution_start=1647622731324 source_hash="240d67c6" cell_id="00002-f742cac5-5b12-46e9-aa36-34e2b57585eb" deepnote_cell_type="code" deepnote_cell_height=6993
class FreelancerScraper:
"""
Class that scrapes for talent listings on Freelancer.com based on a
specified search query.
"""
def __init__(self,search=None, max_rows=float("inf")):
"""
Initializes the scraper.
:search: -- the search term to use when searching for listings.
:max_rows: -- the maximum number of rows to fetch (defaults to infinity, which
fetches the total number of rows available)
"""
# check if a search term was provided
if search is None:
raise ValueError('Please provide a search term for scraping.')
self.search = search
# focusing only on freelancers in the United States
self.url = f'https://www.freelancer.com/freelancers/united-states/'
# sets a hard limit on the amount of rows
# the scraper should fetch. This is needed
# sometimes when there are a lot of results
# and you don't want the scraper
self.max_rows = max_rows
#List to store the scraped user profile links
self.user_profiles = set([])
#List to store scraped user profile info
self.users_info = []
def get_all_usernames(self):
"""
Fetches all usernames (and profile links) associated with the search query.
It stores the retrieved user profile links in self.user_profiles.
"""
print("Fetching usernames...")
# options for selenium that allow it to run
# in DeepNote without having to open any physical
# Chrome tabs
options = Options()
options.add_argument("--headless")
options.add_argument('--no-sandbox')
# create browser instance
self.browser = webdriver.Chrome(options=options)
# get the starting webpage and wait sometime for elements to load
self.browser.get(self.url)
sleep(3)
# see if the online filter is selected, and deselect. Also wait for sometime for elements to load
try:
self.browser.find_element(By.ID,"selected-online").click()
sleep(3)
except:
pass
# input our search term into the search bar
# and press ENTER to run the search
search_input = self.browser.find_element(By.ID, "freeSearchInput")
search_input.clear()
search_input.send_keys(self.search)
search_input.send_keys(Keys.RETURN)
# wait for results
sleep(3)
# get the total results found (to calculate a stopping point)
result_amount_text = self.browser.find_element(By.CLASS_NAME, "result-amount").text
result_amount = int(result_amount_text.split(" ")[1])
print("Found", result_amount, "total results.")
usernames_scraped = 0
# while we still have usernames left to scrape, continue retrieving info
while usernames_scraped < result_amount and usernames_scraped < self.max_rows:
# get the profile links for everyone on the page
usernames = self.browser.find_elements(By.CLASS_NAME,"find-freelancer-username")
for user in usernames:
usernames_scraped += 1
# add username to list of profiles
# to fetch later
self.user_profiles.add(user.get_attribute('href'))
print("Usernames fetched:", usernames_scraped)
# NAVIGATION TO NEXT PAGE
# find all the page navigation buttons
pg_nav_btns = self.browser.find_elements(By.CSS_SELECTOR,"a[data-target='pagination']")
# find and click on the last one (next page button)
pg_nav_btns[-1].click()
# wait for next page to load
sleep(3)
#Close the browser when done
self.browser.quit()
def get_user_profile_info(self,user_profile_link):
"""
Scrapes an inputted user profile link
"""
print("Getting profile information from", user_profile_link, "...")
# options that allow selenium to run on DeepNote
options = Options()
options.add_argument("--headless")
options.add_argument('--no-sandbox')
try:
self.browser = webdriver.Chrome(options=options)
# get profile page
self.browser.get(user_profile_link)
sleep(2)
# dictionary to store the user's info
user_info = {}
# store the search query used
user_info['search_query'] = self.search
# get name
user_info['name'] = self.browser.find_element(By.CSS_SELECTOR,"h3[data-color='dark']").text
# store the profile link
user_info['profile_link'] = user_profile_link
################## GET FREELANCER BADGES
try:
# get the badges
badge_container = self.browser.find_element(By.CSS_SELECTOR,"fl-bit[class ='NameContainer-badges']")
badges = [x.get_attribute('data-type') for x in badge_container.find_elements(By.CSS_SELECTOR,"fl-badge")]
# replace membership with plus_membership
badges = ['plus-membership' if x=='membership' else x for x in badges]
except:
badges = []
if not badges: badges = []
user_info['freelancer_badges'] = badges
#####################################################################################
################## GET VERIFICATIONS
verifications_list = self.browser.find_element(By.CSS_SELECTOR,
"app-user-profile-verifications")
ver_items = verifications_list.find_elements(By.CSS_SELECTOR,
"fl-bit[class='ProfileVerificationItem-label']")
verification_text = [x.text for x in ver_items]
verification_symbs = [x.find_element(By.CSS_SELECTOR,"div[class ='IconContainer']").\
get_attribute('data-color') for x in ver_items]
verification_status = [True if symb=='success' else False for symb in verification_symbs]
verifications = [*zip(verification_text,verification_status)]
user_info['verifications'] = verifications
#####################################################################################
# get tagline
user_info['tagline'] = self.browser.find_element(By.CSS_SELECTOR,"h2[data-color='mid']").text
# get description
description_box = self.browser.find_element(By.CSS_SELECTOR,"fl-text[data-max-lines='15']")
# try to click on the read more button and extract text
try:
description_box.find_element(By.CLASS_NAME,'ReadMoreButton').click()
user_info['user_description'] = description_box.text
# if error is thrown because text doesn't need to be expanded, then we can just pull direct text
except:
user_info['user_description'] = description_box.text
################## GET CERTIFICATIONS
try:
certifications_list = self.browser.find_element(By.CSS_SELECTOR,"app-user-profile-exams")
cert_items = certifications_list.find_elements(By.CSS_SELECTOR,
"fl-bit[class='UserProfileExams-item ng-star-inserted']")
certifications = [tuple(x.text.split('\n')) for x in cert_items]
except:
certifications = []
if not certifications: certifications = []
user_info['certifications'] = certifications
#####################################################################################
################################# EXTRACTING TOP SKILLS
#1. Expanding list to get all top skills
####tracker for view_more top skills
view_more_button = True
####Click view more button until all top_skills appear
while view_more_button:
try:
self.browser.find_element(By.XPATH, "//button[text()=' View More ']").click()
sleep(0.5)
#If error is thrown because view more button disappears – stop trying to click
except:
view_more_button = False
#2. Extracting the top skills
####List to store all top skills
top_skills = []
####Iterate through all listed skills
for skill in self.browser.find_elements(By.CSS_SELECTOR,"fl-bit[class ='UserProfileSkill']"):
#Get the skill
skill_text = skill.text
#If a number is indicated in the skill
if '\n' in skill_text:
#Note skill and count
sk,ct = skill_text.split('\n')
top_skills.append((sk,int(ct)))
#Note count as 1
else:
top_skills.append((skill_text,0))
#Store user top skills
user_info['top_skills'] = top_skills
###########################################################################################
#Get location
user_info['location'] = self.browser.find_element(By.CSS_SELECTOR,"fl-col[class='SupplementaryInfo']").text
#Get join date
user_info['join_date'] = self.browser.find_element(By.XPATH, "//*[contains(text(),'Joined')]").text.replace('Joined ','')
#Hourly rate
user_info['hourly_rate'] = re.findall('\$\d+',self.browser.find_element(By.XPATH, "//*[contains(text(),'USD')]").text)[0]
#Get pay grade
user_info['pay_grade'] = self.browser.find_element(By.CSS_SELECTOR,"div[data-size='xxsmall").text
#######Get rating container
rating_container = self.browser.find_elements(By.CSS_SELECTOR,"fl-bit[class ='RatingContainer']")[1]
#Get average rating and number of reviews
user_info['avg_rating'], reviews = rating_container.text.split('\n')
user_info['num_reviews'] = re.findall('\d+',reviews)[0]
##################################
#Get number of recommendations
user_info['num_recommendations']=re.findall('\d+',self.browser.find_element(By.CSS_SELECTOR,"fl-col[class='RecommendationsText']").text)[0]
### GET STATS ON PERFORMANCE
pct_jobs_completed, pct_on_budget, pct_on_time, repeat_hire_rate = [item.text.\
replace('%','') for item in self.browser.\
find_elements(By.CSS_SELECTOR,"fl-text[class='ReputationItemAmount']")]
user_info['pct_jobs_completed'] = pct_jobs_completed
user_info['pct_on_budget'] = pct_on_budget
user_info['pct_on_time'] = pct_on_time
user_info['repeat_hire_rate'] = repeat_hire_rate
##############################
#Add the extracted info the list for all users
self.users_info.append(user_info)
print("Fetched user info from", user_profile_link)
#Close the browser when done
self.browser.close()
except Exception as e:
print("Failed to fetch user profile:", user_profile_link)
print(e)
def get_pd_dataframe(self):
"""
Exports data to a Pandas DataFrame
"""
export_to_pd_dict_array = []
# turn list features into individual columns
for user in self.users_info:
certifications = {}
for cert in user.get("certifications", []):
if len(cert) > 1:
cert_name, val = cert
certifications[f"certifications_{'_'.join(cert_name.split(' ')).lower()}"] = val
else:
cert_name = cert[0]
certifications[f"certifications_{'_'.join(cert_name.split(' ')).lower()}"] = True
# format is "verification_verification_name": value
verifications = {f"verification_{'_'.join(name.split(' ')).lower()}": val for name, val in user.get("verifications", [])}
# format is "skill_skill_name": value
skills = {f"skill_{'_'.join(name.split(' ')).lower()}": val for name, val in user.get("top_skills", [])}
# format is "badge_badge_name": True
badges = {f"badge_{'_'.join(name.split('-')).lower()}": True for name in user.get("freelancer_badges", [])}
user_copy = {**user}
# delete columns that we've just processed
del user_copy["certifications"]
del user_copy["verifications"]
del user_copy["top_skills"]
del user_copy["freelancer_badges"]
user_for_pd = {
**user_copy,
**certifications,
**verifications,
**skills,
**badges
}
export_to_pd_dict_array.append(user_for_pd)
# create dataframe and return
df = pd.DataFrame(export_to_pd_dict_array)
return df
def get_raw_pd_dataframe(self):
"""
Exports the data as a Pandas DataFrame without doing any pre-processing
"""
df = pd.DataFrame(self.users_info)
return df
def run(self):
# extract all the usernames for the particular search query
self.get_all_usernames()
users_fetched = 0
# get all the info for each of the usernames
for url in self.user_profiles:
self.get_user_profile_info(url)
users_fetched += 1
print("Users fetched:", users_fetched)
sleep(2.5)
print("All done!")
# + deepnote_to_be_reexecuted=false execution_millis=64897201 execution_start=1647622733766 source_hash="f3239a7d" cell_id="00004-0223b5f3-acec-47d6-94be-1ade35369251" deepnote_cell_type="code" deepnote_cell_height=1354
scraper = FreelancerScraper(search="designer", max_rows=5000)
scraper.run()
# + deepnote_to_be_reexecuted=false execution_millis=1304 execution_start=1647744427611 source_hash="4d444fc9" cell_id="00005-ffb99a23-8829-42f1-be58-9e4f2df03dc5" deepnote_cell_type="code" deepnote_cell_height=809
scraped_pd_df = scraper.get_pd_dataframe()
print(scraped_pd_df.head())
scraped_pd_df_raw = scraper.get_raw_pd_dataframe()
print(scraped_pd_df_raw.head())
# + deepnote_to_be_reexecuted=false execution_millis=2031 execution_start=1647744442973 source_hash="8a761bbb" cell_id="00006-82c59ab8-fead-49d5-91e9-2b8732b257b1" deepnote_cell_type="code" deepnote_cell_height=99
scraped_pd_df.to_csv(f'{"_".join(scraper.search.split(" "))}.csv',index=False)
scraped_pd_df_raw.to_csv(f'{"_".join(scraper.search.split(" "))}_raw.csv',index=False)
# + cell_id="e0525eea-9c27-4666-a4f6-6773d469ae24" tags=[] deepnote_to_be_reexecuted=false source_hash="8aa27923" execution_start=1647468322845 execution_millis=34 deepnote_cell_type="code" deepnote_cell_height=81
# + [markdown] cell_id="fbcc56f2-bdd2-4d04-bad0-f08926694819" tags=[] deepnote_cell_type="markdown" deepnote_cell_height=70
# ## Quick test runs on a profiles
# + [markdown] cell_id="942eac97-592e-491a-b4d5-512567182e69" tags=[] deepnote_cell_type="markdown" deepnote_cell_height=62
# ### a. User with badges & certifications
# + cell_id="00003-1cd899a1-57ed-4c82-ad48-d553553ba967" deepnote_to_be_reexecuted=false source_hash="bd8495bb" execution_start=1647449268667 execution_millis=10983 deepnote_cell_type="code" deepnote_cell_height=804.890625 deepnote_output_heights=[null, 606.5]
scraper = FreelancerScraper(search="designer", max_rows=5000)
scraper.get_user_profile_info('https://www.freelancer.com/u/TatianaLLL')
scraper.users_info
# + cell_id="7ee0d430-866d-44b8-9bed-e305bab2c5c7" tags=[] deepnote_to_be_reexecuted=false source_hash="2392b86e" execution_start=1647449304982 execution_millis=146 deepnote_cell_type="code" deepnote_cell_height=249
processed_df_test = scraper.get_pd_dataframe()
processed_df_test
# + cell_id="1fd32784-58c6-4114-a675-12c3c964ff7b" tags=[] deepnote_to_be_reexecuted=false source_hash="b3504316" execution_start=1647449433820 execution_millis=4 deepnote_cell_type="code" deepnote_cell_height=249
raw_df_test = scraper.get_raw_pd_dataframe()
raw_df_test
# + [markdown] cell_id="634893d8-dc06-4a22-822a-edf4770c41bf" tags=[] deepnote_cell_type="markdown" deepnote_cell_height=62
# ### b. User without badges & certifications
# + cell_id="21e10380-debd-46c9-b0ed-f5edca23deec" tags=[] deepnote_to_be_reexecuted=false source_hash="6aa4647e" execution_start=1647442307902 execution_millis=7493 deepnote_cell_type="code" deepnote_cell_height=804.890625 deepnote_output_heights=[null, 606.5]
scraper = FreelancerScraper(search="designer", max_rows=5000)
scraper.get_user_profile_info('https://www.freelancer.com/u/TeenaVernekar')
scraper.users_info
# + [markdown] cell_id="4a2de240-2fad-4027-ada9-0035b5c001aa" tags=[] deepnote_cell_type="markdown" deepnote_cell_height=46
# ---
# + cell_id="00009-1bf43cf3-f222-45b5-b0f2-8c3dc56a5e1e" deepnote_cell_type="code" deepnote_cell_height=66
# + [markdown] tags=[] created_in_deepnote_cell=true deepnote_cell_type="markdown"
# <a style='text-decoration:none;line-height:16px;display:flex;color:#5B5B62;padding:10px;justify-content:end;' href='https://deepnote.com?utm_source=created-in-deepnote-cell&projectId=acc27b92-84be-4130-8026-204943f38189' target="_blank">
# <img alt='Created in deepnote.com' style='display:inline;max-height:16px;margin:0px;margin-right:7.5px;' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iODBweCIgaGVpZ2h0PSI4MHB4IiB2aWV3Qm94PSIwIDAgODAgODAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDU0LjEgKDc2NDkwKSAtIGh0dHBzOi8vc2tldGNoYXBwLmNvbSAtLT4KICAgIDx0aXRsZT5Hcm91cCAzPC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGcgaWQ9IkxhbmRpbmciIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJBcnRib2FyZCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEyMzUuMDAwMDAwLCAtNzkuMDAwMDAwKSI+CiAgICAgICAgICAgIDxnIGlkPSJHcm91cC0zIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMjM1LjAwMDAwMCwgNzkuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8cG9seWdvbiBpZD0iUGF0aC0yMCIgZmlsbD0iIzAyNjVCNCIgcG9pbnRzPSIyLjM3NjIzNzYyIDgwIDM4LjA0NzY2NjcgODAgNTcuODIxNzgyMiA3My44MDU3NTkyIDU3LjgyMTc4MjIgMzIuNzU5MjczOSAzOS4xNDAyMjc4IDMxLjY4MzE2ODMiPjwvcG9seWdvbj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0zNS4wMDc3MTgsODAgQzQyLjkwNjIwMDcsNzYuNDU0OTM1OCA0Ny41NjQ5MTY3LDcxLjU0MjI2NzEgNDguOTgzODY2LDY1LjI2MTk5MzkgQzUxLjExMjI4OTksNTUuODQxNTg0MiA0MS42NzcxNzk1LDQ5LjIxMjIyODQgMjUuNjIzOTg0Niw0OS4yMTIyMjg0IEMyNS40ODQ5Mjg5LDQ5LjEyNjg0NDggMjkuODI2MTI5Niw0My4yODM4MjQ4IDM4LjY0NzU4NjksMzEuNjgzMTY4MyBMNzIuODcxMjg3MSwzMi41NTQ0MjUgTDY1LjI4MDk3Myw2Ny42NzYzNDIxIEw1MS4xMTIyODk5LDc3LjM3NjE0NCBMMzUuMDA3NzE4LDgwIFoiIGlkPSJQYXRoLTIyIiBmaWxsPSIjMDAyODY4Ij48L3BhdGg+CiAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMCwzNy43MzA0NDA1IEwyNy4xMTQ1MzcsMC4yNTcxMTE0MzYgQzYyLjM3MTUxMjMsLTEuOTkwNzE3MDEgODAsMTAuNTAwMzkyNyA4MCwzNy43MzA0NDA1IEM4MCw2NC45NjA0ODgyIDY0Ljc3NjUwMzgsNzkuMDUwMzQxNCAzNC4zMjk1MTEzLDgwIEM0Ny4wNTUzNDg5LDc3LjU2NzA4MDggNTMuNDE4MjY3Nyw3MC4zMTM2MTAzIDUzLjQxODI2NzcsNTguMjM5NTg4NSBDNTMuNDE4MjY3Nyw0MC4xMjg1NTU3IDM2LjMwMzk1NDQsMzcuNzMwNDQwNSAyNS4yMjc0MTcsMzcuNzMwNDQwNSBDMTcuODQzMDU4NiwzNy43MzA0NDA1IDkuNDMzOTE5NjYsMzcuNzMwNDQwNSAwLDM3LjczMDQ0MDUgWiIgaWQ9IlBhdGgtMTkiIGZpbGw9IiMzNzkzRUYiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+' > </img>
# Created in <span style='font-weight:600;margin-left:4px;'>Deepnote</span></a>
| notebooks/1-freelancer-scraper-search.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 確認済みバージョン
#
# ## Linux
#
# - Python 3.8.5
# - notebook 6.0.3
# - matplotlib 3.1.3 (3.3.0 は plt.savefig() がうまくいかない)
# - ipywidgets 7.5.1
# - ipympl 0.4.1, 0.5.7
# - pyserial 3.4
# - pyftdi 0.50.0, 0.51.2
#
# なお、以下のセルを実行すると、バージョンが確認できます。
#
# ## Windows
#
# Windows 7 にて、EVM 上の FT2232 を使用し、以下のバージョンで、2Mbps 通信を確認済みです。
#
# - Python version: 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]
# - notebook: 6.0.3
# - matplotlib: 3.1.3
# - ipywidgets: 7.5.1
# - ipympl: 0.4.1
# - serial: 3.4
# - pyftdi: 0.51.2
#
# ドライバ: libusb-win32 1.2.6.0 (8/2/2012)
| hostapp/checked_versions.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Preparing a proposal
#
# The Story: Suppose that you are preparing to write a proposal on NGC1365, aiming to investigate the intriguing black hole spin this galaxy with Chandra grating observations (see: [Monster Blackhole Spin Revealed](https://www.space.com/19980-monster-black-hole-spin-discovery.html))
#
# In writing proposals, there are often the same tasks that are required: including finding and analyzing previous observations of the proposal, and creating figures that include, e.g., multiwavelength images and spectrum for the source.
#
# +
# As a hint, we include the code block for Python modules that you will likely need to import:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline
# For downloading files
from astropy.utils.data import download_file
from astropy.io import fits
import pyvo as vo
## There are a number of relatively unimportant warnings that
## show up, so for now, suppress them:
import warnings
warnings.filterwarnings("ignore", module="astropy.io.votable.*")
warnings.filterwarnings("ignore", module="pyvo.utils.xml.*")
# -
# ### Step 1: Find out what the previously quoted Chandra 2-10 keV flux of the central source is for NGC 1365.
#
# Hint: Do a Registry search for tables served by the HEASARC (where high energy data are archived) to find potential table with this information
# This gets all services matching, which should be a list of only one:
tap_services=vo.regsearch(servicetype='table',keywords=['heasarc'])
# This fetches the list of tables that this service serves:
heasarc_tables=tap_services[0].service.tables
# Hint: The [Chansngcat](https://heasarc.gsfc.nasa.gov/W3Browse/chandra/chansngcat.html) table is likely the best table. Create a table with ra, dec, exposure time, and flux (and flux errors) from the public.chansngcat catalog for Chandra observations matched within 0.1 degree.
for tablename in heasarc_tables.keys():
if "chansng" in tablename:
print("Table {} has columns={}\n".format(
tablename,
sorted([k.name for k in heasarc_tables[tablename].columns ])))
# Get the coordinate for NGC 1365
import astropy.coordinates as coord
pos=coord.SkyCoord.from_name("ngc1365")
# Construct a query that will get the ra, dec, exposure time, flux, and flux errors
# from this catalog in the region around this source:
query="""SELECT ra, dec, exposure, flux, flux_lower, flux_upper FROM public.chansngcat as cat
where contains(point('ICRS',cat.ra,cat.dec),circle('ICRS',{},{},0.1))=1
and cat.exposure > 0 order by cat.exposure""".format(pos.ra.deg, pos.dec.deg)
# Submit the query. (See the CS_Catalog_queries.ipynb for
# information about these two search options.)
results=tap_services[0].service.run_async(query)
#results=tap_services[0].search(query)
# Look at the results
results.to_table()
#
# ### Step 2: Make Images:
#
# #### Create ultraviolet and X-ray images
# Hint: Start by checking what UV image services exist (e.g., GALEX?)
## Note that to browse the columns, use the .to_table() method
uv_services=vo.regsearch(servicetype='image',keywords='galex', waveband='uv')
uv_services.to_table()['ivoid','short_name']
# The keyword search for 'galex' returned a bunch of things that may have mentioned it, but let's just use the ones that have GALEX as their short name:
uv_services.to_table()[
np.array(['GALEX' in u.short_name for u in uv_services])
]['ivoid', 'short_name', 'access_url']
# Though using the result as an Astropy Table makes it easier to look at the contents, to call the service itself, we cannot use the row of that table. You have to use the entry in the service result list itself. So use the table to browse, but select the list of services itself using the properties that have been defined as attributes such as short_name and ivoid:
galex_stsci=[s for s in uv_services if 'GALEX' in s.short_name and 'stsci' in s.ivoid][0]
galex_heasarc=[s for s in uv_services if 'GALEX' in s.short_name and 'heasarc' in s.ivoid][0]
# Hint: Next create a UV image for the source
# Do an image search for NGC 1365 in the UV service found above
im_table_stsci=galex_stsci.search(pos=pos,size=0.1)
im_table_stsci.to_table()
# Let's see what HEASARC offers, and this time limit it to FITS
# this option doesn't currently work for STScI's service)
im_table_heasarc=galex_heasarc.search(pos=pos,size=0.1,format='image/fits')
im_table_heasarc.to_table()
## If you only run this once, you can do it in memory in one line:
## This fetches the FITS as an astropy.io.fits object in memory
#dataobj=im_table_heasarc[0].getdataobj()
## But if you might run this notebook repeatedly with limited bandwidth,
## download it once and cache it.
file_name = download_file(im_table_heasarc[0].getdataurl(), cache=True, timeout=600)
dataobj=fits.open(file_name)
print(type(dataobj))
# Get the FITS file (which is index 0 for the NUV image or index=2 for the FUV image)
from pylab import figure, cm
from matplotlib.colors import LogNorm
plt.matshow(dataobj[0].data, origin='lower', cmap=cm.gray_r, norm=LogNorm(vmin=0.005, vmax=0.3))
# Hint: Repeat steps for X-ray image. (Note: Ideally, we would find an image in the Chandra 'cxc' catalog)
x_services=vo.regsearch(servicetype='image',keywords=['chandra'], waveband='x-ray')
print(x_services.to_table()['short_name','ivoid'])
## Do an image search for NGC 1365 in the X-ray CDA service found above
xim_table=x_services[0].search(pos=pos,size=0.2)
## Some of these are FITS and some JPEG. Look at the columns:
print( xim_table.to_table().columns )
first_fits_image_row = [x for x in xim_table if 'image/fits' in x.format][0]
# +
## Create an image from the first FITS file (index=1) by downloading:
## See above for options
#xhdu_list=first_fits_image_row.getdataobj()
file_name = download_file(first_fits_image_row.getdataurl(), cache=True, timeout=600)
xhdu_list=fits.open(file_name)
plt.imshow(xhdu_list[0].data, origin='lower', cmap='cool', norm=LogNorm(vmin=0.1, vmax=500.))
plt.xlim(460, 560)
plt.ylim(460, 560)
# -
#
# ### Step 3: Make a spectrum:
#
# #### Find what Chandra spectral observations exist already for this source.
# Hint: try searching for X-ray spectral data tables using the registry query
# Use the TAP protocol to list services that contain X-ray spectral data
xsp_services=vo.regsearch(servicetype='ssa',waveband='x-ray')
xsp_services.to_table()['short_name','ivoid','waveband']
# Hint 2: Take a look at what data exist for our candidate, NGC 1365.
spec_tables=xsp_services[0].search(pos=pos,radius=0.2,verbose=True)
spec_tables.to_table()
# Hint 3: Download the data to make a spectrum. Note: you might end here and use Xspec to plot and model the spectrum. Or ... you can also try to take a quick look at the spectrum.
# +
# Get it and look at it:
#hdu_list=spec_tables[0].getdataobj()
file_name = download_file(spec_tables[0].getdataurl(), cache=True, timeout=600)
hdu_list=fits.open(file_name)
spectra=hdu_list[1].data
print(spectra.columns)
print(len(spectra))
# -
## Or write it to disk
import os
if not os.path.isdir('downloads'):
os.makedirs("downloads")
fname=spec_tables[0].make_dataset_filename()
# Known issue where the suffix is incorrect:
fname=fname.replace('None','fits')
with open('downloads/{}'.format(fname),'wb') as outfile:
outfile.write(spec_tables[0].getdataset().read())
# Extension: Making a "quick look" spectrum. For our purposes, the 1st order of the HEG grating data would be sufficient.
j=1
for i in range(len(spectra)):
matplotlib.rcParams['figure.figsize'] = (8, 3)
if abs(spectra['TG_M'][i]) == 1 and (spectra['TG_PART'][i]) == 1:
ax=plt.subplot(1,2,j)
pha = plt.plot( spectra['CHANNEL'][i],spectra['COUNTS'][i])
ax.set_yscale('log')
if spectra['TG_PART'][i] == 1:
instr='HEG'
ax.set_title("{grating}{order:+d}".format(grating=instr, order=spectra['TG_M'][i]))
plt.tight_layout()
j=j+1
# This can then be analyzed in your favorite spectral analysis tool, e.g., [pyXspec](https://heasarc.gsfc.nasa.gov/xanadu/xspec/python/html/index.html). (For the winter 2018 AAS workshop, we demonstrated this in a [notebook](https://github.com/NASA-NAVO/aas_workshop_2018/blob/master/heasarc/heasarc_Spectral_Access.ipynb) that you can consult for how to use pyXspec, but the pyXspec documentation will have more information.)
# Congratulations! You have completed this notebook exercise.
| UseCase_II.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:analysis3]
# language: python
# name: conda-env-analysis3-py
# ---
# # Zonally Averaged Overturning Circulation
#
# This notebook shows a simple example of calculation the zonally averaged global meridional overturning circulation - in density space.
#
# **Firstly,** load in the requisite libraries:
# +
# %matplotlib inline
import cosima_cookbook as cc
import matplotlib.pyplot as plt
import numpy as np
# -
# **Next,** choose an experiment. This can be any resolution, and can be with or without Gent-McWilliams eddy parameterisation:
expt = '1deg_jra55v13_ryf9091_spinup_A'
# Load up ```ty_trans_rho``` from ```ocean.nc```.
# Also, if there is a ```ty_trans_rho_gm``` variable saved, assume that GM is switched on and load that as well.
# +
psi = cc.get_nc_variable(expt, 'ocean.nc', 'ty_trans_rho',chunks={'potrho': None}, n=10)
psi = psi.sum('grid_xt_ocean')
varlist = cc.get_variables(expt, 'ocean.nc')
if 'ty_trans_rho_gm' in varlist:
GM = True
psiGM = cc.get_nc_variable(expt, 'ocean.nc', 'ty_trans_rho_gm',chunks={'potrho': None}, n=10)
psiGM = psiGM.sum('grid_xt_ocean')
else:
GM = False
# -
# assume units of kg/s, convert to Sv.
psi = psi*1.0e-9
if GM:
psiGM = psiGM*1.0e-9
# +
psi_avg = psi.cumsum('potrho').mean('time') - psi.sum('potrho').mean('time')
if GM:
psi_avg = psi_avg + psiGM.mean('time')
psi_avg.compute()
# +
plt.figure(figsize=(10, 5))
clev = np.arange(-20,20,2)
plt.contourf(psi_avg.grid_yu_ocean,psi_avg.potrho, psi_avg,cmap=plt.cm.PiYG,levels=clev,extend='both')
cb=plt.colorbar(orientation='vertical', shrink = 0.7)
cb.ax.set_xlabel('Sv')
plt.contour(psi_avg.grid_yu_ocean, psi_avg.potrho, psi_avg, levels=clev, colors='k', linewidths=0.25)
plt.contour(psi_avg.grid_yu_ocean, psi_avg.potrho, psi_avg, levels=[0.0,], colors='k', linewidths=0.5)
plt.gca().invert_yaxis()
plt.ylim((1037.5,1034))
plt.ylabel('Potential Density (kg m$^{-3}$)')
plt.xlabel('Latitude ($^\circ$N)')
plt.xlim([-75,85])
plt.title('Overturning in %s' % expt)
# -
# **Finally,** this is all encoded in a script for Paul's convenience:
cc.plots.psi_avg(expt, 5)
| DocumentedExamples/Zonally_Averaged_Global_Meridional_Overturning_Circulation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.7.4 64-bit (''.venv'': venv)'
# language: python
# name: python37464bitvenvvenvc66bc2fda9c74bfbbe9556567278705b
# ---
# In this notebook we will use image compression technique to compress audio signals.
#
# The audio files in this notebook are from the ESC-50 dataset:
# - ESC-50: Dataset for Environmental Sound Classification
# - https://github.com/karoldvl/ESC-50/
# - https://dx.doi.org/10.7910/DVN/YDEPUT
#
#
# A good application of svd and a demo for images is here:
# http://timbaumann.info/svd-image-compression-demo/
#
#
# The outline is as follows:
#
# - Show a function that compresses an image (with a matrix based technique called svd)
# - Load
# %matplotlib inline
import numpy as np
# # Define plotting helper functions
# +
from librosa import display
def plot_spectrum (data, name):
display.specshow(data, y_axis='log', x_axis='time')
plt.title(f'Power spectrogram of {name}')
plt.colorbar(format='%+2.0f dB')
plt.tight_layout()
# plt.show()
# -
# # Define compression helper functions
# +
random_seed = 0
from sklearn.decomposition import TruncatedSVD
np.random.seed(random_seed)
def compress(imageIn, n_components=100,random_seed=0):
image = imageIn
if len (image.shape) == 2:
# print('Found Gray image')
image = image[:,:,np.newaxis] # Equivalent to x[:,np.newaxis]
if len (image.shape) == 3:
# print('Found RGB image')
pass
if len (image.shape) > 3:
raise('not sure what image type this')
n_of_layers = image.shape[2]
compressed_list = []
for layer in range(n_of_layers):
# print(layer)
image_layer = image[:,:,layer] # ie r, g or b
clf = TruncatedSVD(n_components=n_components)
clf.fit(image_layer)
compressed_layer = clf.inverse_transform(clf.transform(image_layer))
compressed_list.append(compressed_layer)
compressed = np.stack(compressed_list, axis=2)
# clip to expected range
compressed = np.clip(compressed, a_min=0, a_max=255)
# cast to same dtype as original image
compressed = np.array(compressed, dtype = image.dtype)
# reshape to original image size
compressed = compressed.reshape(imageIn.shape)
return compressed
# -
def compress_complex(complex_image, n_components=100,random_seed=0, doplot=False):
'''
complex in the sense of complex numbers,
https://en.wikipedia.org/wiki/Complex_number
ie having a real and an imaginary part
'''
real = np.real(complex_image)
imag = np.imag(complex_image)
compress_real = compress(real, n_components, random_seed)
compress_imag = compress(real, n_components, random_seed)
if doplot:
plot_spectrum(real, 'Real Part')
plot_spectrum(compress_real, 'Real Part Compressed')
plot_spectrum(imag, 'Imaginary Part')
plot_spectrum(compress_imag, 'Imaginary Part Compressed')
compressed = compress_real + 1j * compress_imag
return compressed
# # Compress Images
from sklearn.datasets import load_sample_images
dataset = load_sample_images()
dataset.DESCR
def myplot(compressed_image):
plt.imshow(compressed_image)
# +
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import matplotlib.pyplot as plt
@interact(ImageNumber=range(len(dataset.images)),
n_components=widgets.IntSlider(min=1, max=70, step=1, value=10))
def plot_compressed(ImageNumber,n_components):
image = dataset.images[ImageNumber]
compressed_image = compress(image, n_components=n_components)
fig = plt.figure(figsize=(15, 7))
myplot(compressed_image)
fig.canvas.draw()
# -
# # Sounds
# The audio files in this notebook are from the ESC-50 dataset:
#
# - ESC-50: Dataset for Environmental Sound Classification
# - https://github.com/karoldvl/ESC-50/
# - https://dx.doi.org/10.7910/DVN/YDEPUT
def load_audio_file(filepath):
# %%
y_multichannel, sr = lr.load(filepath, mono=False)
print(y_multichannel.shape)
if len(y_multichannel.shape)>1:
channels = [0]
y_channel_selection = y_multichannel[tuple([channels])]
y = np.mean(y_channel_selection, axis=0)
else:
y = np.array(y_multichannel)
return y, sr
# +
# %%
import pathlib
import IPython
import librosa as lr
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
# files = glob(pathname='data/hitachi/0_db/slider/id_00/**/**.wav')
files = glob(pathname='sounds/**/**.wav')
print(files)
filepath = files[0]
# %%
image_dict = {'Cat 1': files[1], 'Cat 2': files[2], 'Can opening':files[0]}
@interact(x=image_dict,
plt=plt.figure(figsize=(15, 7))
)
def myprint(x):
print(x)
y, sr = load_audio_file(x)
IPython.display.display(IPython.display.Audio(y, rate=sr))
mysftf = lr.stft(y, n_fft= 1024, hop_length= 512)
fig=plt.figure(figsize=(15, 7))
plot_spectrum(np.log(np.abs(mysftf)), 'Log of Absolute of Compressed')
fig.canvas.draw()
# -
@interact(x=image_dict,
n_components=widgets.IntSlider(min=1, max=70, step=1, value=25))
def myprint(x, n_components):
print(x)
y, sr = load_audio_file(x)
# IPython.display.display(IPython.display.Audio(y, rate=sr))
mysftf = lr.stft(y, n_fft= 1024, hop_length= 512)
# plot_spectrum(np.abs(mysftf), 'Absolute of Uncompressed')
#
mysftf_compressed = compress_complex(mysftf, n_components=n_components, doplot=False)
plt.figure(figsize=(15, 7))
plot_spectrum(np.log(np.abs(mysftf_compressed)), 'Log of Absolute of Compressed')
Original_memory = np.prod(mysftf_compressed.shape)
Compressed_memory = (1 + np.sum(mysftf_compressed.shape) ) * n_components
print(f'The compressed memory is roughly {100 * 2 * Compressed_memory / Original_memory:0.0f}% of the original')
y_inverted_sftf = lr.istft(mysftf_compressed, hop_length= 512)
IPython.display.display(IPython.display.Audio(y_inverted_sftf, rate=22050))
print('\n')
| .ipynb_checkpoints/Compress_audio_via_images-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <h2 style='color:blue' align="center">Decision Tree Classification</h2>
# ##### In this file using following columns build a model to predict if person would survive or not,
#
# 1. Pclass
# 1. Sex
# 1. Age
# 1. Fare
import pandas as pd
df = pd.read_csv("titanic.csv")
df.head()
df.drop(['PassengerId','Name','SibSp','Parch','Ticket','Cabin','Embarked'],axis='columns',inplace=True)
df.isnull().sum()
inputs = df.drop('Survived',axis='columns')
target = df.Survived
inputs.Sex = inputs.Sex.map({'male': 1, 'female': 2})
inputs.isnull().sum()
inputs.Age[:10]
inputs.Age = inputs.Age.fillna(inputs.Age.mean())
inputs.head()
inputs.isnull().sum()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(inputs,target,test_size=0.2)
X_train
X_test
y_test
len(X_train)
len(X_test)
from sklearn import tree
model = tree.DecisionTreeClassifier()
model.fit(X_train,y_train)
model.score(X_test,y_test)
y_predicted = model.predict(X_test)
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
cm = confusion_matrix(y_test, y_predicted)
cm
import seaborn as sn
plt.figure(figsize = (10,7))
sn.heatmap(cm, annot=True)
plt.xlabel('Predicted')
plt.ylabel('Truth')
model.predict([[3,1,22.0,7.2500]])
# **Exercise: Build decision tree model to predict salary based on certain parameters**
# ##### In this file using following columns build a model to predict if person would get salary more then 100k or not,
# 1. Company
# 2. Job
# 3. Degree
#
# ##### Calculate score of your model
| Week03/Day01/Decision tree/5_decision_tree.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ##### Libraries
# + language="javascript"
# utils.load_extension('collapsible_headings/main')
# utils.load_extension('execute_time/ExecuteTime')
# utils.load_extension('scroll_down/main')
# utils.load_extension('hide_input/main')
# utils.load_extension('jupyter-js-widgets/extension')
#
# +
import pandas as pd
pd.set_option('display.max_columns', None)
import os
import matplotlib.pyplot as plt
plt.style.use("fivethirtyeight")
import seaborn as sns
import numpy as np
from pandas_profiling import ProfileReport
from sklearn.linear_model import Lasso,LogisticRegression
from category_encoders.one_hot import OneHotEncoder
from category_encoders.m_estimate import MEstimateEncoder
from category_encoders.target_encoder import TargetEncoder
from category_encoders.cat_boost import CatBoostEncoder
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, MinMaxScaler,LabelBinarizer
from sklearn.metrics import mean_absolute_error, classification_report, roc_auc_score
from sklearn.tree import DecisionTreeRegressor, plot_tree
from catboost import CatBoostRegressor, CatBoostClassifier
import shap
from matplotlib import rcParams
rcParams["axes.labelsize"] = 14
rcParams["xtick.labelsize"] = 12
rcParams["ytick.labelsize"] = 12
rcParams["figure.figsize"] = 16, 8
# -
def plot_feature_importance(columnas,model_features,columns_ploted=10,model_name='Catboost'):
'''
This method is yet non-tested
This function receives a set of columns feeded to a model, and the importance of each of feature.
Returns a graphical visualization
Call it fot catboost pipe example:
plot_feature_importance(pipe_best_estimator[:-1].transform(X_tr).columns,pipe_best_estimator.named_steps['cb'].get_feature_importance(),20)
Call it for lasso pipe example:
plot_feature_importance(pipe_best_estimator[:-1].transform(X_tr).columns,np.array(pipe_best_estimator.named_steps['clf'].coef_.squeeze()),20)
'''
feature_importance = pd.Series(index = columnas, data = np.abs(model_features))
n_selected_features = (feature_importance>0).sum()
print('{0:d} features, reduction of {1:2.2f}%'.format(n_selected_features,(1-n_selected_features/len(feature_importance))*100))
plt.figure()
feature_importance.sort_values().tail(columns_ploted).plot(kind = 'bar', figsize = (18,6))
plt.title('Feature Importance for {}'.format(model_name))
plt.show()
def multiclass_roc_auc_score(y_test, y_pred, average="macro"):
lb = LabelBinarizer()
lb.fit(y_test)
y_test = lb.transform(y_test)
y_pred = lb.transform(y_pred)
return roc_auc_score(y_test, y_pred, average=average)
file_path = (
os.path.abspath(os.path.join("", "../.."))
+ "/Data/araria-osm-dhs/araria-osm-dhs.csv"
)
df = pd.read_csv(file_path)
file_path = (
os.path.abspath(os.path.join("", "../.."))
+ "/Data/araria-osm-dhs/araria_voronoi_osm.csv"
)
araria = pd.read_csv(file_path)
file_path = os.path.abspath(os.path.join("", "../..")) + "/Data/DHS-PROCESSED-CLEAN.csv"
dhs = pd.read_csv(file_path)
data = pd.merge(araria, df, left_on="osmid", right_on="OSMID")
df = pd.merge(data, dhs, on="DHSCLUST")
del data, araria
df['Wealth'].unique()
# ## Clean
df = df.drop(
columns=[
"Unnamed: 0_x",
"Unnamed: 0_y",
"geometry_x",
"name:en",
"nodes",
"DHSID",
"OSMID",
'geometry_y',
'geometry_x',
'osmid',
'Drinking Water',
'DHSREGNA',
'LATNUM',
'LONGNUM'
]
)
# +
def filter_my_way(data,columna):
'''
If the DHSCLUST does not have any value it will have a NaN on this
'''
temp = data.groupby(['DHSCLUST',columna]).count().reset_index()
t = temp.loc[temp.groupby('DHSCLUST').unique_id.agg('idxmax')]
dic = pd.Series(t[columna].values,index=t['DHSCLUST'].values).to_dict()
data[columna] = data['DHSCLUST'].map(dic)
return data
# -
df = filter_my_way(df,'amenity')
cols = ['amenity','highway','surface','motorroad','building','landuse','element_type']
for c in cols:
df = filter_my_way(df,c)
df = df.loc[:, df.isnull().mean() < .9]
df = df.drop(columns=['unique_id'])
df.DHSCLUST.nunique()
df = df.drop_duplicates()
sns.violinplot(dhs['Wealth Index'])
sns.violinplot(df['Wealth Index'])
# for one district 17MB.
df.shape
profile = ProfileReport(df, title="Pandas Profiling Report")
# +
#profile.to_file("DHS_OSM_EDA_report.html")
# -
# ## Modeling
# +
cols_drop = ['DHSCLUST','Wealth Index','DISTRICTID','Wealth']
scaler = MinMaxScaler()
df[["UN_Population_Density_2015"]] = scaler.fit_transform(
df[["UN_Population_Density_2015"]]
)
X = df.drop(columns=cols_drop)
y = df[["Wealth Index"]]
# -
plt.figure()
plt.title('Target distribution')
sns.violinplot(y.values)
plt.show()
X
X_tr,X_te,y_tr,y_te = train_test_split(X,y)
# ### Regression
# #### Linear OHE
model = Lasso()
enc = OneHotEncoder(use_cat_names=True)
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
mean_absolute_error(pipe.predict(X_te),y_te)
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
np.array(pipe.named_steps["model"].coef_.squeeze()),
20,model_name='Lasso OHE'
)
# #### Linear TE
# +
model = Lasso()
enc = CatBoostEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# -
mean_absolute_error(pipe.predict(X_te),y_te)
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
np.array(pipe.named_steps["model"].coef_.squeeze()),
20,model_name='Lasso OHE'
)
# + [markdown] heading_collapsed=true
# #### Decision Tree TE
# + hidden=true
model = DecisionTreeRegressor(max_depth=5)
enc = CatBoostEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# + hidden=true
mean_absolute_error(pipe.predict(X_te),y_te)
# + hidden=true
pipe.named_steps["model"]
# + hidden=true
plt.figure()
plot_tree(
pipe.named_steps["model"],
max_depth=5,
feature_names=X_tr.columns,
filled=True,
)
plt.savefig('tree_te.svg',format='svg')
plt.show()
# + [markdown] heading_collapsed=true
# #### Decision Tree OHE
# + hidden=true
model = DecisionTreeRegressor(max_depth=8)
enc = OneHotEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# + hidden=true
mean_absolute_error(pipe.predict(X_te),y_te)
# + hidden=true
plt.figure()
plot_tree(
pipe.named_steps["model"],
max_depth=5,
feature_names=pipe[:-1].transform(X_tr).columns,
filled=True,
)
plt.savefig('tree_ohe.svg',format='svg')
plt.show()
# + [markdown] heading_collapsed=true
# #### Catboost TE
# + hidden=true
model = CatBoostRegressor(iterations=200,verbose=0)
enc = CatBoostEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# + hidden=true
mean_absolute_error(pipe.predict(X_te),y_te)
# + hidden=true
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
pipe.named_steps["model"].get_feature_importance(),
20,
)
# + hidden=true
# load JS visualization code to notebook
shap.initjs()
# explain the model's predictions using SHAP
# (same syntax works for LightGBM, CatBoost, scikit-learn and spark models)
explainer = shap.TreeExplainer(pipe.named_steps["model"])
shap_values = explainer.shap_values(pipe[:-1].transform(X_tr))
# visualize the first prediction's explanation (use matplotlib=True to avoid Javascript)
shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])
# + hidden=true
shap.summary_plot(shap_values, X_te, plot_type="bar")
# -
# ## Classification
# +
X = df.drop(columns=cols_drop)
y = df[["Wealth"]]
dic = {"richest": 1, "richer": 2, "middle": 3, "poorer": 4, "poorest": 5}
y = y.Wealth.map(dic)
X_tr,X_te,y_tr,y_te = train_test_split(X,y)
# -
# #### Logistic TE
# +
model = LogisticRegression()
enc = OneHotEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# -
roc_auc_score(pipe.predict(X_te),y_te)
print(classification_report(pipe.predict(X_te),y_te))
df.shape
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
pipe.named_steps["model"].coef_.squeeze(),
20,
)
# ## Converted Regression
# #### Lasso TE
# +
model = Lasso()
enc = CatBoostEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# -
mean_absolute_error(pipe.predict(X_te),y_te)
preds = np.round(pipe.predict(X_te))
dic_rev = {v: k for k, v in dic.items()}
preds = pd.DataFrame(preds,columns=['predictions'])
y_test = preds.predictions.map(dic_rev)
print(classification_report(y_test,[dic_rev[k] for k in y_te]))
multiclass_roc_auc_score(y_test,[dic_rev[k] for k in y_te],average=None)
df.shape
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
pipe.named_steps["model"].get_feature_importance(),
20,
)
# +
# load JS visualization code to notebook
shap.initjs()
# explain the model's predictions using SHAP
# (same syntax works for LightGBM, CatBoost, scikit-learn and spark models)
explainer = shap.TreeExplainer(pipe.named_steps["model"])
shap_values = explainer.shap_values(pipe[:-1].transform(X_tr))
# visualize the first prediction's explanation (use matplotlib=True to avoid Javascript)
shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])
# -
shap.summary_plot(shap_values, X_te, plot_type="bar")
# +
#### Catboost TE
model = CatBoostRegressor(iterations=200,verbose=0)
enc = CatBoostEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
mean_absolute_error(pipe.predict(X_te),y_te)
preds = np.round(pipe.predict(X_te))
dic_rev = {v: k for k, v in dic.items()}
preds = pd.DataFrame(preds,columns=['predictions'])
y_test = preds.predictions.map(dic_rev)
print(classification_report(y_test,[dic_rev[k] for k in y_te]))
multiclass_roc_auc_score(y_test,[dic_rev[k] for k in y_te],average=None)
df.shape
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
pipe.named_steps["model"].get_feature_importance(),
20,
)
# load JS visualization code to notebook
shap.initjs()
# explain the model's predictions using SHAP
# (same syntax works for LightGBM, CatBoost, scikit-learn and spark models)
explainer = shap.TreeExplainer(pipe.named_steps["model"])
shap_values = explainer.shap_values(pipe[:-1].transform(X_tr))
# visualize the first prediction's explanation (use matplotlib=True to avoid Javascript)
shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])
shap.summary_plot(shap_values, X_te, plot_type="bar")
# -
# #### Catboost TE
# +
model = CatBoostRegressor(iterations=200,verbose=0)
enc = CatBoostEncoder()
pipe = Pipeline([('enc',enc), ('model',model)])
pipe.fit(X_tr,y_tr)
# -
mean_absolute_error(pipe.predict(X_te),y_te)
preds = np.round(pipe.predict(X_te))
dic_rev = {v: k for k, v in dic.items()}
preds = pd.DataFrame(preds,columns=['predictions'])
y_test = preds.predictions.map(dic_rev)
print(classification_report(y_test,[dic_rev[k] for k in y_te]))
multiclass_roc_auc_score(y_test,[dic_rev[k] for k in y_te],average=None)
df.shape
plot_feature_importance(
pipe[:-1].transform(X_tr).columns,
pipe.named_steps["model"].get_feature_importance(),
20,
)
# +
# load JS visualization code to notebook
shap.initjs()
# explain the model's predictions using SHAP
# (same syntax works for LightGBM, CatBoost, scikit-learn and spark models)
explainer = shap.TreeExplainer(pipe.named_steps["model"])
shap_values = explainer.shap_values(pipe[:-1].transform(X_tr))
# visualize the first prediction's explanation (use matplotlib=True to avoid Javascript)
shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])
# -
shap.summary_plot(shap_values, X_te, plot_type="bar")
| dssg/data-exploration/carlos/dhs_osm.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Kaggle: IBM Attrition
# Uncover the factors that lead to employee attrition and explore important questions such as:
# 1. Show a breakdown of distance from home by job role and attrition.
# 2. Compare average monthly income by education and attrition.
#
conda install seaborn
# +
#Importing the required packages
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
df = pd.read_csv("WA_Fn-UseC_-HR-Employee-Attrition.csv")
df
# -
#Filtering the unrequired columns from the dataset
df = df.filter(['Attrition', 'DistanceFromHome','JobRole','Education','MonthlyIncome'])
df
# # Inspecting the data
df.isnull().sum()
# +
df.columns
# -
df.info()
df.dtypes
#Describing the data
df.describe()
df.info()
# +
#Visualizing the required columns
# +
#Visualizing distance from home
df["DistanceFromHome"]
df["DistanceFromHome"].plot.hist(alpha=0.5);
# -
df["DistanceFromHome"].value_counts()
#Visualizing attrition
#df.Attrition = df.Attrition.astype('str')
df.Attrition.replace(["Yes","No"],[1,0],inplace=True)
#df.Attrition
df
df["Attrition"].value_counts().sort_values().plot(kind = 'barh', color= "green")
df["Attrition"].value_counts()
sns.histplot(df, x="JobRole", hue="Attrition", multiple="stack")
df['JobRole'].head()
# +
##Visualizing Jobrole
#df["JobRole"].
df["JobRole"].value_counts().sort_values().plot(kind = 'barh',color= "red")
# -
df["JobRole"].value_counts()
# +
correlation_matrix= df.corr(method='pearson')
sns.heatmap(correlation_matrix,annot=True)
plt.title('correlation Matrix for Numeric Features')
plt.xlabel('Attrition Features')
plt.ylabel('Attrition Features')
plt.show()
# -
# Combine levels in a categorical variable by seeing their distribution
JobRoleCrossTab = pd.crosstab(df['JobRole'], df['Attrition'], margins=True)
JobRoleCrossTab
# Plotting countplots for the categorical variables
fig,ax = plt.subplots(3,2, figsize=(20,20))
plt.suptitle("Distribution of Attrition,DistanceFromHome,JobRole,Education and MonthlyIncome factors", fontsize=20)
sns.countplot(df['Attrition'], ax = ax[0,0])
sns.countplot(df['DistanceFromHome'], ax = ax[0,1])
sns.countplot(df['JobRole'], ax = ax[1,0])
sns.countplot(df['Education'], ax = ax[1,1])
sns.countplot(df['MonthlyIncome'], ax = ax[2,1])
plt.xticks(rotation=20)
plt.subplots_adjust(bottom=0.4)
plt.show()
df.head()
sns.histplot(df, x="DistanceFromHome", hue="Attrition", multiple="stack")
# Combine levels in a categorical variable by seeing their distribution
JobRoleCrossTab = pd.crosstab(df['Education'], df['Attrition'], margins=True)
JobRoleCrossTab
sns.histplot(df, x="Education", hue="Attrition", multiple="stack")
# Combine levels in a categorical variable by seeing their distribution
JobRoleCrossTab = pd.crosstab(df['MonthlyIncome'], df['Attrition'], margins=True)
JobRoleCrossTab
sns.histplot(df, x="MonthlyIncome", hue="Attrition", multiple="stack")
| IBM ATTRITION.ANSWERS.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:aind-gpu]
# language: python
# name: conda-env-aind-gpu-py
# ---
# + [markdown] deletable=true editable=true
# # Project 1: Navigation
# ### Test 1 - DQN model
#
# <sub><NAME>. August 24, 2018<sub>
#
# #### Abstract
#
#
# _In this notebook, I will use the Unity ML-Agents environment to train a DQN model for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893)._
# + [markdown] deletable=true editable=true
# ## 1. What we are going to test
#
# Bla bla .... Thus, let's begin by checking the environment where I am going to run these tests.
# + deletable=true editable=true
# %load_ext version_information
# %version_information numpy, unityagents, torch, matplotlib, pandas, gym
# + [markdown] deletable=true editable=true
# Now, let's define some meta variables to use in this notebook
# + deletable=true editable=true
import os
fig_prefix = 'figures/2018-08-24-'
data_prefix = '../data/2018-08-24-'
s_currentpath = os.getcwd()
# + [markdown] deletable=true editable=true
# Also, let's import some of the necessary packages for this experiment.
# + deletable=true editable=true
from unityagents import UnityEnvironment
# + deletable=true editable=true
import sys
import os
sys.path.append("../") # include the root directory as the main
import eda
import pandas as pd
import numpy as np
# + [markdown] deletable=true editable=true
# ## 2. Training the agent
#
# The environment used for this project is the Udacity version of the Banana Collector environment, from [Unity](https://youtu.be/heVMs3t9qSk). The goal of the agent is to collect as many yellow bananas as possible while avoiding blue bananas. Bellow, we are going to start this environment.
# + deletable=true editable=true
env = UnityEnvironment(file_name="../Banana_Linux_NoVis/Banana.x86_64")
# + [markdown] deletable=true editable=true
# Unity Environments contain brains which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.
# + deletable=true editable=true
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# + [markdown] deletable=true editable=true
# Now, we are going to collect some basic information about the environment.
# + deletable=true editable=true
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of actions
action_size = brain.vector_action_space_size
# examine the state space
state = env_info.vector_observations[0]
state_size = len(state)
# + [markdown] deletable=true editable=true
# And finally, we are going to train the model. We will consider that this environment is solved if the agent is able to receive an average reward (over 100 episodes) of at least +13.
# + deletable=true editable=true
# %%time
import gym
import pickle
import random
import torch
import numpy as np
from collections import deque
from drlnd.dqn_agent import DQNAgent, DDQNAgent, DDQNPREAgent
n_episodes = 2000
eps_start = 1.
eps_end=0.01
eps_decay=0.995
max_t = 1000
s_model = 'dqn'
agent = DQNAgent(state_size=state_size, action_size=action_size, seed=0)
scores = [] # list containing scores from each episode
scores_std = [] # List containing the std dev of the last 100 episodes
scores_avg = [] # List containing the mean of the last 100 episodes
scores_window = deque(maxlen=100) # last 100 scores
eps = eps_start # initialize epsilon
for i_episode in range(1, n_episodes+1):
env_info = env.reset(train_mode=True)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
for t in range(max_t):
# action = np.random.randint(action_size) # select an action
action = agent.act(state, eps)
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
agent.step(state, action, reward, next_state, done)
score += reward # update the score
state = next_state # roll over the state to next time step
if done: # exit loop if episode finished
break
scores_window.append(score) # save most recent score
scores.append(score) # save most recent score
scores_std.append(np.std(scores_window)) # save most recent std dev
scores_avg.append(np.mean(scores_window)) # save most recent std dev
eps = max(eps_end, eps_decay*eps) # decrease epsilon
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
if i_episode % 100 == 0:
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))
if np.mean(scores_window)>=13.0:
s_msg = '\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'
print(s_msg.format(i_episode, np.mean(scores_window)))
torch.save(agent.qnet.state_dict(), '%scheckpoint_%s.pth' % (data_prefix, s_model))
break
# save data to use latter
d_data = {'episodes': i_episode,
'scores': scores,
'scores_std': scores_std,
'scores_avg': scores_avg,
'scores_window': scores_window}
pickle.dump(d_data, open('%ssim-data-%s.data' % (data_prefix, s_model), 'wb'))
# + [markdown] deletable=true editable=true
# ## 3. Results
#
# The agent using the vanilla DQN was able to solve the Banana Collector environment in X episodes of 1000 steps, each.
# + deletable=true editable=true
import pickle
d_data = pickle.load(open('../data/2018-08-24-sim-data-dqn.data', 'rb'))
s_msg = 'Environment solved in {:d} episodes!\tAverage Score: {:.2f} +- {:.2f}'
print(s_msg.format(d_data['episodes'], np.mean(d_data['scores_window']), np.std(d_data['scores_window'])))
# + [markdown] deletable=true editable=true
# Now, let's plot the rewards per episode. In the right panel, we will plot the rolling average score over 100 episodes $\pm$ its standard deviation, as well as the goal of this project (13+ on average over the last 100 episodes).
# + deletable=true editable=true
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# %matplotlib inline
#recover data
na_raw = np.array(d_data['scores'])
na_mu = np.array(d_data['scores_avg'])
na_sigma = np.array(d_data['scores_std'])
# plot the scores
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True)
# plot the sores by episode
ax1.plot(np.arange(len(na_raw)), na_raw)
ax1.set_xlim(0, len(na_raw)+1)
ax1.set_ylabel('Score')
ax1.set_xlabel('Episode #')
ax1.set_title('raw scores')
# plot the average of these scores
ax2.axhline(y=13., xmin=0.0, xmax=1.0, color='r', linestyle='--', linewidth=0.7, alpha=0.9)
ax2.plot(np.arange(len(na_mu)), na_mu)
ax2.fill_between(np.arange(len(na_mu)), na_mu+na_sigma, na_mu-na_sigma, facecolor='gray', alpha=0.1)
ax2.set_ylabel('Average Score')
ax2.set_xlabel('Episode #')
ax2.set_title('average scores')
f.tight_layout()
# -
# f.savefig(fig_prefix + 'dqn.eps', format='eps', dpi=1200)
f.savefig(fig_prefix + 'dqn.jpg', format='jpg')
# + deletable=true editable=true
env.close()
# + [markdown] deletable=true editable=true
# ## 4. Conclusion
#
#
# The Deep Q-learning agent was able to solve the environment in 529 episodes. In the next experiment I will implement and test the Double Deep Q-learning model.
# + deletable=true editable=true
| notebooks/2018-08-24-lab-dqn.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
"""
[V1]
* resnest50_fast_2s2x40d
* Add Max./Min. Channels
[V2]
* resnest50_fast_2s2x40d
* final_drop = 0.2
* dropblock_prob = 0.0
[TODO]
* Separate gene expression, cell vaibility and other features
* PCGrad (Project Conflicting Gradients)
* Tuning resolution and image size
ResNeSt:
https://github.com/zhanghang1989/ResNeSt
"""
kernel_mode = True
training_mode = False
import sys
if kernel_mode:
sys.path.insert(0, "../input/iterative-stratification")
sys.path.insert(0, "../input/pytorch-lightning")
sys.path.insert(0, "../input/resnest")
sys.path.insert(0, "../input/pytorch-optimizer")
sys.path.insert(0, "../input/pytorch-ranger")
import os
import numpy as np
import pandas as pd
import time
import random
import math
import pickle
from pickle import dump, load
import glob
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.cm import get_cmap
from matplotlib import rcParams
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import StandardScaler, LabelEncoder, MinMaxScaler, \
RobustScaler, QuantileTransformer, PowerTransformer
from sklearn.decomposition import PCA, KernelPCA
from sklearn.manifold import TSNE
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
import torch
from torch import nn
from torch.utils.data import DataLoader, random_split
import torch.nn.functional as F
from torch.autograd import Function
import torch.optim as optim
from torch.nn import Linear, BatchNorm1d, ReLU
from torchvision import transforms
import torch_optimizer
import pytorch_lightning as pl
from pytorch_lightning import Trainer, seed_everything
from pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.metrics.functional import classification
import resnest
from resnest.torch import resnest50, resnest101, resnest200, resnest269, \
resnest50_fast_2s2x40d, resnest50_fast_1s2x40d, resnest50_fast_1s1x64d
import cv2
import imgaug as ia
from imgaug.augmenters.size import CropToFixedSize
import warnings
warnings.filterwarnings('ignore')
pd.options.display.max_columns = None
sns.set(style="darkgrid")
import gc
gc.enable()
rand_seed = 1120
print(f"PyTorch Version: {torch.__version__}")
print(f"PyTorch Lightning Version: {pl.__version__}")
# +
# if kernel_mode:
# # !mkdir -p /root/.cache/torch/hub/checkpoints/
# # !cp ../input/deepinsight-resnest-v2-resnest50-output/*.pth /root/.cache/torch/hub/checkpoints/
# # !ls -la /root/.cache/torch/hub/checkpoints/
# +
model_type = "resnest50"
pretrained_model = f"resnest50_fast_2s2x40d"
experiment_name = f"deepinsight_ResNeSt_v2_{model_type}"
if kernel_mode:
dataset_folder = "../input/lish-moa"
model_output_folder = f"./{experiment_name}" if training_mode \
else f"../input/deepinsight-resnest-v2-resnest50-output/{experiment_name}"
else:
dataset_folder = "/workspace/Kaggle/MoA"
model_output_folder = f"{dataset_folder}/{experiment_name}" if training_mode \
else f"/workspace/Kaggle/MoA/completed/deepinsight_ResNeSt_v2_resnest50/{experiment_name}"
if training_mode:
os.makedirs(model_output_folder, exist_ok=True)
# Dedicated logger for experiment
exp_logger = TensorBoardLogger(model_output_folder,
name=f"overall_logs",
default_hp_metric=False)
# debug_mode = True
debug_mode = False
num_workers = 2 if kernel_mode else 6
# gpus = [0, 1]
gpus = [0]
# gpus = [1]
epochs = 200
patience = 16
# learning_rate = 1e-3
learning_rate = 0.000352 # Suggested Learning Rate from LR finder (V7)
learning_rate *= len(gpus)
weight_decay = 1e-6
# weight_decay = 0
# T_max = 10 # epochs
T_max = 5 # epochs
T_0 = 5 # epochs
accumulate_grad_batches = 1
gradient_clip_val = 10.0
if "resnest50" in model_type:
batch_size = 128
infer_batch_size = 256 if not kernel_mode else 256
image_size = 224
resolution = 224
elif model_type == "resnest101":
batch_size = 48
infer_batch_size = 96
image_size = 256
resolution = 256
elif model_type == "resnest200":
batch_size = 12
infer_batch_size = 24
image_size = 320
resolution = 320
elif model_type == "resnest269":
batch_size = 4
infer_batch_size = 8
image_size = 416
resolution = 416
# Prediction Clipping Thresholds
prob_min = 0.001
prob_max = 0.999
# Swap Noise
swap_prob = 0.1
swap_portion = 0.15
label_smoothing = 0.001
# DeepInsight Transform
perplexity = 5
fc_size = 512
final_drop = 0.2
dropblock_prob = 0.0
# +
train_features = pd.read_csv(
f"{dataset_folder}/train_features.csv", engine='c')
train_labels = pd.read_csv(
f"{dataset_folder}/train_targets_scored.csv", engine='c')
train_extra_labels = pd.read_csv(
f"{dataset_folder}/train_targets_nonscored.csv", engine='c')
test_features = pd.read_csv(
f"{dataset_folder}/test_features.csv", engine='c')
sample_submission = pd.read_csv(
f"{dataset_folder}/sample_submission.csv", engine='c')
# +
# Sort by sig_id to ensure that all row orders match
train_features = train_features.sort_values(
by=["sig_id"], axis=0, inplace=False).reset_index(drop=True)
train_labels = train_labels.sort_values(by=["sig_id"], axis=0,
inplace=False).reset_index(drop=True)
train_extra_labels = train_extra_labels.sort_values(
by=["sig_id"], axis=0, inplace=False).reset_index(drop=True)
sample_submission = sample_submission.sort_values(
by=["sig_id"], axis=0, inplace=False).reset_index(drop=True)
# -
train_features.shape, train_labels.shape, train_extra_labels.shape
test_features.shape
# ## Include Drug ID
train_drug = pd.read_csv(f"{dataset_folder}/train_drug.csv", engine='c')
train_features = train_features.merge(train_drug, on='sig_id', how='left')
category_features = ["cp_type", "cp_dose"]
numeric_features = [
c for c in train_features.columns
if c not in ["sig_id", "drug_id"] and c not in category_features
]
all_features = category_features + numeric_features
gene_experssion_features = [c for c in numeric_features if c.startswith("g-")]
cell_viability_features = [c for c in numeric_features if c.startswith("c-")]
len(numeric_features), len(gene_experssion_features), len(
cell_viability_features)
train_classes = [c for c in train_labels.columns if c != "sig_id"]
train_extra_classes = [c for c in train_extra_labels.columns if c != "sig_id"]
len(train_classes), len(train_extra_classes)
# ## Drop Control Type Rows
# +
train_features = train_features[train_features["cp_type"] == "trt_cp"].copy()
train_labels = train_labels.iloc[train_features.index, :].copy()
train_extra_labels = train_extra_labels.iloc[train_features.index, :].copy()
train_features = train_features.reset_index(drop=True)
train_labels = train_labels.reset_index(drop=True)
train_extra_labels = train_extra_labels.reset_index(drop=True)
# -
train_features.shape, train_labels.shape, train_extra_labels.shape
# + [markdown] heading_collapsed=true
# ## Label Encoding
# + hidden=true
for df in [train_features, test_features]:
df['cp_type'] = df['cp_type'].map({'ctl_vehicle': 0, 'trt_cp': 1})
df['cp_dose'] = df['cp_dose'].map({'D1': 0, 'D2': 1})
df['cp_time'] = df['cp_time'].map({24: 0, 48: 0.5, 72: 1})
# + hidden=true
train_features["cp_type"].value_counts()
# + hidden=true
train_features["cp_dose"].value_counts()
# + hidden=true
train_features["cp_time"].value_counts()
# + [markdown] heading_collapsed=true
# ## DeepInsight Transform (t-SNE)
# Based on https://github.com/alok-ai-lab/DeepInsight, but with some minor corrections
# + [markdown] heading_collapsed=true hidden=true
# ### Implementation
# + hidden=true
# Modified from DeepInsight Transform
# https://github.com/alok-ai-lab/DeepInsight/blob/master/pyDeepInsight/image_transformer.py
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA, KernelPCA
from sklearn.manifold import TSNE
from scipy.spatial import ConvexHull
from matplotlib import pyplot as plt
import inspect
class DeepInsightTransformer:
"""Transform features to an image matrix using dimensionality reduction
This class takes in data normalized between 0 and 1 and converts it to a
CNN compatible 'image' matrix
"""
def __init__(self,
feature_extractor='tsne',
perplexity=30,
pixels=100,
random_state=None,
n_jobs=None):
"""Generate an ImageTransformer instance
Args:
feature_extractor: string of value ('tsne', 'pca', 'kpca') or a
class instance with method `fit_transform` that returns a
2-dimensional array of extracted features.
pixels: int (square matrix) or tuple of ints (height, width) that
defines the size of the image matrix.
random_state: int or RandomState. Determines the random number
generator, if present, of a string defined feature_extractor.
n_jobs: The number of parallel jobs to run for a string defined
feature_extractor.
"""
self.random_state = random_state
self.n_jobs = n_jobs
if isinstance(feature_extractor, str):
fe = feature_extractor.casefold()
if fe == 'tsne_exact'.casefold():
fe = TSNE(n_components=2,
metric='cosine',
perplexity=perplexity,
n_iter=1000,
method='exact',
random_state=self.random_state,
n_jobs=self.n_jobs)
elif fe == 'tsne'.casefold():
fe = TSNE(n_components=2,
metric='cosine',
perplexity=perplexity,
n_iter=1000,
method='barnes_hut',
random_state=self.random_state,
n_jobs=self.n_jobs)
elif fe == 'pca'.casefold():
fe = PCA(n_components=2, random_state=self.random_state)
elif fe == 'kpca'.casefold():
fe = KernelPCA(n_components=2,
kernel='rbf',
random_state=self.random_state,
n_jobs=self.n_jobs)
else:
raise ValueError(("Feature extraction method '{}' not accepted"
).format(feature_extractor))
self._fe = fe
elif hasattr(feature_extractor, 'fit_transform') and \
inspect.ismethod(feature_extractor.fit_transform):
self._fe = feature_extractor
else:
raise TypeError('Parameter feature_extractor is not a '
'string nor has method "fit_transform"')
if isinstance(pixels, int):
pixels = (pixels, pixels)
# The resolution of transformed image
self._pixels = pixels
self._xrot = None
def fit(self, X, y=None, plot=False):
"""Train the image transformer from the training set (X)
Args:
X: {array-like, sparse matrix} of shape (n_samples, n_features)
y: Ignored. Present for continuity with scikit-learn
plot: boolean of whether to produce a scatter plot showing the
feature reduction, hull points, and minimum bounding rectangle
Returns:
self: object
"""
# Transpose to get (n_features, n_samples)
X = X.T
# Perform dimensionality reduction
x_new = self._fe.fit_transform(X)
# Get the convex hull for the points
chvertices = ConvexHull(x_new).vertices
hull_points = x_new[chvertices]
# Determine the minimum bounding rectangle
mbr, mbr_rot = self._minimum_bounding_rectangle(hull_points)
# Rotate the matrix
# Save the rotated matrix in case user wants to change the pixel size
self._xrot = np.dot(mbr_rot, x_new.T).T
# Determine feature coordinates based on pixel dimension
self._calculate_coords()
# plot rotation diagram if requested
if plot is True:
# Create subplots
fig, ax = plt.subplots(1, 1, figsize=(10, 7), squeeze=False)
ax[0, 0].scatter(x_new[:, 0],
x_new[:, 1],
cmap=plt.cm.get_cmap("jet", 10),
marker="x",
alpha=1.0)
ax[0, 0].fill(x_new[chvertices, 0],
x_new[chvertices, 1],
edgecolor='r',
fill=False)
ax[0, 0].fill(mbr[:, 0], mbr[:, 1], edgecolor='g', fill=False)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
return self
@property
def pixels(self):
"""The image matrix dimensions
Returns:
tuple: the image matrix dimensions (height, width)
"""
return self._pixels
@pixels.setter
def pixels(self, pixels):
"""Set the image matrix dimension
Args:
pixels: int or tuple with the dimensions (height, width)
of the image matrix
"""
if isinstance(pixels, int):
pixels = (pixels, pixels)
self._pixels = pixels
# recalculate coordinates if already fit
if hasattr(self, '_coords'):
self._calculate_coords()
def _calculate_coords(self):
"""Calculate the matrix coordinates of each feature based on the
pixel dimensions.
"""
ax0_coord = np.digitize(self._xrot[:, 0],
bins=np.linspace(min(self._xrot[:, 0]),
max(self._xrot[:, 0]),
self._pixels[0])) - 1
ax1_coord = np.digitize(self._xrot[:, 1],
bins=np.linspace(min(self._xrot[:, 1]),
max(self._xrot[:, 1]),
self._pixels[1])) - 1
self._coords = np.stack((ax0_coord, ax1_coord))
def transform(self, X, empty_value=0):
"""Transform the input matrix into image matrices
Args:
X: {array-like, sparse matrix} of shape (n_samples, n_features)
where n_features matches the training set.
empty_value: numeric value to fill elements where no features are
mapped. Default = 0 (although it was 1 in the paper).
Returns:
A list of n_samples numpy matrices of dimensions set by
the pixel parameter
"""
# Group by location (x1, y1) of each feature
# Tranpose to get (n_features, n_samples)
img_coords = pd.DataFrame(np.vstack(
(self._coords, X.clip(0, 1))).T).groupby(
[0, 1], # (x1, y1)
as_index=False).mean()
img_matrices = []
blank_mat = np.zeros(self._pixels)
if empty_value != 0:
blank_mat[:] = empty_value
for z in range(2, img_coords.shape[1]):
img_matrix = blank_mat.copy()
img_matrix[img_coords[0].astype(int),
img_coords[1].astype(int)] = img_coords[z]
img_matrices.append(img_matrix)
return img_matrices
def transform_3d(self, X, empty_value=0):
"""Transform the input matrix into image matrices
Args:
X: {array-like, sparse matrix} of shape (n_samples, n_features)
where n_features matches the training set.
empty_value: numeric value to fill elements where no features are
mapped. Default = 0 (although it was 1 in the paper).
Returns:
A list of n_samples numpy matrices of dimensions set by
the pixel parameter
"""
# Group by location (x1, y1) of each feature
# Tranpose to get (n_features, n_samples)
img_coords = pd.DataFrame(np.vstack(
(self._coords, X.clip(0, 1))).T).groupby(
[0, 1], # (x1, y1)
as_index=False)
avg_img_coords = img_coords.mean()
min_img_coords = img_coords.min()
max_img_coords = img_coords.max()
img_matrices = []
blank_mat = np.zeros((3, self._pixels[0], self._pixels[1]))
if empty_value != 0:
blank_mat[:, :, :] = empty_value
for z in range(2, avg_img_coords.shape[1]):
img_matrix = blank_mat.copy()
img_matrix[0, avg_img_coords[0].astype(int),
avg_img_coords[1].astype(int)] = avg_img_coords[z]
img_matrix[1, min_img_coords[0].astype(int),
min_img_coords[1].astype(int)] = min_img_coords[z]
img_matrix[2, max_img_coords[0].astype(int),
max_img_coords[1].astype(int)] = max_img_coords[z]
img_matrices.append(img_matrix)
return img_matrices
def fit_transform(self, X, empty_value=0):
"""Train the image transformer from the training set (X) and return
the transformed data.
Args:
X: {array-like, sparse matrix} of shape (n_samples, n_features)
empty_value: numeric value to fill elements where no features are
mapped. Default = 0 (although it was 1 in the paper).
Returns:
A list of n_samples numpy matrices of dimensions set by
the pixel parameter
"""
self.fit(X)
return self.transform(X, empty_value=empty_value)
def fit_transform_3d(self, X, empty_value=0):
"""Train the image transformer from the training set (X) and return
the transformed data.
Args:
X: {array-like, sparse matrix} of shape (n_samples, n_features)
empty_value: numeric value to fill elements where no features are
mapped. Default = 0 (although it was 1 in the paper).
Returns:
A list of n_samples numpy matrices of dimensions set by
the pixel parameter
"""
self.fit(X)
return self.transform_3d(X, empty_value=empty_value)
def feature_density_matrix(self):
"""Generate image matrix with feature counts per pixel
Returns:
img_matrix (ndarray): matrix with feature counts per pixel
"""
fdmat = np.zeros(self._pixels)
# Group by location (x1, y1) of each feature
# Tranpose to get (n_features, n_samples)
coord_cnt = (
pd.DataFrame(self._coords.T).assign(count=1).groupby(
[0, 1], # (x1, y1)
as_index=False).count())
fdmat[coord_cnt[0].astype(int),
coord_cnt[1].astype(int)] = coord_cnt['count']
return fdmat
@staticmethod
def _minimum_bounding_rectangle(hull_points):
"""Find the smallest bounding rectangle for a set of points.
Modified from JesseBuesking at https://stackoverflow.com/a/33619018
Returns a set of points representing the corners of the bounding box.
Args:
hull_points : an nx2 matrix of hull coordinates
Returns:
(tuple): tuple containing
coords (ndarray): coordinates of the corners of the rectangle
rotmat (ndarray): rotation matrix to align edges of rectangle
to x and y
"""
pi2 = np.pi / 2.
# Calculate edge angles
edges = hull_points[1:] - hull_points[:-1]
angles = np.arctan2(edges[:, 1], edges[:, 0])
angles = np.abs(np.mod(angles, pi2))
angles = np.unique(angles)
# Find rotation matrices
rotations = np.vstack([
np.cos(angles),
np.cos(angles - pi2),
np.cos(angles + pi2),
np.cos(angles)
]).T
rotations = rotations.reshape((-1, 2, 2))
# Apply rotations to the hull
rot_points = np.dot(rotations, hull_points.T)
# Find the bounding points
min_x = np.nanmin(rot_points[:, 0], axis=1)
max_x = np.nanmax(rot_points[:, 0], axis=1)
min_y = np.nanmin(rot_points[:, 1], axis=1)
max_y = np.nanmax(rot_points[:, 1], axis=1)
# Find the box with the best area
areas = (max_x - min_x) * (max_y - min_y)
best_idx = np.argmin(areas)
# Return the best box
x1 = max_x[best_idx]
x2 = min_x[best_idx]
y1 = max_y[best_idx]
y2 = min_y[best_idx]
rotmat = rotations[best_idx]
# Generate coordinates
coords = np.zeros((4, 2))
coords[0] = np.dot([x1, y2], rotmat)
coords[1] = np.dot([x2, y2], rotmat)
coords[2] = np.dot([x2, y1], rotmat)
coords[3] = np.dot([x1, y1], rotmat)
return coords, rotmat
# + hidden=true
class LogScaler:
"""Log normalize and scale data
Log normalization and scaling procedure as described as norm-2 in the
DeepInsight paper supplementary information.
Note: The dimensions of input matrix is (N samples, d features)
"""
def __init__(self):
self._min0 = None
self._max = None
"""
Use this as a preprocessing step in inference mode.
"""
def fit(self, X, y=None):
# Min. of training set per feature
self._min0 = X.min(axis=0)
# Log normalized X by log(X + _min0 + 1)
X_norm = np.log(
X +
np.repeat(np.abs(self._min0)[np.newaxis, :], X.shape[0], axis=0) +
1).clip(min=0, max=None)
# Global max. of training set from X_norm
self._max = X_norm.max()
"""
For training set only.
"""
def fit_transform(self, X, y=None):
# Min. of training set per feature
self._min0 = X.min(axis=0)
# Log normalized X by log(X + _min0 + 1)
X_norm = np.log(
X +
np.repeat(np.abs(self._min0)[np.newaxis, :], X.shape[0], axis=0) +
1).clip(min=0, max=None)
# Global max. of training set from X_norm
self._max = X_norm.max()
# Normalized again by global max. of training set
return (X_norm / self._max).clip(0, 1)
"""
For validation and test set only.
"""
def transform(self, X, y=None):
# Adjust min. of each feature of X by _min0
for i in range(X.shape[1]):
X[:, i] = X[:, i].clip(min=self._min0[i], max=None)
# Log normalized X by log(X + _min0 + 1)
X_norm = np.log(
X +
np.repeat(np.abs(self._min0)[np.newaxis, :], X.shape[0], axis=0) +
1).clip(min=0, max=None)
# Normalized again by global max. of training set
return (X_norm / self._max).clip(0, 1)
# + [markdown] heading_collapsed=true
# ## Dataset
# + hidden=true
class MoAImageSwapDataset(torch.utils.data.Dataset):
def __init__(self,
features,
labels,
transformer,
swap_prob=0.15,
swap_portion=0.1):
self.features = features
self.labels = labels
self.transformer = transformer
self.swap_prob = swap_prob
self.swap_portion = swap_portion
self.crop = CropToFixedSize(width=image_size, height=image_size)
def __getitem__(self, index):
normalized = self.features[index, :]
# Swap row featurs randomly
normalized = self.add_swap_noise(index, normalized)
normalized = np.expand_dims(normalized, axis=0)
# Note: we are setting empty_value=0
image = self.transformer.transform_3d(normalized, empty_value=0)[0]
# Resize to target size
image = cv2.resize(image.transpose((1, 2, 0)),
(image_size, image_size),
interpolation=cv2.INTER_CUBIC)
image = image.transpose((2, 0, 1))
return {"x": image, "y": self.labels[index, :]}
def add_swap_noise(self, index, X):
if np.random.rand() < self.swap_prob:
swap_index = np.random.randint(self.features.shape[0], size=1)[0]
# Select only gene expression and cell viability features
swap_features = np.random.choice(
np.array(range(3, self.features.shape[1])),
size=int(self.features.shape[1] * self.swap_portion),
replace=False)
X[swap_features] = self.features[swap_index, swap_features]
return X
def __len__(self):
return self.features.shape[0]
# + hidden=true
class MoAImageDataset(torch.utils.data.Dataset):
def __init__(self, features, labels, transformer):
self.features = features
self.labels = labels
self.transformer = transformer
def __getitem__(self, index):
normalized = self.features[index, :]
normalized = np.expand_dims(normalized, axis=0)
# Note: we are setting empty_value=0
image = self.transformer.transform_3d(normalized, empty_value=0)[0]
# Resize to target size
image = cv2.resize(image.transpose((1, 2, 0)),
(image_size, image_size),
interpolation=cv2.INTER_CUBIC)
image = image.transpose((2, 0, 1))
return {"x": image, "y": self.labels[index, :]}
def __len__(self):
return self.features.shape[0]
class TestDataset(torch.utils.data.Dataset):
def __init__(self, features, labels, transformer):
self.features = features
self.labels = labels
self.transformer = transformer
def __getitem__(self, index):
normalized = self.features[index, :]
normalized = np.expand_dims(normalized, axis=0)
# Note: we are setting empty_value=0
image = self.transformer.transform_3d(normalized, empty_value=0)[0]
# Resize to target size
image = cv2.resize(image.transpose((1, 2, 0)),
(image_size, image_size),
interpolation=cv2.INTER_CUBIC)
image = image.transpose((2, 0, 1))
return {"x": image, "y": -1}
def __len__(self):
return self.features.shape[0]
# -
# ## Model Definition
# +
from torch.nn.modules.loss import _WeightedLoss
# https://www.kaggle.com/vbmokin/moa-pytorch-rankgauss-pca-nn-upgrade-3d-visual#4.7-Smoothing
class SmoothBCEwLogits(_WeightedLoss):
def __init__(self, weight=None, reduction='mean', smoothing=0.0):
super().__init__(weight=weight, reduction=reduction)
self.smoothing = smoothing
self.weight = weight
self.reduction = reduction
@staticmethod
def _smooth(targets: torch.Tensor, n_labels: int, smoothing=0.0):
assert 0 <= smoothing < 1
with torch.no_grad():
targets = targets * (1.0 - smoothing) + 0.5 * smoothing
return targets
def forward(self, inputs, targets):
targets = SmoothBCEwLogits._smooth(targets, inputs.size(-1),
self.smoothing)
loss = F.binary_cross_entropy_with_logits(inputs, targets, self.weight)
if self.reduction == 'sum':
loss = loss.sum()
elif self.reduction == 'mean':
loss = loss.mean()
return loss
# -
def initialize_weights(layer):
for m in layer.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1.0)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
fan_out = m.weight.size(0) # fan-out
fan_in = 0
init_range = 1.0 / math.sqrt(fan_in + fan_out)
m.weight.data.uniform_(-init_range, init_range)
m.bias.data.zero_()
class MoAResNeSt(pl.LightningModule):
def __init__(
self,
pretrained_model_name,
training_set=(None, None), # tuple
valid_set=(None, None), # tuple
test_set=None,
transformer=None,
num_classes=206,
final_drop=0.0,
dropblock_prob=0,
fc_size=512,
learning_rate=1e-3):
super(MoAResNeSt, self).__init__()
self.train_data, self.train_labels = training_set
self.valid_data, self.valid_labels = valid_set
self.test_data = test_set
self.transformer = transformer
self.backbone = getattr(resnest.torch, pretrained_model)(
pretrained=True,
final_drop=final_drop)
self.backbone.fc = nn.Sequential(
nn.Linear(self.backbone.fc.in_features, fc_size, bias=True),
nn.ELU(),
nn.Dropout(p=final_drop),
nn.Linear(fc_size, num_classes, bias=True))
if self.training:
initialize_weights(self.backbone.fc)
# Save passed hyperparameters
self.save_hyperparameters("pretrained_model_name", "num_classes",
"final_drop", "dropblock_prob", "fc_size",
"learning_rate")
def forward(self, x):
return self.backbone(x)
def training_step(self, batch, batch_idx):
x = batch["x"]
y = batch["y"]
x = x.float()
y = y.type_as(x)
logits = self(x)
# loss = F.binary_cross_entropy_with_logits(logits, y, reduction="mean")
# Label smoothing
loss = SmoothBCEwLogits(smoothing=label_smoothing)(logits, y)
self.log('train_loss',
loss,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True)
return loss
def validation_step(self, batch, batch_idx):
x = batch["x"]
y = batch["y"]
x = x.float()
y = y.type_as(x)
logits = self(x)
val_loss = F.binary_cross_entropy_with_logits(logits,
y,
reduction="mean")
self.log('val_loss',
val_loss,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True)
return val_loss
def test_step(self, batch, batch_idx):
x = batch["x"]
y = batch["y"]
x = x.float()
y = y.type_as(x)
logits = self(x)
return {"pred_logits": logits}
def test_epoch_end(self, output_results):
all_outputs = torch.cat([out["pred_logits"] for out in output_results],
dim=0)
print("Logits:", all_outputs)
pred_probs = F.sigmoid(all_outputs).detach().cpu().numpy()
print("Predictions: ", pred_probs)
return {"pred_probs": pred_probs}
def setup(self, stage=None):
# self.train_dataset = MoAImageDataset(self.train_data,
# self.train_labels,
# self.transformer)
self.train_dataset = MoAImageSwapDataset(self.train_data,
self.train_labels,
self.transformer,
swap_prob=swap_prob,
swap_portion=swap_portion)
self.val_dataset = MoAImageDataset(self.valid_data, self.valid_labels,
self.transformer)
self.test_dataset = TestDataset(self.test_data, None, self.transformer)
def train_dataloader(self):
train_dataloader = DataLoader(self.train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=True,
drop_last=False)
print(f"Train iterations: {len(train_dataloader)}")
return train_dataloader
def val_dataloader(self):
val_dataloader = DataLoader(self.val_dataset,
batch_size=infer_batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=True,
drop_last=False)
print(f"Validate iterations: {len(val_dataloader)}")
return val_dataloader
def test_dataloader(self):
test_dataloader = DataLoader(self.test_dataset,
batch_size=infer_batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=True,
drop_last=False)
print(f"Test iterations: {len(test_dataloader)}")
return test_dataloader
def configure_optimizers(self):
print(f"Initial Learning Rate: {self.hparams.learning_rate:.6f}")
# optimizer = optim.Adam(self.parameters(),
# lr=self.hparams.learning_rate,
# weight_decay=weight_decay)
# optimizer = torch.optim.SGD(self.parameters(),
# lr=self.hparams.learning_rate,
# momentum=0.9,
# dampening=0,
# weight_decay=weight_decay,
# nesterov=False)
optimizer = torch_optimizer.RAdam(
self.parameters(),
lr=self.hparams.learning_rate,
betas=(0.9, 0.999),
eps=1e-8,
weight_decay=weight_decay,
)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer,
T_max=T_max,
eta_min=0,
last_epoch=-1)
# scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(
# optimizer,
# T_0=T_0,
# T_mult=1,
# eta_min=0,
# last_epoch=-1)
# scheduler = optim.lr_scheduler.OneCycleLR(
# optimizer=optimizer,
# pct_start=0.1,
# div_factor=1e3,
# max_lr=1e-1,
# # max_lr=1e-2,
# epochs=epochs,
# steps_per_epoch=len(self.train_images) // batch_size)
return [optimizer], [scheduler]
# +
# model = MoAResNeSt(
# pretrained_model,
# training_set=(None, None), # tuple
# valid_set=(None, None), # tuple
# test_set=None,
# transformer=None,
# num_classes=206,
# final_drop=0.0,
# dropblock_prob=0,
# fc_size=fc_size,
# learning_rate=learning_rate)
# print(model)
# -
# ## New CV Splits
# +
kfolds = 10
# skf = MultilabelStratifiedKFold(n_splits=kfolds,
# shuffle=True,
# random_state=rand_seed)
# label_counts = np.sum(train_labels.drop("sig_id", axis=1), axis=0)
# y_labels = label_counts.index.tolist()
# +
scored = (train_features[['sig_id', 'drug_id']]).merge(train_labels,
on='sig_id')
targets = scored.columns[2:]
vc = train_features.drug_id.value_counts()
vc1 = vc.loc[vc <= 18].index
vc2 = vc.loc[vc > 18].index
folds = train_features.copy()
# STRATIFY DRUGS 18X OR LESS
dct1 = {}
dct2 = {}
skf = MultilabelStratifiedKFold(n_splits=kfolds, shuffle=True, random_state=34)
tmp = scored.groupby('drug_id')[targets].mean().loc[vc1]
for fold, (idxT, idxV) in enumerate(skf.split(tmp, tmp[targets])):
dd = {k: fold for k in tmp.index[idxV].values}
dct1.update(dd)
# STRATIFY DRUGS MORE THAN 18X
skf = MultilabelStratifiedKFold(n_splits=kfolds, shuffle=True, random_state=34)
tmp = scored.loc[train_features.drug_id.isin(vc2)].reset_index(drop=True)
for fold, (idxT, idxV) in enumerate(skf.split(tmp, tmp[targets])):
dd = {k: fold for k in tmp.sig_id[idxV].values}
dct2.update(dd)
folds['kfold'] = folds.drug_id.map(dct1)
folds.loc[folds.kfold.isna(),'kfold'] =\
folds.loc[folds.kfold.isna(),'sig_id'].map(dct2)
folds.kfold = folds.kfold.astype('int8')
# -
# ## Training/Inference
# +
kfolds = 10
skf = MultilabelStratifiedKFold(n_splits=kfolds,
shuffle=True,
random_state=rand_seed)
label_counts = np.sum(train_labels.drop("sig_id", axis=1), axis=0)
y_labels = label_counts.index.tolist()
# +
def get_model(training_set, valid_set, test_set, transformer, model_path=None):
if training_mode:
model = MoAResNeSt(
pretrained_model_name=pretrained_model,
training_set=training_set, # tuple
valid_set=valid_set, # tuple
test_set=test_set,
transformer=transformer,
num_classes=len(train_classes),
final_drop=final_drop,
dropblock_prob=dropblock_prob,
fc_size=fc_size,
learning_rate=learning_rate)
else:
model = MoAResNeSt.load_from_checkpoint(
model_path,
pretrained_model_name=pretrained_model,
training_set=training_set, # tuple
valid_set=valid_set, # tuple
test_set=test_set,
transformer=transformer,
num_classes=len(train_classes),
fc_size=fc_size)
model.freeze()
model.eval()
return model
def save_pickle(obj, model_output_folder, fold_i, name):
dump(obj, open(f"{model_output_folder}/fold{fold_i}_{name}.pkl", 'wb'),
pickle.HIGHEST_PROTOCOL)
def load_pickle(model_output_folder, fold_i, name):
return load(open(f"{model_output_folder}/fold{fold_i}_{name}.pkl", 'rb'))
# +
def norm2_normalization(train, valid, test):
scaler = LogScaler()
train = scaler.fit_transform(train)
valid = scaler.transform(valid)
test = scaler.transform(test)
return train, valid, test, scaler
def quantile_transform(train, valid, test):
q_scaler = QuantileTransformer(n_quantiles=1000,
output_distribution='normal',
ignore_implicit_zeros=False,
subsample=100000,
random_state=rand_seed)
train = q_scaler.fit_transform(train)
valid = q_scaler.transform(valid)
test = q_scaler.transform(test)
# Transform to [0, 1]
min_max_scaler = MinMaxScaler(feature_range=(0, 1))
train = min_max_scaler.fit_transform(train)
valid = min_max_scaler.transform(valid)
test = min_max_scaler.transform(test)
return train, valid, test, q_scaler, min_max_scaler
def extract_feature_map(train,
feature_extractor='tsne_exact',
resolution=100,
perplexity=30):
transformer = DeepInsightTransformer(feature_extractor=feature_extractor,
pixels=resolution,
perplexity=perplexity,
random_state=rand_seed,
n_jobs=-1)
transformer.fit(train)
return transformer
# -
def mean_logloss(y_pred, y_true):
logloss = (1 - y_true) * np.log(1 - y_pred +
1e-15) + y_true * np.log(y_pred + 1e-15)
return np.mean(-logloss)
# +
# Ensure Reproducibility
seed_everything(rand_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
best_model = None
oof_predictions = np.zeros((train_features.shape[0], len(train_classes)))
kfold_submit_preds = np.zeros((test_features.shape[0], len(train_classes)))
# for i, (train_index, val_index) in enumerate(
# skf.split(train_features, train_labels[y_labels])):
for i in range(kfolds):
train_index = folds[folds['kfold'] != i].index
val_index = folds[folds['kfold'] == i].index
if training_mode:
print(f"Training on Fold {i} ......")
print(train_index.shape, val_index.shape)
logger = TensorBoardLogger(model_output_folder,
name=f"fold{i}/logs",
default_hp_metric=False)
train = train_features.loc[train_index, all_features].copy().values
fold_train_labels = train_labels.loc[train_index,
train_classes].copy().values
valid = train_features.loc[val_index, all_features].copy().values
fold_valid_labels = train_labels.loc[val_index,
train_classes].copy().values
test = test_features[all_features].copy().values
# LogScaler (Norm-2 Normalization)
print("Running norm-2 normalization ......")
train, valid, test, scaler = norm2_normalization(train, valid, test)
save_pickle(scaler, model_output_folder, i, "log-scaler")
# Extract DeepInsight Feature Map
print("Extracting feature map ......")
transformer = extract_feature_map(train,
feature_extractor='tsne_exact',
resolution=resolution,
perplexity=perplexity)
save_pickle(transformer, model_output_folder, i,
"deepinsight-transform")
model = get_model(training_set=(train, fold_train_labels),
valid_set=(valid, fold_valid_labels),
test_set=test,
transformer=transformer)
callbacks = [
EarlyStopping(monitor='val_loss_epoch',
min_delta=1e-6,
patience=patience,
verbose=True,
mode='min',
strict=True),
LearningRateMonitor(logging_interval='step')
]
# https://pytorch-lightning.readthedocs.io/en/latest/generated/pytorch_lightning.callbacks.ModelCheckpoint.html#pytorch_lightning.callbacks.ModelCheckpoint
checkpoint_callback = ModelCheckpoint(
filepath=f"{model_output_folder}/fold{i}" +
"/{epoch}-{train_loss_epoch:.6f}-{val_loss_epoch:.6f}" +
f"-image_size={image_size}-resolution={resolution}-perplexity={perplexity}-fc={fc_size}",
save_top_k=1,
save_weights_only=False,
save_last=False,
verbose=True,
monitor='val_loss_epoch',
mode='min',
prefix='')
if debug_mode:
# Find best LR
# https://pytorch-lightning.readthedocs.io/en/latest/lr_finder.html
trainer = Trainer(
gpus=[gpus[0]],
distributed_backend="dp", # multiple-gpus, 1 machine
auto_lr_find=True,
benchmark=False,
deterministic=True,
logger=logger,
accumulate_grad_batches=accumulate_grad_batches,
gradient_clip_val=gradient_clip_val,
precision=16,
max_epochs=1)
# Run learning rate finder
lr_finder = trainer.tuner.lr_find(
model,
min_lr=1e-7,
max_lr=1e2,
num_training=100,
mode='exponential',
early_stop_threshold=100.0,
)
fig = lr_finder.plot(suggest=True)
fig.show()
# Pick point based on plot, or get suggestion
suggested_lr = lr_finder.suggestion()
# Update hparams of the model
model.hparams.learning_rate = suggested_lr
print(
f"Suggested Learning Rate: {model.hparams.learning_rate:.6f}")
else:
trainer = Trainer(
gpus=gpus,
distributed_backend="dp", # multiple-gpus, 1 machine
max_epochs=epochs,
benchmark=False,
deterministic=True,
# fast_dev_run=True,
checkpoint_callback=checkpoint_callback,
callbacks=callbacks,
accumulate_grad_batches=accumulate_grad_batches,
gradient_clip_val=gradient_clip_val,
precision=16,
logger=logger)
trainer.fit(model)
# Load best model
seed_everything(rand_seed)
best_model = MoAResNeSt.load_from_checkpoint(
checkpoint_callback.best_model_path,
pretrained_model_name=pretrained_model,
training_set=(train, fold_train_labels), # tuple
valid_Set=(valid, fold_valid_labels), # tuple
test_set=test,
transformer=transformer,
fc_size=fc_size)
best_model.freeze()
print("Predicting on validation set ......")
output = trainer.test(ckpt_path="best",
test_dataloaders=model.val_dataloader(),
verbose=False)[0]
fold_preds = output["pred_probs"]
oof_predictions[val_index, :] = fold_preds
print(fold_preds[:5, :])
fold_valid_loss = mean_logloss(fold_preds, fold_valid_labels)
print(f"Fold {i} Validation Loss: {fold_valid_loss:.6f}")
# Generate submission predictions
print("Predicting on test set ......")
best_model.setup()
output = trainer.test(best_model, verbose=False)[0]
submit_preds = output["pred_probs"]
print(test_features.shape, submit_preds.shape)
kfold_submit_preds += submit_preds / kfolds
del model, trainer, train, valid, test, scaler, transformer
else:
print(f"Inferencing on Fold {i} ......")
print(train_index.shape, val_index.shape)
model_path = glob.glob(f'{model_output_folder}/fold{i}/epoch*.ckpt')[0]
test = test_features[all_features].copy().values
# Load LogScaler (Norm-2 Normalization)
scaler = load_pickle(f'{model_output_folder}', i, "log-scaler")
test = scaler.transform(test)
# Load DeepInsight Feature Map
transformer = load_pickle(f'{model_output_folder}', i,
"deepinsight-transform")
print(f"Loading model from {model_path}")
model = get_model(training_set=(None, None),
valid_set=(None, None),
test_set=test,
transformer=transformer,
model_path=model_path)
trainer = Trainer(
logger=False,
gpus=gpus,
distributed_backend="dp", # multiple-gpus, 1 machine
precision=16,
benchmark=False,
deterministic=True)
output = trainer.test(model, verbose=False)[0]
submit_preds = output["pred_probs"]
kfold_submit_preds += submit_preds / kfolds
del model, trainer, scaler, transformer, test
torch.cuda.empty_cache()
gc.collect()
if debug_mode:
break
# +
if training_mode:
print(oof_predictions.shape)
else:
oof_predictions = glob.glob(f'{model_output_folder}/../oof_*.npy')[0]
oof_predictions = np.load(oof_predictions)
oof_loss = mean_logloss(oof_predictions,
train_labels[train_classes].values)
print(f"OOF Validation Loss: {oof_loss:.6f}")
# +
# oof_filename = "_".join(
# [f"{k}={v}" for k, v in dict(model.hparams).items()])
# with open(f'oof_{experiment_name}_{oof_loss}.npy', 'wb') as f:
# np.save(f, oof_predictions)
# with open(f'oof_{experiment_name}_{oof_loss}.npy', 'rb') as f:
# tmp = np.load(f)
# print(tmp.shape)
# +
# [ResNeSt]
# OOF Validation Loss: 0.014620
# "dropblock_prob": 0.0
# "fc_size": 512
# "final_drop": 0.0
# "learning_rate": 0.000352
# "num_classes": 206
# "pretrained_model_name": resnest50_fast_2s2x40d
# OOF Validation Loss: 0.014560
# "dropblock_prob": 0.0
# "fc_size": 512
# "final_drop": 0.2
# "learning_rate": 0.000352
# "num_classes": 206
# "pretrained_model_name": resnest50_fast_2s2x40d
# -
if training_mode and best_model is not None:
print(best_model.hparams)
extra_params = {
"gpus": len(gpus),
# "pos_weight": True
}
exp_logger.experiment.add_hparams(hparam_dict={
**dict(best_model.hparams),
**extra_params
},
metric_dict={"oof_loss": oof_loss})
oof_filename = "_".join(
[f"{k}={v}" for k, v in dict(best_model.hparams).items()])
with open(f'oof_{experiment_name}_{oof_loss}.npy', 'wb') as f:
np.save(f, oof_predictions)
with open(f'oof_{experiment_name}_{oof_loss}.npy', 'rb') as f:
tmp = np.load(f)
print(tmp.shape)
# Rename model filename to remove `=` for Kaggle Dataset rule
model_files = glob.glob(f'{model_output_folder}/fold*/epoch*.ckpt')
for f in model_files:
new_filename = f.replace("=", "")
os.rename(f, new_filename)
print(new_filename)
del best_model
torch.cuda.empty_cache()
gc.collect()
# ## Submission
# +
print(kfold_submit_preds.shape)
submission = pd.DataFrame(data=test_features["sig_id"].values,
columns=["sig_id"])
submission = submission.reindex(columns=["sig_id"] + train_classes)
submission[train_classes] = kfold_submit_preds
# Set control type to 0 as control perturbations have no MoAs
submission.loc[test_features['cp_type'] == 0, submission.columns[1:]] = 0
# submission.to_csv('submission.csv', index=False)
submission.to_csv('submission_resnest_v2.csv', index=False)
# -
submission
torch.cuda.empty_cache()
gc.collect()
# ## EOF
| models/deepinsight_resnest_lightning_v2_drug_id.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Model setup
#
# here we set the model up and explain how it works
# imports and load data
# all of this is explained in notebook 0
# %run imports.py
from modelinter.preprocessing.imports_load_data import read_csvs, extract_arrays
raw_data = read_csvs()
arrays = extract_arrays(raw_data)
# We'll simulate a portfolio of N stocks and N options. We'll model the price of stocks, and feed the output of this model to the model for options.
#
# ## Stocks model
#
# The model for **stocks** is a linear regression of their returns against S&P500:
#
# $r_{it} = \alpha_i + \beta_i I_t + \epsilon_{it} $.
#
# with:
#
# * $r_{it}$ - returns of stock $i$ at time $t$
# * $I_{t}$ - returns of the index $I$ (S&P500) at time $t$
# * $\alpha_i$ - zero order coefficient for stock $i$
# * $\beta_i$ - first-order coefficient for stock $i$
# * $\epsilon_{it}$ - residuals of the regression for stock $i$ at time $t$
#
# We expect $\alpha_{i}$ to be negligible for stocks, therefore we should be able to approximate:
#
# $r_{it} \approx \beta_i I_t $
#
# We'll call this the **A** model. A more accurate prediction would entail sampling from the distribution of these random variables:
#
# $r_{it} \approx \beta_i I_t + \epsilon_{it} $
#
# where we assume that the $\epsilon$ terms are normally distributed, centered on zero $E[\epsilon_{it}] = 0$, and uncorrelated ($Cov[\epsilon_{it}, \epsilon_{jt}] = 0$ $\forall i \neq j $). We will call this the **B** model, and we'll evaluate it by estimating the standard deviation of the residuals of the regression, and sampling from a normal distribution with adequate parametrisation.
#
# Finally, an even better model, which we'll call the **C** model, would involve removing the assumption of uncorrelated residuals: $\Sigma_{ij} \equiv Cov[\epsilon_{it}, \epsilon_{jt}] \neq 0$. We will estimate this model by evaluating the covariance matrix $\Sigma_{ij}$ with the GLASSO algorithm.
#
#
# ___
#
# #### extrapolating forward in time
#
# this model, being evaluated on daily returns, will predict daily returns. We want to understand what happens on timescales that are characteristic of the CCAR scenario (~4 years). In order to do so, we will have to chain daily predictions. Let's suppose that we want to predict the returns of stock at time $T = D \Delta t$. We can write the returns on index $I$ at time $T$ as the sum of the returns on all days:
#
# $I_T = \prod_t^D (1 + I_t) \approx \sum_t^D I_t$
#
# Mind that this formula works approximately for linear returns, while it's exact for log returns. Similarly for the stock:
#
# $r_T = \prod_t^D (1 + r_t) \approx \sum_t^D r_t \\
# = \sum_t^D (\beta_i I_{t} + \epsilon_{it}) = \beta_i I_T + \sum_t^D \epsilon_{it}$
#
# This is important, because the rules for calculating uncertainty follow from it:
#
# $\sigma(r_T) = \sigma(\sum_t^D \epsilon_{it}) = \sqrt{D} \sigma(\epsilon_i)$
#
# where we made the hypothesis that $\epsilon_{it}$ is a stationary process, i.e. $\epsilon_{it} = \epsilon_{i}$, and that it follows a normal distribution.
#
# ## Options model
#
# For the **options**, we'll consider one put option per stock, with moneyness ($S/K$) of 1.1, that ends in five years. We'll assume a risk free rate of return of 0.25%. The model will be the original black-scholes.
#
# $C(S_t, t) = N(d_1)S_t - N(d_2) Ke^{-r(T - t)} \\
# d_1 = \frac{1}{\sigma\sqrt{T - t}}\left[\ln\left(\frac{S_t}{K}\right) + \left(r + \frac{\sigma^2}{2}\right)(T - t)\right] \\
# d_2 = d_1 - \sigma\sqrt{T - t}$
#
# with:
# * $N(\cdot)$ is the cumulative distribution function of the standard normal distribution
# * $\tau \equiv T - t$ is the time to maturity (expressed in years), with $T$ the maturity date, and $t$ current time
# * $S$ is the spot price of the underlying asset
# * $K$ is the strike price
# * $r$ is the risk free rate (annual rate, expressed in terms of continuous compounding)
# * $\sigma$ is the volatility of returns of the underlying asset
#
# and all values are intended to be calculated at time $t$.
#
# ___
#
# We will model the volatility $\sigma$ with a linear regression on the VIX index similar to the one for the stocks:
#
# $\sigma_{it} = \eta_i + \theta_i J_t + \delta_{it} $
#
# therefore we should have an **A** model like this:
#
# $\sigma_{it} \approx \eta_i + \theta_i J_t $,
#
# where $J_t$ is the VIX index. We will also define, in analogy with the stocks, an **B** model:
#
# $\sigma_{it} \approx \eta_i + \theta_i J_t + \delta_{it}$,
#
# where we consider the $\delta$ to be normally distributed with mean 0, and standard deviation measured from the residuals of the regression. Finally, we'll define a **C** model where $\Sigma_{ij} \equiv Cov[\delta_{it}, \delta_{jt}] \neq 0$.
#
# ---
#
# We won't use implied volatility $VI_t$ data directly to estimate the $\theta_i$ and parametrize the model. We will instead assume that realized future volatility $\sigma_{t+p}$ as a proxy for it, i.e. we assume:
#
# $VI_t \propto \sigma_{t+p}$.
#
# For this reason, we equivalently delayed VIX by $p=-10$ days, following the result of preliminary analysis.
#
# ___
#
# #### extrapolating forward in time
#
# The model for implied volatilities doesn't predict returns, but volatilities directly. The value for implied volatility at time $T$ cannot be expressed as a composition of changes along time, therefore the uncertainty for the predictions doesn't increase over time:
#
# $std(\sigma_T) = std(\delta_i)$
#
# and of course we made the implicit hypothesis the hypothesis that $\delta_{it}$ is a stationary process, i.e. $\delta_{it} = \delta_{i}$, and that it follows a normal distribution.
# let's define the functions that evaluate the model.
# ## Code review
# All the code is in the modelinter.pgm module. let's go through it.
from modelinter.models.pgm import \
BasePgmParams, StocksPgmParams, \
StocksPgm, StocksPgmA, \
StocksPgmB, StocksPgmC, OptionsPgm
# the parameters of the PGM will be stored in an object of class `BasePgmParams`, that only has the logic for saving/loading the parameters and estimating GLASSO on the residuals
view_code(BasePgmParams)
# The realization of a PGM parameters object for the stocks model is a `StocksPgmParams` object. On initialization it estimates the parameters for the model from the regression, and then calculates GLASSO on the residuals.
view_code(StocksPgmParams)
# When predicting, we'll use a realization of the `StocksPgm` base class. This base class just contains the logic for initialization (it gets passed a `StocksPgmParams` when doing `__init__()`), and the part of the prediction logic that will be called by all subclasses.
view_code(StocksPgm)
# The actual realizations of `StocksPgm` are the three kinds of model A, B and C discussed both above and in the paper: `StocksPgmA`, `StocksPgmB` and `StocksPgmC`.
#
# `StocksPgmA` just takes the prediction method from the base class, and changes the signature a little:
view_code(StocksPgmA)
# `StocksPgmB` and `StocksPgmC`'s `predict()` methods instead take the base prediction and generate the residuals.
view_code(StocksPgmB); view_code(StocksPgmC)
# The options model is structured the same way, with
#
# * `BasePgmParams`
# * `OptionsPgmParams`
# * `OptionsPgm`
# * `optionsPgmA`
# * `optionsPgmB`
# * `optionsPgmC`
#
# the logic in `OptionsPgm` is a bit more convoluted, though, because its `predict()` method contains the code to calculate options prices through the Black-Scholes formula, which is structured as two ugly nested loops. The logic for generating volatilities is instead found in the subclasses.
view_code(OptionsPgm)
# ## Test calculation
# Now let's test that they actually work:
#DefaultSettings is just a namespace containing some settings for eval_PGM
from modelinter.models.calculations import eval_PGM, DefaultSettings
#we'll also need a couple of constants
from modelinter.models.constants import Const
import numpy as np
#val_pgm is instead a function that estimates all the model
#parameters from the data:
view_code(eval_PGM)
#let's evaluate them
models = eval_PGM(arrays, DefaultSettings)
#does it work?
#prediction for stocks
(models.PGM_stock_A.predict(.01)[:20],
models.PGM_stock_B.predict(.01)[:20],
models.PGM_stock_C.predict(.01)[:20])
#let's set an arbitrary level for vix
vix_set = np.mean(arrays.vix)
#prediction for options
(
models.PGM_options_A.predict(
vix=vix_set,
r=Const.RISK_FREE_RATE.value,
strike_price = None,
stocks_prices = arrays.stocks_p[-1],
tau_i = [1]*arrays.stocks_p.shape[-1],
flag_i = ['p']*arrays.stocks_p.shape[-1],
moneyness_i=1.1,
)[:20],
models.PGM_options_B.predict(
vix=vix_set,
r=Const.RISK_FREE_RATE.value,
strike_price = None,
stocks_prices = arrays.stocks_p[-1],
tau_i = [1]*arrays.stocks_p.shape[-1],
flag_i = ['p']*arrays.stocks_p.shape[-1],
moneyness_i=1.1,
)[:20],
models.PGM_options_C.predict(
vix=vix_set,
r=Const.RISK_FREE_RATE.value,
strike_price = None,
stocks_prices = arrays.stocks_p[-1],
tau_i = [1]*arrays.stocks_p.shape[-1],
flag_i = ['p']*arrays.stocks_p.shape[-1],
moneyness_i=1.1,
)[:20]
)
| modelinter/notebooks/1-model_setup.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# ---
# # Edit a FITS header
#
# ## Authors
# <NAME>, <NAME>, <NAME>, <NAME>
#
# ## Learning Goals
# * Read a FITS file
# * Retrieve FITS header metadata
# * Edit the FITS header
# * Write the modified file as a FITS file
#
# ## Keywords
# FITS, file input/output
#
# ## Summary
# This tutorial describes how to read in and edit a FITS header, and then write
# it back out to disk. For this example we're going to change the `OBJECT`
# keyword.
from astropy.io import fits
# ``astropy.io.fits`` provides a lot of flexibility for reading FITS
# files and headers, but most of the time the convenience functions are
# the easiest way to access the data. ``fits.getdata()`` reads only the
# data from a FITS file, but with the `header=True` keyword argument will
# also read the header.
data, header = fits.getdata("input_file.fits", header=True)
# There is also a dedicated function for reading only the
# header:
hdu_number = 0 # HDU means header data unit
fits.getheader('input_file.fits', hdu_number)
# But `getdata()` can get both the data and the header, so it's a useful
# command to remember. Since the primary HDU of a FITS file must contain image data,
# the data is now stored in a ``numpy`` array. The header is stored in an
# object that acts like a standard Python dictionary.
# But hdu_number = 0 is the PRIMARY HDU.How many HDUs are in this file?
fits_inf = fits.open("input_file.fits")
fits_inf.info()
fits_inf[0].header
# Using ``fits.open`` allows us to look more generally at our data. ``fits_inf[0].header`` gives us the same output as ``fits.getheader``. What will you learn if you type ``fits_inf[1].header``? Based on ``fits_inf.info()`` can you guess what will happen if you type ``fits_inf[2].header``?
# Now let's change the header to give it the correct object:
header['OBJECT'] = "M31"
# Finally, we have to write out the FITS file. Again, the convenience
# function for this is the most useful command to remember:
fits.writeto('output_file.fits', data, header, overwrite=True)
# That's it; you're done!
# Two common and more complicated cases are worth mentioning (but if your needs
# are much more complex, you should consult the full documentation http://docs.astropy.org/en/stable/io/fits/).
#
# The first complication is that the FITS file you're examining and
# editing might have multiple HDU's (extensions), in which case you can
# specify the extension like this:
data1, header1 = fits.getdata("input_file.fits", ext=1, header=True)
# This will get you the data and header associated with the `index=1` extension
# in the FITS file. Without specifying a number, `getdata()` will get the
# 0th extension (equivalent to saying `ext=0`).
# Another useful tip is if you want to overwrite an existing FITS
# file. By default, `writeto()` won't let you do this, so you need to
# explicitly give it permission using the `clobber` keyword argument:
fits.writeto('output_file.fits', data, header, overwrite=True)
# A final example is if you want to make a small change to a FITS file, like updating a header keyword, but you don't want to read in and write out the whole file, which can take a while. Instead you can use the `mode='update'` read mode to do this:
with fits.open('input_file.fits', mode='update') as filehandle:
filehandle[0].header['MYHDRKW'] = "My Header Keyword"
# ## Exercise
# Read in the file you just wrote and add three header keywords:
#
# 1. 'RA' for the Right Ascension of M31
# 2. 'DEC' for the Declination of M31
# 3. 'RADECSRC' with text indicating where you found the RA/Dec (web URL, textbook name, your photographic memory, etc.)
#
# Then write the updated header back out to a new file:
| tutorials/FITS-header/FITS-header.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# !git clone https://github.com/thtang/CheXNet-with-localization.git
# cd ./CheXNet-with-localization
# !python3 denseNet_localization.py ./image.txt ./
# +
import cv2
import pandas as pd
import os
import numpy
img_folder_path='./00000003_004.png'
frame=cv2.imread(img_folder_path)
ac_bbox = './output/bounding_box.txt'
pd_bbox = './bounding_box.txt'
def plot_bbox(img_folder_path, bbox_filename):
actual_bbox=open(bbox_filename)
img_folder_path=os.path.split(img_folder_path)[-1]
#print(img_folder_path)
count=0
temp_count=0
final_bbox_list=[]
for img in actual_bbox :
if img.find(img_folder_path) != -1:
print('file exist:',count)
print('given image',img)
temp_count=count
print("this is temp count",temp_count)
if count > temp_count:
if img.find('/') == -1 :
final_bbox_list.append(img)
else:
break
count+=1
i=final_bbox_list[1]
temp_i=list(i.split(" "))
temp_i.pop(0)
p = numpy.array(temp_i)
k=p.astype(float)
x1=int(k[0])
y1=int(k[1])
x2=int(k[2])
y2=int(k[3])
return x1,y1,x2,y2
x1,y1,x2,y2=plot_bbox(img_folder_path, ac_bbox)
x_1,y_1,x_2,y_2=plot_bbox(img_folder_path, pd_bbox)
cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),3) #rgb 220,20,60
cv2.rectangle(frame,(x_1,y_1),(x_2,y_2),(60,20,220),3)
print(frame)
cv2.imshow('image',frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -
| CPU_files/Chhati_Net.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Cahn-Hilliard Example
#
# This example demonstrates how to use PyMKS to solve the Cahn-Hilliard equation. The first section provides some background information about the Cahn-Hilliard equation as well as details about calibrating and validating the MKS model. The example demonstrates how to generate sample data, calibrate the influence coefficients and then pick an appropriate number of local states when state space is continuous. The MKS model and a spectral solution of the Cahn-Hilliard equation are compared on a larger test microstructure over multiple time steps.
# ### Cahn-Hilliard Equation
#
# The Cahn-Hilliard equation is used to simulate microstructure evolution during spinodial decomposition and has the following form,
#
# $$ \dot{\phi} = \nabla^2 \left( \phi^3 - \phi \right) - \gamma \nabla^4 \phi $$
#
# where $\phi$ is a conserved ordered parameter and $\sqrt{\gamma}$ represents the width of the interface. In this example, the Cahn-Hilliard equation is solved using a semi-implicit spectral scheme with periodic boundary conditions, see [Chang and Rutenberg](http://dx.doi.org/10.1103/PhysRevE.72.055701) for more details.
# +
import warnings
warnings.filterwarnings('ignore')
import numpy
import dask.array as da
import matplotlib.pyplot as plt
from dask_ml.model_selection import train_test_split, GridSearchCV
from distributed import Client
from sklearn.pipeline import Pipeline
from pymks import (
solve_cahn_hilliard,
plot_microstructures,
PrimitiveTransformer,
LocalizationRegressor,
ReshapeTransformer,
coeff_to_real
)
# +
#PYTEST_VALIDATE_IGNORE_OUTPUT
# %matplotlib inline
# %load_ext autoreload
# %autoreload 2
Client()
# -
# ## Modeling with MKS
#
# In this example the MKS equation will be used to predict microstructure at the next time step using
#
# $$p[s, 1] = \sum_{r=0}^{S-1} \alpha[l, r, 1] \sum_{l=0}^{L-1} m[l, s - r, 0] + ...$$
#
# where $p[s, n + 1]$ is the concentration field at location $s$ and at time $n + 1$, $r$ is the convolution dummy variable and $l$ indicates the local states varable. $\alpha[l, r, n]$ are the influence coefficients and $m[l, r, 0]$ the microstructure function given to the model. $S$ is the total discretized volume and $L$ is the total number of local states `n_states` choosen to use.
#
# The model will march forward in time by recursively replacing discretizing $p[s, n]$ and substituing it back for $m[l, s - r, n]$.
#
# ### Calibration Datasets
#
# Unlike the elastostatic examples, the microstructure (concentration field) for this simulation doesn't have discrete phases. The microstructure is a continuous field that can have a range of values which can change over time, therefore the first order influence coefficients cannot be calibrated with delta microstructures. Instead, a large number of simulations with random initial conditions are used to calibrate the first order influence coefficients using linear regression.
#
# The function `solve_cahn_hilliard` provides an interface to generate calibration datasets for the influence coefficients.
# +
da.random.seed(99)
x_data = (2 * da.random.random((100, 41, 41), chunks=(20, 41, 41)) - 1).persist()
y_data = solve_cahn_hilliard(x_data, delta_t=1e-2).persist()
# -
x_data
y_data
# Plot the first microstructure and its response.
plot_microstructures(x_data[0], y_data[0], titles=("Input Concentration", "Output Concentration"))
# ## The Model
#
# Construct the modeling pipeline and visualizet the task graph. Here a pipeline is used which includes a ReshapeTransformer. This reshapes the data as both the PrimitiveTransformer and the LocalizationRegressor assume that the data is an image while Sklearn uses flat (n_sample, n_feature) data.
model = Pipeline(steps=[
('reshape', ReshapeTransformer(shape=x_data.shape)),
('discretize', PrimitiveTransformer(n_state=5, min_=-1.0, max_=1.0)),
('regressor', LocalizationRegressor())
])
# +
#PYTEST_VALIDATE_IGNORE_OUTPUT
model.fit(x_data, y_data).predict(x_data).visualize()
# -
# ## Optimizing the Number of Local States
#
# As mentioned above, the microstructures (concentration fields) does not have discrete phases. This leaves the number of local states in local state space as a free hyperparameter. In previous work it has been shown that, as you increase the number of local states, the accuracy of MKS model increases (see [Fast et al.](http://dx.doi.org/10.1016/j.actamat.2010.10.008)), but, as the number of local states increases, the difference in accuracy decreases. Some work needs to be done in order to find the practical number of local states that we will use.
#
# Split the calibrate dataset into test and training datasets. The function `train_test_split` for the machine learning Python module [dask_ml](http://dask-ml.readthedocs.io/en/latest/index.html) provides a convenient interface to do this. 80% of the dataset will be used for training and the remaining 20% will be used for testing by setting `test_size` equal to 0.2.
x_train, x_test, y_train, y_test = train_test_split(
x_data.reshape(x_data.shape[0], -1),
y_data.reshape(y_data.shape[0], -1),
test_size=0.2
)
# Calibrate the influence coefficients while varying the number of local states from 2 up to 11. Each of these models will then predict the evolution of the concentration fields. Mean square error will be used to compare the results with the testing dataset to evaluate how the MKS model's performance changes as we change the number of local states.
params = dict(discretize__n_state=range(2, 11))
grid_search = GridSearchCV(model, params, cv=5, n_jobs=-1)
grid_search.fit(x_train, y_train);
# +
#PYTEST_VALIDATE_IGNORE_OUTPUT
print(grid_search.best_estimator_)
print(grid_search.score(x_test, y_test))
# -
plt.plot(params['discretize__n_state'],
grid_search.cv_results_['mean_test_score'],
'o-',
color='#1a9850',
linewidth=2)
plt.xlabel('# of local states', fontsize=16)
plt.ylabel('R-squared', fontsize=16);
# As expected, the accuracy of the MKS model monotonically increases with `n_state`, but accuracy doesn't improve significantly as `n_state` gets larger than single digits.
#
# To save on computation costs, set (calibrate) the influence coefficients with `n_state` equal to 6, but realize that `n_state` can be increased for more accuracy
# +
model.set_params(discretize__n_state=6)
model.fit(x_train, y_train);
# -
# Here are the first 4 influence coefficients.
# +
fcoeff = model.steps[2][1].coeff
coeff = coeff_to_real(fcoeff)
plot_microstructures(
coeff.real[..., 0],
coeff.real[..., 1],
coeff.real[..., 2],
coeff.real[..., 3],
titles=['Influence Coeff {0}'.format(i) for i in range(4)]
)
# -
# ### Predict Microstructure Evolution
#
# After calibration, the evolution of the concentration field can be predicted. First generate a test sample.
# +
da.random.seed(99)
x_test = (2 * da.random.random((1, 41, 41), chunks=(1, 41, 41)) - 1).persist()
y_test = solve_cahn_hilliard(x_test, n_steps=10, delta_t=1e-2).persist()
# -
# Iterate the model forward 10 times to match the parameter `n_steps`.
# +
y_predict = x_test
for _ in range(10):
y_predict = model.predict(y_predict).persist()
# -
# View the concentration fields.
plot_microstructures(y_test[0], y_predict.reshape((1, 41, 41))[0], titles=('Simulation', 'MKS Prediction'))
# The MKS model was able to capture the microstructure evolution with 6 local states.
#
# ## Resizing the Coefficients to use on Larger Systems
#
# Predict a larger simulation by resizing the coefficients and provide a larger initial concentration field. First generate a test sample for a system 3x as large.
# +
da.random.seed(99)
shape = (1, x_data.shape[1] * 3, x_data.shape[1] * 3)
x_large = (2 * da.random.random(shape, chunks=shape) - 1).persist()
y_large = solve_cahn_hilliard(x_large, n_steps=10, delta_t=1e-2).persist()
# -
# Resize the coefficients and the reshape transformer.
model.steps[0][1].shape = shape
model.steps[2][1].coeff_resize(shape[1:]);
# Use the model to predict the data by iterating `n_steps` forward.
# +
y_large_predict = x_large
for _ in range(10):
y_large_predict = model.predict(y_large_predict).persist()
# -
# View the final structure.
plot_microstructures(y_large[0], y_large_predict.reshape(shape)[0], titles=('Simulation', 'MKS Prediction'))
# The MKS model with resized influence coefficients was able to reasonably predict the structure evolution for a larger concentration field.
| notebooks/cahn_hilliard.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 6</font>
#
# ## Download: http://github.com/dsacademybr
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
# ### Gráficos
# Instala a versão exata do pacote matplotlib
# !pip install -q -U matplotlib==3.2.1
import matplotlib as mat
mat.__version__
# +
import sqlite3
import random
import datetime
import matplotlib.pyplot as plt
# %matplotlib notebook
# Criando uma conexão
conn = sqlite3.connect('dsa.db')
# Criando um cursor
c = conn.cursor()
# Função para criar uma tabela
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS produtos(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date TEXT, '\
'prod_name TEXT, valor REAL)')
# Função para inserir uma linha
def data_insert():
c.execute("INSERT INTO produtos VALUES(now, 'Teclado', 130 )")
conn.commit()
c.close()
conn.close()
# Usando variáveis para inserir dados
def data_insert_var():
new_date = datetime.datetime.now()
new_prod_name = 'monitor'
new_valor = random.randrange(50,100)
c.execute("INSERT INTO produtos (date, prod_name, valor) VALUES (?, ?, ?, ?)",
(new_date, new_prod_name, new_valor))
conn.commit()
# Leitura de dados
def leitura_todos_dados():
c.execute("SELECT * FROM PRODUTOS")
for linha in c.fetchall():
print(linha)
# Leitura de registros específicos
def leitura_registros():
c.execute("SELECT * FROM PRODUTOS WHERE valor > 60.0")
for linha in c.fetchall():
print(linha)
# Leitura de colunas específicos
def leitura_colunas():
c.execute("SELECT * FROM PRODUTOS")
for linha in c.fetchall():
print(linha[3])
# Update
def atualiza_dados():
c.execute("UPDATE produtos SET valor = 70.00 WHERE valor > 80.0")
conn.commit()
# Delete
def remove_dados():
c.execute("DELETE FROM produtos WHERE valor = 62.0")
conn.commit()
# Gerar gráfico com os dados no banco de dados
def dados_grafico():
c.execute("SELECT id, valor FROM produtos")
ids = []
valores = []
dados = c.fetchall()
for linha in dados:
ids.append(linha[0])
valores.append(linha[1])
plt.bar(ids, valores)
plt.show()
# -
# Gerando gráficos
dados_grafico()
# # Fim
# ### Obrigado - Data Science Academy - <a href="http://facebook.com/dsacademybr">facebook.com/dsacademybr</a>
| pyfund/Cap06/Notebooks/DSA-Python-Cap06-06-Criando Graficos com Matplotlib e SQLite.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:mytfenv]
# language: python
# name: conda-env-mytfenv-py
# ---
#Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Load data
raw_data = pd.read_csv('Automobile_data.csv')
unprocessed = raw_data.copy()
unprocessed.head()
#Identify missing variables
unprocessed.info()
# Grouping string datatypes
strings = unprocessed.columns[unprocessed.dtypes == 'object']
#Printing out the amount of columns that has a question mark
print(f"{'Variable':^{15}}{'Total Missing':^{50}}{'% Missing':^{10}}")
for i in strings:
print(f"{i:{25}}{(unprocessed[i] == '?').sum():^{30}}{((unprocessed[i] == '?').sum()*100/unprocessed.shape[0]).round(2):^{30}}")
# Drop missing price rows since it is only 4 missing values
unprocessed = unprocessed[unprocessed['price'] != '?']
# Drop missing num-of-doors rows since it is only 2 missing values
unprocessed = unprocessed[unprocessed['num-of-doors'] != '?']
#Printing out the amount of columns that has a question mark
print(f"{'Variable':^{15}}{'Total Missing':^{50}}{'% Missing':^{10}}")
for i in strings:
print(f"{i:{25}}{(unprocessed[i] == '?').sum():^{30}}{((unprocessed[i] == '?').sum()*100/unprocessed.shape[0]).round(2):^{30}}")
# +
#Printing out the number of uniques
for i in strings:
print(f"{i}\n{unprocessed[i].unique()}")
print()
# +
# Convert certain object datatypes to int64,float and use 0 as a placeholder
i64 = unprocessed[['normalized-losses','horsepower', 'peak-rpm','price']]
f = unprocessed[['bore','stroke']]
for j in i64:
try:
unprocessed[j] = unprocessed[j].astype('int64')
except:
unprocessed[j] = unprocessed[j].replace('?',0).astype('int64')
for k in f:
try:
unprocessed[k] = unprocessed[k].astype('float')
except:
unprocessed[k] = unprocessed[k].replace('?',0).astype('float')
# +
# Symboling variable has a 50% correlation with the known normalized-losses variable
plt.figure(figsize=(20,8))
sns.heatmap((unprocessed[unprocessed['normalized-losses'] > 0]).corr(),annot=True,cmap='viridis',vmin=0,vmax=1)
plt.show()
# +
# Import Linear Regression
from sklearn.linear_model import LinearRegression
#Create an instance of Linear Regression and Scaler
lr = LinearRegression()
# -
#Known normalized losses
known_nl = unprocessed[unprocessed['normalized-losses'] > 0]
known_nl
sym = known_nl['symboling']
nl = known_nl['normalized-losses']
lr.fit(sym.values.reshape(-1,1),nl)
# Unknown normalized-losses
unknown_nl = unprocessed[unprocessed['normalized-losses'] == 0]
unknown_nl
unknown_nl = unknown_nl.drop('normalized-losses',axis=1)
unknown_nl
new_pred = lr.predict(unknown_nl['symboling'].values.reshape(-1,1))
new_pred
unknown_nl['normalized-losses'] = new_pred
unknown_nl
unprocessed = pd.concat([unknown_nl, known_nl],axis=0)
unprocessed
# +
# Get Dummies
dummy_1 = pd.get_dummies(unprocessed[['fuel-type','aspiration','num-of-doors','engine-location']],drop_first=True)
# +
# Add new dummies to dataframe
unprocessed = pd.concat([unprocessed,dummy_1],axis=1)
# -
#Drop original columns
unprocessed = unprocessed.drop(['fuel-type','aspiration','num-of-doors',
'engine-location'],axis=1)
unprocessed
# +
# The multi-port fuel injection is the most commonly used fuel system
unprocessed['fuel-system'].value_counts()
# +
# Sedan was the most common vehicle in the yearbook
unprocessed['body-style'].value_counts()
# +
# The most common car seen was the front wheel drive
unprocessed['drive-wheels'].value_counts()
# +
# The rear wheel drive seems to show up in vehicles that are more expensive, whereas fwd seems much
# more affordable for consumers
sns.boxplot(data=unprocessed,x='drive-wheels',y='price')
plt.title('Drive Wheels vs Price')
plt.show()
# -
# Number of Cylinders vs Price
sns.boxplot(data=unprocessed,x='num-of-cylinders',y='price',order=['three','four','two','six','five',
'twelve','eight'])
plt.title('No. Cylinders vs Price')
plt.show()
# +
# From what was online, there are pros/cons when it comes to cylinders. I did have a difficult time
# finding more information on this, but I believe it is mainly my lack of knowledge regarding the world
# of automobiles. This prevented me from using proper keywords or terminologies needed to find the answer to
# my question.
# Going by the graph, the more cylinders inside a vehicle the higher the price.
# -
# Decided to just keep the num-of-cylinders and change it to int 64
unprocessed['num-of-cylinders'] = unprocessed['num-of-cylinders'].map({'four':4, 'six':6,
'five':5,'three':3,'twelve':12, 'two':2, 'eight':8})
# mpfi is the most commonly used in vehicles now, so I'm assuming
# there is a possiblity that many cars used that type of fuel injection
sns.boxplot(data=unprocessed,x='fuel-system',y='price')
plt.title('Fuel System vs Price')
plt.show()
# From the graph itself it seems that the more expensive brands tend to have a mpfi fuel-system
plt.figure(figsize=(15,8),dpi=200)
sns.boxplot(data=unprocessed,x='make',y='price',hue='fuel-system')
plt.title('Make vs Price')
plt.xticks(rotation=90)
plt.show()
# +
# Get Dummies
dummy_2 = pd.get_dummies(unprocessed['drive-wheels'],drop_first=True)
# -
unprocessed = pd.concat([unprocessed,dummy_2],axis=1)
sns.boxplot(data=unprocessed,x='engine-type',y='price')
plt.title('Fuel System vs Price')
plt.show()
# Drop make,body-style,engine-type, and drive-wheels
unprocessed = unprocessed.drop(['drive-wheels','make','engine-type','body-style','fuel-system'],axis=1)
| Notebook Files/LR_Column.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# <h1><center>PISAP: Python Interactive Sparse Astronomical Data Analysis Packages</center></h1>
# <h2><center>DIctionary learning tutorial</center></h2>
# <div style="text-align: center">Credit: </div>
#
# Pisap is a Python package related to sparsity and its application in
# astronomical or mediacal data analysis. This package propose sparse denosing methods reusable in various contexts.
# For more information please visit the project page on github: https://github.com/neurospin/pisap.<br><br>
#
# <h3>First check</h3>
#
# In order to test if the 'pisap' package is installed on your machine, you can check the package version:
import pisap
print pisap.__version__
# <h2>Decomposition / recomposition of images in a learned dictionary</h2>
#
# The package provides a flexible implementation of a dictionary learning method.
# +
import numpy as np
from scipy.io import loadmat
import scipy.fftpack as pfft
import matplotlib.pyplot as plt
# %matplotlib inline
from pisap.data import get_sample_data
from pisap.base.utils import convert_mask_to_locations
from pisap.numerics.noise import add_noise
from pisap.numerics.reconstruct import sparse_rec_fista
from pisap.numerics.gradient import Grad2DSynthesis
from pisap.numerics.fourier import FFT
from pisap.numerics.cost import snr, ssim
from pisap.numerics.linear import DictionaryLearningWavelet
# -
__disp_patches__ = False
# First, we load the atoms of our dictionary from a '.npy' file.
dico = np.load("data/dico_patches_size100x49_30subjects_squareimgs_156x156.npy")
d1, d2 = dico.shape
atoms = np.zeros((int(np.sqrt(d2)), int(np.sqrt(d2)), d1))
for idx, atom in enumerate(dico):
atoms[:, :, idx] = atom.reshape(int(np.sqrt(d2)), int(np.sqrt(d2)))
del dico
if __disp_patches__:
fig, axes = plt.subplots(figsize=(10, 10), nrows=10, ncols=10)
i = 0
for row in axes:
for ax in row:
ax.axis('off')
ax.matshow(atoms[:, :, i], cmap='gray')
i += 1
plt.suptitle('Dictionary', fontsize=22)
plt.show()
# Then, we define our dictionary.
img = np.load("data/masked_normalized_img_testingset_156x156.npy")
#dico = DictionaryLearningWavelet(atoms, img.shape, n_jobs_transform=-1)
# Finally, we decompose and re-compose a brain image.
# +
#coef = dico.op(img)
#recons_img = dico.adj_op(coef)
# +
#print("Original image shape: {0}".format(img.shape))
#print("Coefficients shape: {0}".format(coef.shape))
#print("Reconsturcted image shape: {0}".format(recons_img.shape))
# +
#fig, axes = plt.subplots(figsize=(10, 10), nrows=1, ncols=2)
#axes[0].axis('off')
#axes[0].matshow(img, cmap='gray')
#axes[0].set_title("Ref image")
#axes[1].axis('off')
#axes[1].matshow(recons_img, cmap='gray')
#axes[1].set_title("Decomposed/recomposed image")
#plt.show()
# -
# <h2> CS reconstruction with a learned dictionary</h2>
#
# The package provides a flexible implementation of a dictionary learning representation for the reconstruction functions.
# First, we load the input k-space and the under-sampling scheme.
mask = loadmat("data/scheme_256_R5_power1_fullCenter.mat")['sigma']
c = int(mask.shape[0]/2)
d = 156
d_2 = int(d/2)
mask = mask[c-d_2:c+d_2, c-d_2:c+d_2]
loc = convert_mask_to_locations(pfft.ifftshift(mask))
kspace = pfft.ifftshift(mask) * pfft.ifft2(img)
kspace = add_noise(kspace, sigma=0.1)
# +
metrics = {'snr':{'metric':snr,
'mapping': {'x_new': 'test', 'y_new':None},
'cst_kwargs':{'ref':img},
'early_stopping': False,
},
'ssim':{'metric':ssim,
'mapping': {'x_new': 'test', 'y_new':None},
'cst_kwargs':{'ref':img},
'early_stopping': True,
},
}
params = {
'data':kspace,
'gradient_cls':Grad2DSynthesis,
'gradient_kwargs':{"ft_cls": {FFT: {"samples_locations": loc,
"img_size": img.shape[0]}}},
'linear_cls':DictionaryLearningWavelet,
'linear_kwargs':{"atoms": atoms, "image_size": img.shape, "n_jobs_transform": -1},
'max_nb_of_iter':100,
'mu':2.0e-2,
'metrics':metrics,
'verbose':1,
}
x, y, saved_metrics = sparse_rec_fista(**params)
# +
plt.figure()
plt.imshow(mask, cmap='gray')
plt.title("Mask")
plt.figure()
plt.imshow(np.abs(pfft.ifft2(kspace), interpolation="nearest", cmap="gist_stern")
plt.colorbar()
plt.title("Dirty image")
plt.figure()
plt.imshow(np.abs(x.data), interpolation="nearest", cmap="gist_stern")
plt.colorbar()
plt.title("Analytic sparse reconstruction via Condat-Vu method")
metric = saved_metrics['snr']
fig = plt.figure()
plt.grid()
plt.plot(metric['time'], metric['values'])
plt.xlabel("time (s)")
plt.ylabel("SNR")
plt.title("Evo. SNR per time")
metric = saved_metrics['nrmse']
fig = plt.figure()
plt.grid()
plt.plot(metric['time'], metric['values'])
plt.xlabel("time (s)")
plt.ylabel("NRMSE")
plt.title("Evo. NRMSE per time")
plt.show()
| pisap/demo/dictionaryLearning.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # check history loss
#
# validation from augmented data
# +
# %matplotlib inline
# # %config InlineBackend.figure_format = 'svg'
# %load_ext autoreload
# %autoreload 2
import os
import sys
import pandas as pd
import tensorflow as tf
import numpy as np
import datetime
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.optimizers import Adam
#import data
#import importlib.util
#spec = importlib.util.spec_from_file_location("data", "../mnist/data.py")
#data = importlib.util.module_from_spec(spec)
#spec.loader.exec_module(data)
# -
#import data
# ! cp ../mnist/data.py data_mnist.py
# ! cp ../digit_recognizer/data.py data_digit_recognizer.py
import data_mnist
import data_digit_recognizer
# +
DATA_ROOT = 'contest'
DATA_ROOT = 'dry_run'
SUBMISSION_ROOT = os.path.join(DATA_ROOT, 'submissions')
if not os.path.isdir(SUBMISSION_ROOT):
os.mkdir(SUBMISSION_ROOT)
IMAGE_COLS = 28
IMAGE_ROWS = 28
ORIGINAL_TRAIN_SIZE = 10000
ORIGINAL_TEST_SIZE = 50000
# +
# %%time
# Read contest Data
original_train_id, original_train_label = data_digit_recognizer.read_mnist_id_for_contest(os.path.join(DATA_ROOT, 'train.csv'))
original_train_id, original_train_image = data_digit_recognizer.read_mnist_for_contest(
os.path.join(DATA_ROOT, 'train'), original_train_id)
original_test_id, original_test_image = data_digit_recognizer.read_mnist_for_contest(os.path.join(DATA_ROOT, 'test'))
# +
# check data
print('original_train_id:', original_train_id.shape)
print('original_train_label:', original_train_label.shape)
print('original_train_image:', original_train_image.shape)
assert(original_train_id.shape == (ORIGINAL_TRAIN_SIZE,))
assert(original_train_label.shape == (ORIGINAL_TRAIN_SIZE,))
assert(original_train_image.shape == (ORIGINAL_TRAIN_SIZE, IMAGE_COLS*IMAGE_ROWS))
print('original_test_id:', original_test_id.shape)
print('original_test_image', original_test_image.shape)
assert(original_test_id.shape == (ORIGINAL_TEST_SIZE,))
assert(original_test_image.shape == (ORIGINAL_TEST_SIZE, IMAGE_COLS*IMAGE_ROWS))
for i in range(10, 10+3):
data_digit_recognizer.show_digit(original_train_image[i], original_train_label[i])
data_digit_recognizer.analyze_labels(original_train_label)
for i in range(10, 10+3):
data_digit_recognizer.show_digit(original_test_image[i])
# +
# %%time
# Read dry_run test data as validation
DRY_RUN_DATA_ROOT = '../mnist/dry_run/'
# ! ls ../mnist/dry_run
original_valid_id, original_valid_label = data_mnist.read_contest_ids(os.path.join(DRY_RUN_DATA_ROOT, 'test.csv'))
original_valid_id, original_valid_image = data_mnist.read_contest_images(os.path.join(DRY_RUN_DATA_ROOT, 'test'), original_valid_id)
# +
# check data
print('original_valid_id:', original_valid_id.shape)
print('original_valid_image:', original_valid_image.shape)
print('original_valid_label:', original_valid_label.shape)
for i in range(10, 10+3):
data_digit_recognizer.show_digit(original_valid_image[i], original_valid_label[i])
data_digit_recognizer.analyze_labels(original_valid_label)
# +
# preprocessing
x_train = original_train_image.reshape(-1, 1, IMAGE_ROWS, IMAGE_COLS).astype('float32') / 255
y_train = np_utils.to_categorical(original_train_label, 10)
x_valid = original_valid_image.reshape(-1, 1, IMAGE_ROWS, IMAGE_COLS).astype('float32') / 255
y_valid = np_utils.to_categorical(original_valid_label, 10)
print('x_train shape: {}'.format(x_train.shape))
print('y_train shape: {}'.format(y_train.shape))
print('x_valid shape: {}'.format(x_valid.shape))
print('y_valid shape: {}'.format(y_valid.shape))
# +
# model
import random
seed_num = 333
random.seed(seed_num)
np.random.seed(seed_num) # for reproducibility
model = Sequential()
# Layer 1
model.add(Convolution2D(120, 5, 5,
border_mode='valid',
input_shape=(1, 28, 28)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# Layer 2
model.add(Convolution2D(200, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# Full connect
model.add(Flatten())
model.add(Dense(200))
model.add(Activation('relu'))
model.add(Dropout(0.5))
# Output
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=1e-4))
# +
# %%time
# Train
BATCH_SIZE = 50
# EPOCH_COUNT = 5
EPOCH_COUNT = 30
history = model.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epoch=EPOCH_COUNT,
show_accuracy=True, verbose=1, validation_data=(x_valid, y_valid))
# -
history.history['loss']
# +
import matplotlib.pyplot as plt
x = np.arange(len(history.history['loss']))
plt.plot(x, history.history['loss'])
plt.plot(x, history.history['val_loss'])
plt.legend(['y = loss', 'y = val_loss'], loc='upper right')
plt.show()
# +
for i in range(len(history.history['val_loss'])):
if(history.history['val_loss'][i]==min(history.history['val_loss'])):
print('min val_loss:{:.6f}, index:{}'.format(min(history.history['val_loss']).item(), i))
for i in range(len(history.history['loss'])):
if(history.history['loss'][i]==min(history.history['loss'])):
print('min loss: {:.6f}, index:{}'.format(min(history.history['loss']).item(), i))
# +
#save model
def save_keras_model(model, path):
with open(path + '.json', 'w') as f:
f.write(model.to_json())
model.save_weights(path+'.h5', overwrite=True)
save_keras_model( model, '120C5-MP2-200C3-MP2-200N-10N-alphadog2' )
| CNN/120C5-MP2-200C3-MP2-200N-10N.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] nbpresent={"id": "d2c7bbf4-8ff2-4d52-bb77-18ee9fef0933"} id="Z_nj_BmthD4L"
# <span>
# <img src="http://ndlib.readthedocs.io/en/latest/_static/ndlogo2.png" width="260px" align="right"/>
# </span>
# <span>
# <b>Author:</b> <a href="http://about.giuliorossetti.net"><NAME></a><br/>
# <b>Python version:</b> 3.6<br/>
# <b>NDlib version:</b> 4.0.1<br/>
# <b>Last update:</b> 25/09/2018
# </span>
# + [markdown] nbpresent={"id": "9410d1a8-4b66-4e37-a3d9-8b6c8589fb46"} id="vXeJGzEmhD4Q"
# <a id='top'></a>
# # *Intro to NDlib: Network Diffusion library*
#
# ``NDlib`` is a python library designed to provide support to the analysis of diffusive phenomena occurring on top of complex network structures.
#
# In this notebook are introduced some of the main features of the library and an overview of its functionalities.
#
# **Note:** this notebook is purposely not 100% comprehensive, it only discusses the basic things you need to get started.
# + [markdown] nbpresent={"id": "21707746-7149-4b56-a372-b897903c09ad"} toc-hr-collapsed=true id="BeRLmXx0hD4R"
# ## Table of Contents
#
# 1. [Installing NDlib](#install)
# 2. [Simulation Workflow](#workflow)
# 1. [Graph Creation](#graph)
# 2. [Model Selection and Configuration](#model)
# 3. [Simulation Execution](#simulation)
# 4. [Results Visualisation](#visual)
# 3. [Available models](#models)
# 1. [Epidemics](#epidemics)
# 2. [Opinion Dynamics](#opinion)
# 4. [Advanced Model Configurations](#advanced)
# 1. [Node Attributes](#nodes)
# 2. [Edge Attributes](#edges)
# 3. [Infection Seeds Selection](#seeds)
# 1. [Model Stability](#stability)
# 2. [Stability Visualisation](#stability_vis)
# 5. [Comparing Diffusion models](#comparing)
# 6. [Diffusion on Dynamic Networks](#dynamic)
# 1. [DynetX: a library for dynamic network modeling](#dynetx)
# 1. [Snapshot Graphs](#snapshots)
# 2. [Interaction Networks](#interactions)
# 2. [Available models](#models2)
# 3. [Example: SIR](#dynsir)
# 7. [Custom Model Definition](#custom)
# 1. [Compartments](#compartments)
# 1. [Node compartments](#nc)
# 2. [Edge compartments](#ec)
# 3. [Time compartments](#tc)
# 2. [Compartments Composition](#composition)
# 1. [Cascading Composition](#cascading)
# 2. [Conditional Composition](#conditional)
# 3. [Example: SIR](#sir)
# 8. [NDQL: Network Diffusion Query Language](#ndql)
# 1. [Syntax](#syntax)
# 2. [Command line tools](#cmd)
# 3. [Example: SIR](#sir2)
# 9. [Conclusions](#conclusion)
# + [markdown] nbpresent={"id": "29b525b9-a5e1-4f09-8670-e3f5515eaf5e"} id="2_SoxbhqhD4R"
# <a id='install'></a>
# ## 1. Installing NDlib ([to top](#top))
# + [markdown] nbpresent={"id": "3512527f-fba1-4767-afe0-e440840d2140"} id="v8aTPVl1hD4S"
# As a first step, we need to make sure that ``NDlib`` is installed and working.
#
# The library is available for both python 2.7 and 3.x, and its stable version can be installed using ``pip``:
# + [markdown] nbpresent={"id": "52f89477-51cf-403d-bd7f-cd96e9dfc62d"} id="A3Vx7h9_hD4S"
# pip install ndlib
# + [markdown] nbpresent={"id": "3bc56bde-a391-4af5-8abe-7d2515507d65"} id="8BfRKaEWhD4S"
# On the project [GitHub](https://github.com/GiulioRossetti/ndlib) are also available the nightly builds that can be installed as follows:
# + [markdown] nbpresent={"id": "d5b13b7a-411c-4e83-b686-6c52f8afce43"} id="M_dJ2MNhhD4T"
# pip install git+https://github.com/GiulioRossetti/ndlib.git > /dev/null
# + [markdown] nbpresent={"id": "d256b3e0-a7b9-4280-b039-611b454c0bc8"} id="piNhFrW9hD4T"
# In order to check if ``ndlib`` has been correctly installed just try to import it
# + nbpresent={"id": "7e934716-2cd5-41dc-94f1-e2bec1e46253"} id="DrCk-m1jhD4U"
import ndlib
# + [markdown] nbpresent={"id": "f6ebc361-ba08-4c07-b6e4-70ea0553c85f"} id="b0V9es1dhD4V"
# <a id='workflow'></a>
# ## 2. Simulation Workflow ([to top](#top))
#
# ``Ndlib`` breaks the simulation of diffusive phenomena into a standard workflow:
# - Network Creation
# - Diffusion model Selection and Configuration
# - Simulation execution
# - Results visualisation
#
# In this section we will observe how to templating such workflow describing a simple *SIR* simulation.
#
# <img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/sir.png?raw=1"/>
# + [markdown] nbpresent={"id": "6a27ddf5-b22f-4a18-b356-c4ff88d262c6"} id="_Cqj8-a6hD4W"
# <a id="graph"></a>
# ### 2.A Graph object creation ([to top](#top))
# + [markdown] nbpresent={"id": "5bee6e13-4794-4da7-b48c-9d10fb6d93a2"} id="W2HxAZMhhD4W"
# As a first step we need to define the network topology that will be used as playground to study diffusive phenomena.
#
# ``NDlib`` leverage [``networkx``](https://networkx.github.io) data structure to provide support for both directed and undirected graphs.
#
# In this example, to perform our simulation, we instantiate a Erdos-Renyi graph as follows:
# + nbpresent={"id": "bdb19eea-c3a3-4546-84c0-574217525f31"} id="Cx2pt6InhD4W"
import networkx as nx
g = nx.erdos_renyi_graph(1000, 0.1)
# + [markdown] nbpresent={"id": "edf7e27b-3601-4597-8b2f-c466ce03e4ca"} id="K5geBsinhD4X"
# <a id="model"></a>
# ### 2.B Model Selection and Configuration ([to top](#top))
#
# After having defined the graph, we can select the diffusion model to simulate. In our example we import the SIR model and instantiate it on our graph.
# + nbpresent={"id": "8525a4f9-89f9-4861-8d29-59c8f57fdfe0"} id="qd1dA0QchD4X"
import ndlib.models.epidemics as ep
model = ep.SIRModel(g)
# + [markdown] nbpresent={"id": "346fd5eb-6610-4bc0-b0b1-099755ceb514"} id="F0s0JqUKhD4X"
# Every diffusion model has its own parameter, ``NDlib`` offers a common interface to specify them: ``ModelConfig``.
# ``ModelConfig`` takes care of validating model parameters.
#
# Indeed, every model has its own parameters: model specific parameter list and definitions are available on the project [documentation site](http://ndlib.readthedocs.io).
#
# In order to get a description of the required parameters just access the ``parameter`` field
# + nbpresent={"id": "c7a33f02-ca17-4f0f-9f39-771f0f963aa7"} id="vQL_F25KhD4Y" outputId="8c2fb38b-d5c0-42eb-f7cf-3527f98cf2e5"
import json
print(json.dumps(model.parameters, indent=2))
# + [markdown] nbpresent={"id": "bb1b20e8-1c45-4f32-9aed-286c5cf0c7e7"} id="oRv2YuI2hD4Z"
# Similarly, to obtain a list of the statuses implemented in the selected model just access the ``available_statuses`` field
# + nbpresent={"id": "1bed3093-1658-4a8a-b66a-40b2dbc81936"} id="y5iKQe8GhD4a" outputId="0cc62f96-eb55-4301-f850-c828e08f3c75"
model.available_statuses
# + nbpresent={"id": "1519173d-12c9-422c-a9ec-04cf5b913912"} id="0MuJ-8S0hD4a"
import ndlib.models.ModelConfig as mc
cfg = mc.Configuration()
cfg.add_model_parameter('beta', 0.001) # infection rate
cfg.add_model_parameter('gamma', 0.01) # recovery rate
# + [markdown] nbpresent={"id": "e2d56115-2cd3-4277-bd5c-77200170d4bc"} id="2w5RMfpshD4b"
# ``ModelConfig`` also allows to describe the initial condition of the simulation. It makes possible, for instance, to specify the initial percentage of infected nodes in the network.
# + nbpresent={"id": "9305b01c-51cb-4b7e-ac43-d39e529d6632"} id="uuEOy36PhD4b"
cfg.add_model_parameter("percentage_infected", 0.01)
model.set_initial_status(cfg)
# + [markdown] nbpresent={"id": "a25dd06c-cff2-414a-9fe6-9cfa853a9d65"} id="-CUJJNSwhD4b"
# <a id="simulation"></a>
# ### 2.C Simulation Execution ([to top](#top))
#
# Once described the network, the model and the initial conditions it is possible to perform the simulation.
#
# ``NDlib`` models diffusive phenomena as **discrete-time**, **agent-based** processes: during every iteration all nodes are evaluated and, their statuses are updated accordingly to the model rules.
#
# Iterations can be required (incrementally) by using two methods:
# - ``iteration()``
# - ``iteration_bunch(nbunch, node_status=False)``
#
# The former computes a single iteration step, the latter executes ``nbunch`` iterations.
#
# The ``node_status`` parameter allows to return the individual node status at each iteration.
# + nbpresent={"id": "8cb4dd67-b58f-4bae-82c8-e85d5c4ebd65"} id="7BJ5JhochD4b" outputId="de4a12e6-0704-4ada-d59a-392e8f70db59"
iterations = model.iteration_bunch(200, node_status=True)
iterations
# + [markdown] nbpresent={"id": "9428e785-c5ce-4df3-992c-5863acef8aa6"} id="K1hm9ezEhD4c"
# To abstract from iterations details it is possible to transform them into diffusion **trends** using the ``build_trends(iterations)`` method:
# + nbpresent={"id": "0fe368c9-aee0-4f5f-a37a-a44557b21901"} id="3K1a6TvIhD4c" outputId="4f1a22df-b070-406a-841e-a12b45318b4a"
trends = model.build_trends(iterations)
trends
# + [markdown] nbpresent={"id": "3f73d8fc-52c2-4d61-becb-40cb61b95e01"} id="O-dZRNBthD4c"
# <a id="top"></a>
# ### 2.D Results Visualisation ([to top](#top))
#
# Finally, ``NDlib`` allows to inspect the behavior of the simulated model using standard plots such as the ``DiffusionTrend`` and ``DiffusionPrevalence`` ones.
# + nbpresent={"id": "e99ca466-636e-41c6-92df-5c47e9e8f284"} id="ZBJH9ccYhD4c" outputId="ef69fa90-097e-4b4b-a67d-13e95572e57f"
# %matplotlib inline
from ndlib.viz.mpl.DiffusionTrend import DiffusionTrend
viz = DiffusionTrend(model, trends)
viz.plot()
# + nbpresent={"id": "1329a916-f0ee-426f-a543-c4e93c038fc5"} id="ZSwnDHfahD4d" outputId="a9e5b4cb-52ff-47c8-c410-5709d7edfecc"
from ndlib.viz.mpl.DiffusionPrevalence import DiffusionPrevalence
viz = DiffusionPrevalence(model, trends)
viz.plot()
# + [markdown] nbpresent={"id": "ccea099f-8005-4323-a95c-d62f233c22f8"} id="THaWbQzmhD4d"
# The proposed visualisation are realised using the [``matplotlib``](https://matplotlib.org) python library. They are fully customizable and all the metadata they visualize is gathered by the ``model`` object.
#
# To obtain web-oriented versions of such plots ``NDlib`` exposes a second visualisation endpoint built on top of [``bokeh``](https://bokeh.pydata.org/en/latest/): the plotting facilities its defines are collected within the sub-package ``ndlib.viz.bokeh`` and follow the same rationale of their ``matplotlib`` counterpart.
# + [markdown] nbpresent={"id": "a9bd10e4-0421-4a26-a23f-89a7c4a6d40c"} id="6ETvUrlShD4d"
# <a id="models"></a>
# ## 3. Available models ([to top](#top))
# + [markdown] nbpresent={"id": "000e4199-f50b-4ea2-bbee-504ec2241ceb"} id="-Z7mDXGEhD4e"
# The analysis of diffusive phenomena that unfold on top of complex networks is a task able to attract growing interests from multiple fields of research.
#
# In order to provide a succinct framing of such complex and extensively studied problem it is possible to split the related literature into two broad, related, sub-classes: **Epidemics** and **Opinion Dynamics**.
# + [markdown] nbpresent={"id": "7f7f36d3-bba7-41ee-aef9-178fffde0c92"} id="UcN0qWnDhD4e"
# <a id="epidemics"></a>
# ### 3.A Epidemics ([to top](#top))
#
# When we talk about epidemics, we think about contagious diseases caused by biological pathogens, like influenza, measles, chickenpox and sexually transmitted viruses that spread from person to person.
#
# Several elements determine the patterns by which epidemics spread through groups of people: the properties carried by the pathogen (its contagiousness, the length of its infectious period and its severity), the structure of the network as well as the mobility patterns of the people involved.
#
# In ``NDlib`` are implemented the following 12 Epidemic models:
# + [markdown] nbpresent={"id": "14d28c55-bb33-4479-9fbc-3b988509315b"} id="loAKAFKthD4e"
# <table>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/SIm.html'>SI</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/SIS.html'>SIS</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/SIR.html'>SIR</a></td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/SEIR.html'>SEIR</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/SEIS.html'>SEIS</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/SWIR.html'>SWIR</a></td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/Threshold.html'>Threshold</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/GeneralisedThreshold.html'>Generalised Threshold</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/KThreshold.html'>Kertesz Threshold</a></td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/Profile.html'>Profile</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/ProfileThreshold.html'>Profile-Threshold</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/epidemics/IndependentCascades.html'>Independent Cascades</a></td>
# </tr>
# </table>
# + [markdown] nbpresent={"id": "bdcdf439-7e48-45c9-9a31-f545cd7082a7"} id="rEL_iHiAhD4e"
# <a id="opinions"></a>
# ### 3.B Opinion Dynamics ([to top](#top))
#
# A different field related with modelling social behaviour is that of opinion dynamics.
#
# Recent years have witnessed the introduction of a wide range of models that attempt to explain how opinions form in a population, taking into account various social theories (e.g. bounded confidence or social impact).
#
# These models have a lot in common with those seen in epidemics and spreading. In general, individuals are modelled as agents with a state and connected by a social network.
#
# The social links can be represented by a complete graph (*mean field* models) or by more realistic complex networks, similar to epidemics and spreading.
#
# The state is typically represented by variables, that can be *discrete* (similar to the case of spreading), but also *continuous*, representing for instance a probability to choose one option or another. The state of individuals changes in time, based on a set of update rules, mainly through interaction with the neighbours.
#
# While in many spreading and epidemics models this change is irreversible (susceptible to infected), in opinion dynamics the state can oscillate freely between the possible values, simulating thus how opinions change in reality.
#
# In ``NDlib`` are implemented the following 6 Opinion Dynamics models:
# + [markdown] nbpresent={"id": "f13e6790-2a8f-4245-9116-687e0fca0d78"} id="sGfBqJ2rhD4f"
# <table>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/opinion/Voter.html'>Voter</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/opinion/QVoter.html'>Q-Voter</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/opinion/MajorityRule.html'>Majority Rule</a></td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/opinion/Snajzd.html'>Sznajd</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/opinion/COD.html'>Cognitive Opinion Dynamics</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/opinion/AlgorithmicBias.html'>Algorithmic Bias</a></td>
# </tr>
# </table>
# + [markdown] nbpresent={"id": "c9690abd-6b82-431b-847c-1c13ea64ef82"} id="qm_OmSvqhD4f"
# <a id="advanced"></a>
# ## 4 Advanced Model Configurations ([to top](#top))
#
# As already discussed, the ``ModelConfig`` object is the common interface ``NDlib`` use to set up simulation experiments.
#
# ``ModelConfig`` allows to specify four categories of experiment configurations:
# - **Model** configuration (as already discussed)
# - **Node** Configuration
# - **Edge** Configuration
# - Simulation **Initial Conditions**
# + [markdown] nbpresent={"id": "bd8f5f38-85d0-4670-ad44-7f72d9911956"} id="Cu5YJwxHhD4g"
# <a id="nodes"></a>
# ### 4.A Node Attributes ([to top](#top))
#
# Node configuration involves the instantiation of both the *mandatory* and *optional* parameters attached to individual nodes.
#
# Let's consider as an example the ``Threshold`` model.
#
# In such model a *susceptible* node in order to become *infected* needs that at least $\tau\%$ of its neighbors are already *infected*.
#
# We can assign a value of $\tau\%$ to every node as follows:
# + nbpresent={"id": "efc80df0-5287-4721-80ef-6251b5c4f516"} id="FjZ7g7WGhD4g"
model = ep.ThresholdModel(g)
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
threshold = 0.25
for i in g.nodes():
config.add_node_configuration("threshold", i, threshold) # node attribute setting
model.set_initial_status(config)
# + [markdown] nbpresent={"id": "c03c6a66-b052-4807-86bc-ac9c5a58ef9d"} id="P8LQDBTDhD4g"
# <a id="edges"></a>
# ### 4.B Edge Attributes ([to top](#top))
#
# Edge configuration involves the instantiation of both the *mandatory* and *optional* parameters attached to individual edges.
#
# Let's consider as an example the ``IndependentCascades`` model.
#
# In such model a *susceptible* node become *infected* with probability $p$, where $p$ is a value attached to the link connecting the *susceptible* node to an *infected* neighbor.
#
# We can assign a value of $p$ to every edge as follows:
# + nbpresent={"id": "9bf3f682-408b-4dc5-92ad-37522958f0e6"} id="zZE4ow9YhD4g"
model = ep.IndependentCascadesModel(g)
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
threshold = 0.1
for e in g.edges():
config.add_edge_configuration("threshold", e, threshold) # edge attribute setting
model.set_initial_status(config)
# + [markdown] nbpresent={"id": "696e1baf-ecd9-4023-bc9e-97b47457152f"} id="ypJ4lNhPhD4h"
# <a id="seeds"></a>
# ### 4.C Infection Seeds Selection ([to top](#top))
#
# Status configuration allows to specify explicitly the status of a set of nodes at the beginning of the simulation.
#
# So far we have assumed that a random sample of nodes (10% in our examples) were initially infected: in order to cover more specific simulation scenarios we can also explicitly *specify* the nodes belonging to each *status* at the beginning of the simulation.
# + nbpresent={"id": "7e7040d6-62ab-4455-891a-b622852735aa"} id="PKSeeuVQhD4h"
import ndlib.models.ModelConfig as mc
# Model Configuration
config = mc.Configuration()
infected_nodes = [0, 1, 2, 3, 4, 5]
config.add_model_initial_configuration("Infected", infected_nodes)
# + [markdown] nbpresent={"id": "c2adc5fc-0abe-4c82-9710-ed2fdeb498b4"} id="53wFeAsAhD4h"
# **NB:** Explicit status specification takes priority over the percentage specification expressed via model definition (e.g. percentage_infected).
# + [markdown] nbpresent={"id": "c6ecf5d8-7628-44dd-8378-8d88ebda4f5b"} id="1tK0zRbMhD4h"
# <a id="stability"></a>
# #### 4.C.a Model Stability ([to top](#top))
#
# Indeed, different initial conditions can affect the overall unfolding of the diffusive process.
#
# In order to analyse the stability of a model w.r.t. the initial seeds ``NDlib`` implements a ``multi_runs`` facility.
#
# ``multi_runs`` allows the parallel execution of multiple instances of a given model starting from different initial infection conditions.
#
# We can instantiate ``multi_runs`` as follows:
# + nbpresent={"id": "29974cb8-670b-41ad-b971-a6724156d22c"} id="c3rhKlhGhD4h"
from ndlib.utils import multi_runs
import warnings
warnings.filterwarnings("ignore")
model = ep.SIRModel(g)
config = mc.Configuration()
config.add_model_parameter('beta', 0.001)
config.add_model_parameter('gamma', 0.01)
config.add_model_parameter("percentage_infected", 0.05)
model.set_initial_status(config)
trends = multi_runs(model, execution_number=10, iteration_number=100, nprocesses=4)
# + [markdown] nbpresent={"id": "7ffbd058-8531-45bd-a881-03eb62ed2bd0"} id="V8WDbo6vhD4i"
# In our example the initial seeds for each instance of the model were specified by the ``percentage_infected`` model parameter.
#
# Indeed we can also explicitly parametrize the seed sets as follows:
# + nbpresent={"id": "bf34e091-0643-41c2-96da-31e16396f6a8"} id="eu4RZgc1hD4i"
model = ep.SIRModel(g)
config = mc.Configuration()
config.add_model_parameter('beta', 0.001)
config.add_model_parameter('gamma', 0.01)
model.set_initial_status(config)
infection_sets = [(1, 2, 3, 4, 5), (3, 23, 22, 54, 2), (98, 2, 12, 26, 3), (4, 6, 9) ]
trends1 = multi_runs(model, execution_number=4, iteration_number=100, infection_sets=infection_sets, nprocesses=4)
# + [markdown] nbpresent={"id": "36a0a7ae-1fcc-46d0-814e-b80b2a7c5487"} id="hVG03yCMhD4j"
# <a id="stability_vis"></a>
# #### 4.C.b Stability Visualisation ([to top](#top))
#
# Model stability can be easily analised by using the visualisation facilities offered by the library: both ``DiffusionTrend`` and ``DiffusionPrevalence`` plots allows to plot mean trends along with their point-wise variation.
# + nbpresent={"id": "34df8d46-7ebe-4a2f-8f5e-d6f1872fa631"} id="k6irYNOwhD4j" outputId="216fb018-4eff-4447-8882-6816da3a4e75"
viz = DiffusionTrend(model, trends)
viz.plot(percentile=90)
# + nbpresent={"id": "94fa1df2-f659-4788-baca-ec3a37661630"} id="vSFdzoK9hD4j" outputId="8390e717-f045-4cb5-ee2a-c8a60dbfdb1a"
viz = DiffusionPrevalence(model, trends)
viz.plot(percentile=90)
# + [markdown] nbpresent={"id": "e152a844-f26c-4151-9aaf-276a41d5170d"} id="aogXmBGihD4k"
# <a id="comparing"></a>
# ## 5. Comparing Diffusion models ([to top](#top))
#
# A common goal for which diffusion simulations are executed is to perform comparison among different models (or different instantiations of a same model).
#
# To address such demands ``NDlib`` provides visual comparison plots.
#
# To show how they work, as a first step we execute a second model (in this exampe an **SI** model) over our original graph.
# + nbpresent={"id": "83c9c8d8-c485-4b3e-a5c4-32fec616e3d2"} id="aWQc3rFNhD4k"
model1 = ep.SIModel(g)
cfg = mc.Configuration()
cfg.add_model_parameter('beta', 0.001)
cfg.add_model_parameter("percentage_infected", 0.01)
model1.set_initial_status(cfg)
trends1 = multi_runs(model1, execution_number=10, iteration_number=100, nprocesses=4)
# + [markdown] nbpresent={"id": "eb42ef55-d83f-415e-ab46-34429f6b5253"} id="rmrMIsoYhD4k"
# Then, we can compare them:
# + nbpresent={"id": "8a64a937-c48d-4fbd-a344-3eba502fa205"} id="tZT2BL3OhD4k" outputId="82765231-4764-4793-f53b-6db5c4c8bf9c"
from ndlib.viz.mpl.TrendComparison import DiffusionTrendComparison
viz = DiffusionTrendComparison([model, model1], [trends, trends1], statuses=['Infected'])
viz.plot()
# + nbpresent={"id": "b0908a6c-0be3-448a-bd69-813efb85538f"} id="ohDPeP0JhD4k" outputId="779b03d9-b7f5-4ed2-fa57-c1116aabd10b"
from ndlib.viz.mpl.PrevalenceComparison import DiffusionPrevalenceComparison
viz = DiffusionPrevalenceComparison([model, model1], [trends, trends1], statuses=['Infected'])
viz.plot()
# + [markdown] nbpresent={"id": "72eae37f-eb5f-4c68-b553-98cd57ade290"} id="aoPFBjXzhD4l"
# The method parameter ``statuses`` takes as input a list of the models statuses trends we want to compare.
# So, for instance, if we are interested in comparing both the trends for *Infected* and *Susceptible* nodes we can do something like this:
# + nbpresent={"id": "4b067c6d-aae0-45f3-949b-3e16019becc0"} id="8qlIxO54hD4l" outputId="4c2a65a8-9abf-424a-fbe1-ad62207b58a5"
from ndlib.viz.mpl.TrendComparison import DiffusionTrendComparison
viz = DiffusionTrendComparison([model, model1], [trends, trends1], statuses=['Infected', 'Susceptible'])
viz.plot()
# + [markdown] nbpresent={"id": "5444515e-f990-42c9-8d47-228e2dd6228d"} id="vIp0seOEhD4l"
# <a id="dynamic"></a>
# ## 6. Diffusion on Dynamic Networks ([to top](#top))
#
# So far we assumed that a *static* network topology. In real world scenario it is likely to observe nodes (as well as edges) that appear and desapear as time goes by, deeply affecting network structure and connectivity.
#
# Indeed, topological transformations have huge implications on how diffusive phenomena unfold.
#
# ``NDlib`` leverages [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) to model time-evolving graphs. In the following we briefly introduce some [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) primitives that allows to build and analyse dynamic networks.
#
# A dynamic network is a topology having timestamps attached to edges (and/or nodes). As an example:
#
# + [markdown] id="EddO6gRwhD4l"
# <img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/rete.png?raw=1" width="50%" align="center"/>
# + [markdown] nbpresent={"id": "273f25ce-7799-4ac2-9f53-cd7ff3f6ba0f"} id="QiJlkpSHhD4m"
# <a id="dynetx"></a>
# ### 6.A DyNetX: a library for dynamic network modeling ([to top](#top))
#
# [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) is a Python software package that extends [``networkx``](https://networkx.github.io) with dynamic network models and algorithms.
#
# We developed [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) as a support library for ``NDlib``. It provides a generic implementation of dynamic network topology that can be used to model directed/undirected
# - [Snapshot Graphs](#snapshots)
# - [Interaction Networks](#interactions)
#
# In [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) a generic dynamic graph can be built using:
# + nbpresent={"id": "b1623c00-7e81-47a7-aa4b-adb1d3d8b619"} id="omGbwOGUhD4m"
import dynetx as dn
g = dn.DynGraph() # empty dynamic graph
g.add_interaction(u=1, v=2, t=0, e=2) # adding the edge (1,2) at t=0 that vanishes at time e=2
g.add_interactions_from([(1, 4), (2, 5), (3, 1)], t=1) # adding some edges at time t=1
g.add_interactions_from([(2, 6), (3, 2)], t=2) # adding some edges at time t=2
g.add_interactions_from([(1, 5)], t=3) # adding some edges at time t=3
# + [markdown] nbpresent={"id": "246a6874-119c-4ca3-9f0a-3d9192b81f85"} id="uzCm2qQnhD4m"
# <a id="snapshots"></a>
# #### 6.A.a Snapshot Graphs ([to top](#top))
#
# Often, network history is partitioned into a series of snap- shots, each one of them corresponding either to the state of the network at a time $t$ or to the aggregation of observed interactions during a period. Formally,
#
# > A ``Snapshot Graph`` $G_t$ is defined by a temporally ordered set $⟨G_1, G_2\dots G_t⟩$ of static graphs where each snapshot $G_i = (V_i, E_i)$ is univocally identified by the sets of nodes $V_i$ and edges $E_i$.
#
# Network snapshots can be effectively used, for instance, to model a phenomenon that generates network perturbations (almost) at regular intervals. In this scenario, context-dependent temporal windows are used to partition the network history into consecutive snapshots: time-bounded observations describing a precise, static, discretization of the network life.
#
# Considering our dynamic network example we can identify the following snapshot graphs:
#
# <img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/ex1.png?raw=1" width="35%" align="left"/><img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/ex2.png?raw=1" width="25%" align="left"/><img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/ex3.png?raw=1" width="35%" align="left"/>
#
# [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) allows to (among the other things):
# - List the snapshots of the loaded graph
# + nbpresent={"id": "32c90ef7-d369-41cf-874e-ed1ee42e0eb6"} id="LQfIY55VhD4m" outputId="064f0eac-7e66-4929-e995-3be262b706bb"
g.temporal_snapshots_ids()
# + [markdown] nbpresent={"id": "d1c5b478-a181-41f9-a187-c50a4ab4a6c2"} id="qVjwL1yzhD4m"
# - Access a specific snapshot
# + nbpresent={"id": "4a3c3856-ce1a-410b-bf8d-9ed46f4e0024"} id="d_nQXrCEhD4n" outputId="718bb895-7167-44a7-9e1d-145ed04b3760"
g1 = g.time_slice(1)
g1.edges()
# + [markdown] nbpresent={"id": "860905f3-ca6d-449a-b48b-f8b3b956f262"} id="y-24BHRThD4n"
# Moreover, snapshot graphs can also be read from/wite to file. For additional details refer to the official [documentation](http://dynetx.readthedocs.io/en/latest/index.html).
# + [markdown] nbpresent={"id": "f27a5517-1f54-483f-926e-ec1c78e301b8"} id="_DjEGLirhD4n"
# <a id="interactions"></a>
# #### 6.A.b Interaction networks ([to top](#top))
#
# An ``Interaction network`` models a dynamic structure in which both nodes and edges may appear and disappear as time goes by. Usually, ``Intercation network`` are used in absence of a clear aggregation time scale, or when make sense to analyse a dynamic networok as a continuos stream of edges. Formally,
#
# > An ``interaction network`` is a graph $G = (V, E, T)$ where: $V$ is a set of triplets of the form $(v, t_s, t_e)$, with $v$ a vertex of the graph and $t_s$, $t_e \in T$ are respectively the birth and death timestamps of the corresponding vertex (with $t_s \leq t_e$); $E$ is a set of quadruplets $(u, v, t_s, t_e)$, with $u, v \in V$ are vertices of the graph and $t_s,t_e \in T$ are respectively the birth and death timestamps of the corresponding edge (with $t_s \leq t_e$).
#
# Considering our dynamic network example we can identify the following interaction stream:
#
# <img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/ex4.png?raw=1" />
#
# [``DyNetx``](http://dynetx.readthedocs.io/en/latest/) allows to to obtain the edge stream of a given dynamic graph.
# + nbpresent={"id": "6723d9a3-cf64-4878-a76e-623ee03854ab"} id="j1ZWtpknhD4n" outputId="5de3dc0d-8daf-4b75-a313-4d4a983287ba"
for i in g.stream_interactions():
print(i)
# + [markdown] nbpresent={"id": "37371b56-1291-4287-bfb8-fcf022dcce42"} id="GiYBuRRdhD4o"
# In the former representation:
# - the first two values identify the nodes involved in an edge
# - the third value identify the edge operation ('+' apparence, '-' vanishing)
# - the last value identify the timestamp
#
# Also ``interaction networks`` can be read from/wite to file. For additional details refer to the official [documentation](http://dynetx.readthedocs.io/en/latest/index.html).
# + [markdown] nbpresent={"id": "a3eab819-81a5-43f9-9e24-c5c0c5095f0d"} id="7sB1q_3YhD4o"
# <a id="models2"></a>
# ### 6.B Available models ([to top](#top))
#
# As we have discussed, network topology may evolve as time goes by.
#
# In order to automatically leverage network dynamics ``NDlib`` enables the definition of diffusion models that work on ``Snapshot Graphs`` as well as on ``Interaction Networks``.
#
# In particular, so far, ``NDlib`` implements dynamic network versions of the following epidemic models:
# + [markdown] nbpresent={"id": "04e8b432-d50e-4e74-b43f-10d35a0a660d"} id="k1OIXM4ohD4o"
# <table>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/dynamics/dSI.html'>SI</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/dynamics/dSIS.html'>SIS</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/dynamics/dSIR.html'>SIR</a></td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/dynamics/dProfile.html'>Profile</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/dynamics/dProfileThreshold.html'>Threshold</a></td>
# <td><a href='http://ndlib.readthedocs.io/en/latest/reference/models/dynamics/dKThreshold.html'>Kertesz Threshold</a></td>
# </tr>
# </table>
# + [markdown] nbpresent={"id": "f81d52f6-72f1-4e02-895c-294f91a1910d"} id="3opur6ZehD4o"
# <a id="dynsir"></a>
# ### 6.C Example: SIR ([to top](#top))
#
# Let's instantiate a revised SIR model on a dynamic netework, first on ``snapshot graphs``...
# + nbpresent={"id": "61d9a95d-694c-4a51-a5c5-e8493c7a5eb6"} id="09EWY0s_hD4o" outputId="aacd223e-8604-4f80-987f-7a178a8afa53"
import ndlib.models.dynamic as dm
# Dynamic Network topology
dg = dn.DynGraph()
# Naive synthetic dynamic graph
# At each timestep t a new graph having the same set of node ids is created
for t in range(0, 30):
g = nx.erdos_renyi_graph(200, 0.01)
dg.add_interactions_from(g.edges(), t)
# Model selection
model = dm.DynSIModel(dg)
# Model Configuration
config = mc.Configuration()
config.add_model_parameter('beta', 0.01)
config.add_model_parameter("percentage_infected", 0.1)
model.set_initial_status(config)
# Simulate snapshot based execution
iterations = model.execute_snapshots()
trends = model.build_trends(iterations)
viz = DiffusionTrend(model, trends)
viz.plot()
# + [markdown] nbpresent={"id": "a2b6da6d-a6b0-4c36-914b-c8a794ae8025"} id="pP1Gf_-phD4p"
# then in ``interaction networks``
# + nbpresent={"id": "4e669671-ea40-4b39-8c23-6161e95689c7"} id="_EVovfS0hD4p" outputId="e2f89748-5923-488a-c8ef-92c1dd49b574"
model = dm.DynSIModel(dg)
# Model Configuration
config = mc.Configuration()
config.add_model_parameter('beta', 0.01)
config.add_model_parameter("percentage_infected", 0.1)
model.set_initial_status(config)
# Simulation interaction graph based execution
iterations = model.execute_iterations()
trends = model.build_trends(iterations)
viz = DiffusionTrend(model, trends)
viz.plot()
# + [markdown] nbpresent={"id": "e4c37b2f-5ea8-499f-ac22-fa56132234a2"} id="U1sszMZ5hD4p"
# We can easily observe that the model we adopt to describe network dynamics (``snapshot graphs`` or ``interaction networks``) deeply affects the unfolding of a same diffusive process over a given evolving graph.
# + [markdown] nbpresent={"id": "c4386bf3-1d9d-49be-89d7-4e9297a549ab"} id="hXqj8NYIhD4p"
# <a id="custom"></a>
# ## 7. Custom Model Definition ([to top](#top))
#
# ``NDlib`` comes with a handy syntax for compositional (custom) model definition to support its users in designing novel diffusion models.
#
# At a higher level of abstraction a generic diffusion process can be described by two components:
#
# 1. The nodes' ``statuses`` it exposes, and
# 2. the ``transition rules`` that regulate status changes.
#
# We recall that all models of ``NDlib`` assume an agent-based, discrete-time, simulation engine.
#
# During each iteration all the nodes in the network are asked to
# 1. evaluate their current status and to
# 2. (eventually) apply a matching transition rule.
#
# A generic ``transition rule`` can be expressed with something like:
# + [markdown] nbpresent={"id": "560c2366-88b6-4dfa-b545-ead65a7c8744"} id="9mP2TWAJhD4q"
# > **if** ``actual_node_status`` **and** ``condition`` **then** ``new_node_status``
# + [markdown] nbpresent={"id": "e53c17d4-1b13-4161-b96f-1dbb7c79476e"} id="e00-PiFohD4q"
# The ``condition`` can be easily decomposed into the evaluation of atomic operations that we will call ``compartments``. The evaluation of a compartment can return either ``True`` (condition satisfied) or ``False`` (condition not satisfied).
#
# A simple ``condition`` is composed by a single ``compartment``.
#
# Indeed, several ``compartments`` can be described, each one of them capturing an atomic operation.
# + [markdown] nbpresent={"id": "4ca11e96-1eb1-4123-a705-41012ffcf906"} id="4J1Rc2PLhD4q"
# A custom model, having three statuses (``Susceptible``, ``Infected``, ``Recovered``), can be instantiated as follows:
# + nbpresent={"id": "418542af-5735-4c68-9b84-aabe78496ff9"} id="ukEv9Nq9hD4q"
import ndlib.models.CompositeModel as gc
import ndlib.models.compartments.NodeStochastic as ns
# Composite Model instantiation
model = gc.CompositeModel(g)
model.add_status("Susceptible")
model.add_status("Infected")
model.add_status("Recovered")
# + [markdown] nbpresent={"id": "4c198280-5dfc-4bf1-816a-19150d308637"} id="5pYkvN36hD4q"
# <a id="compartments"></a>
# ### 7.A Compartments ([to top](#top))
#
# > *Which are the atomic conditions that can be used to define complex transition rules?*
#
# To answer such question we identified three families of ``compartments`` (and some operations to combine them).
# + [markdown] nbpresent={"id": "e0c2ef51-f35d-4c53-96dd-0ff4acd914f5"} id="zUaNlfMvhD4r"
# <a id="nc"></a>
# #### 7.A.a Node Compartments ([to top](#top))
# In this class fall all those compartments that evaluate conditions tied to node status/features. They model stochastic events as well as deterministic ones.
#
# <table>
# <tr><td><b>Name</b></td><td><b>Use case</b></td><tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/NodeStochastic.html'>Node Stochastic</a></td>
# <td>Consider a rule that requires a <b>probability</b> $\beta$ to be satisfied. </td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/NodeCategoricalAttribute.html'>Node Categorical Attribute</a></td>
# <td>Consider a rule that requires a specific value of a <b>categorical</b> node attribute to be satisfied (e.g. “Sex”=”male”).</td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/NodeNumericalAttribute.html'>Node Numerical Attribute</a></td>
# <td>Consider a rule that requires a specific value of a <b>numerical</b> node attribute to be satisfied (e.g. “Age” >= 18).</td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/NodeThreshold.html'>Node Threshold</a></td>
# <td>Consider a rule that requires that, at least, a <b>percentage</b> $\beta$ of Infected neighbors for a node to be satisfied.</td>
# </tr>
# </table>
#
# Let's add to our model a rule employing a node stochastic compartment:
# + nbpresent={"id": "25732824-6459-41e9-a222-b7acf1aecbe5"} id="_VJN33fjhD4r"
import ndlib.models.compartments.NodeStochastic as ns
# Compartment description
c1 = ns.NodeStochastic(0.02, triggering_status="Infected")
# Rule definition
model.add_rule("Susceptible", "Infected", c1)
# + [markdown] nbpresent={"id": "c6d15e7b-8171-4ce9-bd79-096f46827a52"} id="EIukPeyihD4r"
# The **Susceptble -> Infected** rule defined works as follows:
# - if a node $n$ is *susceptible*, and
# - if $n$ has at least an *infected* neighbor (``triggering_status``)
# - then, with probability $0.02$, $n$ status will shift to *infected*
# + [markdown] nbpresent={"id": "11070a54-9acc-4fee-af16-2998e2432de4"} id="PU3A1AYRhD4r"
# <a id="ec"></a>
# #### 7.A.b Edge Compartments ([to top](#top))
# In this class fall all those compartments that evaluate conditions tied to edge features. They model stochastic events as well as deterministic ones.
#
#
# <table>
# <tr><td><b>Name</b></td><td><b>Use case</b></td><tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/EdgeStochastic.html'>Edge Stochastic</a></td>
# <td>Consider a rule tha requires a direct link among an infected node and a susceptible one and that is subject to a <b>probability</b> $\beta$ tied to such edge.</td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/EdgeCategoricalAttribute.html'>Edge Categorical Attribute</a></td>
# <td>Consider a rule tha requires a link among an infected node and a susceptible one that has a specific <b>categorical</b> value (e.g. “type”=”co-worker”)</td>
# </tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/EdgeNumericalAttribute.html'>Edge Numerical Attribute</a></td>
# <td>Consider a rule tha requires a link among an infected node and a susceptible one that has a specific <b>numerical</b> value (e.g. “weight”<3)</td>
# </tr>
# </table>
#
# Let's add to our model a rule employing an edge stochastic compartment:
# + nbpresent={"id": "a5b4ec77-7feb-4f22-b163-b00a3c6ca255"} id="iYxVBeCqhD4r"
import ndlib.models.compartments.EdgeStochastic as es
c2 = es.EdgeStochastic(0.02, triggering_status="Recovered")
# Rule definition
model.add_rule("Infected", "Recovered", c2)
# + [markdown] nbpresent={"id": "03512ce9-3ee3-4984-b103-476707831f36"} id="DRcZfPFOhD4s"
# The **Infected -> Recovered** rule defined works as follows:
# - if a node $n$ is *infected*, and
# - let $\Gamma$ be the set containing the *recovered* (``triggering_status``) neighbors of $n$
# - then for each node $v\in \Gamma$ with probability $0.02$, $n$ status will shift to *recovered*
# + [markdown] nbpresent={"id": "57b1e919-113f-4c4f-a95c-88eed24f9dbb"} id="LH0j-VMThD4s"
# <a id="tc"></a>
# #### 7.A.c Time Compartments ([to top](#top))
# In this class fall all those compartments that evaluate conditions tied to temporal execution. They can be used to model, for instance, lagged events as well as triggered transitions.
#
# <table>
# <tr><td><b>Name</b></td><td><b>Use case</b></td><tr>
# <tr>
# <td><a href='http://ndlib.readthedocs.io/en/latest/custom/compartments/CountDown.html'>Count Down</a></td>
# <td>Consider a rule that has an <b>incubation</b> period of $t$ iterations.</td>
# </tr>
# </table>
#
#
# Let's add to our model a rule employing a count down compartment
# + nbpresent={"id": "f6954013-a642-4949-9573-5cd86a86afb2"} id="p01YH2syhD4s"
import ndlib.models.compartments.CountDown as cd
c3 = cd.CountDown("incubation", iterations=10)
# Rule definition
model.add_rule("Recovered", "Susceptible", c1)
# + [markdown] nbpresent={"id": "aa70551b-8f19-4c6f-8e90-7e3b135a489d"} id="crJVoOkyhD4s"
# The **Recovered -> Susceptible** rule defined works as follows:
# - if a node $n$ is *recovered* a count down named ``incubation`` is instantiated
# - during each iteration ``incubation`` is decremented
# - when ``incubation=0`` $n$ shifts to *susceptible*
# + [markdown] nbpresent={"id": "bad9d5cc-c2f5-4d24-8ecb-91f15563a1b3"} id="Uu-6dA3OhD4s"
# <a id="composition"></a>
# ### 7.B Compartments Composition ([to top](#top))
#
# Compartment can be chained in multiple ways so to describe complex transition rules.
#
# In particular, a transition rule can be seen as a tree whose nodes are compartments and edges connections among them.
#
# As an example consider the following picture describing the structure of a composite **Susceptible->Infected** transition rule.
# + [markdown] nbpresent={"id": "5f9418d4-220f-4f32-aeca-202c3b9bb0ba"} id="fNt7_Wa4hD4t"
# <img src="https://github.com/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/img/rule.png?raw=1"/>
# + [markdown] nbpresent={"id": "f2ca9d5b-0b54-48e4-962e-b39a764c7d25"} id="hekRj6H5hD4t"
# - The initial node status is evaluated at the root of the tree (the master compartment)
# - If the operation described by such compartment is satisfied the conditions of (one of) its child compartments is evaluated
# - If a path from the root to one leaf of the tree is completely satisfied the transition rule applies and the node change its status.
#
# Compartments can be combined following two criteria:
#
# - Cascading Composition
# - Conditional Composition
#
# A ``transition rule`` can be defined by employing all possible combinations of cascading and conditional compartment composition.
# + [markdown] nbpresent={"id": "c16e2c4d-83bc-4958-a7e9-92a87011e28c"} id="YW84_M0-hD4t"
# <a id="cascading"></a>
# ### 7.B.a Cascading Composition ([to top](#top))
#
# Since each compartment identifies an atomic condition it is natural to imagine rules described as chains of compartments.
#
# A compartment chain identify and ordered set of conditions that needs to be satisfied to allow status transition (it allows describing an **AND** logic).
#
# To implement such behaviour each compartment exposes a parameter (named ``composed``) that allows to specify the subsequent compartment to evaluate in case it condition is satisfied.
#
# #### Example
#
# In the following scenario the **Susceptible->Infected** rule is implemented using three NodeStochastic compartments chained as follows:
#
# $$C_1 \rightarrow C_2 \rightarrow C_3$$
#
# - If the node $n$ is *Susceptible*
# - $C_1$: if at least a neighbor of the actual node is *Infected*, with probability $0.5$ evaluate compartment $C_2$
# - $C_2$: with probability $0.4$ evaluate compartment $C_3$
# - $C_3$: with probability $0.2$ allow the transition to the *Infected* state
# + nbpresent={"id": "3e1de5f8-a6ff-4a45-9a61-4931005f1e6b"} id="TKfwc6ChhD4t" outputId="b890ceb0-dff6-426c-ec49-38efeded9c95"
# Network generation
g = nx.erdos_renyi_graph(1000, 0.1)
# Composite Model instantiation
model = gc.CompositeModel(g)
# Model statuses
model.add_status("Susceptible")
model.add_status("Infected")
# Compartment definition and chain construction
c3 = ns.NodeStochastic(0.2)
c2 = ns.NodeStochastic(0.4, composed=c3)
c1 = ns.NodeStochastic(0.5, "Infected", composed=c2)
# Rule definition
model.add_rule("Susceptible", "Infected", c1)
# Model initial status configuration
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
# Simulation execution
model.set_initial_status(config)
iterations = model.iteration_bunch(100)
trends = model.build_trends(iterations)
viz = DiffusionTrend(model, trends)
viz.plot()
# + [markdown] nbpresent={"id": "778456fc-636a-4c72-bd1e-498b2faf46e1"} id="_rDes6XVhD4t"
# <a id="conditional"></a>
# ### 7.B.a Conditional Composition ([to top](#top))
#
# Conditional compartment composition allows to describe rules as trees.
#
# A compartment tree identify and ordered and disjoint set of conditions that needs to be satisfied to allow status transition (it allows describing an **OR** logic).
#
# ``ConditionalComposition`` compartment allows to describe branching pattern as follows:
#
# $$if\ C_i then\ C_j else\ C_z$$
#
# ``ConditionalComposition`` evaluate the guard compartment ($C_i$) and, depending from the result it gets (True or False) move to the evaluation of one of its two child compartments ($C_j$ and $C_z$).
#
# #### Example
#
# In the following scenario the **Susceptible->Infected** rule is implemented using three NodeStochastic compartments combined as follows:
#
# - If the node $n$ is *Susceptible*
# - $C_1$: if at least a neighbor of the actual node is *Infected*, with probability $0.5$ evaluate compartment $C_2$ else evaluate compartment $C_3$
# - $C_2$: with probability $0.2$ allow the transition to the *Infected* state
# - $C_3$: with probability $0.1$ allow the transition to the *Infected* state
#
# + nbpresent={"id": "edd9cad1-5539-41b9-90ef-392c49102118"} id="E8Saxf8phD4u" outputId="e1332767-2b5b-4071-8ea9-19f5ce53cdad"
import ndlib.models.compartments.ConditionalComposition as cif
# Network generation
g = nx.erdos_renyi_graph(1000, 0.1)
# Composite Model instantiation
model = gc.CompositeModel(g)
# Model statuses
model.add_status("Susceptible")
model.add_status("Infected")
# Compartment definition
c1 = ns.NodeStochastic(0.5, "Infected")
c2 = ns.NodeStochastic(0.2)
c3 = ns.NodeStochastic(0.1)
# Conditional Composition
cc = cif.ConditionalComposition(c1, c2, c3)
# Rule definition
model.add_rule("Susceptible", "Infected", cc)
# Model initial status configuration
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
# Simulation execution
model.set_initial_status(config)
iterations = model.iteration_bunch(30)
trends = model.build_trends(iterations)
viz = DiffusionTrend(model, trends)
viz.plot()
# + [markdown] nbpresent={"id": "168b9b9a-7b3d-4fa5-8307-8ea107a5ef1a"} id="_xp7aYUYhD4u"
# <a id="sir"></a>
# ### 7.C Example: SIR ([to top](#top))
#
# Let's describe, and simulate, a **SIR** model using compartments.
# + nbpresent={"id": "a04b59c6-a262-4554-922e-4443dd86ec0a"} id="Co3cGB6shD4u" outputId="80c8267f-1c26-46b8-9f69-74f820e6b6af"
from ndlib.models.CompositeModel import CompositeModel
from ndlib.models.compartments.NodeStochastic import NodeStochastic
# Network definition
g1 = nx.erdos_renyi_graph(n=1000, p=0.1)
# Model definition
SIR = CompositeModel(g1)
SIR.add_status('Susceptible')
SIR.add_status('Infected')
SIR.add_status('Removed')
# Compartments
c1 = NodeStochastic(triggering_status='Infected', rate=0.001, probability=1)
c2 = NodeStochastic(rate=0.01, probability=1)
# Rules
SIR.add_rule('Susceptible', 'Infected', c1)
SIR.add_rule('Infected', 'Removed', c2)
# Configuration
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
SIR.set_initial_status(config)
# Simulation
iterations = SIR.iteration_bunch(300, node_status=False)
trends = SIR.build_trends(iterations)
viz = DiffusionTrend(SIR, trends)
viz.plot()
# + [markdown] nbpresent={"id": "d8cf489f-1a62-48ef-a44c-ea6a9181365e"} id="MRDc1tn0hD4v"
# <a id="ndql"></a>
# ## 8. NDQL: Network Diffusion Query Language ([to top](#top))
#
# ``NDlib`` aims to reach an heterogeneous audience composed by technicians as well as analysts.
#
# In order to abstract from the its programming interface we designed a query language to describe diffusion simulations, ``NDQL``.
# + [markdown] nbpresent={"id": "4f3a90ce-4815-4a1d-bbeb-3c7ad2a2818d"} id="elDlqMVPhD4v"
# <a id="syntax"></a>
# ### 8.A Syntax ([to top](#top))
#
# An ``NDQL`` script is composed of a minimum set of directives:
#
# 1. Network specification:
# - CREATE_NETWORK (-), LOAD_NETWORK (-)
# 2. Model definition:
# - MODEL, STATUS, COMPARTMENT (+), IF-THEN-ELSE (+), RULE,
# 3. Model initialization and simulation execution
# - INITIALIZE, EXECUTE
#
# Directives marked with (+) are optional while the ones marked with (-) are mutually exclusive w.r.t. their class.
#
# The complete language directive specification is the following:
#
# > **MODEL** model_name
# >
# > **STATUS** status_name
# >
# > **COMPARTMENT** compartment_name <br/>
# > **TYPE** compartment_type <br/>
# > **COMPOSE** compartment_name <br/>
# > [**PARAM** param_name numeric]+ <br/>
# > [**TRIGGER** status_name]
# >
# > **IF** compartment_name_1 **THEN** compartment_name_2 **ELSE** compartment_name_3 **AS** rule_name
# >
# > **RULE** rule_name <br/>
# > **FROM** status_name <br/>
# > **TO** status_name <br/>
# > **USING** compartment_name
# >
# > **INITIALIZE** <br/>
# > [**SET** status_name ratio]+
# >
# > **CREATE_NETWORK** network_name <br/>
# > **TYPE** network_type <br/>
# > [**PARAM** param_name numeric]+
# >
# > **LOAD_NETWORK** network_name **FROM** network_file
# >
# > **EXECUTE** model_name **ON** network_name **FOR** iterations
#
# The **CREATE_NETWORK** directive can take as network_type any [``networkx``](https://networkx.github.io) graph generator name (param_name are inherited from generator function parameters).
# + [markdown] nbpresent={"id": "33e400c8-4679-4979-84e8-d977b20549de"} id="Rc7bXXQmhD4v"
# <a id="cmd"></a>
# ### 8.B Command line tools ([to top](#top))
# + [markdown] nbpresent={"id": "9c13b623-e83f-448b-b105-dbd744ee3888"} id="-t6qtDTPhD4w"
# ``NDlib`` installs two command line tools:
# - NDQL_translate
# - NDQL_execute
#
# The former command allows to translate a generic, well-formed, ``NDQL`` script into an equivalent Python one. <br/>
# It can be executed as
#
# > ``NDQL_translate`` query_file python_file
#
# where *query_file* identifies the target ``NDQL`` script and *python_file* specifies the desired name for the resulting Python script.
#
# The latter command allows to directly execute a generic, well-formed, ``NDQL`` script. <br/>
# It can be executed as
#
# > ``NDQL_execute`` query_file result_file
#
# where *query_file* identifies the target ``NDQL`` script and *result_file* specifies the desired name for the execution results. Execution results are saved as JSON files with the following syntax:
#
# [{"trends":<br/>
# {"node_count": {"0": [270, 179, 15, 0, 0], "1": [30, 116, 273, 256, 239], "2": [0, 5, 12, 44, 61]},<br/>
# "status_delta": {"0": [0, -91, -164, -15, 0], "1": [0, 86, 157, -17, -17], "2": [0, 5, 7, 32, 17]}},<br/>
# "Statuses": {"1": "Infected", "2": "Removed", "0": "Susceptible"}<br/>
# }]
#
# where
# - ``node_count`` describes the trends built on the number of nodes per status
# - ``status_delta`` describe the trends built on the fluctuations of number of nodes per status
# - ``Statuses`` provides a map from numerical id to status name
# + [markdown] nbpresent={"id": "9366817a-e254-446a-acc3-459f57325ae8"} id="_xFJ9qE4hD4w"
# <a id="sir2"></a>
# ### 8.C Example: SIR ([to top](#top))
# + [markdown] nbpresent={"id": "5eb813d1-a0f4-48ce-ac73-4bf89f11f2c0"} id="kXt2wPgyhD4w"
# Let's describe a **SIR** model using ``NDQL``.
#
# #### Network creation
#
# > **CREATE_NETWORK** g1<br/>
# > **TYPE** erdos_renyi_graph<br/>
# > **PARAM** n 300<br/>
# > **PARAM** p 0.1
#
# #### Model definition
#
# > **MODEL** SIR
# >
# > **STATUS** Susceptible <br/>
# > **STATUS** Infected <br/>
# > **STATUS** Removed <br/>
# >
# > **COMPARTMENT** c1 <br/>
# > **TYPE** NodeStochastic<br/>
# > **PARAM** rate 0.1<br/>
# > **TRIGGER** Infected
# >
# > **COMPARTMENT** c2<br/>
# > **TYPE** NodeStochastic<br/>
# > **PARAM** rate 0.1
# >
# > **RULE**<br/>
# > **FROM** Susceptible<br/>
# > **TO** Infected<br/>
# > **USING** c1
# >
# > **RULE**<br/>
# > **FROM** Infected<br/>
# > **TO** Removed<br/>
# > **USING** c2
#
# #### Simulation initialization and execution
#
# > **INITIALIZE**<br/>
# > **SET** Infected 0.1<br/>
# >
# > **EXECUTE** SIR **ON** g1 **FOR** 100
#
# The complete query can be find in ``data/ndql_sir.txt``.
# + [markdown] nbpresent={"id": "dd77cdb3-9443-49c2-be1f-5d9bf890b3ba"} id="Fv6JfsVohD4w"
# In order to translate our query into the corresponding python script we can run
# + nbpresent={"id": "88a0915e-37d2-4e28-953f-94f0e604e81a"} id="qtvYY0rkhD4x"
# !NDQL_translate data/ndql_sir.txt data/sir_g.py
# + nbpresent={"id": "cb4b21c8-c884-4c34-a071-2adcc0f9c583"} id="m2xCK2I-hD4x" outputId="8da90acd-f39f-4c8b-fb10-d4b3c645b964"
# !python data/sir_g.py
# + [markdown] nbpresent={"id": "4b481601-e190-4359-a541-809eacddb7ec"} id="kWoTmIQwhD4x"
# The translated script is then
# + nbpresent={"id": "a3a08442-2cf5-452a-a366-92c0240fd0d5"} id="Ot-h0g4khD4x" outputId="3a70df59-1211-48bf-8212-1690c2567ec1"
with open("data/sir_g.py") as f:
l = f.read()
print(l)
# + [markdown] nbpresent={"id": "bd098043-0eb5-4cff-8615-2ff87712f004"} id="lyj0iNk1hD4x"
# In order to execute the query we can run
# + nbpresent={"id": "6e76a5e5-a340-46c2-801b-0101dbaaab2f"} id="T8qZHBgGhD4y"
# !NDQL_execute data/ndql_sir.txt data/res.json
# + [markdown] nbpresent={"id": "3736aa2c-e373-4dc9-b66b-ad6acbaaee65"} id="FAUUDMP-hD4y"
# As result we get
# + nbpresent={"id": "3e028c60-fc4e-49d9-8c4c-1d80de6b5550"} id="EB8Fw7eChD4y" outputId="dee00e92-a5c9-4e43-9080-57e53fa8fb74"
with open("data/res.json") as f:
l = f.read()
print(l)
# + [markdown] nbpresent={"id": "04ab94e9-6b79-412d-996c-6c6f1b02f003"} id="ug3TZ65-hD4y"
# <a id="conclusion"></a>
# ## 9. Conclusions ([to top](#top))
#
# + [markdown] nbpresent={"id": "d741d711-e149-4ace-8de4-51140fa190f8"} id="_dcfyTEMhD4y"
# In this notebook we introduced the basic facilities offered by ``NDlib``.
#
# For any issue, suggestion, bug report feel free to contact us on the official [GitHub repository](https://github.com/GiulioRossetti/ndlib) of the project.
#
# Moreover, give also a look to [``NDlib-REST``](https://github.com/GiulioRossetti/ndlib-rest) and [``NDlib-viz``](https://github.com/rinziv/NDLib-Viz) the experiment server and web-based visual interface built on top of our library.
# + nbpresent={"id": "3b74b409-b3f4-41a2-8de2-6035e50f6424"} id="1Zh_hFVPhD4z"
| NDlib.ipynb |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: collapsed,code_folding
# formats: ipynb,py
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# language_info:
# codemirror_mode:
# name: ipython
# version: 3
# file_extension: .py
# mimetype: text/x-python
# name: python
# nbconvert_exporter: python
# pygments_lexer: ipython3
# version: 3.6.9
# latex_envs:
# LaTeX_envs_menu_present: true
# autoclose: false
# autocomplete: true
# bibliofile: biblio.bib
# cite_by: apalike
# current_citInitial: 1
# eqLabelWithNumbers: true
# eqNumInitial: 1
# hotkeys:
# equation: Ctrl-E
# itemize: Ctrl-I
# labels_anchors: false
# latex_user_defs: false
# report_style_numbering: false
# user_envs_cfg: false
# ---
# # Alternative Combinations of Parameter Values
#
# Please write the names and email addresses of everyone who worked on this notebook on the line below.
#
# YOUR NAMES HERE
#
# ## Introduction
#
# The notebook "Micro-and-Macro-Implications-of-Very-Impatient-HHs" is an exercise that demonstrates the consequences of changing a key parameter of the [cstwMPC](http://econ.jhu.edu/people/ccarroll/papers/cstwMPC) model, the time preference factor $\beta$.
#
# The [REMARK](https://github.com/econ-ark/REMARK) `SolvingMicroDSOPs` reproduces the last figure in the [SolvingMicroDSOPs](http://econ.jhu.edu/people/ccarroll/SolvingMicroDSOPs) lecture notes, which shows that there are classes of alternate values of $\beta$ and $\rho$ that fit the data almost as well as the exact 'best fit' combination.
#
# Inspired by this comparison, this notebook asks you to examine the consequences for:
#
# * The consumption function
# * The distribution of wealth
#
# Of _joint_ changes in $\beta$ and $\rho$ together.
#
# One way you can do this is to construct a list of alternative values of $\rho$ (say, values that range upward from the default value of $\rho$, in increments of 0.2, all the way to $\rho=5$). Then for each of these values of $\rho$ you will find the value of $\beta$ that leads the same value for target market resources, $\check{m}$.
#
# As a reminder, $\check{m}$ is defined as the value of $m$ at which the optimal value of ${c}$ is the value such that, at that value of ${c}$, the expected level of ${m}$ next period is the same as its current value:
#
# $\mathbb{E}_{t}[{m}_{t+1}] = {m}_{t}$
#
# Other notes:
# * The cstwMPC model solves and simulates the problems of consumers with 7 different values of $\beta$
# * You should do your exercise using the middle value of $\beta$ from that exercise:
# * `DiscFac_mean = 0.9855583`
# * You are likely to run into the problem, as you experiment with parameter values, that you have asked HARK to solve a model that does not satisfy one of the impatience conditions required for the model to have a solution. Those conditions are explained intuitively in the [TractableBufferStock](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/TractableBufferStock/) model. The versions of the impatience conditions that apply to the $\texttt{IndShockConsumerType}$ model can be found in the paper [BufferStockTheory](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory), table 2.
# * The conditions that need to be satisfied are:
# * The Growth Impatience Condition (GIC)
# * The Return Impatience Condition (RIC)
# * Please accumulate the list of solved consumers' problems in a list called `MyTypes`
# * For compatibility with a further part of the assignment below
# + code_folding=[]
# This cell merely imports and sets up some basic functions and packages
# %matplotlib inline
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
from copy import deepcopy
import HARK # Prevents import error from Demos repo
from HARK.utilities import plotFuncs
# + code_folding=[0, 4]
# Import IndShockConsumerType
from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType
# Define a dictionary with calibrated parameters
cstwMPC_calibrated_parameters = {
"CRRA":1.0, # Coefficient of relative risk aversion
"Rfree":1.01/(1.0 - 1.0/160.0), # Survival probability,
"PermGroFac":[1.000**0.25], # Permanent income growth factor (no perm growth),
"PermGroFacAgg":1.0,
"BoroCnstArt":0.0,
"CubicBool":False,
"vFuncBool":False,
"PermShkStd":[(0.01*4/11)**0.5], # Standard deviation of permanent shocks to income
"PermShkCount":5, # Number of points in permanent income shock grid
"TranShkStd":[(0.01*4)**0.5], # Standard deviation of transitory shocks to income,
"TranShkCount":5, # Number of points in transitory income shock grid
"UnempPrb":0.07, # Probability of unemployment while working
"IncUnemp":0.15, # Unemployment benefit replacement rate
"UnempPrbRet":None,
"IncUnempRet":None,
"aXtraMin":0.00001, # Minimum end-of-period assets in grid
"aXtraMax":40, # Maximum end-of-period assets in grid
"aXtraCount":32, # Number of points in assets grid
"aXtraExtra":[None],
"aXtraNestFac":3, # Number of times to 'exponentially nest' when constructing assets grid
"LivPrb":[1.0 - 1.0/160.0], # Survival probability
"DiscFac":0.97, # Default intertemporal discount factor; dummy value, will be overwritten
"cycles":0,
"T_cycle":1,
"T_retire":0,
'T_sim':1200, # Number of periods to simulate (idiosyncratic shocks model, perpetual youth)
'T_age': 400,
'IndL': 10.0/9.0, # Labor supply per individual (constant),
'aNrmInitMean':np.log(0.00001),
'aNrmInitStd':0.0,
'pLvlInitMean':0.0,
'pLvlInitStd':0.0,
'AgentCount':10000,
}
# -
# Construct a list of solved consumers' problems, IndShockConsumerType is just a place holder
MyTypes = [IndShockConsumerType(**cstwMPC_calibrated_parameters)]
# ## Simulating the Distribution of Wealth for Alternative Combinations
#
# You should now have constructed a list of consumer types all of whom have the same _target_ level of market resources $\check{m}$.
#
# But the fact that everyone has the same target ${m}$ does not mean that the _distribution_ of ${m}$ will be the same for all of these consumer types.
#
# In the code block below, fill in the contents of the loop to solve and simulate each agent type for many periods. To do this, you should invoke the methods $\texttt{solve}$, $\texttt{initializeSim}$, and $\texttt{simulate}$ in that order. Simulating for 1200 quarters (300 years) will approximate the long run distribution of wealth in the population.
for ThisType in tqdm(MyTypes):
ThisType.solve()
ThisType.initializeSim()
ThisType.simulate()
# Now that you have solved and simulated these consumers, make a plot that shows the relationship between your alternative values of $\rho$ and the mean level of assets
# +
# To help you out, we have given you the command needed to construct a list of the levels of assets for all consumers
aLvl_all = np.concatenate([ThisType.aLvlNow for ThisType in MyTypes])
# You should take the mean of aLvl for each consumer in MyTypes, divide it by the mean across all simulations
# and then plot the ratio of the values of mean(aLvl) for each group against the value of $\rho$
# -
# # Interpret
# Here, you should attempt to give an intiutive explanation of the results you see in the figure you just constructed
# ## The Distribution of Wealth...
#
# Your next exercise is to show how the distribution of wealth differs for the different parameter values
# +
from HARK.utilities import getLorenzShares, getPercentiles
# Finish filling in this function to calculate the Euclidean distance between the simulated and actual Lorenz curves.
def calcLorenzDistance(SomeTypes):
'''
Calculates the Euclidean distance between the simulated and actual (from SCF data) Lorenz curves at the
20th, 40th, 60th, and 80th percentiles.
Parameters
----------
SomeTypes : [AgentType]
List of AgentTypes that have been solved and simulated. Current levels of individual assets should
be stored in the attribute aLvlNow.
Returns
-------
lorenz_distance : float
Euclidean distance (square root of sum of squared differences) between simulated and actual Lorenz curves.
'''
# Define empirical Lorenz curve points
lorenz_SCF = np.array([-0.00183091, 0.0104425 , 0.0552605 , 0.1751907 ])
# Extract asset holdings from all consumer types
aLvl_sim = np.concatenate([ThisType.aLvlNow for ThisType in MyTypes])
# Calculate simulated Lorenz curve points
lorenz_sim = getLorenzShares(aLvl_sim,percentiles=[0.2,0.4,0.6,0.8])
# Calculate the Euclidean distance between the simulated and actual Lorenz curves
lorenz_distance = np.sqrt(np.sum((lorenz_SCF - lorenz_sim)**2))
# Return the Lorenz distance
return lorenz_distance
# -
# ## ...and the Marginal Propensity to Consume
#
# Now let's look at the aggregate MPC. In the code block below, write a function that produces text output of the following form:
#
# $\texttt{The 35th percentile of the MPC is 0.15623}$
#
# Your function should take two inputs: a list of types of consumers and an array of percentiles (numbers between 0 and 1). It should return no outputs, merely print to screen one line of text for each requested percentile. The model is calibrated at a quarterly frequency, but Carroll et al report MPCs at an annual frequency. To convert, use the formula:
#
# $\kappa_{Y} \approx 1.0 - (1.0 - \kappa_{Q})^4$
# +
# Write a function to tell us about the distribution of the MPC in this code block, then test it!
# You will almost surely find it useful to use a for loop in this function.
def describeMPCdstn(SomeTypes,percentiles):
MPC_sim = np.concatenate([ThisType.MPCnow for ThisType in SomeTypes])
MPCpercentiles_quarterly = getPercentiles(MPC_sim,percentiles=percentiles)
MPCpercentiles_annual = 1.0 - (1.0 - MPCpercentiles_quarterly)**4
for j in range(len(percentiles)):
print('The ' + str(100*percentiles[j]) + 'th percentile of the MPC is ' + str(MPCpercentiles_annual[j]))
describeMPCdstn(MyTypes,np.linspace(0.05,0.95,19))
# -
# # If You Get Here ...
#
# If you have finished the above exercises quickly and have more time to spend on this assignment, for extra credit you can do the same exercise where, instead of exploring the consequences of alternative values of relative risk aversion $\rho$, you should test the consequences of different values of the growth factor $\Gamma$ that lead to the same $\check{m}$.
| notebooks/Alternative-Combos-Of-Parameter-Values.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
import importlib
from os import listdir
from os.path import isfile, join
def class_for_name(module_name, class_name):
try:
# load the module, will raise ImportError if module cannot be loaded
m = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)()
return c
except:
print('Could not load module: '+module_name+'.'+class_name)
return -1
#Data: dataset to test (from the test datasets that illustrate different requirements)
#Primitive: primitive being tested. We assume it has the fit() method
def passTest(data, primitive):
target = data.iloc[:,-1]
train = data.drop(data.columns[[len(data.columns)-1]], axis=1) #drop target column (the last one)
try:
y_pred = primitive.fit(train,target)#.predict(train)# Not all primitives have a predict, but should have fit
print("PASSED: "+data.name)
except:
print("NOT PASSED: " +data.name)
#CASE HERE with all the values to be printed
#Path: String with the path to the dataset folders. The system assumes to have three: clean_data,
#requirement_data and performance_data
#Primitive module name: string with the module name. E.g., 'sklearn.svm'
#Primitive name: string with the name of the primitive to be loaded. E.g., 'SVC'
#testPerformance: boolean that is true if you want to test the performance tests (will require more time)
def getPrimitiveRequirements(path, primitiveModuleName, primitiveName, testPerformance):
CLEAN = path + "clean_data"
REQ = path + "requirement_data"
PERF = path + "performance_data"
#module = importlib.import_module(primitiveModuleName)
#prim = getattr(module, primitiveName)()
prim = class_for_name(primitiveModuleName,primitiveName)
if(prim == -1):
return
#Clean data files
data_clean_int = pd.read_csv(CLEAN +'/int_clean_data.csv')
data_clean_int.name = "CLEAN DATA INT"
data_clean_float = pd.read_csv(CLEAN +'/float_clean_data.csv')
data_clean_float.name = "CLEAN DATA FLOAT"
passTest(data_clean_int, prim)
passTest(data_clean_float, prim)
#TESTS (this should be a method)
onlyfiles = [f for f in listdir(REQ) if isfile(join(REQ, f))]
#print(onlyfiles)
for d in onlyfiles:
data = pd.read_csv(REQ+"/"+d)
data.name = d
passTest(data, prim)
DATADIR = "data_profiler/"
print('sklearn.svm.SVC')
getPrimitiveRequirements(DATADIR,'sklearn.svm','SVC','false')
print('sklearn.linear_model.LogisticRegression')
getPrimitiveRequirements(DATADIR,'sklearn.linear_model','LogisticRegression','false')
# +
#Files with different issues: missing values, constant values, etc.
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(REQ) if isfile(join(REQ, f))]
#print(onlyfiles)
for d in onlyfiles:
data = pd.read_csv(DATADIR+"/requirement_data"+"/"+d)
data.name = d
passTest(data, prim)
#Files with the performance (TO DO)
# -
| .ipynb_checkpoints/Primitive profiler-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Predicting the phase transition of the two dimensional Ising model using neural networks
#
# We will in this notebook repeat the process of predicting the phase transition of the two dimensional Ising model as we did with logistic regression, but now we will employ a _feed-forwad neural network_.
# ## Predicting the phase of the two-dimensional Ising model using a feed-forward neural network
#
# We now predict the phase transition using Scikit-learn's implementation of a _multilayer perceptron neural network_. This is one of the simpler versions of a neural network.
#
# A neural network consists of layers of _neurons_ or perceptrons. A neuron can take a continuous value where as a perceptron will be either "on" or "off". Scikit-learn's `MLPClassifier` is called a multilayer perceptron model, but it uses neurons. A neuron accepts a vector of inputs $x$ and produces a scalar output $a_i$. A layer of neurons take in the a matrix $X$ and produces an activation vector $a$ consisting of each $a_i$ from each neuron in that layer.
#
# \begin{align}
# z^{(l)} = a^{(l - 1)}w^{(l)} + b^{(l)},
# \end{align}
#
# where $w^{(l)}$ is that layers _weights_ and $b^{(l)}$ is that layers _biases_. The activation $a^{(l)}$ is now computed by
#
# \begin{align}
# a^{(l)} = f(z^{(l)}),
# \end{align}
#
# where $f(z)$ is an _activation function_. The first activation is given by $a^{(0)} = X$, where $X$ is the input data.
#
# It is common to use the cross-entropy as the cost function for a categorical neural network. This is the same the one used in logistic regression.
# ### Training a neural network
#
# The training of a neural network is a tricky affair as each neuron in each layer must be updated to minimize a cost function. The minimization process resembles that of other classifiers and regressors in that we use an optimization algorithm, e.g., stochastic gradient descent, to compute the change in the weights and biases in order to find a minimum of the cost function. The tricky part comes in computing the gradients of the weights and biases in the neural network. Due to an ingenious technique called _backpropagation_ this can be done within reasonable time. The algorithm is listed below.
#
# 1. Do a feedforward pass, i.e., compute all activations $a^{(l)}$ as listed above.
# 2. Calculate the error of the weights and biases using
# \begin{align}
# \delta_{j}^{(l)} = \frac{\partial C}{\partial a_{j}^{(l)}} \frac{\mathrm{d}f(z_j^{(l)})}{\mathrm{d}z}.
# \end{align}
# 3. Propagate the error backwards (hence backpropagation) using
# \begin{align}
# \delta_{j}^{(l)} = \left(
# \sum_{k}\delta_k^{(l + 1)}\omega_{kj}^{(l + 1)}
# \right)\frac{\mathrm{d}f(z_j^{(l)}}{\mathrm{d}z}.
# \end{align}
# 4. Compute the change in the gradients of the weights and biases.
# \begin{align}
# \omega^{(l)} &\to \omega^{(l)} - \frac{\eta}{m}\sum_{k}\delta^{(l)}_ka_k^{(l - 1)}, \\
# b^{(l)} &\to b^{(l)} - \frac{\eta}{m}\sum_{k}\delta^{(l)}_k,
# \end{align}
# where $\eta$ is the learning rate and $m$ is the number of elements (batch size in the case of stochastic gradient descent).
# We will do a large search over a two-dimensional parameter grid for varying hidden layer sizes and learning rate.
# ## DIY Neural net from Keras
#
#
# An easier approach is to use libraries such as Tensorflow or Keras (which by default uses Tensorflow as a backend) to specify how the neural net should be. The libraries then build a neural net based on your specifications and lets you fit and predict on your very own construct. As a bonus, Tensorflow builds a graph from the executing code thus figuring out the most optimal way of executing the code and which parts of the code that can be done in parallel.
#
# A perk of building a neural net this way is that we have a lot of freedom in how we build our neural net. For instance, we can set individual activation functions for each layer, decide the optimization technique to use, the cost function to minimize, which metric to evaluate our model on etc.
# We now build a neural net from Keras with three hidden layers. The input and the hidden layer uses the activation function
#
# \begin{align}
# f(z_j) = \tanh(z_j),
# \end{align}
#
# whereas the output layer uses the _softmax_ activation function.
#
# \begin{align}
# g(z_j) = \frac{e^{z_j}}{\sum_{i = 1}^{n} e^{z_i}}.
# \end{align}
#
# We avoid using the tangent hyperbolicus for the output layer as $f(z_j) \in [-1, 1]$ as opposed to the softmax function with $g(z_j) \in [0, 1]$. The latter more fits the categorical classification. Another perk of using the softmax activation function is that it better weighs all the classes in a multiclassification setting much as the partition function. We use stochastic gradient descent as our optimizer and the cross-entropy (shown in the notebook on logistic regression) as our cost function.
# +
clf = km.Sequential()
clf.add(
kl.Dense(50, activation="tanh", input_dim=X_train.shape[1])
)
clf.add(
kl.Dense(100, activation="tanh")
)
clf.add(
kl.Dense(200, activation="tanh")
)
clf.add(
kl.Dense(2, activation="softmax")
)
clf.compile(
loss="binary_crossentropy",
optimizer=ko.SGD(
lr=0.01
),
metrics=["accuracy"]
)
# -
# We have to convert our integer labels to categorical values in a format that Keras accepts.
y_train_k = to_categorical(y_train[:, np.newaxis])
y_test_k = to_categorical(y_test[:, np.newaxis])
y_critical_k = to_categorical(labels[critical][:, np.newaxis])
# We now fit our model for $10$ epochs and validate on the test data.
history = clf.fit(
X_train, y_train_k,
validation_data=(X_test, y_test_k),
epochs=10,
batch_size=200,
verbose=True
)
# We now evaluate the model.
# +
train_accuracy = clf.evaluate(X_train, y_train_k, batch_size=200)[1]
test_accuracy = clf.evaluate(X_test, y_test_k, batch_size=200)[1]
critical_accuracy = clf.evaluate(data[critical], y_critical_k, batch_size=200)[1]
print ("Accuracy on train data: {0}".format(train_accuracy))
print ("Accuracy on test data: {0}".format(test_accuracy))
print ("Accuracy on critical data: {0}".format(critical_accuracy))
# -
# Then we plot the ROC curve for three datasets.
# +
fig = plt.figure(figsize=(20, 14))
for (_X, _y), label in zip(
[
(X_train, y_train_k),
(X_test, y_test_k),
(data[critical], y_critical_k)
],
["Train", "Test", "Critical"]
):
proba = clf.predict(_X)
fpr, tpr, _ = skm.roc_curve(_y[:, 1], proba[:, 1])
roc_auc = skm.auc(fpr, tpr)
print ("Keras AUC ({0}): {1}".format(label, roc_auc))
plt.plot(fpr, tpr, label="{0} (AUC = {1})".format(label, roc_auc), linewidth=4.0)
plt.plot([0, 1], [0, 1], "--", label="Guessing (AUC = 0.5)", linewidth=4.0)
plt.title(r"The ROC curve for Keras", fontsize=18)
plt.xlabel(r"False positive rate", fontsize=18)
plt.ylabel(r"True positive rate", fontsize=18)
plt.axis([-0.01, 1.01, -0.01, 1.01])
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
plt.legend(loc="best", fontsize=18)
plt.show()
# -
# We see that we get much the same performance as for the `MLPClassifier` from Scikit-learn.
# ## Conclusion
#
# We have successfully used a neural net using Keras and predicted the phase transition of the two-dimensional Ising model. As opposed to the logistic regression we get a much better performance on all datasets. More importantly we successfully predict reasonable values on the critical dataset which is extrapolated from the training and testing data.
| doc/Programs/IsingModel/neuralnetIsing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Super Scratcher
# This is a simple (but powerful) example of grabbing all the stuff from Rotten Tomato website via given list of movies.
# + pycharm={"name": "#%%\n"}
from goje_scrapper.goje import *
import pymongo
# + pycharm={"name": "#%%\n"}
goje_jaan = GojeScraper()
movie_list = goje_jaan.extract_movie_links(1990,1991)
# movie_list[i][0] = movie name
# movie_list[i][1] = movie release year
# movie_list[i][2] = movie link
# +
myclient = pymongo.MongoClient('mongodb://localhost:27017/',
username='root',
password='<PASSWORD>')
mydb = myclient["tomato"]
mycol = mydb["1990"]
# -
for m in movie_list:
# scrape the movie metadata
movie_scraper = GojeScraper(movie_url=m[2])
movie_scraper.extract_metadata()
# scrape all critic reviews
review_list = list()
try:
movie_scraper.number_of_review_pages()
for i in range(1,movie_scraper.number_of_review_pages()):
review_list.append(movie_scraper.extract_critic_reviews(page_number=movie_scraper.number_of_review_pages()))
except IndexError:
review_list.append(movie_scraper.extract_critic_reviews())
# scrape audiance reviews (1000#)
all_audience_reviews = movie_scraper.extract_all_audience_reviews(page_number=100)
print("scape of {} done!".format(m[0]))
mydict = { "movie_name": m[0] , "info": movie_scraper.metadata , "critic_reviews": review_list , "audience_reviews": all_audience_reviews}
x = mycol.insert_one(mydict)
print("storing {} into DB done!".format(m[0]))
# ### Resolve the Critic Reviews
# + pycharm={"name": "#%%\n"}
review_list = list()
try:
movie_scraper.number_of_review_pages()
for i in range(1,movie_scraper.number_of_review_pages()):
review_list.append(movie_scraper.extract_critic_reviews(page_number=movie_scraper.number_of_review_pages()))
print("page {0} is scrapped!".format(i))
except IndexError:
review_list.append(movie_scraper.extract_critic_reviews())
print(review_list)
# -
# ### Resolve the Audience Reviews
# + pycharm={"name": "#%%\n"}
all_audience_reviews = movie_scraper.extract_all_audience_reviews(page_number=100)
print(all_audience_reviews)
# + pycharm={"name": "#%%\n"}
myclient = pymongo.MongoClient('mongodb://localhost:27017/',
username='root',
password='<PASSWORD>')
# + pycharm={"name": "#%%\n"}
print(myclient.list_database_names())
# + pycharm={"name": "#%%\n"}
mydb = myclient["tomato"]
mycol = mydb["movie"]
# + pycharm={"name": "#%%\n"}
mycol
# + pycharm={"name": "#%%\n"}
print(mydb.list_collection_names())
# + pycharm={"name": "#%%\n"}
mydb = myclient["tomato"]
mycol = mydb["movie"]
mydict = { "movie_name": movie_url.split("/m/")[1] , "info": movie_scraper.metadata , "critic_reviews": review_list , "audience_reviews": all_audience_reviews }
x = mycol.insert_one(mydict)
# + pycharm={"name": "#%%\n"}
mycol
# + pycharm={"name": "#%%\n"}
len(all_audience_reviews)
# + pycharm={"name": "#%%\n"}
# + pycharm={"name": "#%%\n"}
for m in movie_list:
print(m[2])
| super_scratcher.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# ## 基礎題 - 算出斜率w與截距b
#
# y = wx + b
#
# 記得計算前X須符合資料格式
# $$[x_1, x_2, \ldots, x_{50}]$$
#
# ==>
#
# $$[[x_1], [x_2], \ldots, [x_{50}]]$$
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.array([ 0. , 0.20408163, 0.40816327, 0.6122449 , 0.81632653,
1.02040816, 1.2244898 , 1.42857143, 1.63265306, 1.83673469,
2.04081633, 2.24489796, 2.44897959, 2.65306122, 2.85714286,
3.06122449, 3.26530612, 3.46938776, 3.67346939, 3.87755102,
4.08163265, 4.28571429, 4.48979592, 4.69387755, 4.89795918,
5.10204082, 5.30612245, 5.51020408, 5.71428571, 5.91836735,
6.12244898, 6.32653061, 6.53061224, 6.73469388, 6.93877551,
7.14285714, 7.34693878, 7.55102041, 7.75510204, 7.95918367,
8.16326531, 8.36734694, 8.57142857, 8.7755102 , 8.97959184,
9.18367347, 9.3877551 , 9.59183673, 9.79591837, 10. ])
y = np.array([ 0.85848224, -0.10657947, 1.42771901, 0.53554778, 1.20216826,
1.81330509, 1.88362644, 2.23557653, 2.7384889 , 3.41174583,
4.08573636, 3.82529502, 4.39723111, 4.8852381 , 4.70092778,
4.66993962, 6.05133235, 5.44529881, 7.22571332, 6.79423911,
7.05424438, 7.00413058, 7.98149596, 7.00044008, 7.95903855,
9.96125238, 9.06040794, 9.56018295, 9.30035956, 9.26517614,
9.56401824, 10.07659844, 11.56755942, 11.38956185, 11.83586027,
12.45642786, 11.58403954, 11.60186428, 13.88486667, 13.35550112,
13.93938726, 13.31678277, 13.69551472, 14.76548676, 14.81731598,
14.9659187 , 15.19213921, 15.28195017, 15.97997265, 16.41258817])
#匯入在sklearn.linear_model套件裡面的LinearRegression模型
from sklearn.linear_model import LinearRegression
#將模型工具指派給一變數做使用
LR = LinearRegression()
#注意轉換x得格式1D->2D
X = x.reshape(-1, 1)
# print(X.shape)
#將x,y資料導入LinearRegression演算法做訓練
LR.fit(X,y)
#列印出訓練完成之函數的斜率與截距
print('斜率: ', LR.coef_)
print('截距: ', LR.intercept_)
# ## 進階題 - 切割資料集分別做訓練與預測(訓練資料80%、測試資料20%)
#
# +
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.array([ 0. , 0.20408163, 0.40816327, 0.6122449 , 0.81632653,
1.02040816, 1.2244898 , 1.42857143, 1.63265306, 1.83673469,
2.04081633, 2.24489796, 2.44897959, 2.65306122, 2.85714286,
3.06122449, 3.26530612, 3.46938776, 3.67346939, 3.87755102,
4.08163265, 4.28571429, 4.48979592, 4.69387755, 4.89795918,
5.10204082, 5.30612245, 5.51020408, 5.71428571, 5.91836735,
6.12244898, 6.32653061, 6.53061224, 6.73469388, 6.93877551,
7.14285714, 7.34693878, 7.55102041, 7.75510204, 7.95918367,
8.16326531, 8.36734694, 8.57142857, 8.7755102 , 8.97959184,
9.18367347, 9.3877551 , 9.59183673, 9.79591837, 10. ])
y = np.array([ 0.85848224, -0.10657947, 1.42771901, 0.53554778, 1.20216826,
1.81330509, 1.88362644, 2.23557653, 2.7384889 , 3.41174583,
4.08573636, 3.82529502, 4.39723111, 4.8852381 , 4.70092778,
4.66993962, 6.05133235, 5.44529881, 7.22571332, 6.79423911,
7.05424438, 7.00413058, 7.98149596, 7.00044008, 7.95903855,
9.96125238, 9.06040794, 9.56018295, 9.30035956, 9.26517614,
9.56401824, 10.07659844, 11.56755942, 11.38956185, 11.83586027,
12.45642786, 11.58403954, 11.60186428, 13.88486667, 13.35550112,
13.93938726, 13.31678277, 13.69551472, 14.76548676, 14.81731598,
14.9659187 , 15.19213921, 15.28195017, 15.97997265, 16.41258817])
# -
#匯入在sklearn.linear_model套件裡面的LinearRegression模型
from sklearn.linear_model import LinearRegression
#匯入在sklearn.model_selection套件裡面的train_test_split模組
from sklearn.model_selection import train_test_split
#切割數據集(訓練資料80%、測試資料20%,設定random_state=20)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=20)
#畫出訓練資料集的matplotlib圖形m
plt.scatter(x_train, y_train)
# ## 用訓練資料來 fit 函數
# 1. 只用訓練資料集的資料進行linear regression演算法<br>
# 2. 並計算出訓練階段的MSE
# 3. 畫出目標點(藍色)與預測點(紅色)的對應圖
# 
# +
regr = LinearRegression()
regr.fit(X_train,y_train)
X_train = x_train.reshape(-1,1)
Y_train = regr.predict(X_train)
mse = np.sum((Y_train-y_train)**2) / len(y_train)
print(mse)
# -
plt.scatter(x_train, y_train)
plt.plot(x_train, Y_train, 'r')
# ## 將訓練出來的函數預測測試集的X值
# 1. 使用剛剛訓練出來的模型進行測試資料集的資料預測*注意reshape<br>
# 使用X = 2.44897959,預測出來數值應該為 4.3025375<br>
# 所有測試集資料
# $$\widehat{y}=xw+b=w_{1}x_{1}+b$$
w = regr.coef_[0]
b = regr.intercept_
print(w, b)
X = 2.44897959
print(X * w + b)
Y_test = regr.predict(x_test.reshape(-1, 1))
Y_test
# 2. 並計算出測試階段的MSE
mse = np.sum((Y_test-y_test)**2) / len(y_test)
print(mse)
# 3. 畫出目標點(藍色)與預測點(紅色)的對應圖
# 
plt.scatter(x_test, y_test)
print(x_test.shape, Y_test.shape)
plt.scatter(x_test, Y_test, c='r')
| Unit04/Linear Regression_HW.ipynb |