text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
!pip3 install requests
```
# Скачиваем мемы
```
import requests
url = 'http://books.toscrape.com/'
res = requests.get(url)
res
url = 'http://books.toscrape.com/jfeahiogeoierg'
res = requests.get(url)
res
url = 'https://knowyourmeme.com/memes'
res = requests.get(url)
res
res.headers
from fake_useragent import UserAgent
UserAgent().chrome
response = requests.get(url, headers={'User-Agent': UserAgent().chrome})
response
from bs4 import BeautifulSoup
# распарсили страничку в дерево
tree = BeautifulSoup(response.content, 'html.parser')
tree.head.text
tree.head.text.strip()
table = tree.find('table', {'class': 'entry_list'})
items = table.find_all('a', {'class': 'photo'})
items[0]
items[0].text
items[0].get("href")
items[0].img
items[0].img.get('alt')
def get_hrefs(p):
url = f'https://knowyourmeme.com/memes/page/{p}'
response = requests.get(url, headers={'User-Agent': UserAgent().chrome})
tree = BeautifulSoup(response.content, 'html.parser')
table = tree.find('table', {'class': 'entry_list'})
items = table.find_all('a', {'class': 'photo'})
infa = {
'name': [x.img.get('alt') for x in items],
'href': [x.get("href") for x in items],
}
return infa
from tqdm import tqdm
infa = {'name': [], 'href': []}
for i in tqdm(range(10)):
cur = get_hrefs(i)
infa['name'].extend(cur['name'])
infa['href'].extend(cur['href'])
import pandas as pd
df = pd.DataFrame(infa)
df.head()
df.to_csv('memes_data.csv', sep='\t', index=None)
```
# Скачиваем табличку с сайта ЦБ
```
resp = requests.get('https://cbr.ru/currency_base/daily/')
tree = BeautifulSoup(resp.content, 'html.parser')
# нашли табличку
table = tree.find_all('table', {'class' : 'data'})[0]
# распарсили её
df = pd.read_html(str(table), header=None)[0]
df.head()
```
# API Вконтакте
```
with open('secret.txt', 'r') as f:
token = f.readlines()
token = ''.join(token)
version = '5.103'
method = 'users.get'
parameters = 'user_ids=6045249'
url = 'https://api.vk.com/method/' + method + '?' + parameters + '&v=' + version + '&access_token=' + token
response = requests.get(url)
response.json()
def vk_download(method, parameters):
url = 'https://api.vk.com/method/' + method + '?' + parameters + '&v=' + version + '&access_token=' + token
response = requests.get(url)
return response.json()['response']
vk_download('users.get', 'user_ids=6045249')
inf = vk_download('users.get', 'user_ids=6045249,1,100,151317520,mylibenliska&fields=bdate,about')
df = pd.DataFrame(inf)
df
inf[0]
```
# Selenium
```
from selenium import webdriver
driver = webdriver.Chrome('./chromedriver')
ref = 'http://google.com'
driver.get(ref)
stroka = driver.find_element_by_name("q")
stroka.click()
stroka.send_keys('Вконтакте')
button = driver.find_element_by_name('btnK')
button.click()
bs = BeautifulSoup(driver.page_source)
dirty_hrefs = bs.find_all('h3',attrs={'class':'r'})
clean_hrefs = [href.a['href'] for href in dirty_hrefs]
clean_hrefs
driver.close()
```
| github_jupyter |
## human judgement data
---
examining some of the human judgement data
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.image as mpimg
from PIL import Image
import progressbar
human_df = pd.read_csv('human_data.csv')
human_df.head()
```
---
data in form left image location, right image location, and a binary variable indicating if the subject chose the left (1) or right (0) image as a better representation of the original. note that the order of compression switches randomly.
---
```
# data sample
f, axarr = plt.subplots(nrows=3, ncols=3, figsize=(9,9))
for ii in range(3):
index = np.random.randint(4040)
temp_left = mpimg.imread('iclr_images/' + human_df['left_file'][index][1:-1])
temp_right = mpimg.imread('iclr_images/' + human_df['right_file'][index][1:-1])
temp_orig = mpimg.imread('iclr_images/' + human_df['orig_file'][index][1:-1])
axarr[ii][0].imshow(temp_orig, cmap='gray')
if human_df['response_left'][index] == 1:
axarr[ii][1].imshow(temp_left, cmap='gray')
axarr[ii][2].imshow(temp_right, cmap='gray')
else:
axarr[ii][2].imshow(temp_left, cmap='gray')
axarr[ii][1].imshow(temp_right, cmap='gray')
for ax_row in axarr:
for ax in ax_row:
ax.set_xticklabels([])
ax.set_yticklabels([])
axarr[0,0].set_title('original', size=15)
axarr[0,1].set_title('preferred', size=15)
axarr[0,2].set_title('rejected', size=15)
# plt.savefig('human_pref.png')
plt.show()
import matplotlib.gridspec as gridspec
plt.figure(figsize = (12,12))
gs1 = gridspec.GridSpec(3, 3)
gs1.update(wspace=0.03, hspace=0.03)
ax_dict = {}
for ii in range(9):
ax_dict[ii] = plt.subplot(gs1[ii])
ax_dict[ii].set_xticklabels([])
ax_dict[ii].set_yticklabels([])
ax_dict[ii].get_xaxis().set_visible(False)
ax_dict[ii].get_yaxis().set_visible(False)
for ii in range(3):
index = np.random.randint(4040)
temp_left = mpimg.imread('iclr_images/' + human_df['left_file'][index][1:-1])
temp_right = mpimg.imread('iclr_images/' + human_df['right_file'][index][1:-1])
temp_orig = mpimg.imread('iclr_images/' + human_df['orig_file'][index][1:-1])
ax_dict[3*ii].imshow(temp_orig, cmap='gray')
if human_df['response_left'][index] == 1:
ax_dict[3*ii+1].imshow(temp_left, cmap='gray')
ax_dict[3*ii+2].imshow(temp_right, cmap='gray')
else:
ax_dict[3*ii+2].imshow(temp_left, cmap='gray')
ax_dict[3*ii+1].imshow(temp_right, cmap='gray')
ax_dict[0].set_title('sample', size=20)
ax_dict[1].set_title('preferred', size=20)
ax_dict[2].set_title('rejected', size=20)
plt.savefig('human.png')
plt.show()
im = Image.open('iclr_images/' + human_df['left_file'][ii][1:-1])
test = np.asarray(im)
test
```
---
now that we have an idea of the human judgement data, we can run ssim and see how well it predicts human behavior.
```
def calculate_ssim_patch(window_orig, window_recon):
k_1, k_2, L = 0.01, 0.03, 255
if window_orig.shape != (11,11) or window_recon.shape != (11,11):
raise ValueError('please check window size for SSIM calculation!')
orig_data, recon_data = window_orig.flatten(), window_recon.flatten()
mean_x, mean_y = np.mean(orig_data), np.mean(recon_data)
var_x, var_y = np.var(recon_data), np.var(orig_data)
covar = np.cov(orig_data, recon_data)[0][1]
c_1, c_2 = (L*k_2)**2, (L*k_1)**2
num = (2*mean_x*mean_y+c_1)*(2*covar+c_2)
den = (mean_x**2+mean_y**2+c_1)*(var_x+var_y+c_2)
return num/den
def calculate_ssim_image(image_orig, image_recon):
ssim_res = []
filter_dim = 11; image_dim = image_orig.shape[0];
number_windows = image_dim - filter_dim + 1
for i in range(number_windows):
for j in range(number_windows):
orig_window = image_orig[i:i+11, j:j+11]
recon_window = image_recon[i:i+11, j:j+11]
temp = calculate_ssim_patch(orig_window, recon_window)
ssim_res.append(temp)
return np.asarray(ssim_res)
bar = progressbar.ProgressBar()
correct = 0
for ii in bar(range(len(human_df['left_file']))):
left_im = Image.open('iclr_images/' + human_df['left_file'][ii][1:-1])
left_im_pix = np.asarray(left_im)
right_im = Image.open('iclr_images/' + human_df['right_file'][ii][1:-1])
right_im_pix = np.asarray(right_im)
orig_im = Image.open('iclr_images/' + human_df['orig_file'][ii][1:-1])
orig_im_pix = np.asarray(orig_im)
left_ssim = calculate_ssim_image(orig_im_pix, left_im_pix)
right_ssim = calculate_ssim_image(orig_im_pix, right_im_pix)
ssims = [np.mean(right_ssim), np.mean(left_ssim)]
if np.argmax(ssims) == human_df['response_left'][ii]:
correct += 1
correct, correct/4040
f, axarr = plt.subplots(nrows=3, ncols=5, figsize=(15,9))
for ii in range(3):
index = np.random.randint(4040)
left_im = Image.open('iclr_images/' + human_df['left_file'][index][1:-1])
left_im_pix = np.asarray(left_im)
right_im = Image.open('iclr_images/' + human_df['right_file'][index][1:-1])
right_im_pix = np.asarray(right_im)
orig_im = Image.open('iclr_images/' + human_df['orig_file'][index][1:-1])
orig_im_pix = np.asarray(orig_im)
left_ssim = calculate_ssim_image(orig_im_pix, left_im_pix)
right_ssim = calculate_ssim_image(orig_im_pix, right_im_pix)
axarr[ii][0].imshow(orig_im_pix, cmap='gray')
axarr[ii][1].imshow(left_im_pix, cmap='gray')
axarr[ii][2].imshow(right_im_pix, cmap='gray')
axarr[ii][3].imshow(np.reshape(left_ssim,(54,54)), cmap='plasma')
axarr[ii][4].imshow(np.reshape(right_ssim,(54,54)), cmap='plasma')
axarr[0,0].set_title('original image', size=15)
axarr[0,1].set_title('left recon', size=15)
axarr[0,2].set_title('right recon', size=15)
axarr[0,3].set_title('left ssim', size=15)
axarr[0,4].set_title('right ssim', size=15)
for ax_row in axarr:
for ax in ax_row:
ax.set_xticklabels([])
ax.set_yticklabels([])
# plt.savefig('human_judge2.png')
plt.show()
```
| github_jupyter |
<font size="+5">#08. Cluster Analysis con k-Means</font>
<ul>
<li>Resolver dudas → Pregunta en <img src="https://discord.com/assets/f9bb9c4af2b9c32a2c5ee0014661546d.png" style="height: 1em; vertical-align: middle;"> <a href="https://discord.gg/cmB3KGsqMy">Discord</a></li>
<li>Tutoriales → <img src="https://openmoji.org/php/download_asset.php?type=emoji&emoji_hexcode=E044&emoji_variant=color" style="height: 1em; vertical-align: middle;"> <a href="https://www.youtube.com/channel/UCovCte2I3loteQE_kRsfQcw">YouTube</a></li>
<li>Reservar Clases → <span style="color: orange">@</span> <a href="https://sotastica.com/reservar">sotastica</a></li>
</ul>
# Cargar Datos
> - Simplemente, copiamos y pegamos las siguientes líneas de código para cargar los datos.
> - La tabla contiene **estadísticas sobre Coches** (columnas).
> - Para distintas **Marcas/Modelos de coche** (filas).
```python
import seaborn as sns
df = sns.load_dataset(name='mpg', index_col='name')
df.sample(10)
```
```
import seaborn as sns
df = sns.load_dataset(name='mpg', index_col='name')
df.sample(10)
```
# Seleccionar 2 Variables para el Análisis de Clúster
> En este caso **ambas variables son explicativas**. La variable que queremos predecir no se la damos al modelo. Sino que tratará de adivinarla en base a cómo de cerca estén los puntos.
```
dfsel = df[['mpg', 'acceleration']].copy()
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
import pandas as pd
dfnorm = pd.DataFrame(scaler.fit_transform(dfsel), columns=dfsel.columns, index=dfsel.index)
```
# Scatterplot con las Variables
> Deberíamos observar en la gráfica cuántos posibles grupos podríamos hacer para agrupar los puntos.
```
sns.scatterplot(x='mpg', y='acceleration', data=dfnorm)
```
# Transformación de los Datos
> Deberíamos valorar si tenemos que realizar algunos cambios a los datos para que el modelo de k-Means se compute adecuadamente y pueda comparar ambas variables.
>
> Las variables originales pueden tener un rango de valores diferente.
>
> Imaginemos que tenemos dos variables:
>
> - Peso (en kilogramos)
> - Altura (en metros)
>
> **Es lo mismo** incrementar 1 kilogramo de peso, que incrementar 1 metro de altura?
>
> - Hazte las mismas preguntas con tus variables.
# Entrenar Modelo `KMeans()`
> Podremos predecir 1, 2, 3,..., k grupos. Tantos como queramos. Sin embargo, seleccionaremos `n_cluster = 3` para no complicarnos la vida.
> 1. **Necesidad:** Entrenar Modelo
> 2. **Solución: Función** `fit()`
```
dfnorm = dfnorm[['mpg', 'acceleration']]
model = KMeans(n_clusters=1)
model.fit(X=dfnorm)
model.inertia_
def calcular_error(pepa):
model = KMeans(n_clusters=pepa)
model.fit(X=dfnorm)
error = model.inertia_
return error
calcular_error(1)
for algo in [1,2,3,4,5,6,7,8,9,10]:
error = calcular_error(algo)
print(error)
wss = []
for algo in [1,2,3,4,5,6,7,8,9,10]:
error = calcular_error(algo)
wss.append(error)
intentos = [1,2,3,4,5,6,7,8,9,10]
wss
sns.scatterplot(x=intentos, y=wss)
sns.lineplot(x=intentos, y=wss)
from sklearn.cluster import KMeans
model = KMeans(n_clusters=3)
model = KMeans(n_clusters=4, verbose=2)
model.fit(X=dfnorm)
```
# Realizar Predicciones
> - `model.predict()`
```
dfpred = dfnorm
dfpred['cluster'] = model.predict(dfnorm)
dfnorm.head()
```
# Visualizar Modelo
> - Scatterplot con puntos coloreados según el grupo al que pertenece cada observación: `hue = model.labels_`
> - Añade otra capa de puntos, los cuales indicarán los centroides (se encuentran en `model.cluster_centers_`)
```
df_centroides = pd.DataFrame(model.cluster_centers_, columns=['mpg', 'acceleration'])
sns.scatterplot(x='mpg', y='acceleration', data=dfpred, hue= 'cluster', palette='Set1')
sns.scatterplot(x='mpg', y='acceleration', data=df_centroides, hue= df_centroides.index, palette='Set1', s=500, marker='X')
dfnorm.head()
model.predict(X=[[0.2, 0.3]])
```
# Interpretar Modelo
> 1. Si tuvieras que ponerle nombre a cada grupo, ¿cuál le darías?
> 2. ¿En qué te basas para ello?
```
dfpred.groupby('cluster').mean()
```
# Objetivos Alcanzados
_Haz doble click sobre esta celda y pon una `X` dentro de las casillas [X] si crees que has superado los objetivos:_
- [X] Entender **cómo la máquina optimiza un modelo**, que no es más que encontrar **los números** una ecuación matemática.
- [X] La importancia de la **Suma de Cuadrados** como concepto fundamental de la estadística para medir el **error**.
- [X] Entender la necesidad de **Normalizar** los datos al emplear un algoritmo que involucra el **cálculo de distancias**.
- [X] Entender que la estadística no es más que una forma de aproximarse a la realidad. Y esta aproximación no es una ciencia exacta, sino **subjetiva**.
- [X] Empezar a distinguir, más aún, que la programación es una herramienta hacia un fin.
- [X] Al principio, nos salen muchos errores programando y creemos que no valemos para esto. Sin embargo, en este momento del programa, veremos que existen unos **patrones que siempre se cumplen en los errores** y empezaremos a **entender la máquina**.
- [X] Una vez más, nos daremos cuenta de que existen **distintos modelos para realizar el Análisis de Cluster**. De la misma manera que en el anterior capítulo también existían diversos Modelos de Regresión.
```
dfnorm = dfnorm[['mpg', 'acceleration']]
from sklearn.mixture import GaussianMixture
model = GaussianMixture(n_components=3)
model.fit(X=dfnorm)
```
# Realizar Predicciones
> - `model.predict()`
```
dfpred = dfnorm
dfpred['cluster'] = model.predict(dfnorm)
dfnorm.head()
```
# Visualizar Modelo
> - Scatterplot con puntos coloreados según el grupo al que pertenece cada observación: `hue = model.labels_`
> - Añade otra capa de puntos, los cuales indicarán los centroides (se encuentran en `model.cluster_centers_`)
```
sns.scatterplot(x='mpg', y='acceleration', data=dfpred, hue= 'cluster', palette='Set1')
dfnorm.head()
model.predict(X=[[0.2, 0.3]])
```
# Interpretar Modelo
> 1. Si tuvieras que ponerle nombre a cada grupo, ¿cuál le darías?
> 2. ¿En qué te basas para ello?
```
dfpred.groupby('cluster').mean()
```
# Objetivos Alcanzados
_Haz doble click sobre esta celda y pon una `X` dentro de las casillas [X] si crees que has superado los objetivos:_
- [X] Entender **cómo la máquina optimiza un modelo**, que no es más que encontrar **los números** una ecuación matemática.
- [X] La importancia de la **Suma de Cuadrados** como concepto fundamental de la estadística para medir el **error**.
- [X] Entender la necesidad de **Normalizar** los datos al emplear un algoritmo que involucra el **cálculo de distancias**.
- [X] Entender que la estadística no es más que una forma de aproximarse a la realidad. Y esta aproximación no es una ciencia exacta, sino **subjetiva**.
- [X] Empezar a distinguir, más aún, que la programación es una herramienta hacia un fin.
- [X] Al principio, nos salen muchos errores programando y creemos que no valemos para esto. Sin embargo, en este momento del programa, veremos que existen unos **patrones que siempre se cumplen en los errores** y empezaremos a **entender la máquina**.
- [X] Una vez más, nos daremos cuenta de que existen **distintos modelos para realizar el Análisis de Cluster**. De la misma manera que en el anterior capítulo también existían diversos Modelos de Regresión.
| github_jupyter |
```
import numpy as np
from fractions import gcd
def psi(a,b):
temp = int(np.floor(a/b))
r = a-temp*b
return r
def LHNF(H,A):
LH = np.transpose(H)
U = np.matmul(H,np.linalg.inv(A))
return (LH, U)
def HNF(A, V):
"""
Args:
A (list): a 3x3 input matrix.
V (list): a 3x3 input matrix.
Returns:
A (list): a 3x3 input matrix.
V (list): a 3x3 input matrix.
"""
A = np.array(A)
V = np.array(V)
for t in range(3):
r = -1
for s in range(3):
if A[s][r+1]!=0 or A[s][t]!=0:
r += 1
ir = s
if t== r and A[s][t] < 0:
V[:,t] = np.sign(A[s][t])*V[:,t]
A[:,t] = np.sign(A[s][t])*A[:,t]
else:
A,V = row_one_gcd(A,V,s,r,t)
for l in range(r-1):
V[:,l] = V[:,l] - psi(A[s][l],A[s][r])*V[:,r]
A[:,l] = A[:,l] - psi(A[s][l],A[s][r])*A[:,r]
if t==r:
break
return (A,V)
def row_one_gcd(A,V,i,j,l):
from fractions import gcd
if A[i][j] != 0 and A[i][l] !=0 and j!=l:
d = gcd(A[i][j],A[i][l])
uv_found = False
u=0
v=0
while not uv_found:
v = (d-u*A[i][j])/float(A[i][l])
if v%1 == 0:
v = int(v)
uv_found = True
else:
u += 1
temp = np.transpose(np.dot(np.transpose([V[:,j],V[:,l]]),[[u, -A[i][l]/d],[v, A[i][j]/d]]))
V[:,j] = temp[0]
V[:,l] = temp[1]
temp = np.transpose(np.dot(np.transpose([A[:,j],A[:,l]]),[[u, -A[i][l]/d],[v, A[i][j]/d]]))
A[:,j] = temp[0]
A[:,l] = temp[1]
return (A,V)
def diagtosmith(A,U,V):
"""
Args:
A (list): a 3x3 input matrix.
U (list): a vector of 3 elements.
V (list): a vector of 3 elements.
Returns:
A (list): a 3x3 input matrix.
U (list): a 3x3 input matrix.
V (list): a 3x3 input matrix.
"""
U = np.array(U)
A = np.array(A)
V = np.array(V)
for k in range(2):
for l in reversed(range(k,2)):
if not A[l+1][l+1]%A[l][l]==0:
g = A[l][l]*A[l+1][l+1]
A[l][l]=gcd(A[l][l],A[l+1][l+1])
A[l+1][l+1] = g/A[l][l]
d = gcd(A[l][l],A[l+1][l+1])
uv_found = False
u=0
v=0
while not uv_found:
v = (d-u*A[l][l])/float(A[l+1][l+1])
if v%1 == 0:
uv_found = True
else:
u += 1
un = np.matmul([[u,v],[-A[l+1][l+1]/d, A[l][l]/d]],[U[:,l],U[:,l+1]])
U[:,l] = un[0]
U[:,l+1] = un[1]
vn = np.transpose(np.matmul(np.transpose([V[:,l],V[:,l+1]]),[[1,-v*A[l+1][l+1]/d],[1, u*A[l][l]/d]]))
V[:,l] = vn[0]
V[:,l+1] = vn[1]
for l in range(3):
if A[l][l] !=0:
beta = np.sign(A[l][l])
V[:,l] = V[:,l]*beta
A[l][l] = A[l][l]*beta
return (A,U,V)
def SNF(A):
U = [[1,0,0],[0,1,0],[0,0,1]]
V = [[1,0,0],[0,1,0],[0,0,1]]
count = 0
while not np.allclose([A[0][1],A[0][2],A[1][2],A[1][0],A[2][0],A[2][1]],0):
print("count",count)
A, V = HNF(A, V)
A, U = LHNF(A, U)
count += 1
#A, U, V = diagtosmith(A,U,V)
return A, U, V
A = [[63,0,0],[0,1,0],[0,432,1175]]
print(np.linalg.det(A))
S,U,V = SNF(A)
S
np.round(np.matmul(U,np.matmul(A,V)),1).astype(int)
np.round(U).astype(int)
HNF(A,[[1,0,0],[0,1,0],[0,0,1]])
temp = [[3, 0, 0],
[0, 1, 0],
[717, 707, 830]]
def get_min_val(N):
"""Finds the minimum value of a matrix that's not in a row or
column of zeros.
Args:
N (list): The input matrix.
Returns:
The minimum value in the matrix that isn't already in
a zeroed row or column."""
temp_N = abs(N)
list_N = sorted(temp_N.flatten())
for v in list_N:
if v == 0:
continue
row, col = np.argwhere(temp_N==v)[0]
if (list(temp_N[:,col]).count(0) < 2 or
list(temp_N[row,:]).count(0) < 2):
return N[row,col], row, col
else:
temp_N[row,col] = -1
print("N",N)
print("temp_N",temp_N)
def Rods_way(N):
"""Finds the SmithNormalForm by reducing starting with the
smallest entry in the matrix.
Args:
N (list): An integer 3x3 matrix.
Returns:
L,S,R: the left transform, the SNF and the right
transform.
"""
from copy import deepcopy
S = np.array(N)
L = np.identity(3)
R = np.identity(3)
is_snf = False
cur_diag = 0
count = 0
while not is_snf and count < 100:
min_val, row, col = get_min_val(S)
#First reduce the row
for j in range(3):
if j == col:
continue
multiple = int(S[row,j]/min_val)
if multiple==0:
continue
S[:,j] = S[:,j]-multiple*S[:,col]
R[:,j] = R[:,j]-multiple*R[:,col]
#then reduce the column
for j in range(3):
if j == row:
continue
multiple = int(S[j,col]/min_val)
if multiple==0:
continue
S[j,:] = S[j,:]-multiple*S[row,:]
L[j,:] = L[j,:]-multiple*L[row,:]
if (np.allclose(S[cur_diag:,cur_diag:]%min_val,0)):
if cur_diag != col:
#Swap rows and columns
tmp_col = deepcopy(S[:,cur_diag])
S[:,cur_diag] = deepcopy(S[:,col])
S[:,col] = tmp_col
tmp_col = deepcopy(R[:,cur_diag])
R[:,cur_diag] = deepcopy(R[:,col])
R[:,col] = tmp_col
if cur_diag != row:
tmp_row = deepcopy(S[cur_diag,:])
S[cur_diag,:] = deepcopy(S[row,:])
S[row,:] = tmp_row
tmp_row = deepcopy(L[cur_diag,:])
L[cur_diag,:] = deepcopy(L[row,:])
L[row,:] = tmp_row
cur_diag += 1
count += 1
if ((S[0][1]==0 and S[0][2]==0 and S[1][0]==0 and S[1][2]==0
and S[2][0]==0 and S[2][1]==0) and S[2][2]%S[1][1]==0
and S[1][1]%S[0][0]==0):
is_snf = True
if (cur_diag==0 and row == 0 and col == 0 and
list(S[0,:]).count(0)==2 and list(S[:,0]).count(0)==2 and
not sp.allclose(S%min_val,0)):
mrow, mcol = np.argwhere(S==S.max())
S[0,:] = S[0, :] + S[mrow,:]
L[0,:] = L[0, :] + L[mrow,:]
if ((cur_diag==1) and
list(S[1,:]).count(0)==2 and list(S[:,1]).count(0)==2 and
not np.allclose(S[1:,1:]%min_val,0)):
S[1,:] = S[1, :] + S[2,:]
L[1,:] = L[1, :] + L[2,:]
for j in range(3):
if S[j,j] < 0:
S[j,:] = -S[j,:]
L[j,:] = -L[j,:]
if count == 100:
print("Failed to find SNF in 100 iterations.")
if not np.allclose(np.matmul(np.matmul(L,N),R),S):
print("Transformation failed in SNF.")
return L, S, R
np.set_printoptions(suppress=True)
N = np.array([[3,0,0],[0,1,0],[717,707,830]])
L,S,R = Rods_way(N)
print(L)
print(S)
print(R)
np.matmul(np.matmul(L,N),R)
sorted(abs(N).flatten())
a = [0,1,0]
a.count(0)
np.linalg.det(N)
np.allclose(N%1,0)
N[1:,1:]
N.max()
from os import getcwd
getcwd()
```
| github_jupyter |
# STEP 5: ETL the data from 3NF tables to Facts & Dimension Tables
**IMPORTANT:** The following exercise depends on first having successing completed Exercise 1: Step 4.
Start by running the code in the cell below to connect to the database. If you are coming back to this exercise, then uncomment and run the first cell to recreate the database. If you recently completed steps 1 through 4, then skip to the second cell.
```
!PGPASSWORD=student createdb -h 127.0.0.1 -U student pagila
!PGPASSWORD=student psql -q -h 127.0.0.1 -U student -d pagila -f Data/pagila-schema.sql
!PGPASSWORD=student psql -q -h 127.0.0.1 -U student -d pagila -f Data/pagila-data.sql
%load_ext sql
DB_ENDPOINT = "127.0.0.1"
DB = 'pagila'
DB_USER = 'student'
DB_PASSWORD = 'student'
DB_PORT = '5432'
# postgresql://username:password@host:port/database
conn_string = "postgresql://{}:{}@{}:{}/{}" \
.format(DB_USER, DB_PASSWORD, DB_ENDPOINT, DB_PORT, DB)
print(conn_string)
%sql $conn_string
```
### Introducing SQL to SQL ETL
When writing SQL to SQL ETL, you first create a table then use the INSERT and SELECT statements together to populate the table. Here's a simple example.
First, you create a table called test_table
```
%%sql
CREATE TABLE test_table
(
date timestamp,
revenue decimal(5,2)
);
```
Then you use the INSERT and SELECT statements to populate the table. In this case, the SELECT statement extracts data from the `payment` table and INSERTs it INTO the `test_table`.
```
%%sql
INSERT INTO test_table (date, revenue)
SELECT payment_date AS date,
amount AS revenue
FROM payment;
```
Then you can use a SELECT statement to take a look at your new table.
```
%sql SELECT * FROM test_table LIMIT 5;
```
If you need to delete the table and start over, use the DROP TABLE command, like below.
```
%sql DROP TABLE test_table
```
Great! Now you'll do the same thing below to create the dimension and fact tables for the Star Schema using the data in the 3NF database.
## ETL from 3NF to Star Schema
### 3NF - Entity Relationship Diagram
<img src="./pagila-3nf.png" width="50%"/>
### Star Schema - Entity Relationship Diagram
<img src="pagila-star.png" width="50%"/>
In this section, you'll populate the tables in the Star schema. You'll `extract` data from the normalized database, `transform` it, and `load` it into the new tables.
To serve as an example, below is the query that populates the `dimDate` table with data from the `payment` table.
* NOTE 1: The EXTRACT function extracts date parts from the payment_date variable.
* NOTE 2: If you get an error that says that the `dimDate` table doesn't exist, then go back to Exercise 1: Step 4 and recreate the tables.
```
%%sql
INSERT INTO dimDate (date_key, date, year, quarter, month, day, week, is_weekend)
SELECT DISTINCT(TO_CHAR(payment_date :: DATE, 'yyyyMMDD')::integer) AS date_key,
date(payment_date) AS date,
EXTRACT(year FROM payment_date) AS year,
EXTRACT(quarter FROM payment_date) AS quarter,
EXTRACT(month FROM payment_date) AS month,
EXTRACT(day FROM payment_date) AS day,
EXTRACT(week FROM payment_date) AS week,
CASE WHEN EXTRACT(ISODOW FROM payment_date) IN (6, 7) THEN true ELSE false END AS is_weekend
FROM payment;
```
TODO: Now it's your turn. Populate the `dimCustomer` table with data from the `customer`, `address`, `city`, and `country` tables. Use the starter code as a guide.
```
%%sql
INSERT INTO dimCustomer (customer_id, first_name, last_name, email, address,
address2, district, city, country, postal_code, phone,
active, create_date, start_date, end_date)
SELECT DISTINCT c.customer_id, c.first_name, c.last_name, c.email, a.address, a.address2,
a.district,ci.city, co.country, a.postal_code, a.phone,
CASE WHEN c.activebool THEN 1 ELSE 0 END,
(cast(c.create_date as text) || ' 00:00:01'):: timestamp,
date(now()) AS start_date, date(now())
FROM customer c
JOIN address a ON (c.address_id = a.address_id)
JOIN city ci ON (a.city_id = ci.city_id)
JOIN country co ON (ci.country_id = co.country_id)
LIMIT 10;
```
TODO: Populate the `dimMovie` table with data from the `film` and `language` tables. Use the starter code as a guide
```
%%sql
INSERT INTO dimMovie (film_id, title, description, release_year, language,
original_language, rental_duration, length, rating,
special_features)
SELECT DISTINCT f.film_id, f.title, f.description, f.release_year, l.name,
orig_lang.name, f.rental_duration, f.length, f.rating,
f.special_features
FROM film f
JOIN language l ON (f.language_id=l.language_id)
LEFT JOIN language orig_lang ON (f.original_language_id = orig_lang.language_id);
```
TODO: Populate the `dimStore` table with data from the `store`, `staff`, `address`, `city`, and `country` tables. This time, there's no guide. You should write the query from scratch. Use the previous queries as a reference.
```
%%sql
INSERT INTO dimStore (store_id, address, address2, district, city, country, postal_code,
manager_first_name, manager_last_name, start_date, end_date)
SELECT DISTINCT s.store_id, a.address, a.address2, a.district, ci.city, co.country, a.postal_code,
st.first_name, st.last_name, date(now()) AS start_date, date(now())
FROM store s
JOIN address a ON (s.address_id=a.address_id)
JOIN city ci ON (a.city_id = ci.city_id)
JOIN country co ON (ci.country_id = co.country_id)
JOIN staff st ON (s.manager_staff_id = st.staff_id);
```
TODO: Populate the `factSales` table with data from the `payment`, `rental`, and `inventory` tables. This time, there's no guide. You should write the query from scratch. Use the previous queries as a reference.
```
%%sql
INSERT INTO factsales (date_key, customer_key, movie_key, store_key, sales_amount)
SELECT TO_CHAR(p.payment_date :: DATE, 'yyyyMMDD')::integer, dc.customer_key,
dm.movie_key, ds.store_key, p.amount
FROM payment p
JOIN rental r ON (p.rental_id = r.rental_id)
JOIN inventory i ON (r.inventory_id = i.inventory_id)
JOIN customer c ON (p.customer_id=c.customer_id)
JOIN dimcustomer dc ON(p.customer_id = dc.customer_id)
JOIN dimstore ds ON (c.store_id = ds.store_id)
JOIN dimmovie dm ON (i.film_id = dm.film_id)
```
| github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Chopping-costs" data-toc-modified-id="Chopping-costs-1"><span class="toc-item-num">1 </span>Chopping costs</a></span><ul class="toc-item"><li><span><a href="#Read-the-data" data-toc-modified-id="Read-the-data-1.1"><span class="toc-item-num">1.1 </span>Read the data</a></span></li><li><span><a href="#Plot-the-data" data-toc-modified-id="Plot-the-data-1.2"><span class="toc-item-num">1.2 </span>Plot the data</a></span></li></ul></li><li><span><a href="#Contraction-cost" data-toc-modified-id="Contraction-cost-2"><span class="toc-item-num">2 </span>Contraction cost</a></span><ul class="toc-item"><li><span><a href="#Theoretical-plot-of-elimination" data-toc-modified-id="Theoretical-plot-of-elimination-2.1"><span class="toc-item-num">2.1 </span>Theoretical plot of elimination</a></span></li></ul></li><li><span><a href="#Experimental-plot" data-toc-modified-id="Experimental-plot-3"><span class="toc-item-num">3 </span>Experimental plot</a></span></li></ul></div>
```
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
sns.set_style('whitegrid')
```
## Chopping costs
### Read the data
data should be output of `python get_contraction_width.py $size $seed $parvars`
```
filenames = [
'./contrw/58_42_6'
#,'./contrw/58_43_6'
,'./contrw/58_42_7'
, './contrw/58_42_8'
]
dfs = [pd.read_csv(f, sep='\t', header=14) for f in filenames]
dfs[0]
```
### Plot the data
```
colors = (plt.cm.gnuplot2(x) for x in np.linspace(.8,.2,len(dfs)))
labels = (f'{x} parallel indices' for x in range(6,9))
f = plt.figure(figsize=(6,4))
#plt.title('Max N with respect to chop point')
for d in dfs:
d.max_nghs.plot(marker='o'
,linewidth=1
,label=next(labels)
,color=next(colors)
)
dfs[0].current_ngh.plot(style='.-', color='red', label='Neighbours at elimination step')
plt.ylabel('Maximum number of neighbours')
plt.xlabel('Step to turn on parallelization')
plt.legend(loc='center left', bbox_to_anchor=(.0,.4))
plt.savefig('figures/max_nngh_vs_chop_index_58_42d3.pdf')
labels = (f'Parallel vars: {x}' for x in range(5,9))
for d in dfs:
d.max_nghs.hist(alpha=.8,label=next(labels))
plt.legend()
```
## Contraction cost
```
import sys
sys.path.append('..')
sys.path.append('../qaoa')
import utils
import utils_qaoa as qu
import json
%load_ext autoreload
%autoreload 2
S = 49
mems, flops, nghs, N = qu.get_cost_of_task(S, seed=42, type='randomreg', degree=3)
N
exp_data = json.load((open('./result_data/contracts_49_42d3.json')))
exp_data.keys()
mems_exp = exp_data['proc_buck memory']
times_exp = exp_data['proc_buck time']
```
### Theoretical plot of elimination
```
fig = plt.figure(figsize=(6,4))
colors = [plt.cm.gnuplot2(x) for x in np.linspace(.8,.2,2)]
ax = plt.gca()
utils.plot_cost(mems, flops)
plt.xlabel('Elimination step')
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()
[l.set_color(c) for l, c in zip(ax.get_lines(),reversed(colors))]
plt.legend(loc='lower left')
plt.ylabel('Step cost')
inset = fig.add_axes([.2, .5, .38, .36])
#plt.xlabel('Elimination step')
L = len(nghs)
c = 102
plt.yscale('log')
inset.plot(range(L-c, L), flops[-c:], color=colors[0])
inset.plot(range(L-c, L), mems[-c:], color=colors[1])
plt.grid(None)
ax2 = plt.gca().twinx()
ax2.plot(range(L-c, L), nghs[-c:], color='red', label='Number of neighbours')
#plt.yscale('log')
plt.grid(None)
plt.legend(loc='lower left')
plt.ylim(0,70)
plt.savefig('figures/contraction_cost_58_42d3.pdf')
```
## Experimental plot
```
slice_ = slice(-50, -18)
xsm = list(range(len(mems)))[slice_]
fig = plt.figure(figsize=(6,5))
plt.plot(xsm, flops[slice_], '--', label='FLOP', color=colors[0])
plt.plot(xsm, 16*np.array(mems)[slice_], '--', label='Memory', color=colors[1])
plt.plot(xsm, 3e9*np.array(times_exp)[slice_], label='experiment FLOP', color=colors[0])
plt.plot(xsm, mems_exp[slice_], label='experiment memory', color=colors[1])
plt.yscale('log')
plt.xlabel('Elimination step')
plt.ylabel('Cost of vertex elimination')
plt.legend()
ax = plt.gca()
sep = ax.twinx()
#plt.ylim(18, 50)
plt.plot(xsm, nghs[slice_], '. ', label='Number of\nneighbours', color='red')
plt.legend(loc='upper right')
plt.grid(None)
inset = fig.add_axes([.5, .2, .3, .25])
inset.plot(flops, color=colors[0])
inset.plot(mems, color=colors[1])
inset.yaxis.set_visible(False)
plt.grid(None)
plt.yscale('log')
_ = inset.indicate_inset_zoom(ax, edgecolor='cyan', alpha=1)
plt.savefig('figures/theory_vs_exp_contract_49_42d3.pdf')
max(mems_exp)/1e9
```
| github_jupyter |
# Legendre transformation
A legendre transformation is used in thermodynamics to derive different relation from one **fundamental** relation, the *internal energy*.
The *internal energy* is defined as:
$$ U(S,V) = TS - pV \\
dU = TdS - pdV $$
and comprises the heat given *to* the system (TdS) and the volumetric work done *by* the system (PdV), all in Joule. These two terms, TdS and pdV are sets of *conjugate variables*.
By transforming the internal energy, we can arrive at other thermodynamic expressions, such as Helmholtz Energy (F(T,V)), Enthalpy (H(S,p)), or Gibbs Free Energy (G(T,p)). These expressions also consist of pairs of conjugate variables, which differ from the conjugate variables of the internal energy.
So, basically the legendre transformation transforms a function of a set of variables (internal energy) to another function of a set of *conjugate* variables (Helmholtz Energy, Enthalpy, etc).
Below you see an example of how calculate the (change in) internal energy of a system. Assume we have a baloon filled with a gas. Its volume is reduced and it transferres heat to its surroundings. What is the change in internal energy?
<img src="imgs/internal_energy_pic.png" width="50%">
```
# Example calculation of Internal energy and Work done
pext = 1.01325e5 # external, atmospheric pressure in Pascal
q = -680 # heat transferred to surroundings in Joule. As heat is given BY the system, it is negative
v1 = 1.2 # volume 1 in m³
v2 = 0.7 # volume 2 in m³
## We calculate the change in internal energy dU = TdS - pdV --> dV is negative, because the baloon shrinks
dU = q - pext * (v2 - v1)
print("The change in internal energy equals %.3f kilo Joule." % (dU/1000.))
```
### Conjugate variables
A force is always accompanied by a displacement. Those two together are called a pair of *conjugate variables*. For example, pressure *p* and volume *V* are such a conjugate pair.
An applied pressure (*p*) causes a change in volume (*dV*).
So all in all, the legendre transformation, is all about the product rule:
If (x,y) is a set of conjugate variables, then their total differential is
$$ d(xy) = xdy + ydx $$
This expression relates the variation dy in quantity y to the variation dx in quantitiy x.
If we apply the product rule to a function f(x,y), we get
$$ df(x,y) = \bigg(\frac{\partial f}{\partial x} \bigg)_y dx + \bigg(\frac{\partial f}{\partial y}\bigg)_x dy $$
The full legendre transformation is defined as:
$$ \tau(\sigma,\omega) = f(x,y) - \bigg(\frac{\partial f}{\partial x} \bigg)_y - \bigg(\frac{\partial f}{\partial y} \bigg)_x $$
The second term on the right side is for transforming $x$ into $\sigma$, and the third term transforms $y$ into $\omega$. Now, if two thermodynamic expressions share a variable (e.g. U(S,V) and F(T,V)), meaning $y == \omega$), that dimension of the full legendre transformation is neglected.
So to get the Helmoltz energy from the internal energy, the Legendre transformation reduces to:
$$ \tau(\sigma,\omega) = f(x,y) - \bigg(\frac{\partial f}{\partial x} \bigg)_y \text{ with $\omega$ = y}$$
# Maxwell Relations
Maxwell relations are used to relate thermodynamic expressions to quantities such as entropy, temperature, pressure, or volume. They are used to relate directly measurable quantities to thermodynamic quantities, which may not be directly accessible in experiments (like chemical potential or entropy).
They give another way of looking at thermodynamic processes. Maxwell relations can be derived by the schwarz theorem:
$$ \bigg[\frac{\partial}{\partial y} \bigg(\frac{\partial f}{\partial x} \bigg)_y \bigg]_x =
\bigg[\frac{\partial}{\partial x} \bigg(\frac{\partial f}{\partial y} \bigg)_x \bigg]_y$$
### Measurable thermodynamic response functions
*Response functions* are called that way because they measure a change in system quantity *in response* to an infinitesimal pertubation.
As said, Maxwell relations relate measurable variables like temperature, pressure to more abstract quantities. Or differently phrased:
Maxwell relations allow expressions of experimentally inaccessible quantities in terms of experimentally measurable response functions.
<center>
$c_v = \bigg(\frac{\partial U}{\partial T}\bigg)_V = T \bigg(\frac{\partial S}{\partial T}\bigg)_V$ const. volume heat capacity
$c_p = \bigg(\frac{\partial H}{\partial T}\bigg)_p = T \bigg(\frac{\partial S}{\partial T}\bigg)_p$ const. pressure heat capacity
$K_T = -\frac{1}{V} \bigg(\frac{\partial V}{\partial p}\bigg)_T = - \bigg(\frac{\partial ln(V)}{\partial p}\bigg)_T$ isothermal compressibility
$\alpha_p = \frac{1}{V} \bigg(\frac{\partial V}{\partial T}\bigg)_p = \bigg(\frac{\partial ln(V)}{\partial T}\bigg)_p$ thermal expansion coefficient
</center>
| github_jupyter |
# Final Micro Project
The time has come to apply what you have learned throughout the course by doing a micro project.
You have two options now.
1. Choose from our list of projects
- [Meteorite Landings](#Meteorite-Landings)
- [Significant Earthquakes](#Significant-Earthquakes)
- [World Ocean Atlas](#World-Ocean-Atlas)
- [Arctic Sea Ice](#Arctic-Sea-Ice)
- [Other](#Other-Data)
2. Use your own data
- If you find our ideas terrible or you are eager to start using Python in your work, you can use your own data.
- The only requirement is that data should be in a format that we have used in this course, preferably **CSV/ASCII** or **netCDF** file.
- We might not be very helpful, but at least we can help you get started and/or point you to a relevant resource.
## Meteorite Landings
NASA has a great [archive of open data](https://data.nasa.gov/browse) that you can use to master your data analysis skills. Moreover, there is even a small Python library to fetch some of the datasets: [pyNASA](https://bmtgoncalves.github.io/pyNASA/).
For example, Meteorite Landings dataset can be either downloaded manually from https://data.nasa.gov/Space-Science/Meteorite-Landings/gh4g-9sfh or fetched as a `pandas.DataFrame` using `pyNASA.meteorite()` method. Some further ideas:
* `pandas` package will be most useful to read in the data, as well as analyse them
* Use `cartopy` to plot the data using longitude and latitude columns
* Use scatter plot to show meteorites' mass in colour
* Create a histogram of earthquakes magnitude
## Significant Earthquakes
US Geological Survey (USGS) provides various [earthquakes data](https://earthquake.usgs.gov/data/data.php#eq) on a global scale. Its Earthquake Catalog contains earthquake source parameters (e.g. hypocenters, magnitudes, phase picks and amplitudes) and other products (e.g. moment tensor solutions, macroseismic information, tectonic summaries, maps) produced by contributing seismic networks.
If you follow this [link](http://earthquake.usgs.gov/earthquakes/search/), you can search throught the catalog and filter data by the magnitude, time and geographic region. In the `data/` folder, we provide an [example dataset](../data/earthquakes_2015_2016_gt45.csv) of earthquakes with magnitude >4.5 that occurred around the world throughout the last year.
So if you want to build your project on these data, some possible ideas are:
* `pandas` package will be most useful to read in the data, as well as analyse them
* Use `cartopy` to plot the data using longitude and latitude columns
* Explore `pandas`' `groupby()` method, which you can use to aggregate data by time or other parameter
* Create a histogram of earthquakes magnitude
To get you started, we provided the minimal code to load the data.
```
# import pandas as pd
# df = pd.read_csv('../data/earthquakes_2015_2016_gt45.csv', parse_dates = ['time',], index_col='time')
# df.head()
```
## World Ocean Atlas
*Inspired by this blog post: https://ocefpaf.github.io/python4oceanographers/blog/2015/05/04/woa13/*
* NOAA's [World Ocean Atlas](https://www.nodc.noaa.gov/OC5/WOA09/netcdf_data.html) provides open-access gridded data of temperature, salinity and other ocean parameters in netCDF format.
* It is a set of objectively analyzed (1$^\circ$ grid) climatological fields at standard depth levels for annual, seasonal, and monthly compositing periods. It also includes associated statistical fields of observed oceanographic profile data.
If you choose to analyse these data, we recommend that you start by:
* downloading 5-degree data of temperature and oxygen
* plotting the data on the global map (do not use jet/rainbow colormap!)
* calculating an average depth profile and plotting it beside the map
## Arctic Sea Ice
### Data
* In this project you are offered to use NOAA/NSIDC Climate Data Record of Passive Microwave Sea Ice Concentration.
* In the `../data/` directory, there are 2 netCDF files `seaice_conc_monthly*` that correspond to September 1991 ([original FTP link](ftp://sidads.colorado.edu/pub/DATASETS/NOAA/G02202_v2/north/monthly/seaice_conc_monthly_nh_f08_199109_v02r00.nc)) and September 2012 ([original FTP link](ftp://sidads.colorado.edu/pub/DATASETS/NOAA/G02202_v2/north/monthly/seaice_conc_monthly_nh_f17_201209_v02r00.nc)).
* If you want to download data for other months, visit the [NSIDC's data portal](https://nsidc.org/data/search/#keywords=sea+ice/sortKeys=score,,desc/facetFilters=%257B%257D/pageNumber=1/itemsPerPage=25).
### Ideas for the project
* Plot one of the time slices on a map with North Polar Stereographic projection
* Create a figure with 3 subplots
* Plot the 1991 sea ice concentration in the 1st subplot, 2012 sea ice in the 2nd, and the difference in the 3rd.
### Getting started
For this project, we recommend that you:
* use `xarray` for opening and reading the netCDF files
* may use `xarray.open_mf_dataset()` to load both files at once
* use `cartopy` for creating a plot with a correct map projection
* use appropriate colormaps for the sea ice concentration and difference
To get started, copy the following cell into your **Project** notebook.
```
# import cartopy.crs as ccrs
# import matplotlib.pyplot as plt
# import xarray as xr
# ds = xr.open_mfdataset('../data/seaice_conc_monthly_*.nc')
## or
# ds1 = xr.open_dataset('../data/seaice_conc_monthly_nh_f08_199109_v02r00.nc')
# ds2 = xr.open_dataset('../data/seaice_conc_monthly_nh_f17_201209_v02r00.nc')
## Extract longitude and latitude values, then the sea ice concentration itself
## Code for creating a map
# fig = plt.figure()
# ax = fig.add_subplot(111, projection=ccrs.???(central_longitude=0))
# ax.coastlines(resolution='110m', linewidth=0.5)
# ax.gridlines()
# ax.set_extent([-180, 180, 40, 90], crs=ccrs.PlateCarree())
```
## Other Data
* In the `../data/` directory, there are several files that haven't been used in the course:
- `met_brw_insitu_1_obop_hour_2015.txt` with accompanying `met_brw_readme.txt` - hourly meteorological observations in Barrow, Alaska (BRW)
- `plot_extent_n_v2.csv` - daily total sea ice extent in the Arctic
- `north_sea_data.csv` - ship observations from several cruises in the North Sea (data provided by Matt Bone)
* You can use any of them: open, plot, calculate statistics, etc.
### Advanced: geospatial data on Amazon
* Amazon Web Services (AWS) host a number of open datasets of geospatial data: satellite, radar, DEM, weather forecast data, etc.: https://aws.amazon.com/earth/
* You can try to use the AWS API to download data and plot it with cartopy.
| github_jupyter |
# 0 - Running *IDWT*
### *Ground Potential*
The following short tutorial focuses in the *Inverse Weighted Distance Transform or IWDT* which forms the basis of the **NetSim** package.
### imports
```
import geopandas as gpd
import numpy as np
import netsim.utils as utils
import netsim.path_tools as ptools
from netsim.cost import calculate_dt, calculate_iwdt
```
### Reading files
```
from pathlib import Path
data_path = Path.cwd().parent / "data"
```
#### *Read DEM*
```
fn_dem = data_path / "sample" / "sampleDEM.tif"
dem, profile = utils.read_raster(fn_dem)
#find the cellsize of the dem
cellsize = profile['transform'].a
```
#### *Read shapefile into a geopandas dataframe*
```
fn_shp = data_path / "sample" / "sample5.shp"
```
##### read and make a copy of original dataframe
```
df_temp = gpd.read_file(fn_shp)
# make a copy
df = df_temp.copy(deep=True)
df
```
### Preliminaries
##### *Convert point coordinates into rows and column and add to dataframe*
```
df['r'], df['c'] = utils.pt2rc(df['geometry'], profile)
df
```
##### *Plot locations*
```
hillshade = utils.calculate_hillshade(dem)
utils.plot_map(raster= {'ras':dem, 'profile':profile, 'bground': hillshade},
loc={'df':df, 'label': 'id'},
title='SampleDEM')
```
##### *read gradient to cost coefficients*
The ``grad2cost.csv`` contains the relation between gradient (degrees) and metabolic cost.
```
# vertical factor table
vftfn = data_path / "iwdt" / "grad2cost.csv"
vftfn
```
##### *find coefficients for gradient (degrees) to cost function*
```
vft = np.genfromtxt(vftfn, delimiter=',')
```
##### *fit a 4<sup>th</sup> degree polynomial to metabolic cost*
First we will transform the degrees into radians and then we calculated the tangent.
```
coef = np.polyfit(np.tan(np.radians(vft[: , 0])), vft[:,1], deg=4)
coef
```
### Creating a path
Next, we shall generate a simple path from point 0 to 2. To do this, we first initialize our *IDWT* raster (a 2D numpy array with the same dimensions as *DEM*) so that the cell value that corresponds to the location of point 0 is set to 0.0 and the rest of the cell values are initialized to some very large number e.g. 99999.0
##### *initializing a numpy 2D array to 99999.0*
```
iwdt = np.full_like(dem, 999999.0)
```
##### *set the cell value for point 0 to 0.0*
```
# retrieve the row and column of point 0
sel = df['id'] == 0
row_0 = df.loc[sel, 'r'].values[0]
col_0 = df.loc[sel, 'c'].values[0]
# set to 0.9
iwdt[row_0, col_0]= 0.0
```
##### generate the *iwdt* dictionary, `iwdt_dict()`
To run the `calculate_iwdt()` we need to generate a dictionary with the following entries:
- 'dem': digital elevation model
- 'netcost': existing netcost (if such exists)
- 'cellsize': cell resolution of the *dem*
- 'weight': weight (0.0-1.0) we want to give to the prexisting *netcost*
- 'coef': coefficients of the polynomial we use to calculate costs based on the slope as derived from
the *dem*
```
cost_dict={
'dem': dem,
'netcost': np.zeros_like(dem), # no previous netcost
'cellsize': cellsize,
'weight': 0.0, # it does not matter what we put here as netcost is made out of 0s
'coef': coef
}
```
##### run `iwdt()`
```
iwdt, blx, bly = calculate_iwdt(iwdt, cost_dict)
utils.plot_map(raster = {'ras':iwdt, 'profile':profile},
loc={'df':df, 'label':'id'},
cmap='magma',
title= 'IWDT from point 0',
cbar = True)
```
##### *find path connecting 0 to 2*
```
# retrieve the row and column of point 2
sel = df['id'] == 2
row_2 = df.loc[sel, 'r'].values[0]
col_2 = df.loc[sel, 'c'].values[0]
origin = [row_0, col_0]
dest = [row_2, col_2]
path0_2, _ = ptools.create_paths(blx, bly, [origin], [dest])
utils.plot_map(raster= {'ras':dem, 'profile':profile, 'paths': path0_2},
loc={'df':df, 'label':'id'},
cmap='Purples')
```
## Exploring path influence
While `calculate_iwdt()` can generate similar paths as generated by other GIS, the true advantage of using `calculate_iwdt()` is the possibility of incorporating an *influence weighted* layer that we can use when calculating additional paths. You should think of this *influence weighted* layer as the inverse of a cost layer. The higher the influence the less the cost and vice versa. In this particular case, we are going to generate our *influence (cost) weighted* layer from the path we just generated so that its influence is maximum (i.e. cost is minimum) while on the path and declines (or increases for the cost) exponentially with distance.
##### *generating influence layer*
Here, we shall consider that at a distance of $d$= 0m the cost of the path is minimum while at a distance of $d$=25m its cost has exponentially increased to $\frac{1}{4} $. To do this we use the following formulae,
$$ PathCost= 1 - e^{d/\alpha} $$
Where,
- $d$ distance from path
- $\alpha$ is a factor calculated using the following formula,
$$ \alpha = \frac {d_0} {ln(1 - NC_0)} $$
In order to calculate such a layer, we first need to generate a layer that calculates distance away from the path. We do this using the `calculate_dt()` function.
##### *initialize a layer to 99999.0 and set path location to 0.0*
```
d = np.full_like(dem, 99999.0)
d[path0_2 >= 1.0] = 0.0
```
##### *calculate distance away*
```
d = calculate_dt(d, cost_dict['cellsize'], option=2)
utils.plot_map(raster= {'ras':d, 'profile':profile},
cmap='magma',
title= 'distance away from path',
cbar= True)
```
##### *calculate the influence (cost) associated with the path*
```
from math import log
d0 = 25 # distance @ which
NC0 = 0.25 # cost is only beta
alpha = d0 / log(1- NC0)
# path influence layer
pathcost = 1.0 - np.exp(d / alpha)
utils.plot_map(raster= {'ras':pathcost, 'profile':profile},
cmap='magma',
title= 'path influence (cost)',
cbar = True)
```
### Generate a second path with varying weight
Now that we have generated a layer that describes the influence of the path from 0 to 2, we are going to generate a second path from 1 to 2. For this however, we are going to be varying the weight associated with our first path.
##### *calculate path connecting 1 to 2*
```
# retrieve the row and column of point 1
sel = df['id'] == 1
row_1 = df.loc[sel, 'r'].values[0]
col_1 = df.loc[sel, 'c'].values[0]
# new origin
origin = [row_1, col_1]
```
#### Loop through weights
```
ws = [0, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9]
# set netcost
cost_dict['netcost'] = pathcost
for w in ws:
# Change weight
cost_dict['weight'] = w
# initialize iwdt
iwdt = np.full_like(dem, 999999.0)
iwdt[origin[0], origin[1]] = 0.0
# run iwdt
iwdt, blx, bly = calculate_iwdt(iwdt, cost_dict)
# find path
path, _ = ptools.create_paths(blx, bly, [origin], [dest])
# printout results
utils.plot_map({'ras':dem, 'profile':profile, 'paths':path},
loc={'df':df, 'label':'id'},
cmap='Purples',
title= 'weight= '+ str(w) )
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
import os
import warnings
import tqdm
import pandas as pd
warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)
import socceraction.atomic.vaep.features as fs
import socceraction.atomic.vaep.labels as lab
## Configure file and folder names
datafolder = "../data-fifa"
spadl_h5 = os.path.join(datafolder, "atomic-spadl-statsbomb.h5")
features_h5 = os.path.join(datafolder, "atomic-features.h5")
labels_h5 = os.path.join(datafolder, "atomic-labels.h5")
predictions_h5 = os.path.join(datafolder, "atomic-predictions-one-action.h5")
games = pd.read_hdf(spadl_h5, "games")
traingames = games
testgames = games
print("nb of games:", len(traingames), len(testgames))
# 1. Select feature set X
xfns = [
#fs.actiontype,
fs.actiontype_onehot,
#fs.bodypart,
fs.bodypart_onehot,
fs.goalscore,
fs.location,
fs.polar,
fs.direction,
fs.team,
fs.time,
fs.time_delta
]
nb_prev_actions = 1
Xcols = fs.feature_column_names(xfns, nb_prev_actions)
def getXY(games, Xcols):
# generate the columns of the selected feature
X = []
for game_id in tqdm.tqdm(games.game_id, desc="Selecting features"):
Xi = pd.read_hdf(features_h5, f"game_{game_id}")
X.append(Xi[Xcols])
X = pd.concat(X).reset_index(drop=True)
# 2. Select label Y
Ycols = ["scores", "concedes"]
Y = []
for game_id in tqdm.tqdm(games.game_id, desc="Selecting label"):
Yi = pd.read_hdf(labels_h5, f"game_{game_id}")
Y.append(Yi[Ycols])
Y = pd.concat(Y).reset_index(drop=True)
return X, Y
X,Y = getXY(traingames, Xcols)
print("X:", list(X.columns))
print("Y:", list(Y.columns))
X = X.fillna(0)
%%time
# train classifiers F(X) = Y
import xgboost
#from sklearn.linear_model import LogisticRegression
Y_hat = pd.DataFrame()
models = {}
for col in list(Y.columns):
print(col)
model = xgboost.XGBClassifier(n_estimators=50, max_depth=3, n_jobs=-3, verbosity=2)
#model = LogisticRegression(solver="lbfgs")
model.fit(X, Y[col])
models[col] = model
testX, testY = X, Y
from sklearn.metrics import brier_score_loss, roc_auc_score, log_loss
def evaluate(y, y_hat):
p = sum(y) / len(y)
base = [p] * len(y)
brier = brier_score_loss(y, y_hat)
print(f" Brier score: %.5f (%.5f)" % (brier, brier / brier_score_loss(y, base)))
ll = log_loss(y, y_hat)
print(f" log loss score: %.5f (%.5f)" % (ll, ll / log_loss(y, base)))
print(f" ROC AUC: %.5f" % roc_auc_score(y, y_hat))
for col in testY.columns:
Y_hat[col] = [p[1] for p in models[col].predict_proba(testX)]
print(f"### Y: {col} ###")
evaluate(testY[col], Y_hat[col])
```
### Save predictions
```
# get rows with game id per action
A = []
for game_id in tqdm.tqdm(testgames.game_id, "Loading actions of each game"):
Ai = pd.read_hdf(spadl_h5,f"atomic_actions/game_{game_id}")
A.append(Ai[["game_id"]])
A = pd.concat(A)
A = A.reset_index(drop=True)
# concatenate action game id rows with predictions and save per game
grouped_predictions = pd.concat([A, Y_hat], axis=1).groupby("game_id")
for k,df in tqdm.tqdm(grouped_predictions, desc="Saving predictions per game"):
df = df.reset_index(drop=True)
df[Y_hat.columns].to_hdf(predictions_h5, f"game_{int(k)}")
```
| github_jupyter |
## Partial Codes
```
%matplotlib inline
# 기본 패키지
import numpy as np
import random
from collections import deque
import matplotlib.pyplot as plt
# 강화학습 환경 패키지
import gym
# 인공지능 패키지: 텐서플로, 케라스
# 호환성을 위해 텐스플로에 포함된 케라스를 불러옴
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
def create_q_model(num_states, num_actions):
inputs = Input(shape=(num_states,))
layer = Dense(32, activation="relu")(inputs)
layer = Dense(16, activation="relu")(layer)
action = Dense(num_actions, activation="linear")(layer)
return Model(inputs=inputs, outputs=action)
model = create_q_model(4,2)
model.summary()
def train(model):
state_size = 4
action_size = 2
states = np.zeros((10,state_size), dtype=np.float32)
with tf.GradientTape() as tape:
predicts = model(states)
def get_env_model():
env = gym.make('CartPole-v1')
num_states = env.observation_space.shape[0]
num_actions = env.action_space.n
model = create_q_model(num_states, num_actions)
return env, model
env, model = get_env_model()
train(model)
print('Simple training is completed!')
class World_00:
def __init__(self):
self.get_env_model()
def get_env_model(self):
self.env = gym.make('CartPole-v1')
self.num_states = env.observation_space.shape[0]
self.num_actions = env.action_space.n
self.model = create_q_model(self.num_states, self.num_actions)
# print(self.model.summary())
def train(self):
states = np.zeros((10,self.num_states), dtype=np.float32)
with tf.GradientTape() as tape:
predicts = self.model(states)
new_world = World_00()
new_world.train()
print('Simple training is completed!')
def env_test_model_memory(memory, env, model, n_episodes=1000,
flag_render=False):
for e in range(n_episodes):
done = False
score = 0
s = env.reset()
while not done:
s_array = np.array(s).reshape((1,-1))
Qsa = model.predict(s_array)[0]
a = np.argmax(Qsa)
next_s, r, done, _ = env.step(a)
if flag_render:
env.render()
score += r
memory.append([s,a,r,next_s,done])
print(f'Episode: {e:5d} --> Score: {score:3.1f}')
print('Notice that the max score is set to 500.0 in CartPole-v1')
def list_rotate(l):
return list(zip(*l))
class World_01(World_00):
def __init__(self):
World_00.__init__(self)
self.memory = deque(maxlen=2000)
self.N_batch = 64
self.t_model = create_q_model(self.num_states, self.num_actions)
self.discount_factor = 0.99
self.learning_rate = 0.001
self.optimizer = Adam(lr=self.learning_rate)
def trial(self, flag_render=False):
env_test_model_memory(self.memory, self.env,
self.model, n_episodes=10, flag_render=flag_render)
print(len(self.memory))
def train_memory(self):
if len(self.memory) >= self.N_batch:
memory_batch = random.sample(self.memory, self.N_batch)
s_l,a_l,r_l,next_s_l,done_l = [np.array(x) for x in list_rotate(memory_batch)]
model_w = self.model.trainable_variables
with tf.GradientTape() as tape:
Qsa_pred_l = self.model(s_l.astype(np.float32))
a_l_onehot = tf.one_hot(a_l, self.num_actions)
Qs_a_pred_l = tf.reduce_sum(a_l_onehot * Qsa_pred_l, axis=1)
Qsa_tpred_l = self.t_model(next_s_l.astype(np.float32))
Qsa_tpred_l = tf.stop_gradient(Qsa_tpred_l)
max_Q_next_s_a_l = np.amax(Qsa_tpred_l, axis=-1)
Qs_a_l = r_l + (1 - done_l) * self.discount_factor * max_Q_next_s_a_l
loss = tf.reduce_mean(tf.square(Qs_a_l - Qs_a_pred_l))
grads = tape.gradient(loss, model_w)
self.optimizer.apply_gradients(zip(grads, model_w))
new_world = World_01()
new_world.trial()
new_world.train_memory()
new_world.env.close()
print('Completed!')
class World_02(World_01):
def __init__(self):
World_01.__init__(self)
self.epsilon = 0.2
def update_t_model(self):
self.t_model.set_weights(self.model.get_weights())
def best_action(self, s):
if random.random() <= self.epsilon:
return random.randrange(self.num_actions)
else:
s_array = np.array(s).reshape((1,-1))
Qsa = self.model.predict(s_array)[0]
return np.argmax(Qsa)
def trials(self, n_episodes=100, flag_render=False):
memory = self.memory
env = self.env
model = self.model
score_l = []
for e in range(n_episodes):
done = False
score = 0
s = env.reset()
while not done:
a = self.best_action(s)
next_s, r, done, _ = env.step(a)
if flag_render:
env.render()
score += r
memory.append([s,a,r,next_s,done])
# self.train_memory()
s = next_s
self.train_memory()
self.update_t_model()
print(f'Episode: {e:5d} --> Score: {score:3.1f}')
score_l.append(score)
return score_l
new_world = World_02()
score_l = new_world.trials(n_episodes=50)
new_world.env.close()
np.save('score_l.npy', score_l)
```
## Full Codes
```
%matplotlib inline
# 기본 패키지
import numpy as np
import random
from collections import deque
import matplotlib.pyplot as plt
# 강화학습 환경 패키지
import gym
# 인공지능 패키지: 텐서플로, 케라스
# 호환성을 위해 텐스플로에 포함된 케라스를 불러옴
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
def create_q_model(num_states, num_actions):
inputs = Input(shape=(num_states,))
layer = Dense(32, activation="relu")(inputs)
layer = Dense(16, activation="relu")(layer)
action = Dense(num_actions, activation="linear")(layer)
return Model(inputs=inputs, outputs=action)
class WorldFull():
def __init__(self):
self.get_env_model() #?
self.memory = deque(maxlen=2000)
self.N_batch = 64
self.t_model = create_q_model(self.num_states, self.num_actions)
self.discount_factor = 0.99
self.learning_rate = 0.001
self.optimizer = Adam(lr=self.learning_rate)
self.epsilon = 0.2
def get_env_model(self):
self.env = gym.make('CartPole-v1')
self.num_states = self.env.observation_space.shape[0]
self.num_actions = self.env.action_space.n
self.model = create_q_model(self.num_states, self.num_actions)
def update_t_model(self):
self.t_model.set_weights(self.model.get_weights())
def best_action(self, s):
if random.random() <= self.epsilon:
return random.randrange(self.num_actions)
else:
s_array = np.array(s).reshape((1,-1))
Qsa = self.model.predict(s_array)[0]
return np.argmax(Qsa)
def trials(self, n_episodes=100, flag_render=False):
memory = self.memory
env = self.env
model = self.model
score_l = []
for e in range(n_episodes):
done = False
score = 0
s = env.reset()
while not done:
a = self.best_action(s)
next_s, r, done, _ = env.step(a)
if flag_render:
env.render()
score += r
memory.append([s,a,r,next_s,done])
# self.train_memory()
s = next_s
self.train_memory()
self.update_t_model()
print(f'Episode: {e:5d} --> Score: {score:3.1f}')
score_l.append(score)
return score_l
new_world = WorldFull()
score_l = new_world.trials(n_episodes=5)
new_world.env.close()
np.save('score_l.npy', score_l)
```
| github_jupyter |
# Índice
1. [Análisis de datos](#Análisisdedatos)
1. [Análisis de la variable dependiente](#Análisisdelavariabledependiente)
2. [Análisis de las variables explicativas](#Análisisdelasvariablesexplicativas)
2. [Entrenamiento de modelos](#Entrenamientodemodelos)
1. [Preparación de datos](#Preparacióndedatos)
2. [Experimentos](#Experimentos)
3. [Comparación de modelos](#Comparacióndemodelos)
3. [Predicción](#Predicción)
```
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import math
from sklearn.linear_model import LinearRegression,Lasso,Ridge,ElasticNet
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, BaggingRegressor
from sklearn.metrics import mean_squared_error,mean_absolute_error,median_absolute_error
from sklearn.preprocessing import MinMaxScaler,StandardScaler
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeRegressor
#Cargamos los datos de entrenamiento
train_df = pd.read_csv("data/original/Dataset_Salesforce_Predictive_Modelling_TRAIN.txt")
```
El objetivo de este reto es es desarollo de un modelo capaz de predecir el poder adquisitivo de un cliente a partir de una serie de variables disponibles para la entidad financiera. Contar con un modelo preciso que pueda llevar a cabo estars predicciones sin duda conllevaría muchas ventajas a la hora de recomendar productos al cliente que se adecuen a sus necesidades y capacidades.
<a name=Análisisdedatos></a>
# Análisis de datos
Veamos un ejemplo de los datos con los que contamos.
```
train_df.head()
train_df.columns
train_df.dtypes
len(train_df)
```
Tal y como se explica en el enunciado, contamos con 88 variables que usar para predecir el poder adquisitivo y la información de cerca de 363.000 clientes con los que entrenar nuestro modelo. Esto hace que contemos con un número importante de datos que nos puede ayudar a desarrollar un modelo que tenga un rendimiento adecuado.
<a name=Análisisdelavariabledependiente> </a>
## Análisis de la variable dependiente
Miremos con más detenimiento la variable a predecir.
```
train_df["Poder_Adquisitivo"].describe()
sns.distplot(train_df["Poder_Adquisitivo"])
print("Skewness: %f" % train_df["Poder_Adquisitivo"].skew())
print("Kurtosis: %f" % train_df["Poder_Adquisitivo"].kurt())
```
```
q1 = train_df["Poder_Adquisitivo"].quantile(0.25)
q3 = train_df["Poder_Adquisitivo"].quantile(0.75)
iqr = q3 - q1
fence_low = q1 - 1.5 * iqr
fence_high = q3 + 1.5 * iqr
train_df_no_outliers = train_df.loc[(train_df["Poder_Adquisitivo"] > fence_low) & (train_df["Poder_Adquisitivo"] < fence_high)]
sns.distplot(train_df_no_outliers["Poder_Adquisitivo"])
print("Skewness: %f" % train_df_no_outliers["Poder_Adquisitivo"].skew())
print("Kurtosis: %f" % train_df_no_outliers["Poder_Adquisitivo"].kurt())
print("Porcentaje de datos eliminados:")
print((len(train_df.index)-len(train_df_no_outliers.index))/len(train_df.index))
```
Eliminando de esta manera los valores extremos, que representan alrededor del 5% de los datos totales, la distribución ahora presenta unos valores de skewness y kurtosis mucho más aceptables que permitan el entrenamiento de un modelo.
Evidentemente esta eliminación se va a realizar únicamente a la hora de entrenar, nunca a la hora de evaluar
<a name=Análisisdelasvariablesexplicativas></a>
## Análisis de las variables explicativas
De las variables explicativas, sabemos que contamos con algunas que son de tipo categórico en vez de númerico. Empezemos explorando estas variables.
```
train_df_no_outliers["Socio_Demo_01"].value_counts()
```
Podemos observar como Socio_Demo_01 que cuenta que muchos valores que solo aparecen un número muy bajo de veces. A la hora de transformar para su uso, es probable que la inclusión de los 921 valores posibles no aporte información discriminativa y solo sirva para aumentar el número de dimensiones. Una primera aproximación que mantenga un equilibrio entre complejidad y utilidad puede ser usar solo un número de estos valores, aquellos que aparezcan un mayor número de veces, y condensar el resto en una categoría "Other".
```
topk_socio_01 = train_df_no_outliers["Socio_Demo_01"].value_counts()[:10]
topk_socio_01
socio_01_keys = list(topk_socio_01.keys())
condition_array = [False] * len(train_df_no_outliers["Socio_Demo_01"])
for i in range(len(condition_array)):
condition_array[i] = str(train_df_no_outliers["Socio_Demo_01"].iloc[i]) in socio_01_keys
sns.violinplot(x=train_df_no_outliers["Socio_Demo_01"].loc[condition_array],y=train_df_no_outliers["Poder_Adquisitivo"].loc[condition_array])
```
Es interesante ver como algunos valores como 09992 parecen concentrar la mayor parte de clientes en valores diferentes del resto, lo cual puede aportar información importante.
```
train_df_no_outliers["Socio_Demo_02"].value_counts()
sns.violinplot(x=train_df_no_outliers["Socio_Demo_02"],y=train_df_no_outliers["Poder_Adquisitivo"])
```
Viendo la distribución de valores (61%/41%), y que las diferencias entre ambos valores no parecen muy grandes, en nuestra opinión es una opción probable que este variable represente el **sexo** del cliente.
Veamos el resto de variables socio demográficas.
```
sns.distplot(train_df_no_outliers["Socio_Demo_03"])
sns.jointplot(x=train_df_no_outliers["Socio_Demo_03"], y=train_df_no_outliers["Poder_Adquisitivo"],kind='kde')
sns.distplot(train_df_no_outliers["Socio_Demo_04"])
sns.jointplot(x=train_df_no_outliers["Socio_Demo_04"], y=train_df_no_outliers["Poder_Adquisitivo"],kind='kde')
train_df_no_outliers["Socio_Demo_04"].value_counts()
```
De nuevo, observamos que una serie pequeña de valores concentra la gran mayoría de ocurrencias. Veamos si existe una relación aparente entre cada valor de esta variable y el poder adquisitivo.
```
fig, ax = plt.subplots(figsize=(16,10))
sns.boxplot(x=train_df_no_outliers["Socio_Demo_04"], y=train_df_no_outliers["Poder_Adquisitivo"],ax=ax)
```
Algunos valores muestran distribuciones que son diferentes a las demás, pero aparecen un número casi insignificante de veces respecto a la totalidad de los datos, por lo que no consideremos que sea necesario complicar el modelo con esos casos.
```
sns.distplot(train_df_no_outliers["Socio_Demo_05"])
sns.jointplot(x=train_df_no_outliers["Socio_Demo_05"], y=train_df_no_outliers["Poder_Adquisitivo"],kind='kde')
```
Veamos ahora la correlación de las variables explicativas con el poder adquisitivo, medida mediante el coeficiente de Pearson.
```
train_df_no_outliers.corr(method='pearson').iloc[-1].sort_values(ascending=False,axis=0)[1:]
```
Vemos como algunas variables presentan coeficientes de correlación medios, lo que indica que serán útiles para los modelos.
<a name=Entrenamientodemodelos></a>
# Entrenamiento de modelos
<a name=Preparacióndedatos></a>
## Preparación de datos
Con todo lo visto anteriormente estamos listos para preparar los datos para la experimentación. Vamos a definir una función que realize este pre-procesado de los datos.
La transformación básica consiste en convertir las variables categóricas a valores one-hot, y eliminar la columna ID_Customer que no es más que un identificador del cliente.
Con processing_type = 1 se puede indicar además que queremos filtrar los outliers (pero únicamente en tiempo de entrenamiento)
```
def process_df(df,processing_type,train = True):
if processing_type == 1:
return process_df_1(df,train)
else:
return process_df_1(df,False)
def process_df_1(df,train = True):
df = df.drop(labels=["ID_Customer"],axis=1)
if train:
# Eliminamos los outliers solo en el caso de que estemos entrenando
q1 = df["Poder_Adquisitivo"].quantile(0.25)
q3 = df["Poder_Adquisitivo"].quantile(0.75)
iqr = q3 - q1
fence_low = q1 - 1.5 * iqr
fence_high = q3 + 1.5 * iqr
df = df.loc[(df["Poder_Adquisitivo"] > fence_low) & (df["Poder_Adquisitivo"] < fence_high)]
# Convertimos las variables a one-hot
# Socio_Demo_01
topk_socio_01 = df["Socio_Demo_01"].value_counts()[:10]
socio_01_keys = list(topk_socio_01.keys())
for key in socio_01_keys:
on = df["Socio_Demo_01"] == key
df.insert(loc=len(df.columns), column="Socio_Demo_01_"+str(key), value=on.astype(int))
# El resto lso agrupamos en 'Other'
condition_array = [False] * len(df["Socio_Demo_01"])
for i in range(len(condition_array)):
condition_array[i] = str(df["Socio_Demo_01"].iloc[i]) not in socio_01_keys
df.insert(loc=len(df.columns), column="Socio_Demo_01_Other", value=condition_array)
df["Socio_Demo_01_Other"] = df["Socio_Demo_01_Other"].astype(int)
df = df.drop(axis=1, columns=["Socio_Demo_01"])
# Socio_Demo_02
c1=df["Socio_Demo_02"] == 1
c2=df["Socio_Demo_02"] == 2
df.insert(loc=len(df.columns), column="Socio_Demo_02_01", value=c1.astype(int))
df.insert(loc=len(df.columns), column="Socio_Demo_02_02", value=c2.astype(int))
df = df.drop(axis=1, columns=["Socio_Demo_02"])
# Convertimos todas las columnas Ind_prod a one-hot
for i in range(1,25):
column_name = "Ind_Prod_" + str(i).zfill(2)
c0=df[column_name] == 0
c1=df[column_name] == 1
c2=df[column_name] == 2
df.insert(loc=len(df.columns), column=column_name + "_00", value=c0.astype(int))
df.insert(loc=len(df.columns), column=column_name + "_01", value=c1.astype(int))
df.insert(loc=len(df.columns), column=column_name + "_02", value=c2.astype(int))
df = df.drop(axis=1, columns=[column_name])
return df
```
En primer lugar vamos a barjar los datos, y a continuación vamos a realizar una partición de los datos para realizar **validación cruzada** en 5 bloques, con el objetivo de realizar un análisis de resultados de los diferentes modelos de manera correcta y fiable.
Este método divide los datos en los conjustos de entrenamiento y test para cada partición, y los almacena en la variable splits.
```
SEED = 4
K = 5
shuffled_data = train_df.sample(frac=1,replace=False,random_state=SEED)
kf = KFold(n_splits=K)
kf.get_n_splits(shuffled_data)
def get_splits(kf,processing_type):
splits=[]
for train_index, test_index in kf.split(shuffled_data):
train_data = shuffled_data.loc[train_index]
test_data = shuffled_data.loc[test_index]
train_data_proc = process_df(train_data,processing_type,train=True)
test_data_proc = process_df(test_data,processing_type,train=False)
splits.append((train_data_proc,test_data_proc))
return splits
```
Dado un modelo y los splits que hemos realizado a los datos, a continuación definimos una función que, para cada partición de entrenamiento y test, entrene un modelo con los datos de entrenamiento correspondiente y calcule métricas sobre el conjunto de validación.
En lo que se refiere a métricas, en primer lugar hemos escogido la **ráiz del error cuadrático medio (RMSE)**, una de las métricas más comunes para evaluar modelos de regresión. El problema que tiene esta métrica es que penaliza de manera desmedida fallos grandes. Resulta mucho más interesante medir el funcionamiento del algoritmo con una métrica que refleje mejor su funcionamiento con la mayoría de clientes, cosa que consideramos más útil a la hora de decidirnos por un modelo u otro. Por eso medimos los resultados con respecto a la **media del error absoluto (MAE)** y a la **mediana del error (MAD).** Esta última métrica no es susceptible a outliers y nos permite conocer mejor cual es el comportamiento "medio" de cada modelo.
```
def train_and_evaluate(model,splits,skcompat=False,scaler=None):
rmse = []
mae = []
mad = []
# Para cada iteración de validación cruzada
for s in range(len(splits)):
train_data_proc,test_data_proc = splits[s]
# Obtenemos los datos de entrenamiento
x_train = train_data_proc.drop(labels=["Poder_Adquisitivo"],axis=1).as_matrix()
y_train = train_data_proc["Poder_Adquisitivo"].as_matrix()
# Obtenemos los datos de test
x_test = test_data_proc.drop(labels=["Poder_Adquisitivo"], axis=1).as_matrix()
y_test = test_data_proc["Poder_Adquisitivo"].as_matrix()
# Damos la posiblidad de usar un scaler
if scaler is not None:
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
# Caso base, entrenamos un modelo y obtenemos las predicciones
if not skcompat:
model.fit(X=x_train,y=y_train)
yhat = model.predict(X=x_test)
# En el caso de que sea un objeto skcompat, las llamadas a los métodos son ligeramente diferentes.
else:
model.fit(x=x_train,y=y_train,steps=STEPS)
yhat = model.predict(x=x_test)['scores']
# Calculamos métricas
rmse.append(math.sqrt(mean_squared_error(y_true=y_test, y_pred=yhat)))
mae.append(mean_absolute_error(y_true=y_test,y_pred=yhat))
mad.append(median_absolute_error(y_true=y_test,y_pred=yhat))
return (rmse,mae,mad)
```
Por último, nos definimos un método para guardar los resultados para su posterior visualización.
```
scores = {'modelo':[], 'rmse':[],'mae':[],'mad':[]}
def record_scores(name,rmse,mae,mad):
scores['modelo'].append(name)
scores['rmse'].append(rmse)
scores['mae'].append(mae)
scores['mad'].append(mad)
```
<a name=Experimentos></a>
## Experimentos
A continuación vamos a exponer una serie de resultados que hemos obtenido evaluando diferentes modelos. Cabe destacar que la cantidad de experimentos realizada es mucho mayor de la mostrada aquí, pero se ha llevado a cabo una selección de aquellos que, a nuestro juicio, son más interesantes. En caso contrario este documento hubiera sido todavía más largo de lo que ya es.
En primer lugar probaremos diferentes modelos tras aplicar el preproceso en el que eliminamos **outliers.**
```
splits = []
splits = get_splits(kf,1)
```
Inicialmente probamos diferentes modelos de regresión lineal.
```
model = LinearRegression()
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('Linear Regresion',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = Lasso(random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('Lasso',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = Ridge(random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('Ridge',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = ElasticNet(random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('ElasticNet',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
```
Todos los modelos lineales parecen obtener resultados comparables. Probamos ahora con redes neuronales.
```
model = MLPRegressor(max_iter=200,hidden_layer_sizes=(25,25,25),early_stopping=True,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = MLPRegressor(max_iter=200,hidden_layer_sizes=(50,50,50),early_stopping=True,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = MLPRegressor(max_iter=200,hidden_layer_sizes=(25,25,25,25),early_stopping=True,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = MLPRegressor(max_iter=200,hidden_layer_sizes=(50,50,50,50),early_stopping=True,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('ANN50*4',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = MLPRegressor(max_iter=200,hidden_layer_sizes=(25,25,25,25,25),early_stopping=True,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
```
Probamos ahora diferentes modelos basados en árboles.
```
model = DecisionTreeRegressor(min_samples_split=200, min_samples_leaf=50, random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('RegressionTree',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=5, max_features='log2',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=7, max_features='log2',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=17, max_features='log2',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('RF_d17',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
```
Podemos ver como la profundidad máxima afecta de manera importante al rendimiento.
```
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=23, max_features='log2',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('RF_d23',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=23, max_features='auto',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('RF_d23_FULL',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
```
El permitir que se hagan splits sobre todas las features incrementa sustancialmente el tiempo de entrenamiento, pero hace que este modelo supere al rest.
Probamos ahora con la técnica de Gradient Boosting.
```
model = GradientBoostingRegressor(random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = GradientBoostingRegressor(random_state=SEED,min_samples_leaf=5)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
model = GradientBoostingRegressor(random_state=SEED,min_samples_leaf=5,max_depth=5)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('Gradient Boost_d5',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = GradientBoostingRegressor(random_state=SEED,min_samples_leaf=5,max_depth=7)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('Gradient Boost_d7',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
```
De nuevo, llegados a este punto los modelos empiezan a requerar un tiempo de entrenamiento elevado a medida que se aumenta la profundidad máxima.
Una comparación importante a realizar es comprobar si nuestra idea inicial de eliminar outliers ha dado sus frutos. Probamos ahora a entrenar una serie de modelos ***sin eliminar outliers***.
```
splits = []
splits = get_splits(kf,0)
model = LinearRegression()
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw Linear Regression',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = MLPRegressor(max_iter=200,hidden_layer_sizes=(50,50,50,50),early_stopping=True,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw ANN50*4',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=23, max_features='log2',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw RF_d23',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = GradientBoostingRegressor(random_state=SEED,min_samples_leaf=5,max_depth=5)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw Gradient Boost_d5',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=23, max_features='auto',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw RF_d23_FULL',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
```
Sorprendentemente, si bien para el resto de modelos si que apreciamos que el filtrado de outliers supone sustanciales ganancias en términos de MAE y MAD, en el caso del Random Forest la pequeña diferencia en MAD se ve compensado por una reducción muy importante en RMSE y MAE.
```
model = RandomForestRegressor(n_estimators=100, criterion='mse', max_depth=23, max_features='auto',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw RF_d23_n100_FULL',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
model = RandomForestRegressor(n_estimators=50, criterion='mse', max_depth=24, max_features='auto',min_samples_leaf=5,random_state=SEED)
scores_rmse,scores_mae,scores_mad = train_and_evaluate(model,splits)
print("RMSE: %f" % np.mean(scores_rmse))
print("MAE: %f" % np.mean(scores_mae))
print("MAD: %f" % np.mean(scores_mad))
record_scores('raw RF_d24_FULL',np.mean(scores_rmse),np.mean(scores_mae),np.mean(scores_mad))
```
Llegados a este punto no hemos podido investigar más configuraciones debido a falta de tiempo y que las diferentes prubas de cambios de hiperparámetros, si bien aportan una pequeña mejora de los resultados, también han traido un aumento muy sustancial del tiempo de cómputo.
<a name=Comparacióndemodelos></a>
## Comparación de modelos
```
scores_df = pd.DataFrame(data=scores)
scores_df = scores_df.set_index('modelo')
display(scores_df)
scores_df = scores_df.sort_values(by="mad")
scores_df.plot(kind='bar',y='mad',colormap='Blues_r',figsize=(12, 8))
scores_df = scores_df.sort_values(by="mae")
scores_df.plot(kind='bar',y='mae',colormap='Oranges_r',figsize=(12, 8))
scores_df = scores_df.sort_values(by="rmse")
scores_df.plot(kind='bar',y='rmse',colormap='Greens_r',figsize=(12, 8))
```
Teniendo en cuenta todo esto, finalmente nos hemos decidido por el modelo **raw RF_d23_n100_FULL**. Inicialmente, y con la mayoría de modelos, nuestra idea inicial de eliminar outliers había obtenido mejoras muy grandes en MAE y MAD que, a nuestro juicio, compensaban de sobra pequeñas pérdidas en RMSE ya que mejoraban el conjunto de las predicciones. Sin embargo, los modelos de Random Forest profundos han demostrado que son capaces de reducir de enorme manera los grandes errores cometidos en algunos clientes puntuales, a cambio de una pequeña pérdida de MAD. Si bien el rendimiento se reducirá muy ligeramente en general (en realidad se reduce de manera ínfima, si nos fijamos en el MAD, significa que el error mediano empeora sólo en 30€), esto nos va a permitir cometer fallos mucho más pequeños en clientes atípicos, ya que reducimos en más de 4000€ el RMSE, por lo que finalmente hemos optado por este modelo.
<a name=Predicción></a>
# Predicción
```
splits = []
model = RandomForestRegressor(n_estimators=100, criterion='mse', max_depth=23, max_features='auto',min_samples_leaf=5,random_state=SEED)
# Entrenamos con todos los datos
f_train_df = process_df(train_df,0,train = True)
x_train = f_train_df.drop(labels=["Poder_Adquisitivo"],axis=1).as_matrix()
y_train = f_train_df["Poder_Adquisitivo"].as_matrix()
model.fit(X=x_train,y=y_train)
test_df = pd.read_csv("data/original/Dataset_Salesforce_Predictive_Modelling_TEST.txt")
ids = test_df["ID_Customer"].copy()
test_df = process_df(test_df,0,train = False)
x_test = test_df.as_matrix()
# Estiamamos el poder adquisitivo
y = model.predict(X=x_test)
```
Solo nos falta escribir estos resultados en disco.
```
out = pd.DataFrame(np.stack((ids, y), axis=1, out=None), columns=['ID_Customer', 'PA_Est']).set_index('ID_Customer')
out.to_csv('Test_Mission.txt')
```
| github_jupyter |
```
import numpy as np
from numpy import pi, cos, sin, array, mean
from scipy.linalg import toeplitz
import matplotlib.pyplot as plt
plt.style.use('dark_background')
np.set_printoptions(precision=4)
from warnings import filterwarnings
filterwarnings('ignore', category=UserWarning)
```
## Convolution
```
x = np.array([2,2,3, 4, 2,2, 4], np.int)
h = np.array([3,3,2], np.int)
np.convolve(x, h, 'full')
toeplitz(x, np.zeros_like(h)) @ h
h_long = np.zeros_like(x)
h_long[:len(h)] = h
toeplitz(h_long, np.zeros_like(x)) @ x
```
## Correlation
```
x = array([1, 1j, -1, -1j])
y = x.copy()
np.correlate(x, y)
n = np.arange(60)
waveform = 2*cos(2*pi*0.1*n) + cos(2*pi*0.2*n) + 4*cos(2*pi*0.3*n)
signal = cos(2*pi*0.3*n)
np.correlate(waveform, signal)/len(signal)
```
### Sinusoid of arbitrary phase
```
waveform = 2*cos(2*pi*0.1*n + pi/4) + cos(2*pi*0.2*n) + 4*cos(2*pi*0.3*n)
signal_i = cos(2*pi*0.1*n)
signal_q = sin(2*pi*0.1*n)
A = 2*np.correlate(waveform, signal_i)/len(signal_i)
B = 2*np.correlate(waveform, signal_q)/len(signal_i)
M = A + B*1j
M = np.squeeze(M)
print(f'Amplitude = {np.abs(M):.1f} Phase = {-np.angle(M, deg=True):.1f}')
```
### Specialized Codes
```
B = array([1, 1, 1, -1, -1, -1, 1, -1, -1, 1, -1])
SNR = 10 # dB
power_of_B = mean(B**2)
SNR_linear = 10**(SNR/10)
noise_power = power_of_B / SNR_linear
awgn = np.sqrt(noise_power) * np.random.randn(200)
rx_signal = awgn + np.pad(B, (50, 139), 'constant')
corr = np.correlate(rx_signal, B, 'full')
plt.plot(rx_signal);
plt.plot(corr/max(corr), 'r');
plt.plot(rx_signal - awgn, 'y')
C = B[::-1]
shift_register = np.zeros_like(C, np.float)
output = np.zeros_like(rx_signal)
for idx, sample in enumerate(rx_signal):
shift_register = np.roll(shift_register, 1)
shift_register[0] = sample
output[idx] = np.dot(shift_register, C)
np.max(corr), np.max(output)
```
### Walsh Codes
```
Walsh = array([[1, 1, 1, 1, 1, 1, 1, 1],
[1, -1, 1, -1, 1, -1, 1, -1],
[1, 1, -1, -1, 1, 1, -1, -1],
[1, -1, -1, 1, 1, -1, -1, 1],
[1, 1, 1, 1, -1, -1, -1, -1],
[1, -1, 1, -1, -1, 1, -1, 1],
[1, 1, -1, -1, -1, -1, 1, 1],
[1, -1, -1, 1, -1, 1, 1, -1]])
Walsh
u0_data = array([1, -1, 1])
u1_data = array([-1, -1, 1])
u2_data = array([-1, 1, -1])
user0_data = array([1, -1, 1])
user1_data = array([-1, -1, 1])
user2_data = array([-1, 1, -1])
u0_coded = (user0_data[:, np.newaxis] * Walsh[0]).flatten()
u1_coded = (user1_data[:, np.newaxis] * Walsh[1]).flatten()
u2_coded = (user2_data[:, np.newaxis] * Walsh[2]).flatten()
composite = u0_coded + u1_coded + u2_coded
fig, ax = plt.subplots(4, 1);
ax[0].stem(u0_coded, use_line_collection = True)
ax[1].stem(u1_coded, use_line_collection = True)
ax[2].stem(u2_coded, use_line_collection = True)
ax[3].stem(composite, use_line_collection = True);
u0_correlator = np.correlate(composite, Walsh[0], 'full')
u1_correlator = np.correlate(composite, Walsh[1], 'full')
u2_correlator = np.correlate(composite, Walsh[2], 'full')
u0_decoded = u0_correlator[7::8]/8
u1_decoded = u1_correlator[7::8]/8
u2_decoded = u2_correlator[7::8]/8
decoded_data = np.vstack([u0_decoded, u1_decoded, u2_decoded]).astype(np.int)
decoded_data
```
#### Auto-correlation
```
B = array([1, 1, 1, -1, -1, -1, 1, -1, -1, 1, -1])
C = array([1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1])
fig, ax = plt.subplots(2, 1)
ax[0].stem(np.correlate(B, B, 'same'), use_line_collection = True)
ax[1].stem(np.correlate(C, C, 'same'), use_line_collection = True)
np.correlate(C, C, 'same')
np.correlate(B, B, 'same')
```
## Fourier Transform
```
N = 20
n = np.arange(N)
test_seq1 = cos(2*pi*0.1*n)
test_seq2 = np.exp(2j*pi*0.315*n)
test_seq3 = np.exp(2j*pi*0.1*n) + 0.01*np.exp(2j*pi*(-0.25)*n)
def DTFT(test_seq, freq_resolution=0.001):
freqs = np.arange(-0.5, 0.5, freq_resolution)
N = len(test_seq)
n = np.arange(N)
dtft = np.zeros_like(freqs, np.complex)
for idx, freq in enumerate(freqs):
analysis_tone = np.exp(2j*pi*freq*n)
dtft[idx] = np.correlate(test_seq, analysis_tone).squeeze()/N
return dtft, freqs
dtft, freqs = DTFT(test_seq3)
magnitude = np.abs(dtft)
plt.plot(freqs, magnitude);
plt.xticks(np.arange(-0.5, 0.6, 0.1));
plt.ylim((0, 1));
magnitude_db = 20*np.log10(magnitude)
plt.plot(freqs, magnitude_db)
plt.xticks(np.arange(-0.5, 0.6, 0.1));
plt.ylim((-60, 0));
n_long = np.arange(100)
test_seq3_long = np.exp(2j*pi*0.1*n_long) + 0.01*np.exp(2j*pi*(-0.25)*n_long)
dtft, _ = DTFT(test_seq3_long)
magnitude = np.abs(dtft)
magnitude_db = 20*np.log10(magnitude)
plt.plot(freqs, magnitude_db)
plt.xticks(np.arange(-0.5, 0.6, 0.1));
plt.ylim((-60, 0));
```
#### WIndow
```
N = 40
n = np.arange(N)
rectangular = np.ones_like(n)
hanning = (40/20.5)*(0.5 - 0.5*cos( 2*pi*(n+1)/(N+1) ))
test_seq = np.exp(2j*pi*0.1*n) + 0.01*np.exp(-2j*pi*0.25*n)
rect_seq = test_seq*rectangular
dtft_rect, freqs = DTFT(rect_seq, 0.002)
mag_rect = np.abs(dtft_rect)
mag_rect_db = 20*np.log10(mag_rect)
hanning_seq = test_seq*hanning
dtft_hann, freqs = DTFT(test_seq*hanning, 0.002)
mag_hann = np.abs(dtft_hann)
mag_hann_db = 20*np.log10(mag_hann)
fig, ax = plt.subplots(2, 1)
ax[0].plot(rect_seq.real, '-o')
ax[0].plot(rect_seq.imag, '-.o')
ax[1].plot(hanning_seq.real, '-o')
ax[1].plot(hanning_seq.imag, '-.o');
plt.plot(freqs, mag_rect_db)
plt.xticks(np.arange(-0.5, 0.6, 0.1));
plt.ylim((-60, 0));
plt.plot(freqs, mag_hann_db)
plt.xticks(np.arange(-0.5, 0.6, 0.1));
plt.ylim((-60, 0));
```
### DFT
```
N = 15
n = np.arange(N)
Fs = 1e6
Ts = 1/Fs
f0 = 100e3
test_seq = np.exp(2j*pi*f0*n*Ts)
dft = np.zeros_like(test_seq, np.complex)
for m in np.arange(N):
analysis_tone = np.exp(2j*pi*n*m/N)
dft[m] = np.correlate(test_seq, analysis_tone).squeeze()/N
freqs = np.arange(N)*Fs/N
freqs[freqs>=Fs/2] -= Fs
dtft, dtft_freqs = DTFT(test_seq, 0.01)
magnitude = np.abs(dft)
plt.stem(freqs, magnitude);
plt.plot(dtft_freqs*Fs, np.abs(dtft), 'r');
```
### IDFT
```
N = len(dft)
m = np.arange(N)
idft = np.zeros_like(dft)
for n in np.arange(N):
tones = np.exp(2j*pi*n*m/N)
idft[n] = np.sum( dft.dot(tones))
np.max(idft-test_seq)
plt.plot(idft.real)
plt.plot(idft.imag, 'r-o');
```
#### 16-Point DFT using radix-2
```
def reverse_bit_order(x, num_bits):
reversed_bits = f'{x:0{num_bits}b}'[::-1]
return int(reversed_bits, 2)
M = 16
stages = np.log2(M).astype(int)
order = [reverse_bit_order(x, stages) for x in range(M)]
# Test sequence
n = np.arange(M)
f = 0.2
test_seq = cos(2*pi*f*n/1) # Sample rate is 1
# Freqs
freqs = np.arange(M)/M
freqs[freqs>=1/2] -= 1
memory = np.zeros((M, stages+1), np.complex) # one extra memory bank to store the input
memory[:, 0] = test_seq[order]
# Butterfly calculation
for section in range(1, stages+1):
N = 2**section # N-point DFT in this section
blocks = M//N # Number of N-point DFTs
I = 2**(section-1) # range of i
prev_section = section-1
for block in range(blocks):
offset = N*block
for i in range(I):
ini = memory[i+offset, prev_section]
iniN_2 = memory[i+N//2+offset, prev_section]
Wi = np.exp(-2j*pi*i/N)
WiN_2 = np.exp(-2j*pi*(i+N/2)/N)
memory[i+offset, section] = ini + Wi * iniN_2
memory[i+N//2+offset, section] = ini + WiN_2 * iniN_2
output = memory[:, stages]/M
dtft, dtft_freqs = DTFT(test_seq)
plt.stem( freqs, np.abs(output) );
plt.plot( dtft_freqs, np.abs(dtft), 'r');
plt.xticks(np.arange(-0.5, 0.6, 0.1));
```
## FIR Filter Design
#### Design
```
# Defining the frequency response
N = 13
f = np.arange(N)/N
f[f>0.5] -= 1
cutoff = 3.5 # MHz
Fs = 20 # Mhz
mag = np.zeros_like(f)
mag[abs(f)<(cutoff/Fs)] = 1
phase = np.zeros_like(f)
H = mag*np.exp(1j*phase)
f_spec = f.copy()
# IDFT
h = np.zeros_like(f, np.complex)
times = np.arange(-(N//2), 1+N//2)
for idx, n in enumerate(times):
tones = np.exp(2j*pi*n*f)
h[idx] = H.dot(tones)
```
##### Vectorized IDFT
```
m = np.arange(N)
times = np.arange(N)
times[times>N//2] -= N
idx_matrix = m*m[:, np.newaxis]
idft_matrix = np.exp(idx_matrix*(2j*pi/N))
h = H @ idft_matrix
```
```
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
ax[0].stem(times, h.real);
ax[1].stem(times, h.imag.round(2));
```
#### Testing the filter
```
# Test the filter
freqs = np.arange(-0.5, 0.5, 0.002)
dtft_output = np.zeros_like(freqs, np.complex)
norm_factor = np.abs(h.sum())
h = h/norm_factor
n = times.copy()
for idx, f_norm in enumerate(freqs):
tones = np.exp(2j*pi*f_norm*n)
dtft_output[idx] = h.dot(tones)
mag_response = np.abs(dtft_output)
mag_response_db = 20*np.log10(mag_response)
plt.plot(freqs, mag_response);
plt.stem(f_spec, mag, 'r');
plt.grid()
plt.plot(freqs, mag_response_db);
plt.grid()
```
#### Adding a window
```
n = np.arange(N)
b = 1 # Exponent of customized Hanning window
custom_hanning = (0.5 - 0.5*cos( 2*pi*(n+1)/(N+1) ))**b
new_h = h*custom_hanning
new_h = new_h/np.abs(new_h.sum())
dtft, freqs = DTFT(new_h*N, 0.002)
new_mag = np.abs(dtft)
new_mag_db = 20*np.log10(new_mag)
plt.plot(freqs, mag_response_db, '-.y')
plt.plot(freqs, new_mag_db)
plt.grid()
scale_factor = np.abs(custom_hanning.sum())
fix, ax = plt.subplots(1, 2, figsize=(10,4))
ax[0].stem(times, h.real)
ax[0].plot(times, custom_hanning/scale_factor, 'r-.')
ax[1].stem(times, new_h.real);
```
#### Check waveform
```
filter_coeffs = new_h.real
filter_coeffs
n = np.arange(200)
waveform = cos(2*pi*n*(2/20)) + cos(2*pi*n*(6/20)) # Fs = 20, cutoff = 3 MHz
output = np.zeros_like(waveform)
delay_line = np.zeros_like(filter_coeffs, np.float)
for idx, sample in enumerate(waveform):
delay_line = np.roll(delay_line, 1)
delay_line[0] = sample
output[idx] = np.dot(delay_line, filter_coeffs)
_, ax = plt.subplots(2, 1)
ax[0].plot(n, waveform)
ax[1].plot(n, output);
```
### Phase and Group delay
```
h = array([0, 0.5, 1, 0]) # Also try [0, 1, 1, 0]
h = h/np.abs(h.sum())
N = len(h)
n = np.arange(N)
delta_f = 0.002
H, freqs = DTFT(N*h, delta_f)
mag = np.abs(H)
phase_response = np.unwrap(np.angle(H))
# Group delay
group_delay = np.zeros_like(freqs)
group_delay[1:] = -(np.diff(phase_response)/delta_f)/(2*pi)
group_delay[0] = group_delay[1]
_, ax = plt.subplots(1, 2, figsize=(10, 4))
ax[0].plot(freqs, phase_response)
ax[0].grid(linestyle='dotted')
ax[1].plot(freqs, group_delay.round(4));
ax[1].grid(linestyle='dotted')
```
| github_jupyter |
## Python Practice
### Problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
```
dictionary = {}
nums = [157, 42, 55, 95, 100]
target = 155
def twoSum(nums, target):
for i, v in enumerate(nums): # creates a list with indices and value
# print(i, v)
diff = target - v # find the difference between target and all the values of the list
# print(diff)
if diff in dictionary: # check if we do have that number in the dict
# print(dictionary[diff])
return [dictionary[diff], i]
dictionary[v] = i
print(dictionary[v])
# print(i)
return []
# if diff in dictionary:
# return [dictionary[temp], i]
# dictionary[v] = i
twoSum(nums, target)
```
#### Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
```
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def addTwoNumbers(self, l1, l2):
pass
l1 = [2,4,3]
l2 = [5,6,4]
str1 = ''.join(str(e) for e in l1)
str2 = ''.join(str(i) for i in l2)
print(str1)
print(str2)
str1 = (str1[::-1])
str2 = (str2[::-1])
addition = int(str1) + int(str2)
print(addition)
str(addition)
out = str(addition)[::-1]
out
output = [int(s) for s in out]
print(output)
```
# NumSum
```
class Solution:
def addTwoNumbers(self, l1, l2):
str1 = ''.join(str(e) for e in l1)
str2 = ''.join(str(i) for i in l2)
addition = str(int(str1) + int(str2))
output = [int(s) for s in addition[::-1]]
return output
l1 = [2, 4, 3]
l2 = [5, 6, 4]
s = Solution()
s.addTwoNumbers(l1, l2)
for i in l1:
print(i)
l1 = []
l2 = []
l1.append(i)
print(l1)
for a, A in J:
if a or A in S:
count +=1
if A in S:
count +=1
return count
# make S into a dictionary?
# check if the strings in J are in S?
count = 0
for j in J:
for s in S:
if j == s:
count +=1
return count
```
# Reverse an Integer
```
x = 210
str_x = str(abs(x))
print(str_x)
rev_x = int(str_x[::-1])
print(rev_x)
# we do not want it to print the 0 before the 12
def reverse(x):
str_x = str(abs(x))
rev_x = (str_x[::-1])
if x < 0:
reverse = '-' + rev_x
else:
reverse = int(rev_x)
return reverse
def reverse(x):
# str_x = str(abs(x))
# rev_x = (str_x[1::-1])
if x < 0:
str_x = str(x)
rev_x = -nt(str_x[:0:-1])
# print(rev_x)
# print(type(rev_x))
reverse = (rev_x*(-1))
else:
str_x = str(abs(x))
rev_x = (str_x[1::-1])
reverse = int(rev_x)
return reverse
x = -321
print(-x)
str_x = str(x)
print()
rev_x = (str_x[:0:-1])
print(rev_x)
print(type(rev_x))
rev_x
def reverse(x):
# str_x = str(abs(x))
# rev_x = (str_x[1::-1])
# if abs(x) >= 0xffffffff:
# return int(0)
if x < 0:
str_x = str(x)
rev_x = "-" + (str(x)[:0:-1])
reverse = int(rev_x)
else:
str_x = str(abs(x))
rev_x = (str_x[::-1])
reverse = int(rev_x)
if abs(reverse) >= 0xffffffff:
return 0
return reverse
list_x = [321, -123, 120, 1534236469]
for i in list_x:
print(reverse(i))
```
| github_jupyter |
```
import numpy as np
import csv
import time
np.random.seed(1234)
def randomize():
np.random.seed(time.time())
RND_MEAN = 0
RND_STD = 0.0030
LEARNING_RATE = 0.001
# Main function
def abalone_exec(epoch_count=10, mb_size=10, report=1):
load_abalone_dataset()
init_model()
train_and_test(epoch_count, mb_size, report)
# Load abalone dataset
def load_abalone_dataset():
with open('data\\abalone.csv') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader, None)
rows = []
for row in csvreader:
rows.append(row)
global data, input_cnt, output_cnt
input_cnt, output_cnt = 10, 1
data = np.zeros([len(rows), input_cnt + output_cnt])
for n, row in enumerate(rows):
if row[0] == 'I':
data[n, 0] = 1
if row[0] == 'M':
data[n, 1] = 1
if row[0] == 'F':
data[n, 2] = 1
data[n, 3:] = row[1:]
# Initialize neural network model
def init_model():
global weight, bias, input_cnt, output_cnt
weight = np.random.normal(RND_MEAN, RND_STD, [input_cnt, output_cnt])
bias = np.zeros([output_cnt])
# Train and test on dataset
def train_and_test(epoch_count, mb_size, report):
step_count = arrange_data(mb_size)
test_x, test_y = get_test_data()
for epoch in range(epoch_count):
losses, accs = [], []
for n in range(step_count):
train_x, train_y = get_train_data(mb_size, n)
loss, acc = run_train(train_x, train_y)
losses.append(loss)
accs.append(acc)
if report > 0 and (epoch + 1) % report == 0:
acc = run_test(test_x, test_y)
print('Epoch {}: loss={:5.3f}, accuracy={:5.3f}/{:5.3f}'.\
format(epoch + 1, np.mean(losses), np.mean(accs), acc))
final_acc = run_test(test_x, test_y)
print('\nFinal Test: final accuracy = {:5.3f}'.format(final_acc))
# Arrange dataset for mini-batch dataset
def arrange_data(mb_size):
global data, shuffle_map, test_begin_idx
shuffle_map = np.arange(data.shape[0])
np.random.shuffle(shuffle_map)
step_count = int(data.shape[0] * 0.8) // mb_size
test_begin_idx = step_count * mb_size
return step_count
# Get test dataset
def get_test_data():
global data, shuffle_map, test_begin_idx, output_cnt
test_data = data[shuffle_map[test_begin_idx:]]
return test_data[:, :-output_cnt], test_data[:, -output_cnt:]
# Get train dataset
def get_train_data(mb_size, nth):
global data, shuffle_map, test_begin_idx, output_cnt
if nth == 0:
np.random.shuffle(shuffle_map[:test_begin_idx])
train_data = data[shuffle_map[:test_begin_idx]]
return train_data[:, :-output_cnt], train_data[:, -output_cnt:]
# Run train processes
def run_train(x, y):
output, aux_nn = forward_neuralnet(x)
loss, aux_pp = forward_postproc(output, y)
accuracy = eval_accuracy(output, y)
G_loss = 1.0
G_output = backprop_postproc(G_loss, aux_pp)
backprop_neuralnet(G_output, aux_nn)
return loss, accuracy
# Run test processes
def run_test(x, y):
output, _ = forward_neuralnet(x)
accuracy = eval_accuracy(output, y)
return accuracy
# Calculate forward computations
def forward_neuralnet(x):
global weight, bias
output = np.matmul(x, weight) + bias
return output, x
# Calculate back-propagations
def backprop_neuralnet(G_output, x):
global weight, bias
g_output_w = x.transpose()
G_w = np.matmul(g_output_w, G_output)
G_b = np.sum(G_output, axis=0)
weight -= LEARNING_RATE * G_w
bias -= LEARNING_RATE * G_b
# Do postprocessing for forward computations
def forward_postproc(output, y):
diff = output - y
square = np.square(diff)
loss = np.mean(square)
return loss, diff
# Do postprocessing for back-propagations
def backprop_postproc(G_loss, diff):
shape = diff.shape
g_loss_square = np.ones(shape) / np.prod(shape)
g_square_diff = 2 * diff
g_diff_output = 1
G_square = g_loss_square * G_loss
G_diff = g_square_diff * G_square
G_output = g_diff_output * G_diff
return G_output
# Do postprocessing for back-propagations
def backprop_postproc_oneline(G_loss, diff):
return 2 * diff / np.prod(diff.shape)
# Evaluate accuracy
def eval_accuracy(output, y):
mdiff = np.mean(np.abs((output - y) / y))
return 1 - mdiff
```
| github_jupyter |
# Intro to BayesHopper
This tutorial is intended to help anyone learn how to run BayesHopper, a trans-dimensional sampler for pulsar timing array data analysis.
### Installation
```
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
%load_ext autoreload
#%load_ext line_profiler
%autoreload 2
exec('from __future__ import division')
import numpy as np
import numdifftools as nd
import os, glob, json
import matplotlib.pyplot as plt
import scipy.linalg as sl
import enterprise
from enterprise.pulsar import Pulsar
import enterprise.signals.parameter as parameter
from enterprise.signals import utils
from enterprise.signals import signal_base
from enterprise.signals import selections
from enterprise.signals.selections import Selection
from enterprise.signals import white_signals
from enterprise.signals import gp_signals
from enterprise.signals import deterministic_signals
import enterprise.constants as const
import corner
import libstempo as T2
import libstempo.toasim as LT
import libstempo.plot as LP
import enterprise_extensions
from enterprise_extensions import models, model_utils
from .. import BayesHopper
import healpy as hp
timdir = './ParGenerator/FakeTims/'
pardir = './ParGenerator/par/'
parfiles = sorted(glob.glob(pardir + '/JPSR*.par'))
timfiles = sorted(glob.glob(timdir + '/*_study4_highergwb.tim'))
print(parfiles)
print(timfiles)
print(len(parfiles))
psrs = []
for p, t in zip(parfiles, timfiles):
#print(p)
psr = Pulsar(p, t, ephem='DE436', clk=None)
psrs.append(psr)
%%time
#T_max should be SNR^2/25 --> hottest chain sees a signal with SNR=5
#SNR = sqrt(2*F_e)
#SNR1=; SNR2=
#T_max = ()^2/25 = () -->10
#number of chains should be set to have a spacing below 2 (maybe even below 1.5)
N=int(1e3)
T_max = 2.5
n_chain = 4
#T_max = 9.0
#n_chain = 6
samples, acc_fraction, swap_record, rj_record = BayesHopper.run_ptmcmc(N, T_max, n_chain, psrs[::4],
#n_source_prior=[30000.0,1.0],
#n_source_prior=[2000.0,1.0],
#T_ladder=[1.0, 1.15, 1.3],
max_n_source=10,
#n_source_start=0,
RJ_weight=2,
regular_weight=3,#was 6
noise_jump_weight=4,#5,
PT_swap_weight=4, #was 8
Fe_proposal_weight=3,#was 2
gwb_switch_weight=0,
fe_file="fstat_map_study2b.npz",
#fe_file="fstat_map_fake4.npz",
#fe_file="fstat_map_gwb.npz",
#fe_file="fstat_map_2source_v4_lowSNR_psrTerm.npz",
#fe_file="fstat_map_2source_v4_unequalSNR.npz",
#fe_file="fstat_map_fake.npz",
prior_recovery=False,
#gwb_log_amp_range=[-18,-13],
rn_log_amp_range=[-18,-13],
cw_log_amp_range=[-18,-13],
gwb_amp_prior='uniform',
rn_amp_prior='uniform',
#gwb_on_prior=0.8,
draw_from_prior_weight=0, de_weight=0,
vary_white_noise=True,
include_gwb=False, include_psr_term=False,
include_rn=True, vary_rn=True)
```
| github_jupyter |
## Homework №2
### Neural Machine Translation in the wild
In the third homework you are supposed to get the best translation you can for the machine translation translation task.
Please, select the language you prefer from the [OPUS webpage](http://opus.nlpl.eu/News-Commentary.php). You need the plain txt format which is availabe in the bottom of the page (last table, lower-left triangle (`Bottom-left triangle: download plain text files (MOSES/GIZA++)`)).
Please, select the language pairs with English (so it might be `en-ar` or `en-ru` etc.)
English will be the target language.
__Please, avoid the language pairs with small corpus (e.g. the en-ja). The link should be green if there is rather big dataset.__
After you downloaded the file, unzip in the working directory (`unzip <FILE_NAME>` in the console. Use `! unzip <FILE NAME>` in Colab).
Basic approach using RNNs as encoder and decoder is implemented for you.
Your ultimate task is to use the techniques we've covered, e.g.
* Optimization enhancements (e.g. learning rate decay)
* CNN encoder (with or without positional encoding)
* Pre-trained word embeddings for the source and target languages
* attention/self-attention mechanism
* pretraining the language model
* [Byte Pair Encoding](https://github.com/rsennrich/subword-nmt)
* or just fine-tunning BERT ;)
to improve the translation quality.
__Please use at least three different approaches/models and compare them (translation quality/complexity/training and evaluation time).__
Write down some summary on your experiments and illustrate it with convergence plots/metrics and your thoughts. Just like you would approach a real problem.
```
# You might need to install the libraries below. Do it in the desired environment
# if you are working locally.
# ! pip install subword-nmt
# ! pip install nltk
# ! pip install torchtext
# Uncomment the following cell on Colab
# ! wget https://raw.githubusercontent.com/neychev/harbour_dlia2020/master/homeworks/homework02/utils.py -nc
# ! wget https://raw.githubusercontent.com/neychev/harbour_dlia2020/master/homeworks/homework02/my_network.py -nc
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torchtext
from torchtext.datasets import TranslationDataset, Multi30k
from torchtext.data import Field, BucketIterator
import spacy
import random
import math
import time
import matplotlib
matplotlib.rcParams.update({'figure.figsize': (16, 12), 'font.size': 14})
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import clear_output
from nltk.tokenize import WordPunctTokenizer
from subword_nmt.learn_bpe import learn_bpe
from subword_nmt.apply_bpe import BPE
```
### Main part
__Here comes the preprocessing. Do not hesitate to use BPE or more complex preprocessing ;)__
```
tokenizer_W = WordPunctTokenizer()
def tokenize(x, tokenizer=tokenizer_W):
return tokenizer.tokenize(x.lower())
```
Change the filenames for your language pairs.
```
# E.g. here comes the download for the en-ru language pair
# !wget http://opus.nlpl.eu/download.php?f=News-Commentary/v11/moses/en-ru.txt.zip -O en-ru.txt.zip
# And unzip it
# !unzip en-ru.txt.zip
with open('News-Commentary.en-ru.ru', 'r') as iofile:
source = iofile.readlines()
with open('News-Commentary.en-ru.en', 'r') as iofile:
target = iofile.readlines()
assert not any(['\t' in x for x in source]), 'Tabulation is used as delimiter and should not be present in the source dataset'
assert not any(['\t' in x for x in target]), 'Tabulation is used as delimiter and should not be present in the target dataset'
```
The cell below combines the pairs into one dataset. `MAX_LENGTH` const can be adjusted, but avoid the phrases longer than 100 tokens.
```
combined = ['\t'.join([source[i].replace('\n', ''), target[i]]).replace('"', '')
for i in range(1, len(source)) if 2<len(tokenize(source[i]))<60 and 2<len(tokenize(target[i]))<60]
with open('combined_dataset.txt', 'w') as iofile:
iofile.writelines(combined)
SRC = Field(tokenize=tokenize,
init_token = '<sos>',
eos_token = '<eos>',
lower = True)
TRG = Field(tokenize=tokenize,
init_token = '<sos>',
eos_token = '<eos>',
lower = True)
dataset = torchtext.data.TabularDataset(
path='./combined_dataset.txt',
format='tsv',
fields=[('src', SRC), ('trg', TRG)]
)
train_data, valid_data, test_data = dataset.split(split_ratio=[0.8, 0.15, 0.05])
print(f"Number of training examples: {len(train_data.examples)}")
print(f"Number of validation examples: {len(valid_data.examples)}")
print(f"Number of testing examples: {len(test_data.examples)}")
```
You can adjust the `MIN_FREQ` as well (stick to ~10k unique tokens in each language).
```
MIN_FREQ_SRC = 40
MIN_FREQ_TRG = 45
SRC.build_vocab(train_data, min_freq = MIN_FREQ_SRC)
TRG.build_vocab(train_data, min_freq = MIN_FREQ_TRG)
print(f"Unique tokens in source vocabulary: {len(SRC.vocab)}")
print(f"Unique tokens in target (EN) vocabulary: {len(TRG.vocab)}")
```
Here are tokens from original corpus:
```
SRC.vocab.itos[::1000]
```
And from target (EN) corpus:
```
TRG.vocab.itos[::1000]
```
And here is example from train dataset:
```
print(vars(train_data.examples[9]))
```
Let's check the length distributions:
```
src_length = map(len, [vars(x)['src'] for x in train_data.examples])
trg_length = map(len, [vars(x)['trg'] for x in train_data.examples])
print('Length distribution in Train data')
plt.figure(figsize=[8, 4])
plt.subplot(1, 2, 1)
plt.title("source length")
plt.hist(list(src_length), bins=20);
plt.subplot(1, 2, 2)
plt.title("translation length")
plt.hist(list(trg_length), bins=20);
src_length = map(len, [vars(x)['src'] for x in test_data.examples])
trg_length = map(len, [vars(x)['trg'] for x in test_data.examples])
print('Length distribution in Test data')
plt.figure(figsize=[8, 4])
plt.subplot(1, 2, 1)
plt.title("source length")
plt.hist(list(src_length), bins=20);
plt.subplot(1, 2, 2)
plt.title("translation length")
plt.hist(list(trg_length), bins=20);
```
### Model side
__Here comes simple pipeline of NMT model learning. It almost copies the week03 practice__
```
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
device
def _len_sort_key(x):
return len(x.src)
BATCH_SIZE = 256
train_iterator, valid_iterator, test_iterator = BucketIterator.splits(
(train_data, valid_data, test_data),
batch_size = BATCH_SIZE,
device = device,
sort_key=_len_sort_key
)
for x in train_iterator:
break
print(x)
print(x.src.shape, x.trg.shape)
import my_network
Encoder = my_network.Encoder
Decoder = my_network.Decoder
Seq2Seq = my_network.Seq2Seq
INPUT_DIM = len(SRC.vocab)
OUTPUT_DIM = len(TRG.vocab)
ENC_EMB_DIM = 256
DEC_EMB_DIM = 256
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5
enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)
# dont forget to put the model to the right device
model = Seq2Seq(enc, dec, device).to(device)
def init_weights(m):
# <YOUR CODE HERE>
for name, param in m.named_parameters():
nn.init.uniform_(param, -0.08, 0.08)
model.apply(init_weights)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'The model has {count_parameters(model):,} trainable parameters')
PAD_IDX = TRG.vocab.stoi['<pad>']
optimizer = optim.Adam(model.parameters())
criterion = nn.CrossEntropyLoss(ignore_index = PAD_IDX)
def train(model, iterator, optimizer, criterion, clip, train_history=None, valid_history=None):
model.train()
epoch_loss = 0
history = []
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
optimizer.zero_grad()
output = model(src, trg)
#trg = [trg sent len, batch size]
#output = [trg sent len, batch size, output dim]
output = output[1:].view(-1, output.shape[-1])
trg = trg[1:].view(-1)
#trg = [(trg sent len - 1) * batch size]
#output = [(trg sent len - 1) * batch size, output dim]
loss = criterion(output, trg)
loss.backward()
# Let's clip the gradient
torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
optimizer.step()
epoch_loss += loss.item()
history.append(loss.cpu().data.numpy())
if (i+1)%10==0:
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 8))
clear_output(True)
ax[0].plot(history, label='train loss')
ax[0].set_xlabel('Batch')
ax[0].set_title('Train loss')
if train_history is not None:
ax[1].plot(train_history, label='general train history')
ax[1].set_xlabel('Epoch')
if valid_history is not None:
ax[1].plot(valid_history, label='general valid history')
plt.legend()
plt.show()
return epoch_loss / len(iterator)
def evaluate(model, iterator, criterion):
model.eval()
epoch_loss = 0
history = []
with torch.no_grad():
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
output = model(src, trg, 0) #turn off teacher forcing
#trg = [trg sent len, batch size]
#output = [trg sent len, batch size, output dim]
output = output[1:].view(-1, output.shape[-1])
trg = trg[1:].view(-1)
#trg = [(trg sent len - 1) * batch size]
#output = [(trg sent len - 1) * batch size, output dim]
loss = criterion(output, trg)
epoch_loss += loss.item()
return epoch_loss / len(iterator)
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
train_history = []
valid_history = []
N_EPOCHS = 10
CLIP = 1
best_valid_loss = float('inf')
for epoch in range(N_EPOCHS):
start_time = time.time()
train_loss = train(model, train_iterator, optimizer, criterion, CLIP, train_history, valid_history)
valid_loss = evaluate(model, valid_iterator, criterion)
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), 'tut1-model.pt')
train_history.append(train_loss)
valid_history.append(valid_loss)
print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')
print(f'\tTrain Loss: {train_loss:.3f} | Train PPL: {math.exp(train_loss):7.3f}')
print(f'\t Val. Loss: {valid_loss:.3f} | Val. PPL: {math.exp(valid_loss):7.3f}')
```
__Let's take a look at our network quality__:
```
import utils
import imp
imp.reload(utils)
generate_translation = utils.generate_translation
remove_tech_tokens = utils.remove_tech_tokens
get_text = utils.get_text
flatten = utils.flatten
```
Take a look at the example translation:
```
batch = next(iter(test_iterator))
for idx in [1,2]:
src = batch.src[:, idx:idx+1]
trg = batch.trg[:, idx:idx+1]
generate_translation(src, trg, model, TRG.vocab)
from nltk.translate.bleu_score import corpus_bleu
# """ Estimates corpora-level BLEU score of model's translations given inp and reference out """
# translations, _ = model.translate_lines(inp_lines, **flags)
# # Note: if you experience out-of-memory error, split input lines into batches and translate separately
# return corpus_bleu([[ref] for ref in out_lines], translations) * 100
import tqdm
original_text = []
generated_text = []
model.eval()
with torch.no_grad():
for i, batch in tqdm.tqdm(enumerate(test_iterator)):
src = batch.src
trg = batch.trg
output = model(src, trg, 0) #turn off teacher forcing
#trg = [trg sent len, batch size]
#output = [trg sent len, batch size, output dim]
output = output.argmax(dim=-1)
original_text.extend([get_text(x, TRG.vocab) for x in trg.cpu().numpy().T])
generated_text.extend([get_text(x, TRG.vocab) for x in output[1:].detach().cpu().numpy().T])
# original_text = flatten(original_text)
# generated_text = flatten(generated_text)
corpus_bleu([[text] for text in original_text], generated_text) * 100
corpus_bleu([[text] for text in original_text], generated_text) * 100
```
Baseline solution BLEU score is quite low. Try to achieve at least __18__ BLEU on the test set.
Here are some thresholds you might refer to (they may vary for different language pairs, but are good references for pairs line EN-FR or EN-GE):
* __18__ – good starting point
* __20__ – better
* __25__ – excellent score
| github_jupyter |
# TFRecord and tf.Example
**Learning Objectives**
1. Understand the TFRecord format for storing data
2. Understand the tf.Example message type
3. Read and Write a TFRecord file
## Introduction
In this notebook, you create, parse, and use the `tf.Example` message, and then serialize, write, and read `tf.Example` messages to and from `.tfrecord` files. To read data efficiently it can be helpful to serialize your data and store it in a set of files (100-200MB each) that can each be read linearly. This is especially true if the data is being streamed over a network. This can also be useful for caching any data-preprocessing.
Each learning objective will correspond to a __#TODO__ in the [student lab notebook](../labs/tfrecord-tf.example.ipynb) -- try to complete that notebook first before reviewing this solution notebook.
### The TFRecord format
The TFRecord format is a simple format for storing a sequence of binary records. [Protocol buffers](https://developers.google.com/protocol-buffers/) are a cross-platform, cross-language library for efficient serialization of structured data. Protocol messages are defined by `.proto` files, these are often the easiest way to understand a message type.
The `tf.Example` message (or protobuf) is a flexible message type that represents a `{"string": value}` mapping. It is designed for use with TensorFlow and is used throughout the higher-level APIs such as [TFX](https://www.tensorflow.org/tfx/).
Note: While useful, these structures are optional. There is no need to convert existing code to use TFRecords, unless you are using [`tf.data`](https://www.tensorflow.org/guide/datasets) and reading data is still the bottleneck to training. See [Data Input Pipeline Performance](https://www.tensorflow.org/datasets/performances) for dataset performance tips.
## Load necessary libraries
We will start by importing the necessary libraries for this lab.
```
# Run the chown command to change the ownership of the repository
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# You can use any Python source file as a module by executing an import statement in some other Python source file.
# The import statement combines two operations; it searches for the named module, then it binds the results of that search
# to a name in the local scope.
#!pip install --upgrade tensorflow==2.5
import tensorflow as tf
import numpy as np
import IPython.display as display
print("TensorFlow version: ",tf.version.VERSION)
```
Please ignore any incompatibility warnings and errors.
## `tf.Example`
### Data types for `tf.Example`
Fundamentally, a `tf.Example` is a `{"string": tf.train.Feature}` mapping.
The `tf.train.Feature` message type can accept one of the following three types (See the [`.proto` file](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto) for reference). Most other generic types can be coerced into one of these:
1. `tf.train.BytesList` (the following types can be coerced)
- `string`
- `byte`
1. `tf.train.FloatList` (the following types can be coerced)
- `float` (`float32`)
- `double` (`float64`)
1. `tf.train.Int64List` (the following types can be coerced)
- `bool`
- `enum`
- `int32`
- `uint32`
- `int64`
- `uint64`
In order to convert a standard TensorFlow type to a `tf.Example`-compatible `tf.train.Feature`, you can use the shortcut functions below. Note that each function takes a scalar input value and returns a `tf.train.Feature` containing one of the three `list` types above:
```
# TODO 1a
# The following functions can be used to convert a value to a type compatible
# with tf.Example.
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _int64_feature(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
```
Note: To stay simple, this example only uses scalar inputs. The simplest way to handle non-scalar features is to use `tf.serialize_tensor` to convert tensors to binary-strings. Strings are scalars in tensorflow. Use `tf.parse_tensor` to convert the binary-string back to a tensor.
Below are some examples of how these functions work. Note the varying input types and the standardized output types. If the input type for a function does not match one of the coercible types stated above, the function will raise an exception (e.g. `_int64_feature(1.0)` will error out, since `1.0` is a float, so should be used with the `_float_feature` function instead):
```
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))
```
All proto messages can be serialized to a binary-string using the `.SerializeToString` method:
```
# TODO 1b
feature = _float_feature(np.exp(1))
# `SerializeToString()` serializes the message and returns it as a string
feature.SerializeToString()
```
### Creating a `tf.Example` message
Suppose you want to create a `tf.Example` message from existing data. In practice, the dataset may come from anywhere, but the procedure of creating the `tf.Example` message from a single observation will be the same:
1. Within each observation, each value needs to be converted to a `tf.train.Feature` containing one of the 3 compatible types, using one of the functions above.
1. You create a map (dictionary) from the feature name string to the encoded feature value produced in #1.
1. The map produced in step 2 is converted to a [`Features` message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto#L85).
In this notebook, you will create a dataset using NumPy.
This dataset will have 4 features:
* a boolean feature, `False` or `True` with equal probability
* an integer feature uniformly randomly chosen from `[0, 5]`
* a string feature generated from a string table by using the integer feature as an index
* a float feature from a standard normal distribution
Consider a sample consisting of 10,000 independently and identically distributed observations from each of the above distributions:
```
# The number of observations in the dataset.
n_observations = int(1e4)
# Boolean feature, encoded as False or True.
feature0 = np.random.choice([False, True], n_observations)
# Integer feature, random from 0 to 4.
feature1 = np.random.randint(0, 5, n_observations)
# String feature
strings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])
feature2 = strings[feature1]
# Float feature, from a standard normal distribution
feature3 = np.random.randn(n_observations)
```
Each of these features can be coerced into a `tf.Example`-compatible type using one of `_bytes_feature`, `_float_feature`, `_int64_feature`. You can then create a `tf.Example` message from these encoded features:
```
def serialize_example(feature0, feature1, feature2, feature3):
"""
Creates a tf.Example message ready to be written to a file.
"""
# Create a dictionary mapping the feature name to the tf.Example-compatible
# data type.
feature = {
'feature0': _int64_feature(feature0),
'feature1': _int64_feature(feature1),
'feature2': _bytes_feature(feature2),
'feature3': _float_feature(feature3),
}
# Create a Features message using tf.train.Example.
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
return example_proto.SerializeToString()
```
For example, suppose you have a single observation from the dataset, `[False, 4, bytes('goat'), 0.9876]`. You can create and print the `tf.Example` message for this observation using `create_message()`. Each single observation will be written as a `Features` message as per the above. Note that the `tf.Example` [message](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/example.proto#L88) is just a wrapper around the `Features` message:
```
# This is an example observation from the dataset.
example_observation = []
serialized_example = serialize_example(False, 4, b'goat', 0.9876)
serialized_example
```
# You can parse TFRecords using the standard protocol buffer `.FromString` method
To decode the message use the `tf.train.Example.FromString` method.
```
# TODO 1c
example_proto = tf.train.Example.FromString(serialized_example)
example_proto
```
## TFRecords format details
A TFRecord file contains a sequence of records. The file can only be read sequentially.
Each record contains a byte-string, for the data-payload, plus the data-length, and CRC32C (32-bit CRC using the Castagnoli polynomial) hashes for integrity checking.
Each record is stored in the following formats:
uint64 length
uint32 masked_crc32_of_length
byte data[length]
uint32 masked_crc32_of_data
The records are concatenated together to produce the file. CRCs are
[described here](https://en.wikipedia.org/wiki/Cyclic_redundancy_check), and
the mask of a CRC is:
masked_crc = ((crc >> 15) | (crc << 17)) + 0xa282ead8ul
Note: There is no requirement to use `tf.Example` in TFRecord files. `tf.Example` is just a method of serializing dictionaries to byte-strings. Lines of text, encoded image data, or serialized tensors (using `tf.io.serialize_tensor`, and
`tf.io.parse_tensor` when loading). See the `tf.io` module for more options.
## TFRecord files using `tf.data`
The `tf.data` module also provides tools for reading and writing data in TensorFlow.
### Writing a TFRecord file
The easiest way to get the data into a dataset is to use the `from_tensor_slices` method.
Applied to an array, it returns a dataset of scalars:
```
tf.data.Dataset.from_tensor_slices(feature1)
```
Applied to a tuple of arrays, it returns a dataset of tuples:
```
features_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))
features_dataset
# Use `take(1)` to only pull one example from the dataset.
for f0,f1,f2,f3 in features_dataset.take(1):
print(f0)
print(f1)
print(f2)
print(f3)
```
Use the `tf.data.Dataset.map` method to apply a function to each element of a `Dataset`.
The mapped function must operate in TensorFlow graph mode—it must operate on and return `tf.Tensors`. A non-tensor function, like `serialize_example`, can be wrapped with `tf.py_function` to make it compatible.
Using `tf.py_function` requires to specify the shape and type information that is otherwise unavailable:
```
# TODO 2a
def tf_serialize_example(f0,f1,f2,f3):
tf_string = tf.py_function(
serialize_example,
(f0,f1,f2,f3), # pass these args to the above function.
tf.string) # the return type is `tf.string`.
return tf.reshape(tf_string, ()) # The result is a scalar
tf_serialize_example(f0,f1,f2,f3)
```
Apply this function to each element in the dataset:
```
# TODO 2b
# `.map` function maps across the elements of the dataset.
serialized_features_dataset = features_dataset.map(tf_serialize_example)
serialized_features_dataset
def generator():
for features in features_dataset:
yield serialize_example(*features)
# Create a Dataset whose elements are generated by generator using `.from_generator` function
serialized_features_dataset = tf.data.Dataset.from_generator(
generator, output_types=tf.string, output_shapes=())
serialized_features_dataset
```
And write them to a TFRecord file:
```
filename = 'test.tfrecord'
# `.TFRecordWriter` function writes a dataset to a TFRecord file
writer = tf.data.experimental.TFRecordWriter(filename)
writer.write(serialized_features_dataset)
```
### Reading a TFRecord file
You can also read the TFRecord file using the `tf.data.TFRecordDataset` class.
More information on consuming TFRecord files using `tf.data` can be found [here](https://www.tensorflow.org/guide/data#consuming_tfrecord_data).
Using `TFRecordDataset`s can be useful for standardizing input data and optimizing performance.
```
# TODO 2c
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
```
At this point the dataset contains serialized `tf.train.Example` messages. When iterated over it returns these as scalar string tensors.
Use the `.take` method to only show the first 10 records.
Note: iterating over a `tf.data.Dataset` only works with eager execution enabled.
```
# Use the `.take` method to pull ten examples from the dataset.
for raw_record in raw_dataset.take(10):
print(repr(raw_record))
```
These tensors can be parsed using the function below. Note that the `feature_description` is necessary here because datasets use graph-execution, and need this description to build their shape and type signature:
```
# Create a description of the features.
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):
# Parse the input `tf.Example` proto using the dictionary above.
return tf.io.parse_single_example(example_proto, feature_description)
```
Alternatively, use `tf.parse example` to parse the whole batch at once. Apply this function to each item in the dataset using the `tf.data.Dataset.map` method:
```
parsed_dataset = raw_dataset.map(_parse_function)
parsed_dataset
```
Use eager execution to display the observations in the dataset. There are 10,000 observations in this dataset, but you will only display the first 10. The data is displayed as a dictionary of features. Each item is a `tf.Tensor`, and the `numpy` element of this tensor displays the value of the feature:
```
for parsed_record in parsed_dataset.take(10):
print(repr(parsed_record))
```
Here, the `tf.parse_example` function unpacks the `tf.Example` fields into standard tensors.
## TFRecord files in Python
The `tf.io` module also contains pure-Python functions for reading and writing TFRecord files.
### Writing a TFRecord file
Next, write the 10,000 observations to the file `test.tfrecord`. Each observation is converted to a `tf.Example` message, then written to file. You can then verify that the file `test.tfrecord` has been created:
```
# Write the `tf.Example` observations to the file.
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)
# `du` stands for disk usage and is used to estimate the amount of disk space used by a given file or directory.
!du -sh {filename}
```
### Reading a TFRecord file
These serialized tensors can be easily parsed using `tf.train.Example.ParseFromString`:
```
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
raw_dataset
for raw_record in raw_dataset.take(1):
example = tf.train.Example()
example.ParseFromString(raw_record.numpy())
print(example)
```
## Walkthrough: Reading and writing image data
This is an end-to-end example of how to read and write image data using TFRecords. Using an image as input data, you will write the data as a TFRecord file, then read the file back and display the image.
This can be useful if, for example, you want to use several models on the same input dataset. Instead of storing the image data raw, it can be preprocessed into the TFRecords format, and that can be used in all further processing and modelling.
First, let's download [this image](https://commons.wikimedia.org/wiki/File:Felis_catus-cat_on_snow.jpg) of a cat in the snow and [this photo](https://upload.wikimedia.org/wikipedia/commons/f/fe/New_East_River_Bridge_from_Brooklyn_det.4a09796u.jpg) of the Williamsburg Bridge, NYC under construction.
### Fetch the images
```
# Downloads a file from a URL if it not already in the cache using `tf.keras.utils.get_file` function.
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')
# Check the image file
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>'))
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>'))
```
### Write the TFRecord file
As before, encode the features as types compatible with `tf.Example`. This stores the raw image string feature, as well as the height, width, depth, and arbitrary `label` feature. The latter is used when you write the file to distinguish between the cat image and the bridge image. Use `0` for the cat image, and `1` for the bridge image:
```
image_labels = {
cat_in_snow : 0,
williamsburg_bridge : 1,
}
# This is an example, just using the cat image.
image_string = open(cat_in_snow, 'rb').read()
label = image_labels[cat_in_snow]
# Create a dictionary with features that may be relevant.
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('...')
```
Notice that all of the features are now stored in the `tf.Example` message. Next, functionalize the code above and write the example messages to a file named `images.tfrecords`:
```
# Write the raw image files to `images.tfrecords`.
# First, process the two images into `tf.Example` messages.
# Then, write to a `.tfrecords` file.
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())
# `du` stands for disk usage and is used to estimate the amount of disk space used by a given file or directory.
!du -sh {record_file}
```
### Read the TFRecord file
You now have the file—`images.tfrecords`—and can now iterate over the records in it to read back what you wrote. Given that in this example you will only reproduce the image, the only feature you will need is the raw image string. Extract it using the getters described above, namely `example.features.feature['image_raw'].bytes_list.value[0]`. You can also use the labels to determine which record is the cat and which one is the bridge:
```
raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')
# Create a dictionary describing the features.
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):
# Parse the input tf.Example proto using the dictionary above.
return tf.io.parse_single_example(example_proto, image_feature_description)
parsed_image_dataset = raw_image_dataset.map(_parse_image_function)
parsed_image_dataset
```
Recover the images from the TFRecord file:
```
for image_features in parsed_image_dataset:
image_raw = image_features['image_raw'].numpy()
display.display(display.Image(data=image_raw))
```
Copyright 2020 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| github_jupyter |
# Dataset Creation
we have files
- `resultsAnnotation.tsv`,
- `datasetAnnotation.tsv`,
- `taskAnnotation.tsv`,
- `paper_links.tsv`,
- `TDM_taxonomy.tsv`,
- `TDMs_taxonomy.tsv`
- `paper_name_taxonomy.tsv`
Created mostly from the file `evaluation-tables.json` from [paperswithcode](https://paperswithcode.com/about)
```
# imports
import ipdb, os, re
import pandas as pd
from sklearn.model_selection import train_test_split
# with open(f"../data/resultsAnnotation.tsv", errors='replace') as f:
# resultsAnnotation = f.read().splitlines()
# with open(f"../data/datasetAnnotation.tsv", errors='replace') as f:
# datasetAnnotation = f.read().splitlines()
# with open(f"../data/taskAnnotation.tsv", errors='replace') as f:
# taskAnnotation = f.read().splitlines()
# with open(f"../data/TDM_taxonomy.tsv", errors='replace') as f:
# TDM_taxonomy = f.read().splitlines()
# with open(f"../data/paper_name_taxonomy.tsv", errors='replace') as f:
# paper_name_taxonomy = f.read().splitlines()
datasetAnnotation_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-nli-extraction/data/annotations_final/datasetAnnotation.tsv"
resultsAnnotation_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-nli-extraction/data/annotations_final/resultsAnnotation.tsv"
taskAnnotation_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-nli-extraction/data/annotations_final/taskAnnotation.tsv"
TDM_taxonomy_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-nli-extraction/data/annotations_final/TDM_taxonomy.tsv"
datasetAnnotation_IBM_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/ibm/NLP-TDMS/annotations/datasetAnnotation.tsv"
resultsAnnotation_IBM_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/ibm/NLP-TDMS/annotations/resultsAnnotation.tsv"
taskAnnotation_IBM_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/ibm/NLP-TDMS/annotations/taskAnnotation.tsv"
TDM_taxonomy_IBM_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/ibm/NLP-TDMS/annotations/TDM_taxonomy.tsv"
datasetAnnotation = pd.read_csv(datasetAnnotation_csv,
sep="\t", names=["label", "datasets"])
resultsAnnotation = pd.read_csv(resultsAnnotation_csv,
sep="\t", names=["label", "TDMS"])
taskAnnotation = pd.read_csv(taskAnnotation_csv,
sep="\t", names=["label", "tasks"])
TDM_taxonomy = pd.read_csv(TDM_taxonomy_csv,
sep="\t", names=["tdm", "count"])
datasetAnnotation_IBM = pd.read_csv(datasetAnnotation_IBM_csv,
sep="\t", names=["label", "datasets"])
resultsAnnotation_IBM = pd.read_csv(resultsAnnotation_IBM_csv,
sep="\t", names=["label", "TDMS"])
taskAnnotation_IBM = pd.read_csv(taskAnnotation_IBM_csv,
sep="\t", names=["label", "tasks"])
TDM_taxonomy_IBM = pd.read_csv(TDM_taxonomy_IBM_csv,
sep="\t", names=["tdm", "count"])
annotations_merged = "/nfs/home/kabenamualus/Research/task-dataset-metric-nli-extraction/data/annotations_merged/"
```
## datasetAnnotation
```
datasetAnnotation.tail()
datasetAnnotation_IBM.tail()
datasetAnnotationMerge = datasetAnnotation.merge(datasetAnnotation_IBM, how='outer')
datasetAnnotationMerge[datasetAnnotationMerge.label.duplicated()]
datasetAnnotationMerge.to_csv(f"{annotations_merged}datasetAnnotation.tsv",
header=False, index=False, sep="\t")
pd.read_csv(f"{annotations_merged}datasetAnnotation.tsv",
sep="\t", names=["label", "datasets"]).head()
```
## taskAnnotation
```
taskAnnotation.tail()
taskAnnotation_IBM.tail()
taskAnnotationMerge = taskAnnotation.merge(taskAnnotation_IBM, how='outer')
taskAnnotationMerge[taskAnnotationMerge.label.duplicated()]
taskAnnotationMerge.to_csv(f"{annotations_merged}taskAnnotation.tsv",
header=False, index=False, sep="\t")
pd.read_csv(f"{annotations_merged}taskAnnotation.tsv",
sep="\t", names=["label", "datasets"]).head()
```
## resultsAnnotation
```
resultsAnnotation.tail()
resultsAnnotation_IBM.tail()
resultsAnnotationMerge = resultsAnnotation.merge(resultsAnnotation_IBM, how='outer')
resultsAnnotationMerge[resultsAnnotationMerge.label.duplicated()]
resultsAnnotationMerge.to_csv(f"{annotations_merged}/resultsAnnotation.tsv",
header=False, index=False, sep="\t")
pd.read_csv(f"{annotations_merged}/resultsAnnotation.tsv",
sep="\t", names=["label", "datasets"]).head()
```
## TDM_taxonomy
```
TDM_taxonomy.tail()
TDM_taxonomy_IBM.tail()
TDM_taxonomyMerge = TDM_taxonomy.merge(TDM_taxonomy_IBM, how='outer')
TDM_taxonomyMerge[TDM_taxonomyMerge.tdm.duplicated()]
TDM_taxonomyMerge.to_csv(f"{annotations_merged}TDM_taxonomy.tsv",
header=False, index=False, sep="\t")
pd.read_csv(f"{annotations_merged}TDM_taxonomy.tsv",
sep="\t", names=["label", "datasets"]).head()
```
## Clean repo
```
# paper_links_csv = "/nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/ibm/NLP-TDMS/downloader/paper_links.tsv"
# paper_links = pd.read_csv(paper_links_csv,
# sep="\t", names=["label", "link", "hash"])
# paper_links.head()
# resultsAnnotation_IBM.tail()
# for paper in list(paper_links.label):
# if paper not in list(resultsAnnotation_IBM.label):
# print(paper)
# !rm /nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/pdf_IBM/$paper
# !rm /nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/pdf_IBM/N16-1020.pdf
# # !rm /nfs/home/kabenamualus/Research/task-dataset-metric-extraction/data/pdf_IBM/N16-1020.pdf
# # "task-dataset-metric-extraction/data/paperwithcode/annotations_merged"
# os.listdir("task-dataset-metric-extraction/data/paperwithcode/annotations_merged")
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import requests as req
from census import Census
import json
import csv
import os
# Census API Key
#from config import api_key
c = Census("49f2db3e7faca8ecd92103d5bd5c5c765442d598", year=2016)
# Logic:
#Get the cites to query
#Get the census fields to query
#sourceFile = pd.ExcelFile('Project1_AmazonSites.xlsx')
sourceFile = pd.ExcelFile(os.path.join('..','Project1_AmazonSites.xlsx'))
SitesDF=sourceFile.parse('AmazonSites')
CitiesDf=sourceFile.parse('AmazonCities')
CitiesDf=CitiesDf[['PlaceCode','StateCode']]
CensusFieldsDF=sourceFile.parse('CensusFields')
CensusFieldsMapDF = CensusFieldsDF[["Datafield","Category","CensusCode"]]
CensusFieldsDF = CensusFieldsDF[["Datafield","CensusCode"]]
#Converting the CensusFieldsDF into a dictionary.
dictCensusFields = CensusFieldsDF.set_index('CensusCode').to_dict()
dictCensusFields = dictCensusFields['Datafield']
#print(dictCensusFields)
#CitiesDf.head()
# Build your Census API call.
arrCensusFields = ['NAME']
for k in dictCensusFields.keys():
arrCensusFields.append(k)
censusDF= pd.DataFrame()
for city in CitiesDf.values:
cityCode = str(city[0])
stateCode = str(city[1])
if len(cityCode)==4:
cityCode = "0"+cityCode
if len(stateCode)==1:
stateCode = "0"+stateCode
varGeo = {'for':'place:'+ cityCode,'in':'state:'+stateCode}
temp1 = c.acs5.get(arrCensusFields, varGeo)
tempDF = pd.DataFrame(temp1[0], index = [0])
censusDF = censusDF.append(tempDF,ignore_index = True)
censusDF = censusDF.rename(columns=dictCensusFields)
censusDF.to_csv("Cities_Demographics.csv")
#Labor Force Statistics
CensusFieldsMapDF.head()
#Get the fields for Labor Force
laborForceFields = CensusFieldsMapDF.loc[CensusFieldsMapDF['Category'] == 'Employment',["Datafield"]]
laborForceFields.head(10)
#laborForceFieldsCols =
dictLaborForceFields = laborForceFields.set_index('Datafield').to_dict()
dictLaborForceFields = laborForceFields['Datafield']
dictLFFields = ['NAME']
for value in dictLaborForceFields.values:
dictLFFields.append(value)
laborForceDF= censusDF.loc[:,dictLFFields]
laborForceDF['Emp_Tech'] = laborForceDF['Emp_Comp_Math_Female']+laborForceDF['Emp_Mgment_Occp_Female']+laborForceDF['Emp_Comp_Math_Male']+laborForceDF['Emp_Mgment_Occp_Male']
laborForceDF['Emp_Tech_Per']=(laborForceDF['Emp_Tech']/laborForceDF['Emp_Total'])*100
laborForceDF = laborForceDF[['NAME','Emp_Total','Emp_Tech','Emp_Tech_Per']]
# Calculating the TechPool based on Percentage of employees in Tech, Business and Financial sectors.
laborForceDF = laborForceDF.sort_values(by = 'Emp_Tech_Per')
laborForceDF = laborForceDF.reset_index(drop=True)
laborForceDF["TechPool_Score"] = laborForceDF.index+1
laborForceDF.head(10)
# Plotting Talent pool
laborForceDF = laborForceDF.sort_values(by='Emp_Tech')
plt.figure(figsize=(8,5))
sns.barplot(y='NAME',x='Emp_Tech',data=laborForceDF)
plt.xlabel("Number of People in Tech, Business and Financial occupations.")
plt.ylabel("")
plt.title("Available Tech Talent Pool")
plt.savefig('Available_Tech_Pool_Raw.png', format='png', bbox_inches='tight')
plt.show()
plt.figure(figsize=(8,5))
laborForceDF = laborForceDF.sort_values(by='Emp_Tech_Per')
sns.barplot(y='NAME',x='Emp_Tech_Per',data=laborForceDF)
plt.xlabel("Percent of Labor Force in Tech, Business and Financial occupations.")
plt.ylabel("")
plt.title("Percentage of the Labor Force in Tech, Business and Financial Occupations.")
plt.savefig('Percentage_oLaborForce_in_Tech.png', format='png', bbox_inches='tight')
plt.show()
#Educational Attainment Statistics
#Get the fields for Educational Attainment
EducationalAttainmentFields = CensusFieldsMapDF.loc[CensusFieldsMapDF['Category'] == 'Educational Attainment',["Datafield"]]
EducationalAttainmentFields.head(10)
dictEducationFields = EducationalAttainmentFields.set_index('Datafield').to_dict()
EducationalAttainmentFields = EducationalAttainmentFields['Datafield']
dictEDFields = ['NAME']
for value in EducationalAttainmentFields.values:
dictEDFields.append(value)
laborEDDF= censusDF.loc[:,dictEDFields]
laborEDDF['Ed_Total'] =laborEDDF['Ed_Associates']+laborEDDF['Ed_Bachelors']+laborEDDF['Ed_Doctorate']+laborEDDF['Ed_GED']+laborEDDF['Ed_HighSchool']+laborEDDF['Ed_Masters']+laborEDDF['Ed_Professional']
laborEDDF['Ed_Total_Bachelors_or_Higher'] = laborEDDF['Ed_Bachelors']+laborEDDF['Ed_Doctorate']+laborEDDF['Ed_Masters']+laborEDDF['Ed_Professional']
laborEDDF['HigherEd_Per']=(laborEDDF['Ed_Total_Bachelors_or_Higher']/laborEDDF['Ed_Total'])*100
EducationalAttainmentFields.head(10)
laborEDDF['Per_HS'] =(laborEDDF['Ed_HighSchool']/laborEDDF['Ed_Total'])*100
laborEDDF['Per_Assoc'] =(laborEDDF['Ed_Associates']/laborEDDF['Ed_Total'])*100
laborEDDF['Per_Bachelors'] =(laborEDDF['Ed_Bachelors']/laborEDDF['Ed_Total'])*100
laborEDDF['Per_Masters'] =(laborEDDF['Ed_Masters']/laborEDDF['Ed_Total'])*100
laborEDDF['Per_Doctorate'] =(laborEDDF['Ed_Doctorate']/laborEDDF['Ed_Total'])*100
laborEDDF['Per_GED'] =(laborEDDF['Ed_GED']/laborEDDF['Ed_Total'])*100
laborEDDF['Per_Prof'] =(laborEDDF['Ed_Professional']/laborEDDF['Ed_Total'])*100
# Calculating the Educational Attainment Rank based on
#Percentage of people whose education level is bachelors or higher.
laborEDDF = laborEDDF.sort_values(by = 'HigherEd_Per', ascending=True)
laborEDDF = laborEDDF.reset_index(drop=True)
laborEDDF["EduAtt_Score"] = laborEDDF.index+1
laborEDDF.head(10)
# Plotting EducationalAttainment
plt.figure(figsize=(8,5))
laborEDDF = laborEDDF.sort_values(by='Ed_Total_Bachelors_or_Higher')
sns.barplot(y='NAME',x='Ed_Total_Bachelors_or_Higher',data=laborEDDF)
plt.xlabel("Number of People with Bachelors degree or higher.")
plt.ylabel("")
plt.title("Population with Education level Bachelors or Higher")
plt.savefig('Pop_Education_Bachelors_Higher.png', format='png', bbox_inches='tight')
plt.show()
plt.figure(figsize=(8,5))
laborEDDF = laborEDDF.sort_values(by='HigherEd_Per')
sns.barplot(y='NAME',x='HigherEd_Per',data=laborEDDF)
plt.xlabel("Percent of people with Bachelors degree or higher .")
plt.ylabel("")
plt.title("Percentage of Population with Education level Bachelors or Higher.")
plt.savefig('Percent_Education_Bachelors_Higher.png', format='png', bbox_inches='tight')
plt.show()
#Educational Attainment - ALL Categories
plt.figure(figsize=(12,6))
laborEDDF1 =laborEDDF.loc[:,['NAME','Per_HS','Per_GED','Per_Assoc','Per_Bachelors','Per_Masters','Per_Doctorate','Per_Prof']]
laborEDDF1 = laborEDDF1.set_index('NAME')
laborEDDF1.plot.barh(use_index = True,stacked=True,figsize=(20,10),fontsize = 20)
plt.legend(title = 'Education Level', fontsize=20,bbox_to_anchor=(1.25, 1), ncol=1)
plt.title("Educational Attainment - All Levels",fontsize = 30 )
plt.xlabel("")
plt.ylabel("")
plt.savefig('Educational_Attainment_All_Levels.png', format='png', bbox_inches='tight')
# xplt.set_yticklabels(['{:3.0f}%'.format(x*10) for x in range(11)])
plt.show()
laborEDDF1.head()
#Diversity
#Get the fields for Educational Attainment
DiversityFields = CensusFieldsMapDF.loc[CensusFieldsMapDF['Category'] == 'Population',["Datafield"]]
DiversityFields.head(10)
dictDiversityFields = DiversityFields.set_index('Datafield').to_dict()
DiversityFields = DiversityFields['Datafield']
dictDiversityFields = ['NAME']
for value in DiversityFields.values:
dictDiversityFields.append(value)
DiversityDF= censusDF.loc[:,dictDiversityFields]
DiversityDF.head(10)
#laborEDDF['Ed_Total'] =laborEDDF['Ed_Associates']+laborEDDF['Ed_Bachelors']+laborEDDF['Ed_Doctorate']+laborEDDF['Ed_GED']+laborEDDF['Ed_HighSchool']+laborEDDF['Ed_Masters']+laborEDDF['Ed_Professional']
#laborEDDF['Ed_Total_Bachelors_or_Higher'] = laborEDDF['Ed_Bachelors']+laborEDDF['Ed_Doctorate']+laborEDDF['Ed_Masters']+laborEDDF['Ed_Professional']
#laborEDDF['HigherEd_Per']=(laborEDDF['Ed_Total_Bachelors_or_Higher']/laborEDDF['Ed_Total'])*100
DiversityDF['Per_White'] =((DiversityDF['Pop_White'])/DiversityDF['Total Population'])*100
DiversityDF['Per_Black'] =(DiversityDF['Pop_Black']/DiversityDF['Total Population'])*100
DiversityDF['Per_Asian'] =(DiversityDF['Population_Asian']/DiversityDF['Total Population'])*100
#DiversityDF['Per_Hispanic'] =(DiversityDF['Pop_Hispanic_Origin']/DiversityDF['Total Population'])*100
DiversityDF['Per_AmericanIndian'] =(DiversityDF['Pop_American_Indian']/DiversityDF['Total Population'])*100
DiversityDF['Per_Hawaiian'] =(DiversityDF['Pop_Native_Hawaiian']/DiversityDF['Total Population'])*100
DiversityDF['Per_Other'] =((DiversityDF['Pop_Other']+DiversityDF['Pop_two_or_more_races'])/DiversityDF['Total Population'])*100
DiversityDF.head(10)
#How Diverse is your City?
plt.figure(figsize=(12,6))
DiversityDF1 =DiversityDF.loc[:,['NAME','Per_White','Per_Black','Per_Asian','Per_AmericanIndian','Per_Hawaiian','Per_Other']]
DiversityDF1 = DiversityDF1.set_index('NAME')
DiversityDF1.plot.barh(use_index = True,stacked=True,figsize=(20,10),fontsize = 20)
DiversityDF1.head(10)
plt.legend(title = 'Diversity', fontsize=20,bbox_to_anchor=(1.27, 1), ncol=1)
plt.title("Cities and Diversity",fontsize = 30 )
plt.xlabel("")
plt.ylabel("")
plt.savefig('Cities and Diversity_ALL.png', format='png', bbox_inches='tight')
# xplt.set_yticklabels(['{:3.0f}%'.format(x*10) for x in range(11)])
plt.show()
#Diversity Score
#Source : https://wallethub.com/edu/most-diverse-cities/12690/
CitiesDiversityDf=sourceFile.parse('AmzonCities_DiversityRating')
CitiesDiversityDf=CitiesDiversityDf[['NAME','DiversityScore']]
CitiesDiversityDf = CitiesDiversityDf.sort_values(by = 'DiversityScore', ascending=True)
CitiesDiversityDf = CitiesDiversityDf.reset_index(drop=True)
CitiesDiversityDf["Diversity_Score"] = CitiesDiversityDf.index+1
CitiesDiversityDf.head(10)
#Plotting Diversity score
plt.figure(figsize=(8,5))
CitiesDiversityDf = CitiesDiversityDf.sort_values(by='DiversityScore')
sns.barplot(y='NAME',x='DiversityScore',data=CitiesDiversityDf)
plt.xlabel("Diveristy Score.")
plt.ylabel("")
plt.title("Cities : Diversity Score ")
plt.savefig('Cities_Diversity_Scores.png', format='png', bbox_inches='tight')
plt.show()
#Crime Score
#Source : city-data.com
CitiesCrimeDf=sourceFile.parse('AmzonCities_Crime')
CitiesCrimeDf=CitiesCrimeDf[['NAME','CrimeIndex']]
CitiesCrimeDf = CitiesCrimeDf.sort_values(by = 'CrimeIndex', ascending=False)
CitiesCrimeDf = CitiesCrimeDf.reset_index(drop=True)
CitiesCrimeDf["Crime_Score"] = CitiesCrimeDf.index+1
CitiesCrimeDf.head(10)
#Plotting Crime Index
plt.figure(figsize=(8,5))
CitiesCrimeDf = CitiesCrimeDf.sort_values(by='CrimeIndex')
sns.barplot(y='NAME',x='CrimeIndex',data=CitiesCrimeDf)
plt.xlabel("Crime Index (Crimes per 100,000 people)")
plt.ylabel("")
plt.title("Cities : Crime Index ")
plt.savefig('Cities_Diversity_Scores.png', format='png', bbox_inches='tight')
plt.show()
#Demographics Scores
# Tech Pool, Education Attainment Diversity,Crime and Diversity Scores.
TechPoolEduAttDf = pd.merge(laborForceDF,laborEDDF, on= 'NAME')
TechPoolEduAttDf = TechPoolEduAttDf[['NAME','TechPool_Score','EduAtt_Score']]
TechPoolEduAttDf.head(10)
DiversityCrimeDf = pd.merge(CitiesCrimeDf,CitiesDiversityDf, on= 'NAME')
DiversityCrimeDf = DiversityCrimeDf[['NAME','Crime_Score','Diversity_Score']]
DiversityCrimeDf.head(10)
DemographicsScoresDf1 = pd.merge(TechPoolEduAttDf,DiversityCrimeDf, on= 'NAME')
CitiesDf=sourceFile.parse('AmazonCities')
CitiesDf = CitiesDf[['NAME','City']]
DemographicsScoresDf = pd.merge(CitiesDf,DemographicsScoresDf1, on= 'NAME')
DemographicsScoresDf.head(10)
DemographicsScoresDf.to_csv("Cities_Demographics_Scores.csv")
```
| github_jupyter |
```
from numpy import zeros,array,sqrt,exp,copy,arange,mean,roll
from numpy import random as nprandom
from random import random,randrange
from pylab import figure,plot,show,xlim,ylim,title,legend,xlabel,ylabel,savefig,grid
import numpy as np
# compute energy of tertiary structure of protein
def calc_energy(monomer_coords,monomer_array):
energy=0.0
# compute energy due to all adjacencies (including directly bonded monomers)
for i in range(N):
for neighbour in [[-1,0],[1,0],[0,-1],[0,1]]: # the four neighbour directions
neighbour_monomer=monomer_array[monomer_coords[i,0]+neighbour[0],monomer_coords[i,1]+neighbour[1]]
if neighbour_monomer==1: # check neighbour is not empty
energy+=eps
# divide by 2 to correct for double-counting
energy=energy/2.0
# correct energy to not count directly bonded monomer neighbours
energy-=(N-1)*eps
return energy
def dist(position1,position2):
return sqrt((position1[0]-position2[0])**2+(position1[1]-position2[1])**2)
eps=-5.0 # interaction energy
N=30 # length of protein
T=0.5 # temperature for Monte Carlo
n=10000000 # number of Monte Carlo steps
T_f=0.5
T_steps=4
T_i=T_f+T_steps-1
T_array= zeros(n)
for step in range(T_steps):
T_array[int(step*n/T_steps):int((step+1)*n/T_steps)]=(T_i-T_f)*(1-float(step)/(T_steps-1))+T_f
T_f=0.5
T_steps=20
T_i=10
T_array= zeros(n)
for step in range(T_steps):
T_array[int(step*n/T_steps):int((step+1)*n/T_steps)]=(T_i-T_f)*(1-float(step)/(T_steps-1))+T_f
energy_array=zeros(n) # initialize array to hold energy
# initialize arrays to store protein information
# first column is x coordinates, second column is y coordinates, of all N monomers
monomer_coords=zeros((N,2),dtype='int')
# initialize position of polymer as straight horizontal line in middle of domain
monomer_coords[:,0]=range(N//2,3*N//2)
monomer_coords[:,1]=N
# 2D array representing lattice, equal to 0 when a lattice point is empty, and equal to 1 when there is a monomer at the lattice point
monomer_array=zeros((2*N+1,2*N+1),dtype='int')
# fill lattice array
for i in range(N):
monomer_array[monomer_coords[i,0],monomer_coords[i,1]]=1
# calculate energy of initial protein structure
energy=calc_energy(monomer_coords,monomer_array)
# do Monte Carlo procedure to find optimal protein structure
for j in range(n):
energy_array[j]=energy
# move protein back to centre of array
shift_x=int(mean(monomer_coords[:,0])-N)
shift_y=int(mean(monomer_coords[:,1])-N)
monomer_coords[:,0]-=shift_x
monomer_coords[:,1]-=shift_y
monomer_array=roll(monomer_array,-shift_x,axis=0)
monomer_array=roll(monomer_array,-shift_y,axis=1)
# pick random monomer
i=randrange(N)
cur_monomer_pos=monomer_coords[i,:]
# pick random diagonal neighbour for monomer
direction=randrange(4)
if direction==0:
neighbour=array([-1,-1]) # left/down
elif direction==1:
neighbour=array([-1,1]) # left/up
elif direction==2:
neighbour=array([1,1]) # right/up
elif direction==3:
neighbour=array([1,-1]) # right/down
new_monomer_pos=cur_monomer_pos+neighbour
# check if neighbour lattice point is empty
if monomer_array[new_monomer_pos[0],new_monomer_pos[1]]==0:
# check if it is possible to move monomer to new position without stretching chain
distance_okay=False
if i==0:
if dist(new_monomer_pos,monomer_coords[i+1,:])<1.1:
distance_okay=True
elif i==N-1:
if dist(new_monomer_pos,monomer_coords[i-1,:])<1.1:
distance_okay=True
else:
if dist(new_monomer_pos,monomer_coords[i-1,:])<1.1 and dist(new_monomer_pos,monomer_coords[i+1,:])<1.1:
distance_okay=True
if distance_okay:
# calculate new energy
new_monomer_coords=copy(monomer_coords)
new_monomer_coords[i,:]=new_monomer_pos
new_monomer_array=copy(monomer_array)
new_monomer_array[cur_monomer_pos[0],cur_monomer_pos[1]]=0
new_monomer_array[new_monomer_pos[0],new_monomer_pos[1]]=1
new_energy=calc_energy(new_monomer_coords,new_monomer_array)
if random()<exp(-(new_energy-energy)/T_array[j]):
# make switch
energy=new_energy
monomer_coords=copy(new_monomer_coords)
monomer_array=copy(new_monomer_array)
figure()
title("Final Temperature={}".format(T_array[-1]))
plot(T_array)
xlabel('Monte Carlo step')
ylabel('Temperature')
grid()
figure()
title('Temperature=%.1f, Protein length=%d'%(T,N))
plot(energy_array)
xlabel('Monte Carlo step')
ylabel('Energy')
# savefig('energy_vs_step_T%d_N%d_n%d.png'%(10*T,N,n))
figure()
plot(monomer_coords[:,0],monomer_coords[:,1],'-k') # plot bonds
title('Temperature=%.1f, Energy = %.1f'%(T,energy))
# plot monomers
for i in range(N):
plot(monomer_coords[i,0],monomer_coords[i,1],'.r',markersize=15)
xlim([N/3.0,5.0*N/3.0])
ylim([N/3.0,5.0*N/3.0])
# savefig('final_protein_T%d_N%d_n%d.png'%(10*T,N,n))
print ('Energy averaged over last half of simulations is: %.2f'%mean(energy_array[int(n/2):]))
print ('Energy averaged over last quarter of simulations is: %.2f'%mean(energy_array[-int(n/4):]))
show()
```
| github_jupyter |
# Self-Driving Car Engineer Nanodegree
## Deep Learning
## Project: Build a Traffic Sign Recognition Classifier
In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
> **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n",
"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project.
The [rubric](https://review.udacity.com/#!/rubrics/481/view) contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
---
## Import all necessary packages
```
import pickle
import numpy as np
import random
import csv
import matplotlib.pyplot as plt
%matplotlib inline
from textwrap import wrap
```
---
## Step 0: Load The Data
```
# Load pickled data
# TODO: Fill this in based on where you saved the training and testing data
training_file = '../../GD_GitHubData/traffic-signs-data/train.p'
validation_file = '../../GD_GitHubData/traffic-signs-data/valid.p'
testing_file = '../../GD_GitHubData/traffic-signs-data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
```
---
## Step 1: Dataset Summary & Exploration
The pickled data is a dictionary with 4 key/value pairs:
- `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
- `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.
- `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.
- `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**
Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results.
### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas
```
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train[:,0,0,0].shape[0]
# TODO: Number of validation examples
n_validation = X_valid[:,0,0,0].shape[0]
# TODO: Number of testing examples.
n_test = X_test[:,0,0,0].shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0,:,:,:].shape if (X_train[0,:,:,:].shape == X_valid[0,:,:,:].shape == X_test[0,:,:,:].shape) else []
# TODO: How many unique classes/labels there are in the dataset.
l_classes = []
n_classes = len([l_classes.append(label) for label in np.concatenate((y_train, y_valid, y_test)) if label not in l_classes])
print("Number of training examples =", n_train)
print("Number of validation examples =", n_validation)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
```
### Include an exploratory visualization of the dataset
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python.
**NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
```
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
# Visualizations will be shown in the notebook.
# define constants
totalimages = 30
def plot_traffic_signs(images, labels):
# define constants
horizontalimages = 10
dpi = 80
horizontalimagesize = 15
titlebasefontsize = 100
titlechars_per_line = 18
# create figure with subplot
verticalimages = np.int(np.ceil(totalimages / horizontalimages))
verticalimagesize = (horizontalimagesize * (verticalimages / horizontalimages))
figure, axes = plt.subplots(verticalimages, horizontalimages, figsize=(horizontalimagesize, verticalimagesize), dpi = dpi)
figure.tight_layout()
# figure.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
axes = axes.reshape(-1)
# plot all images
titlefontsize = (titlebasefontsize / horizontalimages)
for idx, axis in enumerate(axes):
# configure axis
axis.set_axis_off()
axis.get_xaxis().set_visible(False)
axis.get_yaxis().set_visible(False)
# print label and plot image
axis.set_title("\n".join(wrap(labels[idx], titlechars_per_line)), fontsize = titlefontsize)
axis.imshow(images[idx, :, :])
# make sure plot is shown
plt.show()
# read description of labels
with open('signnames.csv') as csvfile:
reader = csv.DictReader(csvfile)
labeldict = dict([(np.int(row['ClassId']), row['SignName']) for row in reader])
# select and plot random images
print('Random images:')
indices = np.random.randint(0, len(X_train), totalimages)
images = X_train[indices].squeeze()
labels = [labeldict[idx] for idx in y_train[indices]]
plot_traffic_signs(images, labels)
# select and plot random images with the same random label
print('Random images of same random label:')
label = np.random.randint(min(y_train), max(y_train), 1)
images = np.asarray([image for idx, image in enumerate(X_train) if (y_train[idx] == label)])
indices = np.random.randint(0, images.shape[0], totalimages)
images = images[indices, :, :]
labels = [labeldict[label[0]] for image in images]
plot_traffic_signs(images, labels)
```
----
## Step 2: Design and Test a Model Architecture
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).
The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
- Neural network architecture (is the network over or underfitting?)
- Play around preprocessing techniques (normalization, rgb to grayscale, etc)
- Number of examples per label (some have more than others).
- Generate fake data.
Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
### Pre-process the Data Set (normalization, grayscale, etc.)
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
```
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
```
### Model Architecture
```
### Define your architecture here.
### Feel free to use as many code cells as needed.
```
### Train, Validate and Test the Model
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation
sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
```
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
```
---
## Step 3: Test a Model on New Images
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name.
### Load and Output the Images
```
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
```
### Predict the Sign Type for Each Image
```
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
```
### Analyze Performance
```
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
```
### Output Top 5 Softmax Probabilities For Each Image Found on the Web
For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#top_k) could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
`tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability:
```
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
```
Running it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces:
```
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
```
Looking just at the first row we get `[ 0.34763842, 0.24879643, 0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices.
```
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
```
### Project Writeup
Once you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file.
> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n",
"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.
---
## Step 4 (Optional): Visualize the Neural Network's State with Test Images
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
<figure>
<img src="visualize_cnn.png" width="380" alt="Combined Image" />
<figcaption>
<p></p>
<p style="text-align: center;"> Your output should look something like this (above)</p>
</figcaption>
</figure>
<p></p>
```
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
```
| github_jupyter |
```
import os
import pickle
random_seed = 42
import random
random.seed(random_seed)
import numpy as np
np.random.seed(random_seed)
import pandas as pd
pd.set_option('display.max_rows', 512)
pd.set_option('display.max_columns', 512)
pd.set_option('display.max_colwidth', -1)
import csv
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
%matplotlib inline
set_matplotlib_formats('svg')
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset
torch.manual_seed(random_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
from tqdm import tqdm
from sklearn.metrics import classification_report
from sklearn.metrics import mean_squared_error
from scipy import stats
output_collections_list = []
for idx in range(0, 6000+1, 1000):
with open("saved/score_42/{}.pkl".format(idx), "rb") as handle:
output_collections = pickle.load(handle)
# print(output_collections[0]['prob'])
print(len(output_collections))
if idx==0:
output_collections_list = output_collections
else:
output_collections_list += output_collections
len(output_collections_list)
data = []
for i in output_collections_list:
data.append([i['index'],
i['influence_prime'],
i['influence'],
i['diff'], i['theta'],
i['sentence'], i['label'], i['prediction'], i['prob'],
i['tokens'], i['attributions'],
])
df_0 = pd.DataFrame(data, columns=['sample_index',
'influence_prime',
'influence',
'diff', 'theta',
'sentence', 'label', 'prediction', 'prob',
'tokens', 'attributions'
])
df_0['theta'] = -df_0['theta']
df_0['attributions'] = -df_0['attributions']
df_0.head()
import nltk
a = nltk.corpus.BracketParseCorpusReader("data/trees", "(train|dev|test)\.txt")
tree = {}
text = {}
pos = {}
labels = {}
keys = ['train',
# 'dev', 'test'
]
for k in keys:
tree[k] = [x for x in a.parsed_sents(k+'.txt') if x.label() != '2']
text[k] = [x.leaves() for x in a.parsed_sents(k+'.txt') if x.label() != '2']
pos[k] = [x.pos() for x in a.parsed_sents(k+'.txt') if x.label() != '2']
labels[k] = [int(x.label()) for x in a.parsed_sents(k+'.txt') if x.label() != '2']
print(len(text[k]))
sentiment_list = []
for i in tree['train']:
sentiment = [j.label() for j in i.subtrees()]
sentiment_list.append(sentiment)
df_0['word_sentiment'] = sentiment_list
def count_sentiment(word_sentiment, sentiment):
return word_sentiment.count(sentiment)
for sentiment in ['0','1', '2', '3', '4']:
df_0[sentiment] = df_0.apply(lambda x: count_sentiment(x['word_sentiment'], sentiment), axis=1)
k = 0.01 # add-k smooth
df_0['length'] = (df_0['0'] + df_0['1']) + (df_0['3'] + df_0['4']) + 2*k
df_0['neg'] = (df_0['0'] + df_0['1'] + k) / df_0['length']
df_0['pos'] = (df_0['3'] + df_0['4'] + k) / df_0['length']
df_0_sorted = df_0.sort_values(by=['influence'], ascending=False)
df_0_sorted[['label', 'sentence', 'prediction', 'prob', 'influence', 'neg', 'pos']].head()
import matplotlib
(df_0[df_0['label']==0]['pos']*100).describe()
matplotlib.rcParams.update({'font.size': 24})
fig, ax0 = plt.subplots(figsize=(8, 8))
ax0.hist((df_0[df_0['label']==0]['pos']*100).values, alpha=0.6, bins=10)
min_ylim, max_ylim = plt.ylim()
x1 = 35.73
ax0.axvline(x=x1, linestyle='--', linewidth=2.5, c='tab:red', label="line at {}".format(x1))
ax0.set_ylabel("Frequency")
ax0.set_xlabel("Positive Phrase Fraction (%)")
ax0.legend(fontsize=24)
# plt.show()
filename = "saved/vis/Atypical_SST_Neg.pdf"
os.makedirs(os.path.dirname(filename), exist_ok=True)
plt.savefig(filename, bbox_inches='tight', pad_inches=0.1)
(df_0[df_0['label']==1]['pos']*100).describe()
import matplotlib.transforms as transforms
matplotlib.rcParams.update({'font.size': 24})
fig, ax0 = plt.subplots(figsize=(8, 8))
ax0.hist((df_0[df_0['label']==1]['pos']*100).values, alpha=0.6, bins=10)
min_ylim, max_ylim = plt.ylim()
x1 = 78.31
ax0.axvline(x=x1, linestyle='--', linewidth=2.5, c='tab:red', label="line at {}".format(x1))
ax0.set_ylabel("Frequency")
ax0.set_xlabel("Positive Phrase Fraction (%)")
ax0.legend(fontsize=24)
# plt.show()
filename = "saved/vis/Atypical_SST_Pos.pdf"
os.makedirs(os.path.dirname(filename), exist_ok=True)
plt.savefig(filename, bbox_inches='tight', pad_inches=0.1)
classes = ['negative', 'positive']
for cls in range(2):
tmp = df_0_sorted[df_0_sorted['label']==cls]
length = len(tmp) // 10
print()
print(classes[cls], length)
decimal = 2
print()
results = [
tmp.head(length)['neg'].mean()*100,
tmp.head(length)['pos'].mean()*100,
]
print(np.round(results, decimal))
print(np.sum(np.round(results, decimal)))
print()
results = [
tmp['neg'].mean()*100,
tmp['pos'].mean()*100,
]
print(np.round(results, decimal))
print(np.sum(np.round(results, decimal)))
print()
results = [
tmp.tail(length)['neg'].mean()*100,
tmp.tail(length)['pos'].mean()*100,
]
print(np.round(results, decimal))
# print(np.sum(np.round(results, decimal)))
```
| github_jupyter |
```
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# Fetch the service account key JSON file contents
cred = credentials.Certificate('/Users/Solomon/Desktop/cauNotiPrivate/cau-hashkeyword-serviceAccountKey.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://cau-hashkeyword.firebaseio.com'
})
from bs4 import BeautifulSoup
from urllib.request import urlopen
from selenium import webdriver
import re
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument('disable-gpu')
cau_title_list = []
cau_date_list = []
cau_url_list = []
driver = webdriver.Chrome("/usr/local/bin/chromedriver", chrome_options=options)
driver.get("https://www.cau.ac.kr/cms/FR_CON/index.do?MENU_ID=100")
driver.implicitly_wait(3)
cau_base_url = "https://www.cau.ac.kr/cms/FR_CON/BoardView.do?MENU_ID=100&CONTENTS_NO=1&SITE_NO=2&P_TAB_NO=&TAB_NO=&BOARD_SEQ=4&BOARD_CATEGORY_NO=&BBS_SEQ="
# BBS_SEQ=19642 (id=board_19642)
board_list = driver.find_element_by_id("tbody").find_elements_by_tag_name("li")
board_list.reverse()
# count = 0
for item in board_list:
# if count < 10: pass # 테스트용
# else:
cau_title_list.append(item.find_element_by_class_name("txtL").find_element_by_tag_name('a').text)
cau_date_list.append(item.find_element_by_class_name("txtInfo").find_element_by_class_name("date").text)
cau_url_list.append(cau_base_url + item.get_attribute("id").replace("board_",""))
# count += 1
driver.close()
# list 앞에 원소를 추가할 때, insert(0,data) 사용 시 O(n)
# class collections.deque([iterable[, maxlen]])의 dequeue() 사용 시 O(1)
# High Performance를 원한다면 사용하자.
# 혹은 list reverse 후, append 계속 사용 (단, reverse의 경우 O(n))
lib_title_list = []
lib_date_list = []
lib_url_list = []
driver = webdriver.Chrome("/usr/local/bin/chromedriver", chrome_options=options)
driver.get("https://library.cau.ac.kr/#/bbs/notice?offset=0&max=20")
driver.implicitly_wait(3)
try:
# tbody[0]는 회색 상단 공지 부분으로 아래 공지 중에서 중요한 것들만 올려놓은듯. 즉, 겹치는 내용임.
board_list = driver.find_elements_by_tag_name("tbody")[1].find_elements_by_class_name("ikc-item")
board_list.reverse()
for item in board_list: # tbody 검색후 ikc-item 검색시, 가끔씩 IndexError: list index out of range 발생 (이유 모름)
lib_title_list.append(item.find_elements_by_tag_name("td")[2].find_element_by_tag_name('a').text) # 대체
lib_date_list.append(item.find_elements_by_tag_name("td")[3].find_elements_by_tag_name("span")[1].text)
except IndexError:
print("IndexError : date와 url이 크롤링되지 않음")
pass
lib_base_url = "https://library.cau.ac.kr/#/bbs/notice/"
# 사이에 id 추가
lib_sub_url = "?offset=0&max=20"
# url id는 어떻게 가져올까..
driver.close()
# 노란색 공지 부분만 가져온다
dorm_title_list = []
dorm_date_list = []
dorm_url_list = []
dormnotice_url = "https://dormitory.cau.ac.kr/bbs/bbs_list.php?bbsID=notice"
dormnotice_page = urlopen(dormnotice_url)
dormnotice_soup = BeautifulSoup(dormnotice_page, "lxml")
dormnotice_list = dormnotice_soup.find(id='content').find('div').find_all('tr',{'bgcolor':'#fffcdb'})
dormnotice_list.reverse()
if dormnotice_list == []:
print("No data")
else :
for item in dormnotice_list:
dorm_title_list.append(item.find('span',class_='bbsTitle').get_text())
dorm_url_list.append(item.find('a')['href'])
dorm_date_list.append("20" + item.find_all('td',class_='t_c')[3].get_text())
#try-except 적용하기?
ict_title_list = []
ict_date_list = []
ict_url_list = []
ictnotice_url = "http://ict.cau.ac.kr/20150610/sub05/sub05_01_list.php"
ictnotice_page = urlopen(ictnotice_url)
ictnotice_soup = BeautifulSoup(ictnotice_page, "lxml")
ict_base_url = "http://ict.cau.ac.kr/20150610/sub05/sub05_01_list.php?cmd=view&cpage=1&idx="
# 사이에 id 작성
ict_sub_url = "&search_gbn=1&search_keyword="
ictnotice_list = ictnotice_soup.find('tbody').find_all('tr')
ictnotice_list.reverse()
if ictnotice_list == []:
print("No data")
else:
for item in ictnotice_list:
ict_title_list.append(item.find('td',class_='cont').find('a').get_text())
ict_url_list.append(ict_base_url + item.find('td',class_='cont').find('a')['href'][-7:-3] + ict_sub_url)
ict_date_list.append(item.find_all('td')[2].get_text())
# 공지표시 되어있는 게시글 제목도 수집? (겹치는 내용임)
cse_title_list = []
cse_date_list = []
cse_url_list = []
csenotice_url = "http://cse.cau.ac.kr/sub05/sub0501.php"
csenotice_page = urlopen(csenotice_url)
csenotice_soup = BeautifulSoup(csenotice_page, "lxml")
csenotice_list = csenotice_soup.find('tbody').find_all('tr')
csenotice_list.reverse()
if csenotice_list == []:
print("No data")
else:
for item in csenotice_list:
if item.find('td').get_text() != '':
cse_title_list.append(re.sub('[\n\t\xa0]','',item.find('a').get_text())) # sub메소드 사용법 검토하기
cse_url_list.append(csenotice_url + item.find_all('td')[2].find('a')['href'])
cse_date_list.append(item.find_all('td')[4].get_text())
# Firebase에 크롤링한 데이터 저장하기
import json
from collections import OrderedDict
ref = db.reference('crawling')
crawling_data = OrderedDict()
crawling_data['cau'] = {'title':cau_title_list, 'date':cau_date_list, 'url':cau_url_list}
crawling_data['library'] = {'title':lib_title_list, 'date':lib_date_list, 'url':"https://library.cau.ac.kr/#/bbs/notice?offset=0&max=20"}
crawling_data['dormitory'] = {'title':dorm_title_list, 'date':dorm_date_list, 'url':dorm_url_list}
crawling_data['ict'] = {'title':ict_title_list, 'date':ict_date_list, 'url':ict_url_list}
crawling_data['cse'] = {'title':cse_title_list, 'date':cse_date_list, 'url':cse_url_list}
crawling_json = json.dumps(crawling_data, ensure_ascii=False, indent="\t")
webpage_ref = ref.child('webpages')
webpage_ref.set(json.loads(crawling_json))
```
| github_jupyter |
# The Night That Taggart and I Reversed Nimble.exe
To finish this presentation, let me tell you a story.
January 5th, 2022. John Hammond tweets the following:

Upon closer inspection, John is attempting to download Nim version 1.6.2 (the current stable build as of writing this). And this download has triggered an alert from Windows Defender.
## The Problem
The Windows Nim language installation executables, for some reason, trigger Windows Defender in certain versions. John's tweet shows that the install binaries for the current Nim package triggers antivirus but this problem extends back several versions. I was made aware of this after I wrote a blog post about performing process injection with Nim and received a comment about the post:

I think this comment highlights the principal issue here.
Even before performing the research for this, I had a feeling that the Nim binaries were not compromised or backdoored. I expected this to be a false positive. And I reflected on what that would mean for the developers of the language.
Imagine you're the developer of Nim and have put (according to the GitHub page) just shy of 20k commits to the codebase. You're working to provide an open-source language that can serve multiple purposes. And Windows Defender aggros on your compiled executables and scares people away from using your language. This, to me, felt incredibly unfair.
So on the night of Oct 26th, 2021, Taggart and I decided to examine the binaries to determine the truth, either to excuplate or to identify a security issue.

## The Experiment

The experiment was set up like this:
- Identify a Nim language installation binary that triggers Windows Defender
- Reliably recreate the Defender alert
- Deploy AV analysis and reverse engineering techniques to find the bytes of Defender that were triggering
### Objectives
- Determine the existence of malicious code in the Nimble executable.
- Determine if the Defender alert is a false positive.
- If it is a false positive, determine the specific part of the executable that triggers AV alerts.
### Hypothesis
My hypothesis was that there would be certain API calls that, once resolved and executed, Defender would identify as malicious.
### Subject
Nimble.exe install binary 1.4.8 x64
Nimble is the one-stop utility for Nim package development. Among many, many other uses, Nimble is used to download Nim packages during development.
### Tools
- FLARE-VM
- Get-FileHash
- VirusTotal
- ThreatCheck
- HxD
- FLOSS
- PEStudio
- x64dbg
- Defender alert logs
- Hatching Triage (https://tria.ge)
### Methods
Basic Static Analysis
- Pull hash and submit to Virustotal
- Examine strings with FLOSS
- Submit sample to Hatching Triage
- Examine in PEStudio
- Use ThreatCheck to identify the bytes that are triggering Defender
- Use HxD to examine the triggering bytes
Advanced Dynamic Analysis
- Debug Nimble.exe in x64dbg and set breakpoints to determine the precise instruction that triggers Defender.
### Full Stream
[#AttackOnTuesday - Nim vs. Defender w/HuskyHacks!](https://youtu.be/suKfsnOa_OU?t=570)
---
## Results
I did not draw conclusive results the night of the stream but continued research the following day (Oct 27th,2021). My findings included the following:
### **Existence of malicious code in the Nimble binary**
I was unable to prove the existence of malicious code in the binary.
### **Malicious code in Nimble would be extremely unlikely**
The applied tools and methodology was enough to reasonably conclude that the existence of malicious code in the Nimble binary would be extremely unlikely.
### **Hypothesis: Windows APIs Triggering Defender**
My research identified the root cause of Nimble's Defender alerts as the syscall of **NtTerminateProcess** located at the exit of the program.


*Above: call instruction in ntdll.dll to NtTerminateProcess*

*Above: the syscall instruction for the identified call to NtTerminateProcess*
By setting breakpoints on the above instructions, I was able to reliably recreate Defender alerts when executing the instructions.
---
# Follow On
I relayed my findings to the Nim developers and they were very appreciative of the research.

It was unclear to me how the devs might go about removing that syscall, or even if it would be necessary to do so. I am not a language developer and have little understanding of how much control a dev would have over the ASM level instructions that occur during the compilation of the language binary. More research needs to be done to detemrine if there is a way to avoid this syscall.
I also was curious about the syscall itself and why Defender might flag on it. My original hypothesis was that, due to its method of execution, calling the API via ntdll and a direct syscall may trigger antivirus due to its similarities to other contemporary red team tradecraft. Syscall execution of the NTDLL APIs is a popular tactic to bypass EDR and antivirus as it allows the threat actor to perform post-compromise activity without calling hooked APIs in user land.
However, one of my colleagues sent the following paper to me after learning about the stream: [Early detection of crypto-ransomware using pre-encryption detection algorithm](https://www.sciencedirect.com/science/article/pii/S1319157820304122) (Authors: S.H. Kok, Azween Abdullah, NZ Jhanjhi)
This paper covers early detection mechanisms of crypto-ransomware by employing an algorithm that scores characteristics of a program in different categories. One of these categories includes API calls. The paper includes a list of API calls that are commonly present in ransomware but less common in benign programs.

---
## [Previous: Nim's Offensive Applications](OffensiveNim.ipynb) ||--0--|| [Next: Conclusion](Conclusion.ipynb)
| github_jupyter |
# Face Generation
In this project, you'll use generative adversarial networks to generate new images of faces.
### Get the Data
You'll be using two datasets in this project:
- MNIST
- CelebA
Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.
If you're using [FloydHub](https://www.floydhub.com/), set `data_dir` to "/input" and use the [FloydHub data ID](http://docs.floydhub.com/home/using_datasets/) "R5KrjnANiKVhLWAkpXhNBe".
```
data_dir = '/data'
!pip install matplotlib==2.0.2
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
```
## Explore the Data
### MNIST
As you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`.
```
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
```
### CelebA
The [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing `show_n_images`.
```
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
```
## Preprocess the Data
Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.
The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images).
## Build the Neural Network
You'll build the components necessary to build a GANs by implementing the following functions below:
- `model_inputs`
- `discriminator`
- `generator`
- `model_loss`
- `model_opt`
- `train`
### Check the Version of TensorFlow and Access to GPU
This will check to make sure you have the correct version of TensorFlow and access to a GPU
```
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
```
### Input
Implement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.
- Z input placeholder with rank 2 using `z_dim`.
- Learning rate placeholder with rank 0.
Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)
```
import problem_unittests as tests
def model_inputs(image_width, image_height, image_channels, z_dim):
"""
Create the model inputs
:param image_width: The input image width
:param image_height: The input image height
:param image_channels: The number of image channels
:param z_dim: The dimension of Z
:return: Tuple of (tensor of real input images, tensor of z data, learning rate)
"""
# TODO: Implement Function
return None, None, None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
```
### Discriminator
Implement `discriminator` to create a discriminator neural network that discriminates on `images`. This function should be able to reuse the variables in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).
```
def discriminator(images, reuse=False):
"""
Create the discriminator network
:param images: Tensor of input image(s)
:param reuse: Boolean if the weights should be reused
:return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
"""
# TODO: Implement Function
return None, None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
```
### Generator
Implement `generator` to generate an image using `z`. This function should be able to reuse the variables in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x `out_channel_dim` images.
```
def generator(z, out_channel_dim, is_train=True):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:return: The tensor output of the generator
"""
# TODO: Implement Function
return None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
```
### Loss
Implement `model_loss` to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:
- `discriminator(images, reuse=False)`
- `generator(z, out_channel_dim, is_train=True)`
```
def model_loss(input_real, input_z, out_channel_dim):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
# TODO: Implement Function
return None, None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
```
### Optimization
Implement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).
```
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
# TODO: Implement Function
return None, None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
```
## Neural Network Training
### Show Output
Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training.
```
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
"""
Show example output for the generator
:param sess: TensorFlow session
:param n_images: Number of Images to display
:param input_z: Input Z Tensor
:param out_channel_dim: The number of channels in the output image
:param image_mode: The mode to use for images ("RGB" or "L")
"""
cmap = None if image_mode == 'RGB' else 'gray'
z_dim = input_z.get_shape().as_list()[-1]
example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])
samples = sess.run(
generator(input_z, out_channel_dim, False),
feed_dict={input_z: example_z})
images_grid = helper.images_square_grid(samples, image_mode)
pyplot.imshow(images_grid, cmap=cmap)
pyplot.show()
```
### Train
Implement `train` to build and train the GANs. Use the following functions you implemented:
- `model_inputs(image_width, image_height, image_channels, z_dim)`
- `model_loss(input_real, input_z, out_channel_dim)`
- `model_opt(d_loss, g_loss, learning_rate, beta1)`
Use the `show_generator_output` to show `generator` output while you train. Running `show_generator_output` for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the `generator` output every 100 batches.
```
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
"""
Train the GAN
:param epoch_count: Number of epochs
:param batch_size: Batch Size
:param z_dim: Z dimension
:param learning_rate: Learning Rate
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:param get_batches: Function to get batches
:param data_shape: Shape of the data
:param data_image_mode: The image mode to use for images ("RGB" or "L")
"""
# TODO: Build Model
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epoch_count):
for batch_images in get_batches(batch_size):
# TODO: Train Model
```
### MNIST
Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
```
batch_size = None
z_dim = None
learning_rate = None
beta1 = None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
mnist_dataset.shape, mnist_dataset.image_mode)
```
### CelebA
Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
```
batch_size = None
z_dim = None
learning_rate = None
beta1 = None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
celeba_dataset.shape, celeba_dataset.image_mode)
```
### Submitting This Project
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.
| github_jupyter |
# Neural networks with PyTorch
Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the term "deep" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. PyTorch has a nice module `nn` that provides a nice way to efficiently build large neural networks.
```
# Import necessary packages
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import torch
import helper
import matplotlib.pyplot as plt
```
Now we're going to build a larger network that can solve a (formerly) difficult problem, identifying text in an image. Here we'll use the MNIST dataset which consists of greyscale handwritten digits. Each image is 28x28 pixels, you can see a sample below
<img src='assets/mnist.png'>
Our goal is to build a neural network that can take one of these images and predict the digit in the image.
First up, we need to get our dataset. This is provided through the `torchvision` package. The code below will download the MNIST dataset, then create training and test datasets for us. Don't worry too much about the details here, you'll learn more about this later.
```
### Run this cell
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
])
# Download and load the training data
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
```
We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. Later, we'll use this to loop through the dataset for training, like
```python
for image, label in trainloader:
## do things with images and labels
```
You'll notice I created the `trainloader` with a batch size of 64, and `shuffle=True`. The batch size is the number of images we get in one iteration from the data loader and pass through our network, often called a *batch*. And `shuffle=True` tells it to shuffle the dataset every time we start going through the data loader again. But here I'm just grabbing the first batch so we can check out the data. We can see below that `images` is just a tensor with size `(64, 1, 28, 28)`. So, 64 images per batch, 1 color channel, and 28x28 images.
```
dataiter = iter(trainloader)
images, labels = dataiter.next()
print(type(images))
print(images.shape)
print(labels.shape)
plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r');
```
This is what one of the images looks like.
```
np.unique(images.numpy().squeeze())
```
First, let's try to build a simple network for this dataset using weight matrices and matrix multiplications. Then, we'll see how to do it using PyTorch's `nn` module which provides a much more convenient and powerful method for defining network architectures.
The networks you've seen so far are called *fully-connected* or *dense* networks. Each unit in one layer is connected to each unit in the next layer. In fully-connected networks, the input to each layer must be a one-dimensional vector (which can be stacked into a 2D tensor as a batch of multiple examples). However, our images are 28x28 2D tensors, so we need to convert them into 1D vectors. Thinking about sizes, we need to convert the batch of images with shape `(64, 1, 28, 28)` to a have a shape of `(64, 784)`, 784 is 28 times 28. This is typically called *flattening*, we flattened the 2D images into 1D vectors.
Previously you built a network with one output unit. Here we need 10 output units, one for each digit. We want our network to predict the digit shown in an image, so what we'll do is calculate probabilities that the image is of any one digit or class. This ends up being a discrete probability distribution over the classes (digits) that tells us the most likely class for the image. That means we need 10 output units for the 10 classes (digits). We'll see how to convert the network output into a probability distribution next.
> **Exercise:** Flatten the batch of images `images`. Then build a multi-layer network with 784 input units, 256 hidden units, and 10 output units using random tensors for the weights and biases. For now, use a sigmoid activation for the hidden layer. Leave the output layer without an activation, we'll add one that gives us a probability distribution next.
```
## Your solution
## Activation function
def activation(x):
""" Sigmoid activation function
Arguments
---------
x: torch.Tensor
"""
return 1/(1+torch.exp(-x))
### Neural network
def multi_Layer_NW(inputUnits, hiddenUnits, outputUnits):
torch.manual_seed(7) # Set the random seed so things are predictable
# Define the size of each layer in our network
n_input = inputUnits # Number of input units, must match number of input features
n_hidden = hiddenUnits # Number of hidden units
n_output = outputUnits # Number of output units
# Weights for inputs to hidden layer
W1 = torch.randn(n_input, n_hidden)
# Weights for hidden layer to output layer
W2 = torch.randn(n_hidden, n_output)
# and bias terms for hidden and output layers
B1 = torch.randn((1, n_hidden))
B2 = torch.randn((1, n_output))
return W1,W2,B1,B2
def calc_output(features,W1,W2,B1,B2):
h = activation(torch.matmul(features,W1).add_(B1))
output = activation(torch.matmul(h,W2).add_(B2))
return output
# Features are flattened batch input
features = torch.flatten(images,start_dim=1)
W1,W2,B1,B2 = multi_Layer_NW(features.shape[1],256,10)
out = calc_output(features,W1,W2,B1,B2) # output of your network, should have shape (64,10)
out.shape
```
Now we have 10 outputs for our network. We want to pass in an image to our network and get out a probability distribution over the classes that tells us the likely class(es) the image belongs to. Something that looks like this:
<img src='assets/image_distribution.png' width=500px>
Here we see that the probability for each class is roughly the same. This is representing an untrained network, it hasn't seen any data yet so it just returns a uniform distribution with equal probabilities for each class.
To calculate this probability distribution, we often use the [**softmax** function](https://en.wikipedia.org/wiki/Softmax_function). Mathematically this looks like
$$
\Large \sigma(x_i) = \cfrac{e^{x_i}}{\sum_k^K{e^{x_k}}}
$$
What this does is squish each input $x_i$ between 0 and 1 and normalizes the values to give you a proper probability distribution where the probabilites sum up to one.
> **Exercise:** Implement a function `softmax` that performs the softmax calculation and returns probability distributions for each example in the batch. Note that you'll need to pay attention to the shapes when doing this. If you have a tensor `a` with shape `(64, 10)` and a tensor `b` with shape `(64,)`, doing `a/b` will give you an error because PyTorch will try to do the division across the columns (called broadcasting) but you'll get a size mismatch. The way to think about this is for each of the 64 examples, you only want to divide by one value, the sum in the denominator. So you need `b` to have a shape of `(64, 1)`. This way PyTorch will divide the 10 values in each row of `a` by the one value in each row of `b`. Pay attention to how you take the sum as well. You'll need to define the `dim` keyword in `torch.sum`. Setting `dim=0` takes the sum across the rows while `dim=1` takes the sum across the columns.
```
torch.exp(out).sum(1)
out
torch.div(torch.exp(out),torch.exp(out).sum(1).view(-1,1))
def softmax(x):
## TODO: Implement the softmax function here
return torch.div(torch.exp(x),torch.exp(x).sum(1).view(-1,1))
# Here, out should be the output of the network in the previous excercise with shape (64,10)
probabilities = softmax(out)
# Does it have the right shape? Should be (64, 10)
print(probabilities.shape)
# Does it sum to 1?
print(probabilities.sum(dim=1))
```
## Building networks with PyTorch
PyTorch provides a module `nn` that makes building networks much simpler. Here I'll show you how to build the same one as above with 784 inputs, 256 hidden units, 10 output units and a softmax output.
```
from torch import nn
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(256, 10)
# Define sigmoid activation and softmax output
self.sigmoid = nn.Sigmoid()
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
# Pass the input tensor through each of our operations
x = self.hidden(x)
x = self.sigmoid(x)
x = self.output(x)
x = self.softmax(x)
return x
```
Let's go through this bit by bit.
```python
class Network(nn.Module):
```
Here we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class for your network. The name of the class itself can be anything.
```python
self.hidden = nn.Linear(784, 256)
```
This line creates a module for a linear transformation, $x\mathbf{W} + b$, with 784 inputs and 256 outputs and assigns it to `self.hidden`. The module automatically creates the weight and bias tensors which we'll use in the `forward` method. You can access the weight and bias tensors once the network (`net`) is created with `net.hidden.weight` and `net.hidden.bias`.
```python
self.output = nn.Linear(256, 10)
```
Similarly, this creates another linear transformation with 256 inputs and 10 outputs.
```python
self.sigmoid = nn.Sigmoid()
self.softmax = nn.Softmax(dim=1)
```
Here I defined operations for the sigmoid activation and softmax output. Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns.
```python
def forward(self, x):
```
PyTorch networks created with `nn.Module` must have a `forward` method defined. It takes in a tensor `x` and passes it through the operations you defined in the `__init__` method.
```python
x = self.hidden(x)
x = self.sigmoid(x)
x = self.output(x)
x = self.softmax(x)
```
Here the input tensor `x` is passed through each operation and reassigned to `x`. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the `__init__` method doesn't matter, but you'll need to sequence the operations correctly in the `forward` method.
Now we can create a `Network` object.
```
# Create the network and look at its text representation
model = Network()
model
```
You can define the network somewhat more concisely and clearly using the `torch.nn.functional` module. This is the most common way you'll see networks defined as many operations are simple element-wise functions. We normally import this module as `F`, `import torch.nn.functional as F`.
```
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden = nn.Linear(784, 256)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(256, 10)
def forward(self, x):
# Hidden layer with sigmoid activation
x = F.sigmoid(self.hidden(x))
# Output layer with softmax activation
x = F.softmax(self.output(x), dim=1)
return x
```
### Activation functions
So far we've only been looking at the sigmoid activation function, but in general any function can be used as an activation function. The only requirement is that for a network to approximate a non-linear function, the activation functions must be non-linear. Here are a few more examples of common activation functions: Tanh (hyperbolic tangent), and ReLU (rectified linear unit).
<img src="assets/activation.png" width=700px>
In practice, the ReLU function is used almost exclusively as the activation function for hidden layers.
### Your Turn to Build a Network
<img src="assets/mlp_mnist.png" width=600px>
> **Exercise:** Create a network with 784 input units, a hidden layer with 128 units and a ReLU activation, then a hidden layer with 64 units and a ReLU activation, and finally an output layer with a softmax activation as shown above. You can use a ReLU activation with the `nn.ReLU` module or `F.relu` function.
It's good practice to name your layers by their type of network, for instance 'fc' to represent a fully-connected layer. As you code your solution, use `fc1`, `fc2`, and `fc3` as your layer names.
```
## Your solution here
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 64)
# Output layer, 10 units - one for each digit
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
# Hidden layers with relu activation
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
# Output layer with softmax activation
x = F.softmax(self.fc3(x), dim=1)
return x
model = Network()
model
```
### Initializing weights and biases
The weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance.
```
print(model.fc1.weight)
print(model.fc1.bias)
```
For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values.
```
# Set biases to all zeros
model.fc1.bias.data.fill_(0)
# sample from random normal with standard dev = 0.01
model.fc1.weight.data.normal_(std=0.01)
```
### Forward pass
Now that we have a network, let's see what happens when we pass in an image.
```
# Grab some data
dataiter = iter(trainloader)
images, labels = dataiter.next()
# Resize images into a 1D vector, new shape is (batch size, color channels, image pixels)
images.resize_(64, 1, 784)
# or images.resize_(images.shape[0], 1, 784) to automatically get batch size
# Forward pass through the network
img_idx = 0
ps = model.forward(images[img_idx,:])
img = images[img_idx]
helper.view_classify(img.view(1, 28, 28), ps)
```
As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random!
### Using `nn.Sequential`
PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](https://pytorch.org/docs/master/nn.html#torch.nn.Sequential)). Using this to build the equivalent network:
```
# Hyperparameters for our network
input_size = 784
hidden_sizes = [128, 64]
output_size = 10
# Build a feed-forward network
model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
nn.ReLU(),
nn.Linear(hidden_sizes[0], hidden_sizes[1]),
nn.ReLU(),
nn.Linear(hidden_sizes[1], output_size),
nn.Softmax(dim=1))
print(model)
# Forward pass through the network and display output
images, labels = next(iter(trainloader))
images.resize_(images.shape[0], 1, 784)
ps = model.forward(images[0,:])
helper.view_classify(images[0].view(1, 28, 28), ps)
```
Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output.
The operations are available by passing in the appropriate index. For example, if you want to get first Linear operation and look at the weights, you'd use `model[0]`.
```
print(model[0])
model[0].weight
```
You can also pass in an `OrderedDict` to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so _each operation must have a different name_.
```
from collections import OrderedDict
model = nn.Sequential(OrderedDict([
('fc1', nn.Linear(input_size, hidden_sizes[0])),
('relu1', nn.ReLU()),
('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])),
('relu2', nn.ReLU()),
('output', nn.Linear(hidden_sizes[1], output_size)),
('softmax', nn.Softmax(dim=1))]))
model
```
Now you can access layers either by integer or the name
```
print(model[0])
print(model.fc1)
```
In the next notebook, we'll see how we can train a neural network to accuractly predict the numbers appearing in the MNIST images.
| github_jupyter |
# Effect of scaling $\alpha$
In this notebook, we will discuss the impact of scaling of the top layer, which will determine the distance from initialzation to the solution
## Preparation
Here we use MNIST dataset and batch_size = 128, the number of hidden neurons is $m=10^4$.
```
import torch
from torch import optim, nn
from torchvision import datasets, transforms
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
import random
from models import train, train_2
# training parameters
batch_size = 128
transform = transforms.Compose([
transforms.ToTensor()
])
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('data', train=True, download=True, transform=transform),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('data', train=False, download=True, transform=transform),
batch_size=batch_size, shuffle=True)
h_dim = 10000
train_epoch = 50
alpha_set = [h_dim**(0.1*k) for k in range(11)]
```
## Different $\alpha$
We set $\alpha = m^t$, where $t=0,0.3,0.5,1$ and compare the dynamics of NN parameters.
Note that there are two types of learning rate ratio are analysed in the theory which justify the behavior of NN with different $\alpha$:
(1) $\eta_u/\eta_\theta=1$ as Fig.2 in the paper;
(2) $\eta_u/\eta_\theta=\alpha$.
### $\eta_u/\eta_\theta=1$
```
alpha = alpha_set[0]
r1,a1,l1 = train(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
alpha = alpha_set[3]
r2,a2,l2 = train(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
alpha = alpha_set[5]
r3,a3,l3 = train(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
alpha = alpha_set[7]
r4,a4,l4 = train(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
plt.plot(np.arange(50)+1,np.array(r1)[:,0],label = r'$\alpha = 1$')
plt.plot(np.arange(50)+1,np.array(r2)[:,0],label = r'$\alpha = {m}^{0.3}$')
plt.plot(np.arange(50)+1,np.array(r3)[:,0],label = r'$\alpha = {m}^{0.5}$')
plt.plot(np.arange(50)+1,np.array(r4)[:,0],label = r'$\alpha = m^{0.7}$')
plt.legend(fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=11)
plt.ylabel(r'${\Vert \theta-\tilde{\theta} \Vert}$',fontsize=11)
plt.xlabel('epoch',fontsize=15)
#plt.ylim([0.1,10])
plt.yscale('log')
plt.plot(np.arange(50)+1,np.array(r1)[:,1],label = r'$\alpha = 1$')
plt.plot(np.arange(50)+1,np.array(r2)[:,1],label = r'$\alpha = {m}^{0.3}$')
plt.plot(np.arange(50)+1,np.array(r3)[:,1],label = r'$\alpha = {m}^{0.5}$')
plt.plot(np.arange(50)+1,np.array(r4)[:,1],label = r'$\alpha = m^{0.7}$')
plt.legend(fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=11)
plt.ylabel(r'${\Vert u- \tilde{u} \Vert}$',fontsize=11)
plt.xlabel('epoch',fontsize=15)
plt.yscale('log')
```
### $\eta_u/\eta_\theta=\alpha$
```
train_epoch = 100
alpha = alpha_set[0]
r1_,a1_,l1_ = train_2(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
alpha = alpha_set[3]
r2_,a2_,l2_ = train_2(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
alpha = alpha_set[5]
r3_,a3_,l3_ = train_2(train_loader,test_loader,h_dim,alpha,train_epoch,.1)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
plt.plot(np.arange(train_epoch)+1,np.array(r1_)[:,0],label = r'$\alpha = 1$')
plt.plot(np.arange(train_epoch)+1,np.array(r2_)[:,0],label = r'$\alpha = {m}^{0.3}$')
plt.plot(np.arange(train_epoch)+1,np.array(r3_)[:,0],label = r'$\alpha = {m}^{0.5}$')
plt.legend(fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=11)
plt.ylabel(r'${\Vert \theta-\tilde{\theta} \Vert}$',fontsize=11)
plt.xlabel('epoch',fontsize=15)
#plt.ylim([0.1,10])
plt.yscale('log')
plt.plot(np.arange(train_epoch)+1,np.array(r1_)[:,1],label = r'$\alpha = 1$')
plt.plot(np.arange(train_epoch)+1,np.array(r2_)[:,1],label = r'$\alpha = {m}^{0.3}$')
plt.plot(np.arange(train_epoch)+1,np.array(r3_)[:,1],label = r'$\alpha = {m}^{0.5}$')
plt.legend(fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=11)
plt.ylabel(r'${\Vert u- \tilde{u} \Vert}$',fontsize=11)
plt.xlabel('epoch',fontsize=15)
plt.yscale('log')
```
| github_jupyter |
# Tests and Exceptions
In this lesson we will look at how to make your code more reliable by writing tests. Tests when used cleverly can give you a lot of confidence in your code and therefore your results!
Lets start with our (broken) square function from the last lesson:
```
def square(x):
return x**3
```
Tests can take many forms, they can compare your code against known results i.e. ones in a published paper, or they can just test that the result of some function returns the type of object you expect or even just check that your code results always stays the same, so you know if something breaks.
A simple test for our square function we defined above might look like:
```
def test_square():
assert square(10) == 10*10
```
<section class="callout panel panel-warning">
<div class="panel-heading">
<h2><span class="fa fa-thumb-tack"></span> The `assert` statement</h2>
</div>
<div class="panel-body">
<p>As we will see later, the way to make a test fail is to raise an error. Therefore the <code>assert</code> statement in Python is a useful shortcut when writing tests.</p>
<p>The <code>assert</code> statement will raise an error if a condition is not satisfied. The general form of the assert statement is:</p>
<div class="codehilite"><pre><span></span><span class="k">assert</span> <span class="n">condition</span><span class="p">,</span> <span class="s2">"message"</span>
</pre></div>
<p>i.e.</p>
<div class="codehilite"><pre><span></span><span class="k">assert</span> <span class="mi">5</span> <span class="o">==</span> <span class="mi">6</span><span class="p">,</span> <span class="s2">"Five is not equal to six"</span>
</pre></div>
</div>
</section>
We can run our test function the same way that we run any other function. Although this dosent scale very well to thousands of tests!
```
test_square()
```
<section class="challange panel panel-success">
<div class="panel-heading">
<h2><span class="fa fa-pencil"></span> Writing Tests</h2>
</div>
<div class="panel-body">
<p>The following function has bugs in it. Write some tests below the function to find all the bugs.</p>
</div>
</section>
```
def quadratic(a, b, c):
return ((-1* b) * np.sqrt(b**2 - 4*a*c) / (2 * a))
import numpy as np
def test_quadratic():
assert(quadratic(1,1,-1)) == -1.118033988749895
test_quadratic()
```
## Running Tests Automatically with pytest
Once you have a few test functions written, you will probably start getting bored with typing out their names and running them one-by-one. There are a few different modules to help you write and run tests. The one we will be using is called [`pytest`](https://docs.pytest.org/en/latest/).
For the next section of this session we will be using the two Python (`.py`) files named `askdl.py` and `lsadkj.py`.
| github_jupyter |
### Imports
In most Python projects it is unlikely that all the functionality you need is part of the plain vanilla (built-in) Python.
Like in any other language, Python has a concept of libraries (modules) that can be imported and then used.
In Python, all the module files you create can be imported into other modules (in a Jupyter notebook, you essentially have a single module, called the main module) - but in larger projects you typically do not use Jupyter, and instead strcuture your application using folders, sub-folders, modules, etc.
Python comes with a huge assortment of pre-defined modules that can easily be imported into any module.
When a module is imported by Python, it essentially **executes** the code in the module, and caches that internally (so if you import the same module in multiple places in your code, it only runs the code once, and thereafter gives you back the "pre-compiled" module).
In this primer we're going to stick to some of the modules provided as part of CPython - the so-called **standard library**.
One thing that is really important to understand is that a module is essentially just a namespace - i.e. it is a dictionary of symbols that point to objects, often functions and classes, but possibly other object types too (such as floats, etc).
A module is very much like a class - you access the symbols in the module using dot notation - and Python then looks up the symbol from the module's namespace (which is in fact just a dictionary).
And in case you're wondering, a class in Python is also essentially a dictionary, but with a few extra bells and whistles - but a dictionary nonetheless).
#### The `import` Statement
Let's import the `math` module, documented [here](https://docs.python.org/3/library/math.html):
```
import math
```
That's it, now we have a symbol, called `math` in **our** name space, that points to the compiled `math` module that is being cached by Python.
Let's look at our namespace:
```
globals()
```
As you can see we have quite a few things in our global namespace - including an entry for `math`:
```
globals()['math']
```
And yes, we used dictionary notation to recover the `math` symbol - that's because namespaces are essentially just dictionaries.
```
type(globals())
```
But of course, we can access the `math` symbol using the easier dot notation (Python essentially translates that dot notation into a dictionary lookup).
```
math
```
And we can access anything inside this `math` module:
```
math.pi
math.sin(math.pi)
```
Note: What does **global** namespace actually mean?
There is no "global" global namespace in Python - each module (including this main module Jupyter notebook) has it's own namespace - this root namespace for a module is called the **global** namespace - but it is specific to the module - there is no such thing as an overarching global namespace for your entire application.
#### Aliasing Imports
As you can see, when we wrote:
```import math```
we basically created a symbol named `math` in our global namespace
We could alias this symbol if we wanted to:
```
my_math = math
```
Now we added another symbol `my_math` in our global namespace that points to the same object as `math`:
```
math is my_math
```
In fact, we could even delete `math` from our global namespace:
```
del math
'math' in globals()
'my_math' in globals()
```
As you can see `math` is gone, but our alias `my_math` is still there, and we can use it just as before:
```
my_math.pi, my_math.sin(my_math.pi)
```
This sort of aliasing is common enough, especially with long winded module names that we don't want to be typing all the time, that Python builds this right into the import statement:
```
import math as math2
```
Now `math2` is in our global namespace, and points to the same cached module as before (so imported modules are essentially singletons):
```
my_math is math2
math2.pi, math2.sin(math2.pi)
```
#### Importing Specific Symbols
You'll notice that the approach we took here was to just import the entire module - this means our global namespace holds on to a reference to the module itself.
And then when we reach inside the module, we always need to specify which module to use:
```
import math
import random
math.pi, random.randint(1, 10)
```
Sometimes, we only use a few symbols from a particular import, and there is a way to get a reference to those specific symbols directly, without holding on to a reference to the module itself.
First let's delete any references to the `math` and `random` modules:
```
del math
del random
del math2
del my_math
```
Now, let's just import what we need from those modules:
```
from math import pi, sin
from random import randint
```
At this point, we **do not** have a reference to either `math` or `random` in our globals:
```
'math' in globals(), 'random' in globals()
```
But we **do** have a direct reference to the symbols we imported:
```
'pi' in globals(), 'sin' in globals(), 'randint' in globals()
```
And now we can use them without having to prefix them with the name of the module they came from:
```
sin(pi), randint(1, 10)
```
**Note**: A common misconception is that by importing only a few symbols from a particular module you are saving memory by only loading these symbols into memory.
That is **not** the case.
Remember, Python will import the entire module (using a cached instance if present), and then just add references to our global namespace. Whether we ask for a reference to the module itself (`import math`), or just a few symbols (`from math import pi, sin`), the module has to be loaded and stored in memory anyway.
#### Aliasing - Redux
Just like we could alias a module name as we imported it into our global namespace, so can we alias individual symbols we import from a particular module.
We could do it the long way:
```
from math import pi
PI = pi
del pi
PI
```
But we can use the `alias` clause of the import for this as well:
Let's first delete `PI` from our namespace:
```
del PI
'PI' in globals()
```
And now let's do the aliased import:
```
from math import pi as PI
```
Now `pi` is not in our namespace:
```
'pi' in globals()
```
But `PI` is:
```
'PI' in globals()
```
There are a ton of modules (or packages which are collections of modules) provided by the standard library.
See these [docs](https://docs.python.org/3/library/index.html) for more info.
There are also many 3rd party Python libraries available as well, most of which are documented in **PyPI** - the Python Package Index - available [here](https://pypi.org/)
As of writing this, there are well over 300,000 such libraries.
To install these packages you just have to `pip install` the specific package name into your virtual environment (so remember to activate it first), by using the command line. (In fact, that's what you woudl have done to install Jupyter Notebooks - except we listed all the packages we wanted to install in a `requirements.txt` file, and then told pip to install anything listed in there.
Some of the most common packages to get installed will depend on your project, but common ones include:
- `requests` for making http requests, like API requests for example
- `pytz` for dealing with those pesky time zones and daylight savings - if you have to deal with timezones then `pytz` is essential!
- `numpy` for fast vectorized calculations
- `pandas` for dealing with datasets in a structured manner, and plenty of tools to manipulate these datasets - almost like a mini in-memory database
- and many more...
-
| github_jupyter |
# End to end image classification workflow with distributed training
The following example demonstrates an end to end data science workflow for building an an image classifier <br>
The model is trained on an images dataset of cats and dogs. Then the model is deployed as a function in a serving layer <br>
Users can send http request with an image of cats/dogs image and get a respond back that identify whether it is a cat or a dog
This typical data science workflow comprises of the following:
* Download anb label the dataset
* Training a model on the images dataset
* Deploy a function with the new model in a serving layer
* Testing the function
Key technologies:
* Keras and TensorFlow for training the model
* Horovod for running a distributed training
* MLRun (open source library for tracking experiments https://github.com/mlrun/mlrun) for building the functions and tracking experiments
* Nuclio function for creating a funciton that runs the model in a serving layer
This demo is based on the following:<br>
* https://github.com/tensorflow/docs/tree/master/site/en/tutorials
* https://www.kaggle.com/uysimty/keras-cnn-dog-or-cat-classification/log
```
# nuclio: ignore
import nuclio
#!pip install kfp
%nuclio config spec.build.baseImage = "python:3.6-jessie"
```
## Helper functions for downloading and labeling images
In the code below we have two functions:
1. open_archive - Get and extract a zip file that contains cats and dog images. users need to pass the source URL and the target directory which is stored in Iguazio data layer
2. categories_map_builder - labeling the dataset based on the file name. the functions creates a pandas dataframe with the filename and category (i.e. cat & dog)
Note that sometime after running pip install you need to restart the jupyer kernel
```
import os
import zipfile
import json
from tempfile import mktemp
import pandas as pd
def open_archive(context,
target_dir='content',
archive_url=''):
"""Open a file/object archive into a target directory"""
# Define locations
os.makedirs(target_dir, exist_ok=True)
context.logger.info('Verified directories')
# Extract dataset from zip
context.logger.info('Extracting zip')
zip_ref = zipfile.ZipFile(archive_url, 'r')
zip_ref.extractall(target_dir)
zip_ref.close()
context.logger.info(f'extracted archive to {target_dir}')
context.log_artifact('content', local_path=target_dir)
def categories_map_builder(context,
source_dir,
df_filename='file_categories_df.csv',
map_filename='categories_map.json'):
"""Read labeled images from a directory and create category map + df
filename format: <category>.NN.jpg"""
# create filenames list (jpg only)
filenames = [file for file in os.listdir(source_dir) if file.endswith('.jpg')]
categories = []
# Create a pandas DataFrame for the full sample
for filename in filenames:
category = filename.split('.')[0]
categories.append(category)
df = pd.DataFrame({
'filename': filenames,
'category': categories
})
df['category'] = df['category'].astype('str')
categories = df.category.unique()
categories = {i: category for i, category in enumerate(categories)}
with open(os.path.join(context.artifact_path, map_filename), 'w') as f:
f.write(json.dumps(categories))
context.logger.info(categories)
context.log_artifact('categories_map', local_path=map_filename)
context.log_dataset('file_categories', df=df, local_path=df_filename)
# nuclio: end-code
```
# Complete Data-Science Pipeline with MLRun
We are using a library called MLRun for running the functions and storing the experiments meta data in the MLRun database <br>
Users can query the database to view all the experiments along with their associated meta data <br>
- Get data
- Create categories map
- Train horovod model on the cluster
- Deploy model
Set the MLRun database location and the base directory
```
import mlrun
base_dir = os.path.dirname(os.getcwd())
images_path = os.path.join(base_dir, 'images')
code_dir = os.path.join(base_dir, 'src') # Where our source code files are saved
yaml_dir = os.path.join(base_dir, 'yaml')
artifact_path = os.path.join(base_dir, 'artifacts')
# define artifact path for MLRun
# mlrun.mlconf.artifact_path = artifact_path
# Set MLRun API Endpoint
mlrun.mlconf.dbpath = 'http://mlrun-api:8080'
```
### Step 1: Download and extract image archive
The dataset is taken from the Iguazio-sample bucket in S3 <br>
>Note that this step is captured in the MLRun database. <br>
We create a new local function with our inline code from above (while saving the code output to our `src` directory).
We then define a `NewTask` with the `open_archive` function handler and the needed parameters.
```
utils = mlrun.code_to_function(project='image-classification',
kind='job',
code_output=os.path.join(code_dir, 'utils.py'),
with_doc=True)
# download images from s3 using the local `open_archive` function
open_archive_task = mlrun.NewTask(name='download',
project='image-classification',
handler=open_archive,
params={'target_dir': images_path},
inputs={'archive_url': 'http://iguazio-sample-data.s3.amazonaws.com/catsndogs.zip'})
open_archive = mlrun.run_local(open_archive_task)
```
### Step 2: Tag Images with Categories (cat & dog)
We define a `NewTask` with the `categories_map_builder` function handler and the needed parameters.
We then use a Local Runtime (the default for new functions) to run the task.
```
# Create categories map
label_task = mlrun.NewTask(name='label',
project='image-classification',
handler=categories_map_builder,
artifact_path=images_path,
params={'source_dir': os.path.join(images_path, 'cats_n_dogs'),
'map_filename': 'categories_map.json'})
labeler_run = mlrun.run_local(label_task)
```
### Step 3: Distributed Training with TensorFlow, Keras and Horovod
Here we use the same structure as before to deploy our [cats vs. dogs tensorflow model training file](horovod-training.py) to run on the defined horovod cluster in a distributed manner.
We define the input parameters for the training function.
We set the function's `kind='mpijob'` to let MLRun know to apply the job to the MPI CRD and create the requested horovod cluster.
We set the number of workers for the horovod cluster to use by setting `trainer.spec.replicas = 4` (default is 1 replica).
We set the number of GPUs each worker will receive by setting `trainer.gpus(1)` (default is 0 GPUs).
> Please verify that the `HOROVOD_FILE` path is available from the cluster (Local path and Mounted path may vary)
```
HOROVOD_FILE = os.path.join(code_dir, 'horovod-training.py')
params = {
'data_path' : os.path.join(images_path, 'cats_n_dogs'),
'checkpoints_dir' : os.path.join(base_dir, 'checkpoints'),
'model_path' : os.path.join(base_dir, 'models', 'cats_n_dogs.h5'),
'epochs' : 1,
'batch_size' : 64,
'image_width': 128,
'image_height': 128,
'image_channels': 3
}
inputs = {
'categories_map': labeler_run.outputs['categories_map'],
'file_categories': labeler_run.outputs['file_categories']
}
image = 'mlrun/mpijob:latest'
trainer = mlrun.new_function(name='horovod-trainer',
kind='mpijob',
command=HOROVOD_FILE,
image=image)
trainer.apply(mlrun.mount_v3io())
trainer.spec.image_pull_policy = 'Always'
trainer.spec.replicas = 4
# trainer.gpus(1)
mprun = trainer.run(name='train',
params=params,
out_path='/User/mlrun',
inputs=inputs,
watch=True)
```
#### Save the training function
We can use the MLRun DB to store functions for later use.
When calling `trainer.save()`, the files, the function code, deployment parameters and requested inputs and params are saved.
We can then call them from any location connected to the current DB by using `import_function('db://<function-name>)`, as in this case `import_function('db://horovod-trainer')`.
```
# save our function object to the DB
trainer.save()
trainer.export(os.path.join(yaml_dir, 'trainer.yaml'))
```
### Step 4: Deploy Model Serving Function
In the following cells we use MLRun to deploy a Model Serving Class from the [nuclio-serving-tf-images](nuclio-serving-tf-images.ipynb) notebook and deploy it with the arguments from our current runs.
Using `filename=<jupyter notebook file>` in the `new_model_server` we parse the given Jupyter Notebook and build our model server from it.
> All the annotations given in the notebook will be parsed and saved to the function normally
The model server will deploy the model given under `models={<model_name>:<model_file_path>}` as `model_class=<model_class_name>` .
Just like any other MLRun function we can set our environment variables, workers and add mounts.
The model server will provide us with a `/<model_name>/predict` endpoint where we can query the model.
After we finish setting up the function parameters, we deploy it to the appropriate project using `deploy()`.
```
model_name = 'cat_dog_v1'
# convert the notebook code to a model server and configure it
inference_function = mlrun.new_model_server('tf-images-server',
filename='./nuclio-serving-tf-images.ipynb',
model_class='TFModel',
models={model_name: params['model_path']})
inference_function.set_env('classes_map', labeler_run.outputs['categories_map'])
inference_function.with_http(workers=2).apply(mlrun.mount_v3io())
addr = inference_function.deploy(project='nuclio-serving')
```
## Test the serving function
After the function has been deployed we can test it as a regular REST Endpoint using `requests`.
```
import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
```
### Define test params
```
# Testing event
cat_image_url = 'https://s3.amazonaws.com/iguazio-sample-data/images/catanddog/cat.102.jpg'
response = requests.get(cat_image_url)
cat_image = response.content
img = Image.open(BytesIO(cat_image))
print('Test image:')
plt.imshow(img)
```
### Test The Serving Function (with Image URL)
```
headers = {'Content-type': 'text/plain'}
response = requests.post(url=f'{addr}/{model_name}/predict',
data=json.dumps({'data_url': cat_image_url}),
headers=headers)
print(response.content.decode('utf-8'))
```
### Test The Serving Function (with Jpeg Image)
```
headers = {'Content-type': 'image/jpeg'}
response = requests.post(url=f'{addr}/{model_name}/predict',
data=cat_image,
headers=headers)
print(response.content.decode('utf-8'))
```
| github_jupyter |
```
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
!ls ensemble/
yw = np.load('ensemble/cb6133test_yw3169_yh3050.npy') # uses warped list
yw_new = np.load('ensemble/cb6133test_yw3169_yh3050_newscore.npy') # uses warped list
ddl = np.load('ensemble/cb6133test_ddl2133_ks3311_.prob.npy') # uses original label indices
hk = np.load('ensemble/cb6133test_am4564_hk2903.prob.npy') # uses warped list
ln = np.load('ensemble/cb6133_ln2401_kat2193.prob.npy') # uses warped list
ps = np.load('ensemble/cb6133test_ps2958_jw3468.prob.npy') # uses warped list
stack = np.load('ensemble/cb6133test_stacker_prob.npy') # uses warped list
print (yw.shape,yw_new.shape, ddl.shape, hk.shape,ln.shape, ps.shape,stack.shape)
# warped_order_1 = ['NoSeq', 'H', 'E', 'L','T', 'S', 'G', 'B', 'I']
# 0 1 2 3 4 5 6 7 8
# ['L', 'B', 'E', 'G','I', 'H', 'S', 'T', 'NoSeq'] # new order
fix_warp_list = [8,5,2,0,7,6,3,1,4]
labels = ['L', 'B', 'E', 'G','I', 'H', 'S', 'T', 'NoSeq']
# fix order for hk
ln_fixed = np.zeros_like(ddl)
for count, i in enumerate(fix_warp_list):
ln_fixed[:,:,i] = ln[:,:700,count]
# fix order for hk
hk_fixed = np.zeros_like(ddl)
for count, i in enumerate(fix_warp_list):
hk_fixed[:,:,i] = hk[:,:700,count]
# fix order for hk
stack_fixed = np.zeros_like(ddl)
for count, i in enumerate(fix_warp_list):
stack_fixed[:,:,i] = stack[:,:700,count]
# fix order for hk
ps_fixed = np.zeros_like(ddl)
for count, i in enumerate(fix_warp_list):
ps_fixed[:,:,i] = ps[:,:700,count]
# fix order for yw
yw_fixed = np.zeros_like(ddl)
for count, i in enumerate(fix_warp_list):
yw_fixed[:,:,i] = yw[:,:700,count]
yw_new_fixed = np.zeros_like(ddl)
for count, i in enumerate(fix_warp_list):
yw_new_fixed[:,:,i] = yw_new[:,:700,count]
def check_softmax(T):
for i in range(T.shape[0]):
for j in range(T.shape[1]):
try:
assert np.abs(np.sum(T[i,j,:])-1.0)<0.0001
except:
print (np.sum(T[i,j,:]), 'failed')
return
print ('outputs are softmaxed')
check_softmax(ddl)
check_softmax(hk_fixed)
check_softmax(yw_fixed)
check_softmax(yw_new_fixed)
check_softmax(ps_fixed)
#check_softmax(ln_fixed)
check_softmax(stack_fixed)
summed_probs = ddl+ yw_fixed + hk_fixed + yw_new_fixed + ps_fixed #stack#+ ln
length_list = [len(line.strip().split(',')[2]) for line in open('testing/cb6133test_solution.csv').readlines()]
print ('max protein seq length is', np.max(length_list))
ensemble_predictions = []
for protein_idx, i in enumerate(length_list):
new_pred = ''
for j in range(i):
new_pred += labels[np.argmax(summed_probs[protein_idx, j ,:])]
ensemble_predictions.append(new_pred)
with open('ensemble_predictions.csv','w') as f:
for idx, i in enumerate(ensemble_predictions):
f.write(str(idx)+','+i + '\n')
# calculating accuracy
def get_acc(gt,pred):
assert len(gt)== len(pred)
correct = 0
for i in range(len(gt)):
if gt[i]==pred[i]:
correct+=1
return (1.0*correct)/len(gt)
gt_all = [line.strip().split(',')[3] for line in open('testing/cb6133test_solution.csv').readlines()]
acc_list = []
for gt,pred in zip(gt_all,ensemble_predictions):
acc = get_acc(gt,pred)
acc_list.append(acc)
print ('mean accuracy is', np.mean(acc_list))
name2label = {j:i for i,j in enumerate(labels[:-1])}
label2name = {i:j for i,j in enumerate(labels[:-1])}
name2label
label2name
classes = len(labels[:-1])
conf_matrix = np.zeros((classes,classes))
for gt,pred in zip(gt_all,ensemble_predictions):
for g,p in zip(gt,pred):
conf_matrix[name2label[p],name2label[g]]+=1.0
recall_list = np.zeros((classes,))
precision_list = np.zeros((classes,))
for i in range(classes):
if np.sum(conf_matrix[:,i])!=0:
recall_list[i] = conf_matrix[i,i]/float(np.sum(conf_matrix[:,i]))
else:
recall_list[i] = 0
if np.sum(conf_matrix[i,:])!=0:
precision_list[i] = conf_matrix[i,i]/float(np.sum(conf_matrix[i,:]))
else:
precision_list[i] = 0
fscore = np.zeros((classes,))
for i in range(classes):
if precision_list[i] + recall_list[i]!=0:
fscore[i] = 2.0 *precision_list[i] * recall_list[i] / (precision_list[i] + recall_list[i])
else:
fscore[i] = 0
for i in range(classes):
print ('precision of class',label2name[i], precision_list[i])
print ('average precision', np.mean(precision_list))
for i in range(classes):
print ('recall of class',label2name[i], recall_list[i])
print ('average recall', np.mean(recall_list))
for i in range(classes):
print ('fscore of class',label2name[i], fscore[i])
print ('average f-score', np.mean(fscore))
with open('metrics_cb6133.csv', 'w') as f:
f.write('secondary structure, precision, recall, f-score' + '\n')
for i in range(classes):
f.write(str(label2name[i]) + ',' +str(precision_list[i]) + ',' + str(recall_list[i]) + ',' + str(fscore[i]) + '\n')
f.write('mean,'+str(np.mean(precision_list)) +','+ str(np.mean(recall_list))+','+str(np.mean(fscore)) + '\n' )
```
| github_jupyter |
<a href="https://colab.research.google.com/github/cxbxmxcx/EvolutionaryDeepLearning/blob/main/EDL_9_4_DCGAN_Encoder.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!pip install livelossplot --quiet
#@title The Imports
from tensorflow.keras.datasets import mnist as data
#from tensorflow.keras.datasets import fashion_mnist as data
#from tensorflow.keras.datasets import cifar10 as data
#from tensorflow.keras.utils import np_utils
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Input, Dense, Activation, Flatten, Reshape, Dropout, ZeroPadding2D
from tensorflow.keras.layers import Conv2D, Conv2DTranspose, UpSampling2D, Convolution2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras.optimizers import Adam, RMSprop
from tensorflow.keras.initializers import RandomNormal
import tensorflow.keras.backend as K
import numpy as np
import matplotlib.pyplot as plt
from livelossplot import PlotLosses
from tqdm import tqdm_notebook
import random
from tqdm.notebook import tqdm as tqdm
plt.gray()
#@title Extract Class of Images
def extract(images, labels, class_):
labels = np.squeeze(labels)
idx = labels == class_
imgs = images[idx]
print(imgs.shape)
return imgs
#@title Load and Normalize Training/Test Data
(train_images, train_labels), (test_images, test_labels) = data.load_data()
# split dataset
#train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype("float32") / 255.0
print(train_images.shape)
train_images = extract(train_images, train_labels, 5)
plt.imshow(train_images[0])
# Rescale -1 to 1
train_images = (train_images.astype(np.float32) - 127.5) / 127.5
if len(train_images.shape)<4:
train_images = np.expand_dims(train_images, axis=3)
print(train_images.shape)
#@title Determine Global Parameters
latent_dim = 100
channels = train_images.shape[3]
image_shape = (train_images.shape[1], train_images.shape[2], channels)
print(image_shape)
#@title Range Helper Functions
def clamp(num, min_value, max_value):
return max(min(num, max_value), min_value)
def linespace(v, min, max):
range = max - min
return v * range + min
def linespace_int(v, min, max):
range = max - min
return int(v * range + min)
def reverse_space(x, min, max):
range = max - min
if range==0: return 0
return (x - min) / range
#@title Defining the DCGAN Class
# ENCODING CONSTANTS
FILTERS = 0
MIN_FILTERS = 16
MAX_FILTERS = 128
ALPHA = 1
MIN_ALPHA = .05
MAX_ALPHA = .5
CRITICS = 2
MIN_CRITICS = 1
MAX_CRITICS = 10
CLIP = 3
MIN_CLIP = .005
MAX_CLIP = .1
LR = 4
MIN_LR = .00000001
MAX_LR = .0001
class DCGAN:
def __init__(self, i):
'''
=== GLOBAL ===
image_shape=(32, 32, 1),
z_size=(1, 1, latent_dim),
=== ENCODED ===
n_filters=128,
alpha=0.2,
disc_iters=5
clip_lower=-0.01,
clip_upper=0.01,
lr=5e-5,
'''
assert image_shape[0] % 4 == 0, "Image shape must be divisible by 4."
self.image_shape = image_shape
self.z_size = (1, 1, latent_dim)
self.n_filters = linespace_int(i[FILTERS], MIN_FILTERS, MAX_FILTERS)
self.alpha = linespace_int(i[ALPHA], MIN_ALPHA, MAX_ALPHA)
self.lr = linespace(i[LR], MIN_LR, MAX_LR)
self.clip_lower = -linespace(i[CLIP], MIN_CLIP, MAX_CLIP)
self.clip_upper = linespace(i[CLIP], MIN_CLIP, MAX_CLIP)
self.critic_iters = linespace_int(i[CRITICS], MAX_CRITICS, MIN_CRITICS)
self.weight_init = RandomNormal(mean=0., stddev=0.02)
self.optimizer = RMSprop(self.lr)
self.critic = self.build_critic()
self.g = self.build_generator()
self.gan = self.build_gan()
def build_critic(self):
model = Sequential(name="Critic")
model.add(Conv2D(self.n_filters//4, kernel_size=3, strides=2, input_shape=self.image_shape, padding="same"))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(self.n_filters//2, kernel_size=3, strides=2, padding="same"))
model.add(ZeroPadding2D(padding=((0,1),(0,1))))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(self.n_filters, kernel_size=3, strides=2, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Conv2D(self.n_filters*2, kernel_size=3, strides=1, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1))
img = Input(shape=self.image_shape)
validity = model(img)
model = Model(img, validity)
model.compile(loss=self.wasserstein_loss,
optimizer=self.optimizer,
metrics=['accuracy'])
return model
def build_generator(self):
model = Sequential(name="Generator")
cs = self.image_shape[1] // 4
model.add(Dense(self.n_filters * cs * cs, activation="relu", input_dim=latent_dim))
model.add(Reshape((cs, cs, self.n_filters)))
model.add(UpSampling2D())
model.add(Conv2D(self.n_filters, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(Activation("relu"))
model.add(UpSampling2D())
model.add(Conv2D(self.n_filters//2, kernel_size=3, padding="same"))
model.add(BatchNormalization(momentum=0.8))
model.add(Activation("relu"))
model.add(Conv2D(channels, kernel_size=3, padding="same"))
model.add(Activation("tanh"))
noise = Input(shape=(latent_dim,))
img = model(noise)
return Model(noise, img)
def build_gan(self):
z = Input(shape=(latent_dim,))
img = self.g(z)
# For the combined model we will only train the generator
self.critic.trainable = False
# The discriminator takes generated images as input and determines validity
valid = self.critic(img)
# The combined model (stacked generator and discriminator)
# Trains the generator to fool the discriminator
gan = Model(z, valid)
gan.compile(loss=self.wasserstein_loss, optimizer=self.optimizer)
return gan
def train(self, train_images, epochs=10, batch_size=128, verbose=0):
#track minium/maximum losses
min_g_loss = 1000
min_fake_loss = 1000
min_real_loss = 1000
max_g_loss = -1000
max_fake_loss = -1000
max_real_loss = -1000
# Adversarial ground truths
valid = -np.ones((batch_size, 1))
fake = np.ones((batch_size, 1))
batches = int(train_images.shape[0] / batch_size)
history = []
if verbose:
groups = { "Critic" : {"Real", "Fake"}, "Generator":{"Gen"}}
plotlosses = PlotLosses(groups=groups)
for e in range(epochs):
for i in tqdm(range(batches)):
for _ in range(self.critic_iters):
# ---------------------
# Train critic
# ---------------------
# Select a random half of images
idx = np.random.randint(0, train_images.shape[0], batch_size)
imgs = train_images[idx]
# Sample noise and generate a batch of new images
noise = np.random.normal(0, 1, (batch_size, latent_dim))
gen_imgs = self.g.predict(noise)
# Train the critic (real classified as ones and generated as zeros)
c_loss_real = self.critic.train_on_batch(imgs, valid)
c_loss_fake = self.critic.train_on_batch(gen_imgs, fake)
c_loss = 0.5 * np.add(c_loss_real, c_loss_fake)
#clip discriminator/critic weights
for l in self.critic.layers:
weights = l.get_weights()
weights = [np.clip(w, self.clip_lower, self.clip_upper) for w in weights]
l.set_weights(weights)
# ---------------------
# Train Generator
# ---------------------
# Train the generator (wants discriminator to mistake images as real)
g_loss = self.gan.train_on_batch(noise, valid)
min_g_loss = min(min_g_loss, g_loss)
min_fake_loss = min(min_fake_loss, c_loss[1])
min_real_loss = min(min_real_loss, c_loss[0])
max_g_loss = max(max_g_loss, g_loss)
max_fake_loss = max(max_fake_loss, c_loss[1])
max_real_loss = max(max_real_loss, c_loss[0])
loss = dict(
Real = reverse_space(c_loss[0],min_real_loss, max_real_loss),
Fake = reverse_space(c_loss[1],min_fake_loss, max_fake_loss),
Gen = reverse_space(g_loss, min_g_loss, max_g_loss) )
history.append(loss)
if verbose:
plotlosses.update(loss)
plotlosses.send()
self.plot_generated()
print(min_g_loss, max_g_loss, min_fake_loss, max_fake_loss, min_real_loss, max_real_loss)
return history
def wasserstein_loss(self, y_true, y_pred):
return K.mean(y_true * y_pred)
def plot_generated(self, n_ex=10, dim=(1, 10), figsize=(12, 2)):
noise = np.random.normal(0, 1, size=(n_ex, latent_dim))
generated_images = self.g.predict(noise)
generated_images = generated_images.reshape(n_ex, image_shape[0], image_shape[1])
plt.figure(figsize=figsize)
for i in range(generated_images.shape[0]):
plt.subplot(dim[0], dim[1], i+1)
plt.imshow((1-generated_images[i])*255, interpolation='nearest', cmap='gray_r')
plt.axis('off')
plt.tight_layout()
plt.show()
individual = np.random.random((10))
dcgan = DCGAN(individual)
dcgan.g.summary()
dcgan.critic.summary()
dcgan.gan.summary()
individual = np.random.random((5))
dcgan = DCGAN(individual)
history = dcgan.train(train_images, verbose=1)
individual = np.random.random((10))
individual[FILTERS] = reverse_space(128, MIN_FILTERS, MAX_FILTERS)
individual[ALPHA] = reverse_space(.2, MIN_ALPHA, MAX_ALPHA)
individual[CLIP] = reverse_space(.01, MIN_CLIP, MAX_CLIP)
individual[CRITICS] = reverse_space(5, MIN_CRITICS, MAX_CRITICS)
individual[LR] = reverse_space(.00005, MIN_LR, MAX_LR)
print(individual)
dcgan = DCGAN(individual)
history = dcgan.train(train_images, verbose=1)
```
| github_jupyter |
```
cc.VerificationHandler.close_browser()
```
## Time to crack in and find some more mother elements
#### Dont let complexity ruin tempo
```
% run contactsScraper.py
orgsForToday = ['National Association for Multi-Ethnicity In Communications (NAMIC)',
'Association for Women in Science',
'Brain Injury Association of America',
'American Society of Home Inspectors',
'NAADAC, the Association for Addiction Professionals',
'American Public Transportation Association',
'Indiana Soybean Alliance',
'Associated Builders and Contractors (ABC)',
'National Association of Social Workers',
'American Marketing Association (AMA)']
org = orgsForToday[8]
vh = cc.MotherSetVerifier(org)
pointers = vh.verifiedPointers
len(pointers)
cc.VerificationHandler.orgRecords.orgSessionStatusCheck()
import numpy as np
np.matrix([pointers, pointers])
gmElements = []
gmMatrix = []
for i in range(len(pointers)):
igmElements = []
for j in range(i):
if pointers[i].get_mother_element() is pointers[j].get_mother_element():
gm = pointers[i].get_mother_element()
else:
gm = pointers[i].common_parent(pointers[j])
# Append Match to Grand Mother Matrix
igmElements.append(gm)
# Check to see if this is a new grand mother element,
# if so append to the gmElements list of unique grandmother elements
if gm not in gmElements:
gmElements.append(gm)
# Append Matrix Row
gmMatrix.append(igmElements)
grandMotherMatrix = np.matrix(gmMatrix)
grandMotherMatrix
```
## Just what was Expexted, 1 grandmother element
```
len(gmElements)
type(gmElements[0])
```
## Find other Mother elements with the same attributes within the found GrandMother
```
a = pointers[1].get_mother_element()
b = pointers[0].get_mother_element()
a is gm
print(gm.prettify())
b.attrs
a.attrs == b.attrs
a.name
b.name
gm = gmElements[0]
finds = gm.find_all(class_='team-member-right')
len(finds)
findsSib = gm.find_all("h2")
findsSib
```
## There are verified pointers and there are elements that mimic them
```
gm
mothers = pointers
mothers[0].tom_here()
mothers[0].tom
mothers[0].mary_here()
mothers[0].tom.parent.parent is mothers[0].mary
mothers[0].tom.parent.attrs
mothers[0].tom.parent.contents
mothers[0].tom.parent['toms'] = 0
mothers[0].nathan_here()
mothers[0].nathan
mothers[0].nathan.parent['nathans'] = 0
mothers[0].nathan.parent.parent is mothers[0].get_mother_element()
## Tag elements with atributes up the ancestrial chain from tom all the way to the mother element
def tag_nathans(pt):
## Precondition: The name pointer for this verified pointer is a nathan
return parent_cycle(pt.get_mother_element(), pt.nathan.parent, 'nathans', 0)
def tag_toms(pt):
return parent_cycle_up(pt.get_mother_element(), pt.tom.parent, 'toms', 0)
def parent_cycle_up(motherElement, element, atr, num):
if element is motherElement:
return
else:
element[atr] = num
return parent_cycle(motherElement, element.parent, atr, num + 1)
def get_nathan(fnd, taggedPt):
## Lean fnd from a mother
## get from the root to the foot
## precondition fnd is a found mother element
return parent_cycle_down(fnd.children, taggedPt.get_mother_element().children, 'nathans')
def get_tom(fnd, taggedPt):
## Learn a find from a mother
## get tom from the root to the froot
## precondition fnd is a found mother element
return parent_cycle_down(fnd.children, taggedPt.get_mother_element().children, 'toms')
def parent_cycle_down(fi, mi, atr):
## Loop accoss both found and mother iterators
## Precondition the 'atr' is an atribute of at least one elment in mi
for f, s in zip(fi, mi):
## look for attr
print('foundTrunk: ' + f.name + str(f.attrs) + ' motherTrunk: ' + s.name + str(s.attrs))
if atr in s.attrs:
if s[atr] == 0: ## Tag enclosing the pointer
## Return String inside, thats all!
return f.string
else:
return parent_cycle_down(f.children, s.children, atr)
tag_nathans(mothers[1])
tag_toms(mothers[1])
```
## Walking the Tree of a verified pointer
```
mother1 = mothers[1].get_mother_element()
mi = mother1.children
s = next(mi)
s
'nathans' in s.attrs
si = s.children
s = next(si)
s
s.string
mothers[0].get_mother_element
get_tom(mothers[1].get_mother_element(), mothers[0])
get_tom(mothers[0].get_mother_element(), mothers[1])
mothers[1].tom
mothers[0].tom
mothers[1].nathan
get_nathan(mothers[1].get_mother_element(), mothers[0])
mothers[0].nathan
get_nathan(mothers[0].get_mother_element(), mothers[1])
```
## Bring it all together
#### For all verified pointers tag the nathans and toms
#### Test each tagged verfied pointer against each found mother element to identifiy nathans and toms!
#### reunite the estranged family!
```
import pandas as pd
## For all verfied pointers tag the nathans and toms
for mother in mothers:
tag_nathans(mother)
tag_toms(mother)
tomSet = pd.DataFrame([{mother.tom:get_tom(find, mother) for mother in mothers} for find in finds])
nathanSet = pd.DataFrame([{mother.nathan:get_nathan(find, mother) for mother in mothers} for find in finds])
len(finds)
tomSet
nathanSet
```
| github_jupyter |
```
import pandas as pd
import numpy as np
from scipy.stats import trim_mean, kurtosis
from scipy.stats.mstats import mode, gmean, hmean
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline, FeatureUnion, Pipeline, make_union
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
credit_data = pd.read_csv('german_credit.csv')
```
In k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k − 1 subsamples are used as training data. The cross-validation process is then repeated k times, with each of the k subsamples used exactly once as the validation data. The k results can then be averaged to produce a single estimation. The advantage of this method over repeated random sub-sampling (see below) is that all observations are used for both training and validation, and each observation is used for validation exactly once. 10-fold cross-validation is commonly used, but in general k remains an unfixed parameter.
Source: https://en.wikipedia.org/wiki/Cross-validation_(statistics)#k-fold_cross-validation
```
lb_make = LabelEncoder()
credit_data2 = credit_data.copy()
credit_data2['AgeCat'] = pd.cut(credit_data2['Age (years)'], 4)
credit_data2['AgeCat'] = lb_make.fit_transform(credit_data2["AgeCat"].astype(str))
credit_data2['CredAmtCat'] = pd.cut(credit_data2['Credit Amount'],3)
credit_data2['CredAmtCat'] = lb_make.fit_transform(credit_data2["CredAmtCat"].astype(str))
credit_data2['CredDurCat'] = pd.cut(credit_data2['Duration of Credit (month)'],4)
credit_data2['CredDurCat'] = lb_make.fit_transform(credit_data2["CredDurCat"].astype(str))
credit_data2 = credit_data2.drop(["Age (years)", "Credit Amount", "Duration of Credit (month)"], axis=1)
credit_data2.describe()
X = credit_data2.loc[:, credit_data.columns != 'Creditability']
y = credit_data2["Creditability"]
X_train, X_validation, y_train, y_validation = train_test_split(X, y, test_size=1/3., random_state=42)
## function to select the columns
class ColumnSelector(BaseEstimator, TransformerMixin):
def __init__(self, columns):
self.columns = columns
def fit(self, X, y=None):
return self
def transform(self, X):
assert isinstance(X, pd.DataFrame)
try:
return X[self.columns]
except KeyError:
cols_error = list(set(self.columns) - set(X.columns))
raise KeyError("The DataFrame does not include the columns: %s" % cols_error)
pipeline = Pipeline(steps = [
("features", make_union(
ColumnSelector(list(X)),
)),
("model",RandomForestClassifier(random_state=42))
])
pipeline.fit(X_train, y_train)
pipeline.score(X_validation, y_validation)
print("RF Score before CV: %s" % pipeline.score(X_validation, y_validation))
# get list of hyperparameters
hyperparameters = { 'model__max_depth': [50, 70,90],
'model__min_samples_leaf': [1,2,3]
}
clf = GridSearchCV(pipeline, hyperparameters, cv=10)
clf.fit(X_train, y_train)
print("RF Score after CV: %s" % clf.score(X_validation, y_validation))
```
| github_jupyter |
# Consolidate DBpedia Person Data
In this notebook we consolidate person data from all editions into one file, by removing duplicates.
By [Eduardo Graells-Garrido](http://carnby.github.io).
```
from __future__ import print_function, unicode_literals
import gzip
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import dbpedia_config
sns.set_context('poster', font_scale=0.8)
%matplotlib inline
target_folder = dbpedia_config.TARGET_FOLDER
languages = dbpedia_config.LANGUAGES
filenames = ['{1}/person_data_{0}.csv.gz'.format(lang, target_folder) for lang in languages]
```
### Person DataFrame
We will create a single dataframe with all the editions.
```
all_bios = None
for lang, filename in zip(languages, filenames):
this_edition = pd.read_csv(filename, encoding='utf-8')
this_edition['language'] = lang
if all_bios is None:
all_bios = this_edition
else:
all_bios = pd.concat([all_bios, this_edition])
all_bios.language.value_counts()
def w_fraction(arr):
#print arr
return np.sum(arr == 'female') / float(len(arr))
col_labels = all_bios.groupby('language').aggregate(
{'edition_count': lambda x: len(x), 'gender': w_fraction, 'available_english': np.mean}
).sort('edition_count', ascending=False)
col_labels['female_median_count'] = [all_bios[(all_bios.language == idx)
& (all_bios.gender == 'female')].edition_count.median()
for idx in col_labels.index]
col_labels['male_median_count'] = [all_bios[(all_bios.language == idx)
& (all_bios.gender == 'male')].edition_count.median()
for idx in col_labels.index]
col_labels['female_mean_count'] = [all_bios[(all_bios.language == idx)
& (all_bios.gender == 'female')].edition_count.mean()
for idx in col_labels.index]
col_labels['male_mean_count'] = [all_bios[(all_bios.language == idx)
& (all_bios.gender == 'male')].edition_count.mean()
for idx in col_labels.index]
col_labels
```
### Consolidations
Let's remove duplicates and build a single dataset for all languages.
```
all_bios.drop_duplicates(subset=['same_as'], inplace=True)
all_bios.drop_duplicates(subset=['wikidata_entity'], inplace=True)
all_bios.drop_duplicates(subset=['label'], inplace=True)
all_bios.gender.value_counts()
all_bios = all_bios[all_bios.gender.isin(['male', 'female'])].copy()
print(all_bios.shape)
all_bios.gender.value_counts()
all_bios.sample(n=5)
with gzip.open('{0}/consolidated_person_data.csv.gz'.format(target_folder), 'wb') as f:
all_bios.to_csv(f, encoding='utf-8')
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Multi-worker training with Keras
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/distribute/multi_worker_with_keras.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/distribute/multi_worker_with_keras.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/distribute/multi_worker_with_keras.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Overview
This tutorial demonstrates multi-worker distributed training with Keras model using `tf.distribute.Strategy` API, specifically `tf.distribute.experimental.MultiWorkerMirroredStrategy`. With the help of this strategy, a Keras model that was designed to run on single-worker can seamlessly work on multiple workers with minimal code change.
[Distributed Training in TensorFlow](../../guide/distributed_training.ipynb) guide is available for an overview of the distribution strategies TensorFlow supports for those interested in a deeper understanding of `tf.distribute.Strategy` APIs.
## Setup
First, setup TensorFlow and the necessary imports.
```
!pip install tf-nightly
import tensorflow as tf
import numpy as np
```
## Preparing dataset
Now, let's prepare the MNIST dataset. The [MNIST dataset](http://yann.lecun.com/exdb/mnist/) comprises 60,000
training examples and 10,000 test examples of the handwritten digits 0–9,
formatted as 28x28-pixel monochrome images. In this example, we will take the training part of the datasets to demonstrate.
```
def mnist_dataset(batch_size):
(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()
# The `x` arrays are in uint8 and have values in the range [0, 255].
# We need to convert them to float32 with values in the range [0, 1]
x_train = x_train / np.float32(255)
y_train = y_train.astype(np.int64)
train_dataset = tf.data.Dataset.from_tensor_slices(
(x_train, y_train)).shuffle(60000).repeat().batch(batch_size)
return train_dataset
```
## Build the Keras model
Here we use `tf.keras.Sequential` API to build and compile a simple convolutional neural networks Keras model to train with our MNIST dataset.
Note: For a more comprehensive walkthrough of building Keras model, please see [TensorFlow Keras Guide](https://www.tensorflow.org/guide/keras#sequential_model).
```
def build_and_compile_cnn_model():
model = tf.keras.Sequential([
tf.keras.Input(shape=(28, 28)),
tf.keras.layers.Reshape(target_shape=(28, 28, 1)),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10)
])
model.compile(
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),
metrics=['accuracy'])
return model
```
Let's first try training the model for a small number of epochs and observe the results in single worker to make sure everything works correctly. You should expect to see the loss dropping and accuracy approaching 1.0 as epoch advances.
```
per_worker_batch_size = 64
single_worker_dataset = mnist_dataset(per_worker_batch_size)
single_worker_model = build_and_compile_cnn_model()
single_worker_model.fit(single_worker_dataset, epochs=3, steps_per_epoch=70)
```
## Multi-worker Configuration
Now let's enter the world of multi-worker training. In TensorFlow, `TF_CONFIG` environment variable is required for training on multiple machines, each of which possibly has a different role. `TF_CONFIG` is a JSON string used to specify the cluster configuration on each worker that is part of the cluster.
There are two components of `TF_CONFIG`: `cluster` and `task`. `cluster` provides information about the training cluster, which is a dict consisting of different types of jobs such as `worker`. In multi-worker training with `MultiWorkerMirroredStrategy`, there is usually one `worker` that takes on a little more responsibility like saving checkpoint and writing summary file for TensorBoard in addition to what a regular `worker` does. Such worker is referred to as the 'chief' worker, and it is customary that the `worker` with `index` 0 is appointed as the chief `worker` (in fact this is how `tf.distribute.Strategy` is implemented). `task` on the other hand provides information of the current task. The first component `cluster` is the same for all workers, and the second component `task` is different on each worker and specifies the `type` and `index` of that worker.
In this example, we set the task `type` to `"worker"` and the task `index` to `0`. This means the machine that has such setting is the first worker, which will be appointed as the chief worker and do more work than other workers. Note that other machines will need to have `TF_CONFIG` environment variable set as well, and it should have the same `cluster` dict, but different task `type` or task `index` depending on what the roles of those machines are.
For illustration purposes, this tutorial shows how one may set a `TF_CONFIG` with 2 workers on `localhost`. In practice, users would create multiple workers on external IP addresses/ports, and set `TF_CONFIG` on each worker appropriately.
Warning: Do not execute the following code in Colab. TensorFlow's runtime will attempt to create a gRPC server at the specified IP address and port, which will likely fail.
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"]
},
'task': {'type': 'worker', 'index': 0}
})
```
Note that while the learning rate is fixed in this example, in general it may be necessary to adjust the learning rate based on the global batch size.
## Choose the right strategy
In TensorFlow, distributed training consists of synchronous training, where the steps of training are synced across the workers and replicas, and asynchronous training, where the training steps are not strictly synced.
`MultiWorkerMirroredStrategy`, which is the recommended strategy for synchronous multi-worker training, will be demonstrated in this guide.
To train the model, use an instance of `tf.distribute.experimental.MultiWorkerMirroredStrategy`. `MultiWorkerMirroredStrategy` creates copies of all variables in the model's layers on each device across all workers. It uses `CollectiveOps`, a TensorFlow op for collective communication, to aggregate gradients and keep the variables in sync. The [`tf.distribute.Strategy` guide](../../guide/distributed_training.ipynb) has more details about this strategy.
```
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
```
Note: `TF_CONFIG` is parsed and TensorFlow's GRPC servers are started at the time `MultiWorkerMirroredStrategy()` is called, so `TF_CONFIG` environment variable must be set before a `tf.distribute.Strategy` instance is created.
`MultiWorkerMirroredStrategy` provides multiple implementations via the [`CollectiveCommunication`](https://github.com/tensorflow/tensorflow/blob/a385a286a930601211d78530734368ccb415bee4/tensorflow/python/distribute/cross_device_ops.py#L928) parameter. `RING` implements ring-based collectives using gRPC as the cross-host communication layer. `NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster.
## Train the model with MultiWorkerMirroredStrategy
With the integration of `tf.distribute.Strategy` API into `tf.keras`, the only change you will make to distribute the training to multi-worker is enclosing the model building and `model.compile()` call inside `strategy.scope()`. The distribution strategy's scope dictates how and where the variables are created, and in the case of `MultiWorkerMirroredStrategy`, the variables created are `MirroredVariable`s, and they are replicated on each of the workers.
Note: Currently there is a limitation in `MultiWorkerMirroredStrategy` where TensorFlow ops need to be created after the instance of strategy is created. If you see `RuntimeError: Collective ops must be configured at program startup`, try creating the instance of `MultiWorkerMirroredStrategy` at the beginning of the program and put the code that may create ops after the strategy is instantiated.
Note: In this Colab, the following code can run with expected result, but however this is effectively single-worker training since `TF_CONFIG` is not set. Once you set `TF_CONFIG` in your own example, you should expect speed-up with training on multiple machines.
Note: Always pass in `steps_per_epoch` argument to `model.fit()` since `MultiWorkerMirroredStrategy` does not support last partial batch handling. When using `steps_per_epoch`, `model.fit()` does not create a new iterator from the input every epoch, but continues from wherever the last epoch ended. Hence, make sure to call `.repeat()` on the dataset so it has an adequate number of examples for N epochs. If your dataset is not a repeated dataset, the `steps_per_epoch` should be set based on the amount of training data on each worker so that all workers would perform the same number of steps of training or evaluation, which is required by allreduce. In particular, if the sharding is not balanced, `steps_per_epoch` should be set to the size of the smallest sharded devided by the per-worker batch size.
```
num_workers = 4
# Here the batch size scales up by number of workers since
# `tf.data.Dataset.batch` expects the global batch size. Previously we used 64,
# and now this becomes 128.
global_batch_size = per_worker_batch_size * num_workers
multi_worker_dataset = mnist_dataset(global_batch_size)
with strategy.scope():
# Model building/compiling need to be within `strategy.scope()`.
multi_worker_model = build_and_compile_cnn_model()
# Keras' `model.fit()` trains the model with specified number of epochs and
# number of steps per epoch. Note that the numbers here are for demonstration
# purposes only and may not sufficiently produce a model with good quality.
multi_worker_model.fit(multi_worker_dataset, epochs=3, steps_per_epoch=70)
```
### Dataset sharding and batch size
In multi-worker training with `MultiWorkerMirroredStrategy`, sharding the dataset is needed to ensure convergence and performance. However, note that in above code snippet, the datasets are directly passed to `model.fit()` without needing to shard; this is because `tf.distribute.Strategy` API takes care of the dataset sharding automatically. It shards the dataset at the file level which may create skewed shards. In extreme cases where there is only one file, only the first shard (i.e. worker) will get training or evaluation data and as a result all workers will get errors.
If you prefer manual sharding for your training, automatic sharding can be turned off via `tf.data.experimental.DistributeOptions` api. Concretely,
```
options = tf.data.Options()
options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
dataset_no_auto_shard = multi_worker_dataset.with_options(options)
```
Another thing to notice is the batch size for the `datasets`. In the code snippet above, we use `global_batch_size = per_worker_batch_size * num_workers`, which is `num_workers` times as large as the case it was for single worker, because the effective per worker batch size is the global batch size (the parameter passed in `tf.data.Dataset.batch()`) divided by the number of workers, and with this change we are keeping the per worker batch size same as before.
### Evaluation
If you pass `validation_data` into `model.fit`, it will alternate between training and evaluation for each epoch. The evaluation taking `validation_data` is distributed across the same set of workers and the evaluation results are aggregated and available for all workers. Similar to training, the validation dataset is automatically sharded at the file level. You need to set a global batch size in the validation dataset and set `validation_steps`. A repeated dataset is also recommended for evaluation.
Alternatively, you can also create another task that periodically reads checkpoints and runs the evaluation. This is what Estimator does. But this is not a recommended way to perform evaluation and thus its details are omitted.
### Prediction
Currently `model.predict` doesn't work with `MultiWorkerMirroredStrategy.`
## Performance
You now have a Keras model that is all set up to run in multiple workers with `MultiWorkerMirroredStrategy`. You can try the following techniques to tweak performance of multi-worker training with `MultiWorkerMirroredStrategy`.
* `MultiWorkerMirroredStrategy` provides multiple [collective communication implementations](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/distribute/cross_device_ops.py). `RING` implements ring-based collectives using gRPC as the cross-host communication layer. `NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. To override the automatic choice, specify a valid value to the `communication` parameter of `MultiWorkerMirroredStrategy`'s constructor, e.g. `communication=tf.distribute.experimental.CollectiveCommunication.NCCL`.
* Cast the variables to `tf.float` if possible. The official ResNet model includes [an example](https://github.com/tensorflow/models/blob/8367cf6dabe11adf7628541706b660821f397dce/official/resnet/resnet_model.py#L466) of how this can be done.
## Fault tolerance
In synchronous training, the cluster would fail if one of the workers fails and no failure-recovery mechanism exists. Using Keras with `tf.distribute.Strategy` comes with the advantage of fault tolerance in cases where workers die or are otherwise unstable. We do this by preserving training state in the distributed file system of your choice, such that upon restart of the instance that previously failed or preempted, the training state is recovered.
Since all the workers are kept in sync in terms of training epochs and steps, other workers would need to wait for the failed or preempted worker to restart to continue.
Note:
Previously, the `ModelCheckpoint` callback provided a mechanism to restore training state upon restart from job failure for multi-worker training. We are introducing a new [`BackupAndRestore`](#scrollTo=kmH8uCUhfn4w) callback, to also add the support to single worker training for a consistent experience, and removed fault tolerance functionality from existing `ModelCheckpoint` callback. From now on, applications that rely on this behavior should migrate to the new callback.
### ModelCheckpoint callback
`ModelCheckpoint` callback no longer provides fault tolerance functionality, please use [`BackupAndRestore`](#scrollTo=kmH8uCUhfn4w) callback instead.
The `ModelCheckpoint` callback can still be used to save checkpoints. But with this, if training was interrupted or successfully finished, in order to continue training from the checkpoint, user is responsible to load the model manually.
Optionally user can choose to save and restore model/weights outside `ModelCheckpoint` callback.
#### Save/Restore outside `ModelCheckpoint` callback
You can save/restore your model using `model.save` or `tf.saved_model.save`, and `tf.keras.models.load_model`.
Or you can save/restore a checkpoint with `tf.train.Checkpoint`. And `restore` from the latest checkpoint in the model directory using `tf.train.latest_checkpoint`.
You will need to save the model/checkpoint to a temporary directory on the workers and to the provided directory on the chief. Each worker saves separately, so the temporary directories on the workers need to be unique to prevent errors resulting from multiple workers trying to write to the same location.
The model/checkpoint saved in all the directories are identical and typically only the one saved by the chief should be referenced for restoring or serving.
We recommend that you have some cleanup logic that deletes the temporary directories created by the workers once your training has completed.
For multi-worker training, the reason we need to save on the chief and workers is because we might be aggregating variables during checkpointing which requires the chief and workers to participate in the allreduce communication protocol. Letting chief and workers save to the same model directory will result in errors due to contention.
```
# Saving a model
# Let `is_chief` be a utility function that inspects the cluster spec and
# current task type and returns True if the worker is the chief and False
# otherwise.
def is_chief():
return True
if is_chief():
# This is the model directory will be ideally be a cloud bucket.
path = '/tmp/model_dir'
else:
# Save to a path that is unique across workers.
worker_id = 1
path = '/tmp/model_dir/worker_tmp_' + str(worker_id)
# checkpoint current model
checkpoint = tf.train.Checkpoint(model=multi_worker_model)
manager = tf.train.CheckpointManager(
checkpoint, directory=path, max_to_keep=5)
manager.save()
# Restoring a checkpoint
# On the Chief
checkpoint = tf.train.Checkpoint(model=multi_worker_model)
manager = tf.train.CheckpointManager(
checkpoint, directory=path, max_to_keep=5)
status = checkpoint.restore(manager.latest_checkpoint)
# On the Workers
# This is the path that the chief saves the model to
model_dir_path = '/tmp/model_dir'
checkpoint = tf.train.Checkpoint(model=multi_worker_model)
latest_checkpoint = tf.train.latest_checkpoint(model_dir_path)
status = checkpoint.restore(latest_checkpoint)
```
### BackupAndRestore callback
Note: `tf.keras.callbacks.experimental.BackupAndRestore` callback is only available in tf-nightly.
BackupAndRestore callback provides fault tolerance functionality, by backing up the model and current epoch number in a temporary checkpoint file under `backup_dir` argument to `BackupAndRestore`. This is done at the end of each epoch.
Once jobs get interrupted and restart, the callback restores the last checkpoint, and training continues from the beginning of the interrupted epoch. Any partial training already done in the unfinished epoch before interruption will be thrown away, so that it doesn't affect the final model state.
To use it, provide an instance of `tf.keras.callbacks.experimental.BackupAndRestore` at the `tf.keras.Model.fit()` call.
With MultiWorkerMirroredStrategy, if a worker gets interrupted, the whole cluster pauses until the interrupted worker is restarted. Other workers will also restart, and the interrupted worker rejoins the cluster. Then, every worker reads the checkpoint file that was previously saved and picks up its former state, thereby allowing the cluster to get back in sync. Then the training continues.
`BackupAndRestore` callback uses `CheckpointManager` to save and restore the training state, which generates a file called checkpoint that tracks existing checkpoints together with the latest one. For this reason, `backup_dir` should not be re-used to store other checkpoints in order to avoid name collision.
Currently, `BackupAndRestore` callback supports single worker with no strategy, MirroredStrategy, and multi-worker with MultiWorkerMirroredStrategy.
Below are two examples for both multi-worker training and single worker training.
```
# Multi-worker training with MultiWorkerMirroredStrategy.
callbacks = [tf.keras.callbacks.experimental.BackupAndRestore(backup_dir='/tmp/backup')]
with strategy.scope():
multi_worker_model = build_and_compile_cnn_model()
multi_worker_model.fit(multi_worker_dataset,
epochs=3,
steps_per_epoch=70,
callbacks=callbacks)
```
If you inspect the directory of `backup_dir` you specified in `BackupAndRestore`, you may notice some temporarily generated checkpoint files. Those files are needed for recovering the previously lost instances, and they will be removed by the library at the end of `tf.keras.Model.fit()` upon successful exiting of your training.
Note: Currently BackupAndRestore only supports eager mode. In graph mode, consider using [Save/Restore Model](#scrollTo=EUNV5Utc1d0s) mentioned above, and by providing `initial_epoch` in `model.fit()`.
## See also
1. [Distributed Training in TensorFlow](https://www.tensorflow.org/guide/distributed_training) guide provides an overview of the available distribution strategies.
2. [Official models](https://github.com/tensorflow/models/tree/master/official), many of which can be configured to run multiple distribution strategies.
3. The [Performance section](../../guide/function.ipynb) in the guide provides information about other strategies and [tools](../../guide/profiler.md) you can use to optimize the performance of your TensorFlow models.
| github_jupyter |
1. Classify ImageNEt and Dogs images by confidence intervals, remove low-quality images, remove MINDs
2. Generate explanations for COnf, GradCAM, SHAP, 3-NN
3. Generate samples images and intro images for Dogs and ImageNet
4. Generate visualizations for Gorilla Instructions
5. Generate validation image aggregations, class samples, ImageNEt/Dogs distribution for paper writing
```
%load_ext autoreload
%autoreload 2
import torch
import torchvision
from torchvision.models import *
from visualisation.core.utils import device, image_net_postprocessing, image_net_preprocessing
from torch import nn
from operator import itemgetter
from visualisation.core.utils import imshow
import xml.etree.ElementTree as ET
import random
import os
from torchvision import models
from shutil import copyfile, rmtree
import glob
import matplotlib.pyplot as plt
import numpy as np
from utils import *
from PIL import Image
from IPython.core.debugger import Tracer
plt.rcParams["figure.figsize"]= 16,8
from torchvision.transforms import ToTensor, Resize, Compose, ToPILImage
from visualisation.core import *
size= 224
# Pre-process the image and convert into a tensor
transform = torchvision.transforms.Compose([
torchvision.transforms.Resize(256),
torchvision.transforms.CenterCrop(224),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
def make_dir(path):
if os.path.isdir(path) == False:
os.mkdir(path)
# Added for loading ImageNet classes
def load_imagenet_label_map():
"""
Load ImageNet label dictionary.
return:
"""
input_f = open("input_txt_files/imagenet_classes.txt")
label_map = {}
for line in input_f:
parts = line.strip().split(": ")
(num, label) = (int(parts[0]), parts[1].replace('"', ""))
label_map[num] = label
input_f.close()
return label_map
# Added for loading ImageNet classes
def load_imagenet_id_map():
"""
Load ImageNet ID dictionary.
return;
"""
input_f = open("input_txt_files/synset_words.txt")
label_map = {}
for line in input_f:
parts = line.strip().split(" ")
(num, label) = (parts[0], ' '.join(parts[1:]))
label_map[num] = label
input_f.close()
return label_map
def load_imagenet_validation_gt():
count = 0
input_f = open("input_txt_files/ILSVRC2012_validation_ground_truth.txt")
gt_dict = {}
while True:
count += 1
# Get the next line
line = input_f.readline()
# if line is empty, EOL is reached
if not line:
break
gt_dict [count] = int(line.strip())
input_f.close()
return gt_dict
def convert_imagenet_label_to_id(label_map, key_list, val_list, prediction_class):
"""
Convert imagenet label to ID: for example - 245 -> "French bulldog" -> n02108915
:param label_map:
:param key_list:
:param val_list:
:param prediction_class:
:return:
"""
class_to_label = label_map[prediction_class]
prediction_id = key_list[val_list.index(class_to_label)]
return prediction_id
gt_dict = load_imagenet_validation_gt()
id_map = load_imagenet_id_map()
label_map = load_imagenet_label_map()
key_list = list(id_map.keys())
val_list = list(id_map.values())
print(key_list[200])
def convert_imagenet_id_to_label(key_list, class_id):
"""
Convert imagenet label to ID: for example - n02108915 -> "French bulldog" -> 245
:param label_map:
:param key_list:
:param val_list:
:param prediction_class:
:return:
"""
return key_list.index(str(class_id))
def load_imagenet_dog_label():
count = 0
dog_id_list = list()
input_f = open("input_txt_files/dog_type.txt")
for line in input_f:
dog_id = (line.split('-')[0])
dog_id_list.append(dog_id)
return dog_id_list
dogs_id = load_imagenet_dog_label()
############# Prepare images for all experiments
UPPER_THRESH = 0.8
LOWER_THRESH = 0.2
NAT_DATASET_TRAIN_INTERVAL = '/home/dexter/Downloads/Dataset/Interval_train_nat/'
DOG_DATASET_TRAIN_INTERVAL = '/home/dexter/Downloads/Dataset/Interval_train_dog/'
NAT_DATASET_INTERVAL = '/home/dexter/Downloads/Dataset/Interval_nat/'
DOG_DATASET_INTERVAL = '/home/dexter/Downloads/Dataset/Interval_dog/'
ADV_NAT_INTERVAL = '/home/dexter/Downloads/Dataset/Interval_adv_nat/'
ADV_DOG_INTERVAL = '/home/dexter/Downloads/Dataset/Interval_adv_dog/'
NAT_RESNET34_CORRECT = '/home/dexter/Downloads/Dataset/Natural_correct_resnet34/'
NAT_RESNET34_WRONG = '/home/dexter/Downloads/Dataset/Natural_wrong_resnet34/'
NAT_RESNET34_HARD = '/home/dexter/Downloads/Dataset/Natural_hard_images_resnet34/'
NAT_RESNET34_EASY = '/home/dexter/Downloads/Dataset/Natural_easy_images_resnet34/'
NAT_ADV_RESNET34 = '/home/dexter/Downloads/Dataset/Natural_Adv_images_resnet34/'
NAT_RESNET34_CORRECT_UPPER_THRESH = '/home/dexter/Downloads/Dataset/Natural_correct_resnet34_above_08/'
NAT_RESNET34_CORRECT_LOWER_THRESH = '/home/dexter/Downloads/Dataset/Natural_correct_resnet34_below_02/'
NAT_RESNET34_WRONG_UPPER_THRESH = '/home/dexter/Downloads/Dataset/Natural_wrong_resnet34_above_08/'
NAT_RESNET34_WRONG_LOWER_THRESH = '/home/dexter/Downloads/Dataset/Natural_wrong_resnet34_below_02/'
NAT_ATTACKED = '/home/dexter/Downloads/Dataset/Adv_nat_examples/'
NAT_ATTACKED_VERIFIED = '/home/dexter/Downloads/Dataset/Adv_nat_examples_verified/'
DOG_RESNET34_CORRECT = '/home/dexter/Downloads/Dataset/Dog_correct_resnet34/'
DOG_RESNET34_WRONG = '/home/dexter/Downloads/Dataset/Dog_wrong_resnet34/'
DOG_RESNET34_HARD = '/home/dexter/Downloads/Dataset/Dog_hard_images_resnet34/'
DOG_RESNET34_EASY = '/home/dexter/Downloads/Dataset/Dog_easy_images_resnet34/'
DOG_ADV_RESNET34 = '/home/dexter/Downloads/Dataset/Dog_Adv_images_resnet34/'
DOG_RESNET34_CORRECT_UPPER_THRESH = '/home/dexter/Downloads/Dataset/Dog_correct_resnet34_above_08/'
DOG_RESNET34_CORRECT_LOWER_THRESH = '/home/dexter/Downloads/Dataset/Dog_correct_resnet34_below_02/'
DOG_RESNET34_WRONG_UPPER_THRESH = '/home/dexter/Downloads/Dataset/Dog_wrong_resnet34_above_08/'
DOG_RESNET34_WRONG_LOWER_THRESH = '/home/dexter/Downloads/Dataset/Dog_wrong_resnet34_below_02/'
DOG_ATTACKED = '/home/dexter/Downloads/Dataset/Adv_dog_examples/'
DOG_ATTACKED_VERIFIED = '/home/dexter/Downloads/Dataset/Adv_dog_examples_verified/'
# Classify ImageNet and Dogs by confidence interval.Remove low-quality images, MIND samples
model = resnet34(pretrained=True).to(device)
model.eval()
from shutil import copyfile
dog_flag = True
imagenet_folders = glob.glob('/home/dexter/Downloads/train/*')
if dog_flag:
dataset_path = DOG_DATASET_TRAIN_INTERVAL
else:
dataset_path = NAT_DATASET_TRAIN_INTERVAL
make_dir(dataset_path)
correct = 0
wrong = 0
indomain_wrong = 0
for i, imagenet_folder in enumerate(imagenet_folders):
print(i)
imagenet_id = imagenet_folder.split('train/')[1]
if dog_flag:
if imagenet_id not in dogs_id:
continue
image_paths = glob.glob(imagenet_folder + '/*.*')
for idx, image_path in enumerate(image_paths):
if idx == 50:
break
img = Image.open(image_path)
if img.mode != 'RGB' or img.size[0] < 224 or img.size[1] < 224:
continue
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1)
confidence_score = score[0][0].item()
predicted_confidence = ("%.2f") %(confidence_score)
category_id = int(index[0][0].item())
prediction_id = convert_imagenet_label_to_id(label_map, key_list, val_list, category_id)
conf_interval = str(int(confidence_score*10))
if int(confidence_score*10) == 10:
conf_interval = str(9)
if prediction_id == imagenet_id:
correct +=1
if os.path.isdir(dataset_path + 'correct_' + conf_interval + '/') == False:
os.mkdir(dataset_path + 'correct_' + conf_interval + '/')
dst_file = dataset_path + 'correct_' + conf_interval + '/' + prediction_id + '_' + image_path.split(imagenet_id + '/')[1].split('.JPEG')[0] + '_' + imagenet_id + '.jpeg'
else:
wrong +=1
# Ensure the prediction is in dog ids
if dog_flag:
if prediction_id not in dogs_id:
continue
else:
indomain_wrong += 1
if os.path.isdir(dataset_path + 'wrong_' + conf_interval + '/') == False:
os.mkdir(dataset_path + 'wrong_' + conf_interval + '/')
dst_file = dataset_path + 'wrong_' + conf_interval + '/' + prediction_id + '_' + image_path.split(imagenet_id + '/')[1].split('.JPEG')[0] + '_' + imagenet_id + '.jpeg'
copyfile(image_path, dst_file)
print([correct, wrong])
print(indomain_wrong)
# Generate Confidence explanations
import cv2 as cv
method = 'Conf'
# test_image_paths = corrects_bin1[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# wrongs_bin1[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# corrects_bin2[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# wrongs_bin2[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# corrects_bin3[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# wrongs_bin3[methods.index(method)*img_num:methods.index(method)*img_num + img_num]
# test_image_paths = ['/home/dexter/Downloads/Dataset/Interval_train_nat/correct_0/n03250847_n03250847_8348_n03250847.jpeg']
test_image_paths = glob.glob('/home/dexter/Downloads/Human_experiments/Training/*.*')
# Tracer()()
# for idx, image_path in enumerate(test_image_paths[methods.index(method)*img_num:methods.index(method)*img_num + img_num]):
for idx, image_path in enumerate(test_image_paths):
print(idx + 1)
distance_dict = dict()
neighbors = list()
categories_confidences = list()
confidences= list ()
img = Image.open(image_path)
input_image = img.resize((size,size), Image.ANTIALIAS)
image_name = (image_path.split('.jpeg')[0]).split('Training/')[1]
print(image_name)
# Get the ground truth of the input image
gt_label_id = image_path[-14:-5]
gt_label = id_map.get(gt_label_id)
id = key_list.index(gt_label_id)
gt_label = gt_label.split(',')[0]
# Get the prediction for the input image
img = Image.open(image_path)
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1)
input_category_id = index[0][0].item()
predicted_confidence = score[0][0].item()
predicted_confidence = ("%.2f") %(predicted_confidence)
# print(predicted_confidence)
input_prediction_id = convert_imagenet_label_to_id(label_map, key_list, val_list, input_category_id)
predicted_label = id_map.get(input_prediction_id).split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
# Original image
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}% {}'.format(int(float(predicted_confidence)*100), predicted_label))
plt.imshow(input_image)
# plt.imshow(modified_img[idx])
plt.savefig('tmp/original.jpeg', bbox_inches='tight')
plt.close()
img = cv.resize(cv.imread(image_path,0),((size,size)))
edges = cv.Canny(img,100,200)
edges = edges - 255
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.imshow(edges, cmap = 'gray')
plt.savefig('tmp/Edge.jpeg', bbox_inches='tight')
plt.close()
# Confidence score only
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}: {}'.format(predicted_label, predicted_confidence))
plt.imshow(input_image)
plt.savefig('/home/dexter/Downloads/Human_experiments/Training/{}/{}.jpeg'.format(method, image_name), bbox_inches='tight', dpi=300)
plt.close()
# Generate GradCAM explanations
from torchray.attribution.grad_cam import grad_cam
method = 'GradCAM'
## Creating colormap
from matplotlib import cm
from matplotlib.colors import ListedColormap
uP = cm.get_cmap('Reds', 129)
dowN = cm.get_cmap('Blues_r', 128)
newcolors = np.vstack((
dowN(np.linspace(0, 1, 128)),
uP(np.linspace(0, 1, 129))
))
cMap = ListedColormap(newcolors, name='RedBlues')
cMap.colors[257 // 2, :] = [1, 1, 1, 1]
test_image_paths = glob.glob('/home/dexter/Downloads/Human_experiments/Training/*.*')
# for idx, image_path in enumerate(test_image_paths[methods.index(method)*img_num:methods.index(method)*img_num + img_num]):
for idx, image_path in enumerate(test_image_paths):
print(idx + 1)
distance_dict = dict()
neighbors = list()
categories_confidences = list()
confidences= list ()
img = Image.open(image_path)
# print(test_image_paths[idx])
input_image = img.resize((size,size), Image.ANTIALIAS)
image_name = (image_path.split('.jpeg')[0]).split('Training/')[1]
print(image_name)
# Get the ground truth of the input image
gt_label_id = image_path[-14:-5]
gt_label = id_map.get(gt_label_id)
id = key_list.index(gt_label_id)
gt_label = gt_label.split(',')[0]
# Get the prediction for the input image
img = Image.open(image_path)
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1)
input_category_id = index[0][0].item()
predicted_confidence = score[0][0].item()
predicted_confidence = ("%.2f") %(predicted_confidence)
# print(predicted_confidence)
input_prediction_id = convert_imagenet_label_to_id(label_map, key_list, val_list, input_category_id)
predicted_label = id_map.get(input_prediction_id).split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
# Original image
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}% {}'.format(int(float(predicted_confidence)*100), predicted_label))
plt.imshow(input_image)
# plt.imshow(modified_img[idx])
plt.savefig('tmp/original.jpeg', bbox_inches='tight')
plt.close()
img = cv.resize(cv.imread(image_path,0),((size,size)))
edges = cv.Canny(img,100,200)
edges = edges - 255
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.imshow(edges, cmap = 'gray')
plt.savefig('tmp/Edge.jpeg', bbox_inches='tight')
plt.close()
# GRAD-CAM
saliency = grad_cam(
model, x, input_category_id,
saliency_layer='layer4',
resize=True
)
saliency_path = 'saliency_maps/GradCAM_resnet34/'
saliency *= 1.0/saliency.max()
GradCAM = saliency[0][0].cpu().detach().numpy()
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('Explanation')
plt.imshow(GradCAM, cmap=cMap, vmin=0, vmax=1)
plt.colorbar(orientation='vertical')
plt.savefig('tmp/heatmap.jpeg', bbox_inches='tight')
plt.close()
# Get overlay version
myCmd = 'composite -blend 10 Edge.jpeg -gravity SouthWest heatmap.jpeg overlay.jpeg'
os.system(myCmd)
img_path = '/home/dexter/Downloads/Human_experiments/Training/{}/{}.jpeg'.format(method, image_name)
myCmd = 'montage original.jpeg overlay.jpeg -tile 2x1 -geometry +0+0 ' + img_path
print(myCmd)
os.system(myCmd)
# Generate SHAP explanations
import shap
import json
##########################################
bg_image_paths = glob.glob('/home/dexter/Downloads/Dataset/bg/*.*')
bg_inputs = list(map(lambda x: Image.open(x), bg_image_paths))
bg_inputs = [transform(x).unsqueeze(0) for x in bg_inputs]
bg_inputs = [i.to(device) for i in bg_inputs]
background = torch.cat(bg_inputs[:100])
background = background.detach()
e = shap.DeepExplainer(model, background)
# load the ImageNet class names
url = "https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json"
fname = shap.datasets.cache(url)
with open(fname) as f:
class_names = json.load(f)
method = 'SHAP'
# SHAP
# for idx, image_path in enumerate(test_image_paths[methods.index(method)*img_num:methods.index(method)*img_num + img_num]):
for idx, image_path in enumerate(test_image_paths):
print(idx + 1)
distance_dict = dict()
neighbors = list()
categories_confidences = list()
confidences= list ()
img = Image.open(image_path)
# print(test_image_paths[idx])
input_image = img.resize((size,size), Image.ANTIALIAS)
image_name = (image_path.split('.jpeg')[0]).split('Training/')[1]
print(image_name)
gt_label_id = image_path[-14:-5]
gt_label = id_map.get(gt_label_id)
id = key_list.index(gt_label_id)
gt_label = gt_label.split(',')[0]
# Get the prediction for the input image
img = Image.open(image_path)
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1)
input_category_id = index[0][0].item()
predicted_confidence = score[0][0].item()
predicted_confidence = ("%.2f") %(predicted_confidence)
# print(predicted_confidence)
input_prediction_id = convert_imagenet_label_to_id(label_map, key_list, val_list, input_category_id)
predicted_label = id_map.get(input_prediction_id).split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
# Original image
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}% {}'.format(int(float(predicted_confidence)*100), predicted_label))
plt.imshow(input_image)
# plt.imshow(modified_img[idx])
plt.savefig('tmp/original.jpeg', bbox_inches='tight')
plt.close()
img = cv.resize(cv.imread(image_path,0),((size,size)))
edges = cv.Canny(img,100,200)
edges = edges - 255
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.imshow(edges, cmap = 'gray')
plt.savefig('tmp/Edge.jpeg', bbox_inches='tight')
plt.close()
test_images = Image.open(image_path)
test_images = [transform(test_images).unsqueeze(0)]
test_images = [i.to(device) for i in test_images]
test_images_t = torch.cat(test_images)
shap_values = e.shap_values(test_images_t, ranked_outputs=1, output_rank_order='max') # 2xranked_outputsx1x3x224x224
square_img = np.sum(shap_values[0][0][0], axis=0)
min_val = square_img.min()
max_val = square_img.max()
if (-1*min_val) > max_val:
max_val = -1.0*min_val
square_img *= 1.0/max_val
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('Explanation')
plt.imshow(square_img, cmap=cMap, vmin=0, vmax=1)
plt.colorbar(orientation='vertical')
plt.savefig('tmp/heatmap.jpeg', bbox_inches='tight')
plt.close()
# Get overlay version
myCmd = 'composite -blend 10 tmp/Edge.jpeg -gravity SouthWest tmp/heatmap.jpeg tmp/overlay.jpeg'
os.system(myCmd)
img_path = '/home/dexter/Downloads/Human_experiments/Training/{}/{}.jpeg'.format(method, image_name)
myCmd = 'montage tmp/original.jpeg tmp/overlay.jpeg -tile 2x1 -geometry +0+0 ' + img_path
os.system(myCmd)
# Generate 3-NN explanations
imagenet_train_path = '/home/dexter/Downloads/train'
K = 3
layer = 4
feature_extractor = nn.Sequential(*list(model.children())[:layer-6])
method = 'NNs'
# NNs
test_image_paths = glob.glob('/home/dexter/Downloads/Human_experiments/Training/*.*')
# for idx, image_path in enumerate(test_image_paths[methods.index(method)*img_num:methods.index(method)*img_num + img_num]):
for idx, image_path in enumerate(test_image_paths):
print(idx + 1)
distance_dict = dict()
neighbors = list()
categories_confidences = list()
confidences= list ()
img = Image.open(image_path)
if 1:
embedding = feature_extractor(transform(img).unsqueeze(0).to(device)).flatten(start_dim=1)
# print(test_image_paths[idx])
input_image = img.resize((size,size), Image.ANTIALIAS)
image_name = (image_path.split('.jpeg')[0]).split('Training/')[1]
print(image_name)
# Get the ground truth of the input image
gt_label_id = image_path[-14:-5]
gt_label = id_map.get(gt_label_id)
id = key_list.index(gt_label_id)
gt_label = gt_label.split(',')[0]
# Get the prediction for the input image
img = Image.open(image_path)
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1)
input_category_id = index[0][0].item()
predicted_confidence = score[0][0].item()
predicted_confidence = ("%.2f") %(predicted_confidence)
input_prediction_id = convert_imagenet_label_to_id(label_map, key_list, val_list, input_category_id)
predicted_label = id_map.get(input_prediction_id).split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
# Original image
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}% {}'.format(int(float(predicted_confidence)*100), predicted_label))
plt.imshow(input_image)
# plt.imshow(modified_img[idx])
plt.savefig('tmp/original.jpeg', bbox_inches='tight')
plt.close()
img = cv.resize(cv.imread(image_path,0),((size,size)))
edges = cv.Canny(img,100,200)
edges = edges - 255
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.imshow(edges, cmap = 'gray')
plt.savefig('tmp/Edge.jpeg', bbox_inches='tight')
plt.close()
if 1:
from utils import *
## Nearest Neighbors
predicted_set_path = os.path.join(imagenet_train_path, input_prediction_id)
predicted_set_img_paths = glob.glob(predicted_set_path + '/*.*')
predicted_set_color_images= list()
embedding = embedding.detach()
embedding.to(device)
# Build search space for nearest neighbors
for i, path in enumerate(predicted_set_img_paths):
img = Image.open(path)
if img.mode != 'RGB':
img.close()
del img
continue
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
del out
score, index = torch.topk(p, 1)
del p
category_id = index[0][0].item()
del score, index
# This is to avoid the confusion from crane 134 and crane 517 and to make NNs work :)
if input_category_id != category_id:
continue
f = feature_extractor(x)
feature_vector = f.flatten(start_dim=1).to(device)
feature_vector = feature_vector.detach()
del f
distance_dict[path] = torch.dist(embedding, feature_vector)
del feature_vector
torch.cuda.empty_cache()
img.close()
del img
predicted_set_color_images.append(path)
# Get K most similar images
res = dict(sorted(distance_dict.items(), key = itemgetter(1))[:K])
print("Before...")
print(res)
while distance_dict[list(res.keys())[0]] < 100:
del distance_dict[list(res.keys())[0]]
res = dict(sorted(distance_dict.items(), key = itemgetter(1))[:K])
print("After...")
print(res)
# del distance_dict
del embedding
similar_images = list(res.keys())
# print(similar_images)
# print([distance_dict[x] for x in similar_images])
for similar_image in similar_images:
img = Image.open(similar_image)
neighbors.append(img.resize((size,size), Image.ANTIALIAS))
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1) # Get 1 most probable classes
category_id = index[0][0].item()
confidence = score[0][0].item()
label = label_map.get(category_id).split(',')[0].replace("\"", "")
label = label[0].lower() + label[1:]
print(label + ": %.2f" %(confidence))
categories_confidences.append((label + ": %.2f" %(confidence)))
confidences.append(confidence)
img.close()
img_path = '/home/dexter/Downloads/Human_experiments/Training/{}/{}.jpeg'.format(method, image_name)
print(img_path)
for index, neighbor in enumerate(neighbors):
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title(' ')
plt.imshow(neighbor)
plt.savefig('tmp/{}.jpeg'.format(index), bbox_inches='tight')
plt.close()
myCmd = 'montage tmp/[0-2].jpeg -tile x1 -geometry +0+0 ' + 'tmp/aggregate.jpeg'
os.system(myCmd)
myCmd = 'montage tmp/original.jpeg ' + 'tmp/aggregate.jpeg' + ' -tile 2x -geometry +20+0 ' + img_path
os.system(myCmd)
# Generate intro images for dog/ImageNet image classification
from shutil import copyfile
imagenet_folders = glob.glob('/home/dexter/Downloads/train/*')
cnt = 0
correct = 0
wrong = 0
cmd = 'montage '
SPACE = ' '
for idx, imagenet_folder in enumerate(imagenet_folders):
if cnt == 50:
break
imagenet_id = imagenet_folder.split('train/')[1]
if imagenet_id not in dogs_id:
continue
cnt += 1
print(imagenet_id)
image_paths = glob.glob(imagenet_folder + '/*.*')
print(image_paths[0])
predicted_label = id_map[imagenet_id].split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
predicted_label = predicted_label.replace(' ','_')
print(predicted_label)
cmd += SPACE + '-label' + SPACE + predicted_label + SPACE + image_paths[1]
cmd += SPACE + '-tile 10x5 -title \'120 breeds\' tmp/dog_image_classification.jpeg'
os.system(cmd)
# Generate sample images for dog/ImageNet classes
from shutil import copyfile
imagenet_folders = glob.glob('/home/dexter/Downloads/train/*')
samples_folder = 'dog_sample_images/'
SPACE = ' '
import cv2
for idx, imagenet_folder in enumerate(imagenet_folders):
print(idx)
imagenet_id = imagenet_folder.split('train/')[1]
if imagenet_id not in dogs_id:
continue
image_paths = glob.glob(imagenet_folder + '/*.*')
random_image_paths = random.sample(list(image_paths), 3)
while cv2.imread(random_image_paths[0]).shape[0] < 320 or cv2.imread(random_image_paths[1]).shape[0] < 320 or cv2.imread(random_image_paths[2]).shape[0] < 320 or \
cv2.imread(random_image_paths[0]).shape[1] < 240 or cv2.imread(random_image_paths[1]).shape[1] < 240 or cv2.imread(random_image_paths[2]).shape[1] < 240:
random_image_paths = random.sample(list(image_paths), 3)
predicted_label = id_map[imagenet_id].split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
predicted_label = predicted_label.replace(' ','_')
cmd = 'montage -mode concatenate' + SPACE + random_image_paths[0] + SPACE + random_image_paths[1] + SPACE + random_image_paths[2] + \
SPACE + '-resize 320x240 -pointsize 8 -geometry +2+30' + SPACE + samples_folder + \
imagenet_id + '.jpeg'
os.system(cmd)
# Generate visualizations for instructions
import cv2 as cv
method = 'Conf'
# test_image_paths = corrects_bin1[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# wrongs_bin1[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# corrects_bin2[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# wrongs_bin2[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# corrects_bin3[methods.index(method)*img_num:methods.index(method)*img_num + img_num] + \
# wrongs_bin3[methods.index(method)*img_num:methods.index(method)*img_num + img_num]
# test_image_paths = ['/home/dexter/Downloads/Dataset/Interval_train_nat/correct_0/n03250847_n03250847_8348_n03250847.jpeg']
test_image_paths = glob.glob('/home/dexter/Downloads/Human_experiments/Dog/Instructions/Inputs/*.*')
# for idx, image_path in enumerate(test_image_paths[methods.index(method)*img_num:methods.index(method)*img_num + img_num]):
for idx, image_path in enumerate(test_image_paths):
print(idx + 1)
distance_dict = dict()
neighbors = list()
categories_confidences = list()
confidences= list ()
img = Image.open(image_path)
input_image = img.resize((size,size), Image.ANTIALIAS)
image_name = (image_path.split('.jpeg')[0]).split('Inputs/')[1]
print(image_name)
# Get the prediction for the input image
img = Image.open(image_path)
x = transform(img).unsqueeze(0).to(device)
out = model(x)
p = torch.nn.functional.softmax(out, dim=1)
score, index = torch.topk(p, 1)
input_category_id = index[0][0].item()
predicted_confidence = score[0][0].item()
predicted_confidence = ("%.2f") %(predicted_confidence)
input_prediction_id = convert_imagenet_label_to_id(label_map, key_list, val_list, input_category_id)
predicted_label = id_map.get(input_prediction_id).split(',')[0]
predicted_label = predicted_label[0].lower() + predicted_label[1:]
# Original image
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}: {}'.format(predicted_label, predicted_confidence))
plt.imshow(input_image)
# plt.imshow(modified_img[idx])
plt.savefig('tmp/original.jpeg', bbox_inches='tight')
plt.close()
img = cv.resize(cv.imread(image_path,0),((size,size)))
edges = cv.Canny(img,100,200)
edges = edges - 255
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.imshow(edges, cmap = 'gray')
plt.savefig('tmp/Edge.jpeg', bbox_inches='tight')
plt.close()
# Confidence score only
fig = plt.figure()
plt.figure(figsize=(6.0,4.5), dpi=300)
plt.axis('off')
plt.title('{}% {}'.format(int(float(predicted_confidence)*100), predicted_label))
plt.imshow(input_image)
plt.savefig('/home/dexter/Downloads/Human_experiments/Dog/Instructions/{}/{}.jpeg'.format(method, image_name), bbox_inches='tight', dpi=300)
plt.close()
# Generate validation image aggregation for paper writing
path = '/home/dexter/Downloads/Human_experiments/Stimuli_Natural/Validation/Inputs/'
correct_path = path + 'Yes/'
wrong_path = path + 'No/'
cmd = 'convert {}/*.jpeg -resize 600x600\! tmp/yes.jpeg'.format(correct_path)
os.system(cmd)
cmd = 'convert {}/*.jpeg -resize 600x600\! tmp/no.jpeg'.format(wrong_path)
os.system(cmd)
correct_labels = ['goldfish', 'hen', 'ostrich', 'balloon', 'hay']
wrong_labels = ['african grey', 'hornbill', 'band aid', 'bannister', 'flute']
gt_for_wrong_labels = ['dial telephone', 'banana', 'rule', 'cornet', 'hand blower']
for idx, label in enumerate(correct_labels):
cmd = 'convert tmp/yes-{}.jpeg -fill green -pointsize 56 -gravity North -background White -splice 0x64 -annotate +0+4 "{}" tmp/yes-{}.jpeg'.format(idx, label, idx)
os.system(cmd)
for idx, label in enumerate(wrong_labels):
cmd = 'convert tmp/no-{}.jpeg -fill red -pointsize 56 -gravity North -background White -splice 0x64 -annotate +0+4 "{}" tmp/no-{}.jpeg'.format(idx, label, idx)
os.system(cmd)
cmd = 'convert tmp/no-{}.jpeg -fill green -pointsize 56 -gravity North -background White -splice 0x64 -annotate +0+4 "{}" tmp/no-{}.jpeg'.format(idx, gt_for_wrong_labels[idx], idx)
os.system(cmd)
cmd = 'montage tmp/yes-[0-4].jpeg tmp/no-[0-4].jpeg -tile 5x2 -geometry 448x448+10+10 tmp/nat.jpeg'
os.system(cmd)
# Generate validation image aggregation for paper writing
path = '/home/dexter/Downloads/Human_experiments/Stimuli_Dog/Validation/Inputs/'
correct_path = path + 'Yes/'
wrong_path = path + 'No/'
cmd = 'convert {}/*.jpeg -resize 600x600\! tmp/yes.jpeg'.format(correct_path)
os.system(cmd)
cmd = 'convert {}/*.jpeg -resize 600x600\! tmp/no.jpeg'.format(wrong_path)
os.system(cmd)
correct_labels = ['japanese spaniel', 'rhodesian ridgeback', 'basset', 'irish wolfhound', 'african hunting dog']
wrong_labels = ['toy terrier', 'walker hound', 'italian greyhound', 'saluki', 'west highland white terrier']
gt_for_wrong_labels = ['welsh springer spaniel', 'basset', 'french bulldog', 'cardigan', 'siberian husky']
for idx, label in enumerate(correct_labels):
cmd = 'convert tmp/yes-{}.jpeg -fill green -pointsize 56 -gravity North -background White -splice 0x64 -annotate +0+4 "{}" tmp/yes-{}.jpeg'.format(idx, label, idx)
os.system(cmd)
for idx, label in enumerate(wrong_labels):
cmd = 'convert tmp/no-{}.jpeg -fill red -pointsize 56 -gravity North -background White -splice 0x64 -annotate +0+4 "{}" tmp/no-{}.jpeg'.format(idx, label, idx)
os.system(cmd)
cmd = 'convert tmp/no-{}.jpeg -fill green -pointsize 56 -gravity North -background White -splice 0x64 -annotate +0+4 "{}" tmp/no-{}.jpeg'.format(idx, gt_for_wrong_labels[idx], idx)
os.system(cmd)
cmd = 'montage tmp/yes-[0-4].jpeg tmp/no-[0-4].jpeg -tile 5x2 -geometry 448x448+10+10 tmp/dog.jpeg'
os.system(cmd)
# Visualize MIND samples
imgs = ['/home/dexter/Downloads/Dataset/Dog_wrong_resnet34/ILSVRC2012_val_00013611_n02099601.jpeg',
'/home/dexter/Downloads/Dataset/Dog_wrong_resnet34/ILSVRC2012_val_00024756_n02097298.jpeg',
'/home/dexter/Downloads/Dataset/Dog_wrong_resnet34/ILSVRC2012_val_00005351_n02106550.jpeg',
'/home/dexter/Downloads/Dataset/Dog_wrong_resnet34/ILSVRC2012_val_00001137_n02091244.jpeg']
wrong_labels = ['soccer ball', 'teddy', 'tennis ball', 'punching bag']
gt_for_wrong_labels = ['golden retriever', 'scotch terrier', 'rottweiler', 'ibizan hound']
for idx, img in enumerate(imgs):
cmd = 'convert {} -resize 600x600\! tmp/mind.jpeg'.format(img)
os.system(cmd)
cmd = 'convert tmp/mind.jpeg -fill red -pointsize 28 -gravity North -background White -splice 0x32 -annotate +0+4 "{}" mind.jpeg'.format(wrong_labels[idx])
os.system(cmd)
cmd = 'convert tmp/mind.jpeg -fill green -pointsize 28 -gravity North -background White -splice 0x32 -annotate +0+4 "{}" {}.jpeg'.format(gt_for_wrong_labels[idx], idx)
os.system(cmd)
# cmd = 'montage [0-4].jpeg -tile 4x1 -geometry 448x448+10+10 minds.jpeg'
# os.system(cmd)
# Visualize class samples
imgs = ['n02085620.jpeg',
'n02130308.jpeg',
'n03786901.jpeg',
'n04591157.jpeg',
'n07747607.jpeg']
labels = ['chihuahua', 'cheetah', 'mortar', 'windsor tie', 'orange']
definitions = ['an old breed of tiny short-haired dog with protruding eyes from Mexico held to antedate Aztec civilization',
'long-legged spotted cat of Africa and southwestern Asia having nonretractile claws',
'a bowl-shaped vessel in which substances can be ground and mixed with a pestle',
'a wide necktie worn in a loose bow',
'round yellow to orange fruit of any of several citrus trees']
for idx, img in enumerate(imgs):
cmd = 'convert sample_images/{} -resize 1400x600\! tmp/sample.jpeg'.format(img)
os.system(cmd)
cmd = 'convert -font Times-New-Roman tmp/sample.jpeg -pointsize 24 -gravity North -background White -splice 0x32 -annotate +0+4 "{}: {}" {}'.format(labels[idx], definitions[idx], imgs[idx])
os.system(cmd)
# Visualize image distribution of ImageNEt and Dogs
exp = 'ImageNet'
conf_int = [0,1,2,3,4,5,6,7,8,9]
imagenet_img_num = [199, 1250, 2171, 2641, 3049, 3599, 3412, 3627, 4748, 23507]
dog_img_num = [3, 57, 136, 232, 409, 507, 514, 526, 736, 2690]
img_num_percent = []
if exp == 'Stanford Dogs':
img_num = dog_img_num
else:
img_num = imagenet_img_num
for value in img_num:
img_num_percent.append(value/sum(img_num))
ax = plt.figure().gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
plt.bar(conf_int, img_num, width=1, align='edge', color='b', ec='black')
for index, value in enumerate(img_num):
plt.annotate(str(value), xy=(index, value), ha='left', va='bottom')
plt.title('{} image distribution by confidence intervals'.format(exp))
plt.ylabel('Numb. of images')
plt.xlabel('Confidence')
plt.savefig('tmp/{}.jpeg'.format(exp), dpi=300, format='jpeg', bbox_inches='tight')
plt.show()
import matplotlib.pyplot as plt
labels = ['ImageNet', 'Stanford Dogs']
# ImageNet = [16.67, 16.67, 16.66, 16.67, 16.67, 16.66]
# Stanford_Dogs = [16.67, 16.67, 16.66, 16.67, 16.67, 16.66]
easy_correct = [16.67, 16.67]
medium_correct = [16.67, 16.67]
hard_correct = [16.66, 16.66]
easy_wrong = [16.67, 16.67]
medium_wrong = [16.67, 16.67]
hard_wrong = [16.66, 16.66]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
ax.bar(labels, easy_correct, width, label='Easy Correct')
ax.bar(labels, medium_correct, width, bottom=medium_correct, label='Medium Correct')
ax.bar(labels, hard_correct, width, bottom=hard_correct, label='Hard Correct')
ax.set_ylabel('Percentage')
ax.set_title('Experiments')
ax.legend()
plt.show()
%matplotlib inline
import pandas as pd
df = pd.DataFrame({
'Easy Correct': [16.67, 16.67, 16.67],
'Medium Correct': [16.67, 16.67, 16.67],
'Hard Correct': [16.66, 16.67, 16.67],
'Easy Wrong': [16.67, 16.67, 16.67],
'Medium Wrong': [16.67, 16.67, 16.67],
'Hard Wrong': [16.66, 16.67, 16.67]})
# Save the chart that's drawn
ax = df.plot(stacked=True, kind='barh', figsize=(10, 5))
# .patches is everything inside of the chart, lines and
# rectangles and circles and stuff. In this case we only
# have rectangles!
for rect in ax.patches:
# Find where everything is located
height = rect.get_height()
width = rect.get_width()
x = rect.get_x()
y = rect.get_y()
# The width of the bar is also not pixels, it's the
# number of animals. So we can use it as the label!
label_text = width
# ax.text(x, y, text)
label_x = x + width / 2
label_y = y + height / 2
print(label_text)
ax.text(label_x, label_y, label_text, ha='center', va='center')
import numpy as np
import matplotlib.pyplot as plt
# font = {'family' : 'serif',
# 'weight' : 'bold',
# 'size' : 12}
font = {'weight' : 'bold',
'size' : 12}
plt.rc('font', **font)
category_names = ['Easy Correct', 'Medium Correct', 'Hard Correct', 'Easy Wrong', 'Medium Wrong', 'Hard Wrong']
# results = {
# 'Question 1': [10, 15, 17, 32, 26],
# 'Question 2': [26, 22, 29, 10, 13],
# 'Question 3': [35, 37, 7, 2, 19],
# 'Question 4': [32, 11, 9, 15, 33],
# 'Question 5': [21, 29, 5, 5, 40],
# 'Question 6': [8, 19, 5, 30, 38]
# }
results = {
'Controlled ImageNet': [16.67, 16.67, 16.66, 16.67, 16.67, 16.66],
'Controlled Stanford Dogs': [16.67, 16.67, 16.66, 16.67, 16.67, 16.66],
'Original ImageNet': [67.77, 7.91, 1.97, 7.42, 9.35, 5.53],
'Original Stanford Dogs': [70.93, 10.45, 1.12, 3.20, 9.74, 4.56],
}
def survey(results, category_names):
"""
Parameters
----------
results : dict
A mapping from question labels to a list of answers per category.
It is assumed all lists contain the same number of entries and that
it matches the length of *category_names*.
category_names : list of str
The category labels.
"""
labels = list(results.keys())
data = np.array(list(results.values()))
data_cum = data.cumsum(axis=1)
category_colors = plt.get_cmap('tab10')(
np.linspace(0.15, 0.85, data.shape[1]))
fig, ax = plt.subplots(figsize=(24, 12))
ax.invert_yaxis()
ax.xaxis.set_visible(False)
ax.set_xlim(0, np.sum(data, axis=1).max())
for i, (colname, color) in enumerate(zip(category_names, category_colors)):
widths = data[:, i]
starts = data_cum[:, i] - widths
ax.barh(labels, widths, left=starts, height=0.8,
label=colname, color=color)
print(colname)
print(labels)
xcenters = starts + widths / 2
for tick in ax.get_yticklabels():
tick.set_fontsize('x-large')
r, g, b, _ = color
text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
for y, (x, c) in enumerate(zip(xcenters, widths)):
ax.text(x, y, str((c)), ha='center', va='center',
color=text_color, fontsize='12', weight='bold', family='serif')
# color=text_color, fontsize='medium')
ax.legend()
ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1),
loc='lower left', fontsize='x-large')
return fig, ax
survey(results, category_names)
plt.savefig('tmp/distribution_plot1.jpeg',dpi=400, format='jpeg', bbox_inches='tight')
plt.show()
# Importing the matplotlib library
import numpy as np
import matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)
import matplotlib
font = {'weight' : 'bold',
'size' : 12}
plt.rc('font', **font)
# matplotlib.rcParams.update(matplotlib.rcParamsDefault)
plt.figure(figsize=[20, 10])# Data to be plotted
Natural_ImageNet_acc = [80.79, 84.79, 88.77, 87.97, 86.95, 88.23]
Natural_Dogs_acc = [81.14, 76.45, 79.78, 76.03, 75.05, 82.88]
Adversarial_ImageNet_acc = [0.0, 71.00, 69.93, 74.77, 71.68, 75.07]
Adversarial_Dogs_acc = [0.0, 68.36, 64.77, 58.58, 67.19, 58.17]
Autonomous_AI = [Natural_ImageNet_acc[0], Natural_Dogs_acc[0], Adversarial_ImageNet_acc[0], Adversarial_Dogs_acc[0]]
Confidence = [Natural_ImageNet_acc[1], Natural_Dogs_acc[1], Adversarial_ImageNet_acc[1], Adversarial_Dogs_acc[1]]
GradCAM = [Natural_ImageNet_acc[2], Natural_Dogs_acc[2], Adversarial_ImageNet_acc[2], Adversarial_Dogs_acc[2]]
EP = [Natural_ImageNet_acc[3], Natural_Dogs_acc[3], Adversarial_ImageNet_acc[3], Adversarial_Dogs_acc[3]]
SOD = [Natural_ImageNet_acc[4], Natural_Dogs_acc[4], Adversarial_ImageNet_acc[4], Adversarial_Dogs_acc[4]]
NNs = [Natural_ImageNet_acc[5], Natural_Dogs_acc[5], Adversarial_ImageNet_acc[5], Adversarial_Dogs_acc[5]]
X = np.arange(len(Autonomous_AI))# Passing the parameters to the bar function, this is the main function which creates the bar plot
# Using X now to align the bars side by side
plt.bar(X, Autonomous_AI, color = 'blue', width = 0.15)
plt.bar(X + 0.15, Confidence, color = 'orange', width = 0.15)
plt.bar(X + 0.30, GradCAM, color = 'forestgreen', width = 0.15)
plt.bar(X + 0.45, EP, color = 'skyblue', width = 0.15)
plt.bar(X + 0.60, SOD, color = 'darkviolet', width = 0.15)
plt.bar(X + 0.75, NNs, color = 'firebrick', width = 0.15)
for i in range(len(Autonomous_AI)):
plt.annotate(Autonomous_AI[i], (-0.075 + i, Autonomous_AI[i]), va='bottom')
plt.annotate(Confidence[i], (-0.075 + i + 0.15, Confidence[i]), va='bottom')
plt.annotate(GradCAM[i], (-0.075 + i + 0.30, GradCAM[i]), va='bottom')
plt.annotate(EP[i], (-0.075 + i + 0.45, EP[i]), va='bottom')
plt.annotate(SOD[i], (-0.075 + i + 0.60, SOD[i]), va='bottom')
plt.annotate(NNs[i], (-0.075 + i + 0.75, NNs[i]), va='bottom')
# plt.legend(['Natural ImageNet', 'Natural Stanford Dogs', 'Adversarial ImageNet', 'Adversarial Stanford Dogs'])# Overiding the x axis with the country names
# plt.xticks([i + 0.3 for i in range(6)], ['Autonomous AI', 'Confidence', 'GradCAM', 'EP', 'SOD', '3-NNs'])# Giving the tilte for the plot
plt.legend(['AI only', 'Confidence', 'GradCAM', 'EP', 'SOD', '3-NNs'])# Overiding the x axis with the country names
plt.xticks([i + 0.375 for i in range(4)], ['Natural ImageNet', 'Natural Stanford Dogs', 'Adversarial ImageNet', 'Adversarial Stanford Dogs'])# Giving the tilte for the plot
# plt.style.use('default')
# plt.rcParams['text.usetex'] = True
# plt.title("Human accuracy")# Namimg the x and y axis
plt.xlabel('Experiments', fontsize=14, weight='bold')
plt.ylabel('Accuracy (Acc/%)', fontsize=14, weight='bold')#
plt.savefig('tmp/accuracy_random.jpeg',dpi=600, format='jpeg', bbox_inches='tight')
plt.show()
# dang annotate cac bars
```
| github_jupyter |
# PPI1-Molla
```
import matplotlib.pyplot as plt
import numpy as np
from numpy import pi, sqrt
import pandas as pd
from lab import plot_histogram, linear_fit, plot_linear_fit, plot_residuals
# Numero misurazioni
N = 10
```
## 1 - Misure massa $m$
```
m = pd.read_csv("Data/Massa.csv")
m
# Deviazione standard massa
m.std(ddof=1)
# Media massa
mu_m = m.mean()
mu_m
# Deviazione standard media massa
sigma_m = m.std(ddof=1) / np.sqrt(N)
sigma_m
```
## 2 - Misure posizione di equlibrio $x_{eq}$
```
xeq = pd.read_csv("Data/Xeq.csv")
xeq
# Deviazione standard xeq
xeq.std(ddof=1)
# Media xeq
mu_xeq = xeq.mean()
mu_xeq
# Deviazione standard media xeq
sigma_xeq = xeq.std(ddof=1) / np.sqrt(N)
sigma_xeq
```
## 3.1 - Misure periodo 5 oscillazioni $T_{5osc}$
```
T5 = pd.read_csv("Data/Periodo.csv")
T5
# Deviazione standard periodo 5 oscillazioni
T5.std(ddof=1)
```
## 3.2 - Misure periodo singola oscillazione $T$
```
T = T5 / 5
# Media singola oscillazione
T.mean()
# Deviazione standard media singola oscillazione
T.std(ddof=1) / np.sqrt(N)
```
## 3.3 - Misure periodo singola oscillazione al quadrato $T^2$
```
T2 = T * T
# Media singola oscillazione ^ 2
mu_T2 = T2.mean()
mu_T2
# Deviazione standard media singola oscillazione ^ 2
sigma_T2 = T2.std(ddof=1) / np.sqrt(N)
sigma_T2
```
## 4 - Istrogrammi periodo singola oscillazione
```
plot_histogram(
data=T["T4"],
xlabel="$T$ [s]",
bindiv=1.4
)
plt.savefig("Images/Histo_T4.pdf")
plot_histogram(
data=T["T6"],
xlabel="$T$ [s]",
bindiv=1.3
)
plt.savefig("Images/Histo_T6.pdf")
plot_histogram(
data=T["T8"],
xlabel="$T$ [s]",
bindiv=1.2
)
plt.savefig("Images/Histo_T8.pdf")
plot_histogram(
data=T["T10"],
xlabel="$T$ [s]",
bindiv=1.3
)
plt.savefig("Images/Histo_T10.pdf")
```
## 5 - Misura della costante elastica della molla $k$
$ 1 \; k = 1 \frac{\text{N}}{\text{m}} = 1 \frac{\text{kg} \cdot \text{m}}{\text{s}^2} \frac{1}{\text{m}} $
```
# Costante elastica
delta_m = (mu_m["m10"] - mu_m["m4"]) * 0.001 # g -> kg
delta_T = mu_T2["T10"] - mu_T2["T4"] # s
k = 4 * (pi ** 2) * (delta_m / delta_T)
print(f"k = {k}")
# Incertezza costante elastica
sigma_delta_m = sqrt(
sigma_m["m10"] ** 2 +
sigma_m["m4"] ** 2
) * 0.001 # g -> kg
sigma_delta_T = sqrt(
sigma_T2["T10"] ** 2 +
sigma_T2["T4"] ** 2
) # s
sigma_k = 4 * (pi ** 2) * sqrt(
(1 / delta_T * sigma_delta_m) ** 2 +
(delta_m / delta_T ** 2 * sigma_delta_T) ** 2
)
print(f"sigma_k = {sigma_k}")
```
## 6.1 - Fit lineare
```
x = np.array(mu_T2)
sigma_x = np.array(sigma_T2)
y = np.array(mu_xeq)
sigma_y = np.array(sigma_xeq)
print(f"x = {x}")
print(f"sigma_x = {sigma_x}\n")
print(f"y = {y}")
print(f"sigma_y = {sigma_y}")
fit = linear_fit(x, y, sigma_y)
sigma_y = sqrt(sigma_y ** 2 + (fit.m * sigma_x) ** 2)
print(f"sigma_y = {sigma_y}")
# Fit
fit = plot_linear_fit(
x, y, sigma_y,
xlabel="$T^2$ [s$^2$]",
ylabel="$x_{eq}$ [cm]",
sigmas=[5],
verbosity=2
)
plt.savefig("Images/Fit.pdf")
# Residui
plot_residuals(
x, y, sigma_y,
xlabel="$T^2$ [s$^2$]",
yunit="[cm]"
)
plt.savefig("Images/Residui.pdf")
# Residui standardizzati
plot_residuals(
x, y, sigma_y,
xlabel="$T^2$ [s$^2$]",
yunit="[cm]",
standardized=True
)
plt.savefig("Images/ResiduiS.pdf")
# Risultati fit lineare
alpha = fit.m
sigma_alpha = fit.sigma_m
x0 = fit.c
sigma_x0 = fit.sigma_c
print(f"alpha = {alpha}")
print(f"sigma_alpha = {sigma_alpha}\n")
print(f"x0 = {x0}")
print(f"sigma_x0 = {sigma_x0}")
```
## 6.2 Misura dell'accelerazione di gravità $g$
```
g = 4 * (pi ** 2) * alpha * 0.01 # cm/s^2 -> m/s^2
sigma_g = 4 * (pi ** 2) * sigma_alpha * 0.01
print(f"g = {g}")
print(f"sigma_g = {sigma_g}")
# Discrepanza
z = abs(g - 9.805) / sigma_g
print(f"z = {z}")
```
| github_jupyter |
# Table of Contents
<p><div class="lev1"><a href="#What-is-exploratory-data-analysis?"><span class="toc-item-num">1 </span>What is exploratory data analysis?</a></div><div class="lev1"><a href="#Why-we-EDA"><span class="toc-item-num">2 </span>Why we EDA</a></div><div class="lev1"><a href="#Things-to-keep-in-mind"><span class="toc-item-num">3 </span>Things to keep in mind</a></div><div class="lev1"><a href="#The-game-plan"><span class="toc-item-num">4 </span>The game plan</a></div><div class="lev2"><a href="#1.-Brainstorm-areas-of-investigation"><span class="toc-item-num">4.1 </span>1. Brainstorm areas of investigation</a></div><div class="lev2"><a href="#2.-Wrangle-the-data"><span class="toc-item-num">4.2 </span>2. Wrangle the data</a></div><div class="lev2"><a href="#3.-Assess-data-quality-and-profile"><span class="toc-item-num">4.3 </span>3. Assess data quality and profile</a></div><div class="lev2"><a href="#4.-Explore-each-individual-variable-in-the-dataset"><span class="toc-item-num">4.4 </span>4. Explore each individual variable in the dataset</a></div><div class="lev2"><a href="#5.-Assess-the-relationship-between-each-variable-and-the-target"><span class="toc-item-num">4.5 </span>5. Assess the relationship between each variable and the target</a></div><div class="lev2"><a href="#6.-Assess-interactions-between-the-variables"><span class="toc-item-num">4.6 </span>6. Assess interactions between the variables</a></div><div class="lev2"><a href="#7.-Explore-data-across-many-dimensions"><span class="toc-item-num">4.7 </span>7. Explore data across many dimensions</a></div><div class="lev1"><a href="#Our-objectives-for-this-tutorial"><span class="toc-item-num">5 </span>Our objectives for this tutorial</a></div>
<img src="https://raw.githubusercontent.com/jbwhit/svds-style/master/figures/logo-medium.png" alt="SVDS" width="590" align="left">
# What is exploratory data analysis?
<img src="https://github.com/cmawer/pycon-2017-eda-tutorial/raw/master/notebooks/figures/crisp.png" alt="Crisp-DM" width="590" align="left">
# Why we EDA
Sometimes the consumer of your analysis won't understand why you need the time for EDA and will want results NOW! Here are some of the reasons you can give to convince them it's a good use of time for everyone involved.
**Reasons for the analyst**
* Identify patterns and develop hypotheses.
* Test technical assumptions.
* Inform model selection and feature engineering.
* Build an intuition for the data.
**Reasons for consumer of analysis**
* Ensures delivery of technically-sound results.
* Ensures right question is being asked.
* Tests business assumptions.
* Provides context necessary for maximum applicability and value of results.
* Leads to insights that would otherwise not be found.
# Things to keep in mind
* You're never done with EDA. With every analytical result, you want to return to EDA, make sure the result makes sense, test other questions that come up because of it.
* Stay open-minded. You're supposed to be challenging your assumptions and those of the stakeholder who you're performing the analysis for.
* Repeat EDA for every new problem. Just because you've done EDA on a dataset before doesn't mean you shouldn't do it again for the next problem. You need to look at the data through the lense of the problem at hand and you will likely have different areas of investigation.
# The game plan
<img src="https://github.com/cmawer/pycon-2017-eda-tutorial/raw/master/notebooks/figures/branches.jpg" alt="Crisp-DM" width="390" align="right">
Exploratory data analysis consists of the following major tasks, which we present linearly here because each task doesn't make much sense to do without the ones prior to it. However, in reality, you are going to constantly jump around from step to step. You may want to do all the steps for a subset of the variables first. Or often, an observation will bring up a question you want to investigate and you'll branch off and explore to answer that question before returning down the main path of exhaustive EDA.
2. Form hypotheses/develop investigation themes to explore
3. Wrangle data
3. Assess data quality and profile
5. Explore each individual variable in the dataset
6. Assess the relationship between each variable and the target
7. Assess interactions between variables
8. Explore data across many dimensions
Throughout the entire analysis you want to:
* Capture a list of hypotheses and questions that come up for further exploration.
* Record things to watch out for/ be aware of in future analyses.
* Show intermediate results to colleagues to get a fresh perspective, feedback, domain knowledge. Don't do EDA in a bubble! Get feedback throughout especially from people removed from the problem and/or with relevant domain knowledge.
* Position visuals and results together. EDA relies on your natural pattern recognition abilities so maximize what you'll find by putting visualizations and results in close proximity.
## 1. Brainstorm areas of investigation
Yes, you're exploring, but that doesn't mean it's a free for all.
* What do you need to understand the question you're trying to answer?
* List before diving in and update throughout the analysis
## 2. Wrangle the data
* Make your data [tidy](https://tomaugspurger.github.io/modern-5-tidy.html).
1. Each variable forms a column
2. Each observation forms a row
3. Each type of observational unit forms a table
* Transform data
* Log
* Binning
* Aggegration into higher level categories
## 3. Assess data quality and profile
* What data isnât there?
* Is the data that is there right?
* Is the data being generated in the way you think?
## 4. Explore each individual variable in the dataset
* What does each field in the data look like?
* How can each variable be described by a few key values?
* Are the assumptions often made in modeling valid?
## 5. Assess the relationship between each variable and the target
How does each variable interact with the target variable?
Assess each relationshipâs:
* Linearity
* Direction
* Rough size
* Strength
## 6. Assess interactions between the variables
* How do the variables interact with each other?
* What is the linearity, direction, rough size, and strength of the relationships between pairs of variables?
## 7. Explore data across many dimensions
Are there patterns across many of the variables?
# Our objectives for this tutorial
Our objectives for this tutorial are to help you:
* Develop the EDA mindset
* Questions to consider while exploring
* Things to look out for
* Learn basic methods for effective EDA
* Slicing and dicing
* Calculating summary statistics
* Basic plotting
* Basic mapping
* Using widgets for interactive exploration
The actual exploration you do in this tutorial is *yours*. We have no answers or set of conclusions we think you should come to about the datasets. Our goal is simply to aid in making your exploration as effective as possible.
<center><p style="text-align:center;font-size:160%">© <a href="http://www.svds.com">2017 Silicon Valley Data Science LLC</a></p></center>
| github_jupyter |
# Building your Recurrent Neural Network - Step by Step
Welcome to Course 5's first assignment! In this assignment, you will implement your first Recurrent Neural Network in numpy.
Recurrent Neural Networks (RNN) are very effective for Natural Language Processing and other sequence tasks because they have "memory". They can read inputs $x^{\langle t \rangle}$ (such as words) one at a time, and remember some information/context through the hidden layer activations that get passed from one time-step to the next. This allows a uni-directional RNN to take information from the past to process later inputs. A bidirection RNN can take context from both the past and the future.
**Notation**:
- Superscript $[l]$ denotes an object associated with the $l^{th}$ layer.
- Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.
- Superscript $(i)$ denotes an object associated with the $i^{th}$ example.
- Example: $x^{(i)}$ is the $i^{th}$ training example input.
- Superscript $\langle t \rangle$ denotes an object at the $t^{th}$ time-step.
- Example: $x^{\langle t \rangle}$ is the input x at the $t^{th}$ time-step. $x^{(i)\langle t \rangle}$ is the input at the $t^{th}$ timestep of example $i$.
- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.
- Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$.
We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started!
Let's first import all the packages that you will need during this assignment.
```
import numpy as np
from rnn_utils import *
```
## 1 - Forward propagation for the basic Recurrent Neural Network
Later this week, you will generate music using an RNN. The basic RNN that you will implement has the structure below. In this example, $T_x = T_y$.
<img src="images/RNN.png" style="width:500;height:300px;">
<caption><center> **Figure 1**: Basic RNN model </center></caption>
Here's how you can implement an RNN:
**Steps**:
1. Implement the calculations needed for one time-step of the RNN.
2. Implement a loop over $T_x$ time-steps in order to process all the inputs, one at a time.
Let's go!
## 1.1 - RNN cell
A Recurrent neural network can be seen as the repetition of a single cell. You are first going to implement the computations for a single time-step. The following figure describes the operations for a single time-step of an RNN cell.
<img src="images/rnn_step_forward.png" style="width:700px;height:300px;">
<caption><center> **Figure 2**: Basic RNN cell. Takes as input $x^{\langle t \rangle}$ (current input) and $a^{\langle t - 1\rangle}$ (previous hidden state containing information from the past), and outputs $a^{\langle t \rangle}$ which is given to the next RNN cell and also used to predict $y^{\langle t \rangle}$ </center></caption>
**Exercise**: Implement the RNN-cell described in Figure (2).
**Instructions**:
1. Compute the hidden state with tanh activation: $a^{\langle t \rangle} = \tanh(W_{aa} a^{\langle t-1 \rangle} + W_{ax} x^{\langle t \rangle} + b_a)$.
2. Using your new hidden state $a^{\langle t \rangle}$, compute the prediction $\hat{y}^{\langle t \rangle} = softmax(W_{ya} a^{\langle t \rangle} + b_y)$. We provided you a function: `softmax`.
3. Store $(a^{\langle t \rangle}, a^{\langle t-1 \rangle}, x^{\langle t \rangle}, parameters)$ in cache
4. Return $a^{\langle t \rangle}$ , $y^{\langle t \rangle}$ and cache
We will vectorize over $m$ examples. Thus, $x^{\langle t \rangle}$ will have dimension $(n_x,m)$, and $a^{\langle t \rangle}$ will have dimension $(n_a,m)$.
```
# GRADED FUNCTION: rnn_cell_forward
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell as described in Figure (2)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias, numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
"""
# Retrieve parameters from "parameters"
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
### START CODE HERE ### (≈2 lines)
# compute next activation state using the formula given above
a_next = None
# compute output of the current cell using the formula given above
yt_pred = None
### END CODE HERE ###
# store values you need for backward propagation in cache
cache = (a_next, a_prev, xt, parameters)
return a_next, yt_pred, cache
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
Waa = np.random.randn(5,5)
Wax = np.random.randn(5,3)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
a_next, yt_pred, cache = rnn_cell_forward(xt, a_prev, parameters)
print("a_next[4] = ", a_next[4])
print("a_next.shape = ", a_next.shape)
print("yt_pred[1] =", yt_pred[1])
print("yt_pred.shape = ", yt_pred.shape)
```
**Expected Output**:
<table>
<tr>
<td>
**a_next[4]**:
</td>
<td>
[ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978
-0.18887155 0.99815551 0.6531151 0.82872037]
</td>
</tr>
<tr>
<td>
**a_next.shape**:
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**yt[1]**:
</td>
<td>
[ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212
0.36920224 0.9966312 0.9982559 0.17746526]
</td>
</tr>
<tr>
<td>
**yt.shape**:
</td>
<td>
(2, 10)
</td>
</tr>
</table>
## 1.2 - RNN forward pass
You can see an RNN as the repetition of the cell you've just built. If your input sequence of data is carried over 10 time steps, then you will copy the RNN cell 10 times. Each cell takes as input the hidden state from the previous cell ($a^{\langle t-1 \rangle}$) and the current time-step's input data ($x^{\langle t \rangle}$). It outputs a hidden state ($a^{\langle t \rangle}$) and a prediction ($y^{\langle t \rangle}$) for this time-step.
<img src="images/rnn.png" style="width:800px;height:300px;">
<caption><center> **Figure 3**: Basic RNN. The input sequence $x = (x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, ..., x^{\langle T_x \rangle})$ is carried over $T_x$ time steps. The network outputs $y = (y^{\langle 1 \rangle}, y^{\langle 2 \rangle}, ..., y^{\langle T_x \rangle})$. </center></caption>
**Exercise**: Code the forward propagation of the RNN described in Figure (3).
**Instructions**:
1. Create a vector of zeros ($a$) that will store all the hidden states computed by the RNN.
2. Initialize the "next" hidden state as $a_0$ (initial hidden state).
3. Start looping over each time step, your incremental index is $t$ :
- Update the "next" hidden state and the cache by running `rnn_step_forward`
- Store the "next" hidden state in $a$ ($t^{th}$ position)
- Store the prediction in y
- Add the cache to the list of caches
4. Return $a$, $y$ and caches
```
# GRADED FUNCTION: rnn_forward
def rnn_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
ba -- Bias numpy array of shape (n_a, 1)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of caches, x)
"""
# Initialize "caches" which will contain the list of all caches
caches = []
# Retrieve dimensions from shapes of x and Wy
n_x, m, T_x = x.shape
n_y, n_a = parameters["Wya"].shape
### START CODE HERE ###
# initialize "a" and "y" with zeros (≈2 lines)
a = None
y_pred = None
# Initialize a_next (≈1 line)
a_next = None
# loop over all time-steps
for t in range(None):
# Update next hidden state, compute the prediction, get the cache (≈1 line)
a_next, yt_pred, cache = None
# Save the value of the new "next" hidden state in a (≈1 line)
a[:,:,t] = None
# Save the value of the prediction in y (≈1 line)
y_pred[:,:,t] = None
# Append "cache" to "caches" (≈1 line)
None
### END CODE HERE ###
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y_pred, caches
np.random.seed(1)
x = np.random.randn(3,10,4)
a0 = np.random.randn(5,10)
Waa = np.random.randn(5,5)
Wax = np.random.randn(5,3)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
a, y_pred, caches = rnn_forward(x, a0, parameters)
print("a[4][1] = ", a[4][1])
print("a.shape = ", a.shape)
print("y_pred[1][3] =", y_pred[1][3])
print("y_pred.shape = ", y_pred.shape)
print("caches[1][1][3] =", caches[1][1][3])
print("len(caches) = ", len(caches))
```
**Expected Output**:
<table>
<tr>
<td>
**a[4][1]**:
</td>
<td>
[-0.99999375 0.77911235 -0.99861469 -0.99833267]
</td>
</tr>
<tr>
<td>
**a.shape**:
</td>
<td>
(5, 10, 4)
</td>
</tr>
<tr>
<td>
**y[1][3]**:
</td>
<td>
[ 0.79560373 0.86224861 0.11118257 0.81515947]
</td>
</tr>
<tr>
<td>
**y.shape**:
</td>
<td>
(2, 10, 4)
</td>
</tr>
<tr>
<td>
**cache[1][1][3]**:
</td>
<td>
[-1.1425182 -0.34934272 -0.20889423 0.58662319]
</td>
</tr>
<tr>
<td>
**len(cache)**:
</td>
<td>
2
</td>
</tr>
</table>
Congratulations! You've successfully built the forward propagation of a recurrent neural network from scratch. This will work well enough for some applications, but it suffers from vanishing gradient problems. So it works best when each output $y^{\langle t \rangle}$ can be estimated using mainly "local" context (meaning information from inputs $x^{\langle t' \rangle}$ where $t'$ is not too far from $t$).
In the next part, you will build a more complex LSTM model, which is better at addressing vanishing gradients. The LSTM will be better able to remember a piece of information and keep it saved for many timesteps.
## 2 - Long Short-Term Memory (LSTM) network
This following figure shows the operations of an LSTM-cell.
<img src="images/LSTM.png" style="width:500;height:400px;">
<caption><center> **Figure 4**: LSTM-cell. This tracks and updates a "cell state" or memory variable $c^{\langle t \rangle}$ at every time-step, which can be different from $a^{\langle t \rangle}$. </center></caption>
Similar to the RNN example above, you will start by implementing the LSTM cell for a single time-step. Then you can iteratively call it from inside a for-loop to have it process an input with $T_x$ time-steps.
### About the gates
#### - Forget gate
For the sake of this illustration, lets assume we are reading words in a piece of text, and want use an LSTM to keep track of grammatical structures, such as whether the subject is singular or plural. If the subject changes from a singular word to a plural word, we need to find a way to get rid of our previously stored memory value of the singular/plural state. In an LSTM, the forget gate lets us do this:
$$\Gamma_f^{\langle t \rangle} = \sigma(W_f[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_f)\tag{1} $$
Here, $W_f$ are weights that govern the forget gate's behavior. We concatenate $[a^{\langle t-1 \rangle}, x^{\langle t \rangle}]$ and multiply by $W_f$. The equation above results in a vector $\Gamma_f^{\langle t \rangle}$ with values between 0 and 1. This forget gate vector will be multiplied element-wise by the previous cell state $c^{\langle t-1 \rangle}$. So if one of the values of $\Gamma_f^{\langle t \rangle}$ is 0 (or close to 0) then it means that the LSTM should remove that piece of information (e.g. the singular subject) in the corresponding component of $c^{\langle t-1 \rangle}$. If one of the values is 1, then it will keep the information.
#### - Update gate
Once we forget that the subject being discussed is singular, we need to find a way to update it to reflect that the new subject is now plural. Here is the formulat for the update gate:
$$\Gamma_u^{\langle t \rangle} = \sigma(W_u[a^{\langle t-1 \rangle}, x^{\{t\}}] + b_u)\tag{2} $$
Similar to the forget gate, here $\Gamma_u^{\langle t \rangle}$ is again a vector of values between 0 and 1. This will be multiplied element-wise with $\tilde{c}^{\langle t \rangle}$, in order to compute $c^{\langle t \rangle}$.
#### - Updating the cell
To update the new subject we need to create a new vector of numbers that we can add to our previous cell state. The equation we use is:
$$ \tilde{c}^{\langle t \rangle} = \tanh(W_c[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_c)\tag{3} $$
Finally, the new cell state is:
$$ c^{\langle t \rangle} = \Gamma_f^{\langle t \rangle}* c^{\langle t-1 \rangle} + \Gamma_u^{\langle t \rangle} *\tilde{c}^{\langle t \rangle} \tag{4} $$
#### - Output gate
To decide which outputs we will use, we will use the following two formulas:
$$ \Gamma_o^{\langle t \rangle}= \sigma(W_o[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_o)\tag{5}$$
$$ a^{\langle t \rangle} = \Gamma_o^{\langle t \rangle}* \tanh(c^{\langle t \rangle})\tag{6} $$
Where in equation 5 you decide what to output using a sigmoid function and in equation 6 you multiply that by the $\tanh$ of the previous state.
### 2.1 - LSTM cell
**Exercise**: Implement the LSTM cell described in the Figure (3).
**Instructions**:
1. Concatenate $a^{\langle t-1 \rangle}$ and $x^{\langle t \rangle}$ in a single matrix: $concat = \begin{bmatrix} a^{\langle t-1 \rangle} \\ x^{\langle t \rangle} \end{bmatrix}$
2. Compute all the formulas 2-6. You can use `sigmoid()` (provided) and `np.tanh()`.
3. Compute the prediction $y^{\langle t \rangle}$. You can use `softmax()` (provided).
```
# GRADED FUNCTION: lstm_cell_forward
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev -- Memory state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:
Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
Wi -- Weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
bi -- Bias of the save gate, numpy array of shape (n_a, 1)
Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
Wo -- Weight matrix of the focus gate, numpy array of shape (n_a, n_a + n_x)
bo -- Bias of the focus gate, numpy array of shape (n_a, 1)
Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a_next -- next hidden state, of shape (n_a, m)
c_next -- next memory state, of shape (n_a, m)
yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
cache -- tuple of values needed for the backward pass, contains (a_next, c_next, a_prev, c_prev, xt, parameters)
Note: ft/it/ot stand for the forget/update/output gates, cct stands for the candidate value (c tilda),
c stands for the memory value
"""
# Retrieve parameters from "parameters"
Wf = parameters["Wf"]
bf = parameters["bf"]
Wi = parameters["Wi"]
bi = parameters["bi"]
Wc = parameters["Wc"]
bc = parameters["bc"]
Wo = parameters["Wo"]
bo = parameters["bo"]
Wy = parameters["Wy"]
by = parameters["by"]
# Retrieve dimensions from shapes of xt and Wy
n_x, m = xt.shape
n_y, n_a = Wy.shape
### START CODE HERE ###
# Concatenate a_prev and xt (≈3 lines)
concat = None
concat[: n_a, :] = None
concat[n_a :, :] = None
# Compute values for ft, it, cct, c_next, ot, a_next using the formulas given figure (4) (≈6 lines)
ft = None
it = None
cct = None
c_next = None
ot = None
a_next = None
# Compute prediction of the LSTM cell (≈1 line)
yt_pred = None
### END CODE HERE ###
# store values needed for backward propagation in cache
cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters)
return a_next, c_next, yt_pred, cache
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
c_prev = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
print("a_next[4] = ", a_next[4])
print("a_next.shape = ", c_next.shape)
print("c_next[2] = ", c_next[2])
print("c_next.shape = ", c_next.shape)
print("yt[1] =", yt[1])
print("yt.shape = ", yt.shape)
print("cache[1][3] =", cache[1][3])
print("len(cache) = ", len(cache))
```
**Expected Output**:
<table>
<tr>
<td>
**a_next[4]**:
</td>
<td>
[-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482
0.76566531 0.34631421 -0.00215674 0.43827275]
</td>
</tr>
<tr>
<td>
**a_next.shape**:
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**c_next[2]**:
</td>
<td>
[ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942
0.76449811 -0.0981561 -0.74348425 -0.26810932]
</td>
</tr>
<tr>
<td>
**c_next.shape**:
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**yt[1]**:
</td>
<td>
[ 0.79913913 0.15986619 0.22412122 0.15606108 0.97057211 0.31146381
0.00943007 0.12666353 0.39380172 0.07828381]
</td>
</tr>
<tr>
<td>
**yt.shape**:
</td>
<td>
(2, 10)
</td>
</tr>
<tr>
<td>
**cache[1][3]**:
</td>
<td>
[-0.16263996 1.03729328 0.72938082 -0.54101719 0.02752074 -0.30821874
0.07651101 -1.03752894 1.41219977 -0.37647422]
</td>
</tr>
<tr>
<td>
**len(cache)**:
</td>
<td>
10
</td>
</tr>
</table>
### 2.2 - Forward pass for LSTM
Now that you have implemented one step of an LSTM, you can now iterate this over this using a for-loop to process a sequence of $T_x$ inputs.
<img src="images/LSTM_rnn.png" style="width:500;height:300px;">
<caption><center> **Figure 4**: LSTM over multiple time-steps. </center></caption>
**Exercise:** Implement `lstm_forward()` to run an LSTM over $T_x$ time-steps.
**Note**: $c^{\langle 0 \rangle}$ is initialized with zeros.
```
# GRADED FUNCTION: lstm_forward
def lstm_forward(x, a0, parameters):
"""
Implement the forward propagation of the recurrent neural network using an LSTM-cell described in Figure (3).
Arguments:
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
parameters -- python dictionary containing:
Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
Wi -- Weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
bi -- Bias of the save gate, numpy array of shape (n_a, 1)
Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
Wo -- Weight matrix of the focus gate, numpy array of shape (n_a, n_a + n_x)
bo -- Bias of the focus gate, numpy array of shape (n_a, 1)
Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
caches -- tuple of values needed for the backward pass, contains (list of all the caches, x)
"""
# Initialize "caches", which will track the list of all the caches
caches = []
### START CODE HERE ###
# Retrieve dimensions from shapes of xt and Wy (≈2 lines)
n_x, m, T_x = None
n_y, n_a = None
# initialize "a", "c" and "y" with zeros (≈3 lines)
a = None
c = None
y = None
# Initialize a_next and c_next (≈2 lines)
a_next = None
c_next = None
# loop over all time-steps
for t in range(None):
# Update next hidden state, next memory state, compute the prediction, get the cache (≈1 line)
a_next, c_next, yt, cache = None
# Save the value of the new "next" hidden state in a (≈1 line)
a[:,:,t] = None
# Save the value of the prediction in y (≈1 line)
y[:,:,t] = None
# Save the value of the next cell state (≈1 line)
c[:,:,t] = None
# Append the cache into caches (≈1 line)
None
### END CODE HERE ###
# store values needed for backward propagation in cache
caches = (caches, x)
return a, y, c, caches
np.random.seed(1)
x = np.random.randn(3,10,7)
a0 = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a, y, c, caches = lstm_forward(x, a0, parameters)
print("a[4][3][6] = ", a[4][3][6])
print("a.shape = ", a.shape)
print("y[1][4][3] =", y[1][4][3])
print("y.shape = ", y.shape)
print("caches[1][1[1]] =", caches[1][1][1])
print("c[1][2][1]", c[1][2][1])
print("len(caches) = ", len(caches))
```
**Expected Output**:
<table>
<tr>
<td>
**a[4][3][6]** =
</td>
<td>
0.172117767533
</td>
</tr>
<tr>
<td>
**a.shape** =
</td>
<td>
(5, 10, 7)
</td>
</tr>
<tr>
<td>
**y[1][4][3]** =
</td>
<td>
0.95087346185
</td>
</tr>
<tr>
<td>
**y.shape** =
</td>
<td>
(2, 10, 7)
</td>
</tr>
<tr>
<td>
**caches[1][1][1]** =
</td>
<td>
[ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139
0.41005165]
</td>
</tr>
<tr>
<td>
**c[1][2][1]** =
</td>
<td>
-0.855544916718
</td>
</tr>
</tr>
<tr>
<td>
**len(caches)** =
</td>
<td>
2
</td>
</tr>
</table>
Congratulations! You have now implemented the forward passes for the basic RNN and the LSTM. When using a deep learning framework, implementing the forward pass is sufficient to build systems that achieve great performance.
The rest of this notebook is optional, and will not be graded.
## 3 - Backpropagation in recurrent neural networks (OPTIONAL / UNGRADED)
In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers do not need to bother with the details of the backward pass. If however you are an expert in calculus and want to see the details of backprop in RNNs, you can work through this optional portion of the notebook.
When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in recurrent neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are quite complicated and we did not derive them in lecture. However, we will briefly present them below.
### 3.1 - Basic RNN backward pass
We will start by computing the backward pass for the basic RNN-cell.
<img src="images/rnn_cell_backprop.png" style="width:500;height:300px;"> <br>
<caption><center> **Figure 5**: RNN-cell's backward pass. Just like in a fully-connected neural network, the derivative of the cost function $J$ backpropagates through the RNN by following the chain-rule from calculas. The chain-rule is also used to calculate $(\frac{\partial J}{\partial W_{ax}},\frac{\partial J}{\partial W_{aa}},\frac{\partial J}{\partial b})$ to update the parameters $(W_{ax}, W_{aa}, b_a)$. </center></caption>
#### Deriving the one step backward functions:
To compute the `rnn_cell_backward` you need to compute the following equations. It is a good exercise to derive them by hand.
The derivative of $\tanh$ is $1-\tanh(x)^2$. You can find the complete proof [here](https://www.wyzant.com/resources/lessons/math/calculus/derivative_proofs/tanx). Note that: $ \sec(x)^2 = 1 - \tanh(x)^2$
Similarly for $\frac{ \partial a^{\langle t \rangle} } {\partial W_{ax}}, \frac{ \partial a^{\langle t \rangle} } {\partial W_{aa}}, \frac{ \partial a^{\langle t \rangle} } {\partial b}$, the derivative of $\tanh(u)$ is $(1-\tanh(u)^2)du$.
The final two equations also follow same rule and are derived using the $\tanh$ derivative. Note that the arrangement is done in a way to get the same dimensions to match.
```
def rnn_cell_backward(da_next, cache):
"""
Implements the backward pass for the RNN-cell (single time-step).
Arguments:
da_next -- Gradient of loss with respect to next hidden state
cache -- python dictionary containing useful values (output of rnn_step_forward())
Returns:
gradients -- python dictionary containing:
dx -- Gradients of input data, of shape (n_x, m)
da_prev -- Gradients of previous hidden state, of shape (n_a, m)
dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)
dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)
dba -- Gradients of bias vector, of shape (n_a, 1)
"""
# Retrieve values from cache
(a_next, a_prev, xt, parameters) = cache
# Retrieve values from parameters
Wax = parameters["Wax"]
Waa = parameters["Waa"]
Wya = parameters["Wya"]
ba = parameters["ba"]
by = parameters["by"]
### START CODE HERE ###
# compute the gradient of tanh with respect to a_next (≈1 line)
dtanh = None
# compute the gradient of the loss with respect to Wax (≈2 lines)
dxt = None
dWax = None
# compute the gradient with respect to Waa (≈2 lines)
da_prev = None
dWaa = None
# compute the gradient with respect to b (≈1 line)
dba = None
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dxt": dxt, "da_prev": da_prev, "dWax": dWax, "dWaa": dWaa, "dba": dba}
return gradients
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
Wax = np.random.randn(5,3)
Waa = np.random.randn(5,5)
Wya = np.random.randn(2,5)
b = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
a_next, yt, cache = rnn_cell_forward(xt, a_prev, parameters)
da_next = np.random.randn(5,10)
gradients = rnn_cell_backward(da_next, cache)
print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
print("gradients[\"dba\"][4] =", gradients["dba"][4])
print("gradients[\"dba\"].shape =", gradients["dba"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dxt"][1][2]** =
</td>
<td>
-0.460564103059
</td>
</tr>
<tr>
<td>
**gradients["dxt"].shape** =
</td>
<td>
(3, 10)
</td>
</tr>
<tr>
<td>
**gradients["da_prev"][2][3]** =
</td>
<td>
0.0842968653807
</td>
</tr>
<tr>
<td>
**gradients["da_prev"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWax"][3][1]** =
</td>
<td>
0.393081873922
</td>
</tr>
<tr>
<td>
**gradients["dWax"].shape** =
</td>
<td>
(5, 3)
</td>
</tr>
<tr>
<td>
**gradients["dWaa"][1][2]** =
</td>
<td>
-0.28483955787
</td>
</tr>
<tr>
<td>
**gradients["dWaa"].shape** =
</td>
<td>
(5, 5)
</td>
</tr>
<tr>
<td>
**gradients["dba"][4]** =
</td>
<td>
[ 0.80517166]
</td>
</tr>
<tr>
<td>
**gradients["dba"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
#### Backward pass through the RNN
Computing the gradients of the cost with respect to $a^{\langle t \rangle}$ at every time-step $t$ is useful because it is what helps the gradient backpropagate to the previous RNN-cell. To do so, you need to iterate through all the time steps starting at the end, and at each step, you increment the overall $db_a$, $dW_{aa}$, $dW_{ax}$ and you store $dx$.
**Instructions**:
Implement the `rnn_backward` function. Initialize the return variables with zeros first and then loop through all the time steps while calling the `rnn_cell_backward` at each time timestep, update the other variables accordingly.
```
def rnn_backward(da, caches):
"""
Implement the backward pass for a RNN over an entire sequence of input data.
Arguments:
da -- Upstream gradients of all hidden states, of shape (n_a, m, T_x)
caches -- tuple containing information from the forward pass (rnn_forward)
Returns:
gradients -- python dictionary containing:
dx -- Gradient w.r.t. the input data, numpy-array of shape (n_x, m, T_x)
da0 -- Gradient w.r.t the initial hidden state, numpy-array of shape (n_a, m)
dWax -- Gradient w.r.t the input's weight matrix, numpy-array of shape (n_a, n_x)
dWaa -- Gradient w.r.t the hidden state's weight matrix, numpy-arrayof shape (n_a, n_a)
dba -- Gradient w.r.t the bias, of shape (n_a, 1)
"""
### START CODE HERE ###
# Retrieve values from the first cache (t=1) of caches (≈2 lines)
(caches, x) = None
(a1, a0, x1, parameters) = None
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = None
n_x, m = None
# initialize the gradients with the right sizes (≈6 lines)
dx = None
dWax = None
dWaa = None
dba = None
da0 = None
da_prevt = None
# Loop through all the time steps
for t in reversed(range(None)):
# Compute gradients at time step t. Choose wisely the "da_next" and the "cache" to use in the backward propagation step. (≈1 line)
gradients = None
# Retrieve derivatives from gradients (≈ 1 line)
dxt, da_prevt, dWaxt, dWaat, dbat = gradients["dxt"], gradients["da_prev"], gradients["dWax"], gradients["dWaa"], gradients["dba"]
# Increment global derivatives w.r.t parameters by adding their derivative at time-step t (≈4 lines)
dx[:, :, t] = None
dWax += None
dWaa += None
dba += None
# Set da0 to the gradient of a which has been backpropagated through all time-steps (≈1 line)
da0 = None
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dx": dx, "da0": da0, "dWax": dWax, "dWaa": dWaa,"dba": dba}
return gradients
np.random.seed(1)
x = np.random.randn(3,10,4)
a0 = np.random.randn(5,10)
Wax = np.random.randn(5,3)
Waa = np.random.randn(5,5)
Wya = np.random.randn(2,5)
ba = np.random.randn(5,1)
by = np.random.randn(2,1)
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
a, y, caches = rnn_forward(x, a0, parameters)
da = np.random.randn(5, 10, 4)
gradients = rnn_backward(da, caches)
print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
print("gradients[\"dx\"].shape =", gradients["dx"].shape)
print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
print("gradients[\"da0\"].shape =", gradients["da0"].shape)
print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
print("gradients[\"dba\"][4] =", gradients["dba"][4])
print("gradients[\"dba\"].shape =", gradients["dba"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dx"][1][2]** =
</td>
<td>
[-2.07101689 -0.59255627 0.02466855 0.01483317]
</td>
</tr>
<tr>
<td>
**gradients["dx"].shape** =
</td>
<td>
(3, 10, 4)
</td>
</tr>
<tr>
<td>
**gradients["da0"][2][3]** =
</td>
<td>
-0.314942375127
</td>
</tr>
<tr>
<td>
**gradients["da0"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWax"][3][1]** =
</td>
<td>
11.2641044965
</td>
</tr>
<tr>
<td>
**gradients["dWax"].shape** =
</td>
<td>
(5, 3)
</td>
</tr>
<tr>
<td>
**gradients["dWaa"][1][2]** =
</td>
<td>
2.30333312658
</td>
</tr>
<tr>
<td>
**gradients["dWaa"].shape** =
</td>
<td>
(5, 5)
</td>
</tr>
<tr>
<td>
**gradients["dba"][4]** =
</td>
<td>
[-0.74747722]
</td>
</tr>
<tr>
<td>
**gradients["dba"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
## 3.2 - LSTM backward pass
### 3.2.1 One Step backward
The LSTM backward pass is slighltly more complicated than the forward one. We have provided you with all the equations for the LSTM backward pass below. (If you enjoy calculus exercises feel free to try deriving these from scratch yourself.)
### 3.2.2 gate derivatives
$$d \Gamma_o^{\langle t \rangle} = da_{next}*\tanh(c_{next}) * \Gamma_o^{\langle t \rangle}*(1-\Gamma_o^{\langle t \rangle})\tag{7}$$
$$d\tilde c^{\langle t \rangle} = dc_{next}*\Gamma_i^{\langle t \rangle}+ \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * i_t * da_{next} * \tilde c^{\langle t \rangle} * (1-\tanh(\tilde c)^2) \tag{8}$$
$$d\Gamma_u^{\langle t \rangle} = dc_{next}*\tilde c^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * \tilde c^{\langle t \rangle} * da_{next}*\Gamma_u^{\langle t \rangle}*(1-\Gamma_u^{\langle t \rangle})\tag{9}$$
$$d\Gamma_f^{\langle t \rangle} = dc_{next}*\tilde c_{prev} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * c_{prev} * da_{next}*\Gamma_f^{\langle t \rangle}*(1-\Gamma_f^{\langle t \rangle})\tag{10}$$
### 3.2.3 parameter derivatives
$$ dW_f = d\Gamma_f^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{11} $$
$$ dW_u = d\Gamma_u^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{12} $$
$$ dW_c = d\tilde c^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{13} $$
$$ dW_o = d\Gamma_o^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{14}$$
To calculate $db_f, db_u, db_c, db_o$ you just need to sum across the horizontal (axis= 1) axis on $d\Gamma_f^{\langle t \rangle}, d\Gamma_u^{\langle t \rangle}, d\tilde c^{\langle t \rangle}, d\Gamma_o^{\langle t \rangle}$ respectively. Note that you should have the `keep_dims = True` option.
Finally, you will compute the derivative with respect to the previous hidden state, previous memory state, and input.
$$ da_{prev} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c^{\langle t \rangle} + W_o^T * d\Gamma_o^{\langle t \rangle} \tag{15}$$
Here, the weights for equations 13 are the first n_a, (i.e. $W_f = W_f[:n_a,:]$ etc...)
$$ dc_{prev} = dc_{next}\Gamma_f^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} * (1- \tanh(c_{next})^2)*\Gamma_f^{\langle t \rangle}*da_{next} \tag{16}$$
$$ dx^{\langle t \rangle} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c_t + W_o^T * d\Gamma_o^{\langle t \rangle}\tag{17} $$
where the weights for equation 15 are from n_a to the end, (i.e. $W_f = W_f[n_a:,:]$ etc...)
**Exercise:** Implement `lstm_cell_backward` by implementing equations $7-17$ below. Good luck! :)
```
def lstm_cell_backward(da_next, dc_next, cache):
"""
Implement the backward pass for the LSTM-cell (single time-step).
Arguments:
da_next -- Gradients of next hidden state, of shape (n_a, m)
dc_next -- Gradients of next cell state, of shape (n_a, m)
cache -- cache storing information from the forward pass
Returns:
gradients -- python dictionary containing:
dxt -- Gradient of input data at time-step t, of shape (n_x, m)
da_prev -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
dc_prev -- Gradient w.r.t. the previous memory state, of shape (n_a, m, T_x)
dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
dWi -- Gradient w.r.t. the weight matrix of the input gate, numpy array of shape (n_a, n_a + n_x)
dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
dWo -- Gradient w.r.t. the weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
dbo -- Gradient w.r.t. biases of the save gate, of shape (n_a, 1)
"""
# Retrieve information from "cache"
(a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache
### START CODE HERE ###
# Retrieve dimensions from xt's and a_next's shape (≈2 lines)
n_x, m = None
n_a, m = None
# Compute gates related derivatives, you can find their values can be found by looking carefully at equations (7) to (10) (≈4 lines)
dot = None
dcct = None
dit = None
dft = None
# Code equations (7) to (10) (≈4 lines)
dit = None
dft = None
dot = None
dcct = None
# Compute parameters related derivatives. Use equations (11)-(14) (≈8 lines)
dWf = None
dWi = None
dWc = None
dWo = None
dbf = None
dbi = None
dbc = None
dbo = None
# Compute derivatives w.r.t previous hidden state, previous memory state and input. Use equations (15)-(17). (≈3 lines)
da_prev = None
dc_prev = None
dxt = None
### END CODE HERE ###
# Save gradients in dictionary
gradients = {"dxt": dxt, "da_prev": da_prev, "dc_prev": dc_prev, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
"dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
return gradients
np.random.seed(1)
xt = np.random.randn(3,10)
a_prev = np.random.randn(5,10)
c_prev = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
Wy = np.random.randn(2,5)
by = np.random.randn(2,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
da_next = np.random.randn(5,10)
dc_next = np.random.randn(5,10)
gradients = lstm_cell_backward(da_next, dc_next, cache)
print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
print("gradients[\"dc_prev\"][2][3] =", gradients["dc_prev"][2][3])
print("gradients[\"dc_prev\"].shape =", gradients["dc_prev"].shape)
print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
print("gradients[\"dbo\"].shape =", gradients["dbo"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dxt"][1][2]** =
</td>
<td>
3.23055911511
</td>
</tr>
<tr>
<td>
**gradients["dxt"].shape** =
</td>
<td>
(3, 10)
</td>
</tr>
<tr>
<td>
**gradients["da_prev"][2][3]** =
</td>
<td>
-0.0639621419711
</td>
</tr>
<tr>
<td>
**gradients["da_prev"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dc_prev"][2][3]** =
</td>
<td>
0.797522038797
</td>
</tr>
<tr>
<td>
**gradients["dc_prev"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWf"][3][1]** =
</td>
<td>
-0.147954838164
</td>
</tr>
<tr>
<td>
**gradients["dWf"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWi"][1][2]** =
</td>
<td>
1.05749805523
</td>
</tr>
<tr>
<td>
**gradients["dWi"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWc"][3][1]** =
</td>
<td>
2.30456216369
</td>
</tr>
<tr>
<td>
**gradients["dWc"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWo"][1][2]** =
</td>
<td>
0.331311595289
</td>
</tr>
<tr>
<td>
**gradients["dWo"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dbf"][4]** =
</td>
<td>
[ 0.18864637]
</td>
</tr>
<tr>
<td>
**gradients["dbf"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbi"][4]** =
</td>
<td>
[-0.40142491]
</td>
</tr>
<tr>
<td>
**gradients["dbi"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbc"][4]** =
</td>
<td>
[ 0.25587763]
</td>
</tr>
<tr>
<td>
**gradients["dbc"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbo"][4]** =
</td>
<td>
[ 0.13893342]
</td>
</tr>
<tr>
<td>
**gradients["dbo"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
### 3.3 Backward pass through the LSTM RNN
This part is very similar to the `rnn_backward` function you implemented above. You will first create variables of the same dimension as your return variables. You will then iterate over all the time steps starting from the end and call the one step function you implemented for LSTM at each iteration. You will then update the parameters by summing them individually. Finally return a dictionary with the new gradients.
**Instructions**: Implement the `lstm_backward` function. Create a for loop starting from $T_x$ and going backward. For each step call `lstm_cell_backward` and update the your old gradients by adding the new gradients to them. Note that `dxt` is not updated but is stored.
```
def lstm_backward(da, caches):
"""
Implement the backward pass for the RNN with LSTM-cell (over a whole sequence).
Arguments:
da -- Gradients w.r.t the hidden states, numpy-array of shape (n_a, m, T_x)
dc -- Gradients w.r.t the memory states, numpy-array of shape (n_a, m, T_x)
caches -- cache storing information from the forward pass (lstm_forward)
Returns:
gradients -- python dictionary containing:
dx -- Gradient of inputs, of shape (n_x, m, T_x)
da0 -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
dWo -- Gradient w.r.t. the weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
dbo -- Gradient w.r.t. biases of the save gate, of shape (n_a, 1)
"""
# Retrieve values from the first cache (t=1) of caches.
(caches, x) = caches
(a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0]
### START CODE HERE ###
# Retrieve dimensions from da's and x1's shapes (≈2 lines)
n_a, m, T_x = None
n_x, m = None
# initialize the gradients with the right sizes (≈12 lines)
dx = None
da0 = None
da_prevt = None
dc_prevt = None
dWf = None
dWi = None
dWc = None
dWo = None
dbf = None
dbi = None
dbc = None
dbo = None
# loop back over the whole sequence
for t in reversed(range(None)):
# Compute all gradients using lstm_cell_backward
gradients = None
# Store or add the gradient to the parameters' previous step's gradient
dx[:,:,t] = None
dWf = None
dWi = None
dWc = None
dWo = None
dbf = None
dbi = None
dbc = None
dbo = None
# Set the first activation's gradient to the backpropagated gradient da_prev.
da0 = None
### END CODE HERE ###
# Store the gradients in a python dictionary
gradients = {"dx": dx, "da0": da0, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
"dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
return gradients
np.random.seed(1)
x = np.random.randn(3,10,7)
a0 = np.random.randn(5,10)
Wf = np.random.randn(5, 5+3)
bf = np.random.randn(5,1)
Wi = np.random.randn(5, 5+3)
bi = np.random.randn(5,1)
Wo = np.random.randn(5, 5+3)
bo = np.random.randn(5,1)
Wc = np.random.randn(5, 5+3)
bc = np.random.randn(5,1)
parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
a, y, c, caches = lstm_forward(x, a0, parameters)
da = np.random.randn(5, 10, 4)
gradients = lstm_backward(da, caches)
print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
print("gradients[\"dx\"].shape =", gradients["dx"].shape)
print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
print("gradients[\"da0\"].shape =", gradients["da0"].shape)
print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
print("gradients[\"dbo\"].shape =", gradients["dbo"].shape)
```
**Expected Output**:
<table>
<tr>
<td>
**gradients["dx"][1][2]** =
</td>
<td>
[-0.00173313 0.08287442 -0.30545663 -0.43281115]
</td>
</tr>
<tr>
<td>
**gradients["dx"].shape** =
</td>
<td>
(3, 10, 4)
</td>
</tr>
<tr>
<td>
**gradients["da0"][2][3]** =
</td>
<td>
-0.095911501954
</td>
</tr>
<tr>
<td>
**gradients["da0"].shape** =
</td>
<td>
(5, 10)
</td>
</tr>
<tr>
<td>
**gradients["dWf"][3][1]** =
</td>
<td>
-0.0698198561274
</td>
</tr>
<tr>
<td>
**gradients["dWf"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWi"][1][2]** =
</td>
<td>
0.102371820249
</td>
</tr>
<tr>
<td>
**gradients["dWi"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWc"][3][1]** =
</td>
<td>
-0.0624983794927
</td>
</tr>
<tr>
<td>
**gradients["dWc"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dWo"][1][2]** =
</td>
<td>
0.0484389131444
</td>
</tr>
<tr>
<td>
**gradients["dWo"].shape** =
</td>
<td>
(5, 8)
</td>
</tr>
<tr>
<td>
**gradients["dbf"][4]** =
</td>
<td>
[-0.0565788]
</td>
</tr>
<tr>
<td>
**gradients["dbf"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbi"][4]** =
</td>
<td>
[-0.06997391]
</td>
</tr>
<tr>
<td>
**gradients["dbi"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbc"][4]** =
</td>
<td>
[-0.27441821]
</td>
</tr>
<tr>
<td>
**gradients["dbc"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
<tr>
<td>
**gradients["dbo"][4]** =
</td>
<td>
[ 0.16532821]
</td>
</tr>
<tr>
<td>
**gradients["dbo"].shape** =
</td>
<td>
(5, 1)
</td>
</tr>
</table>
### Congratulations !
Congratulations on completing this assignment. You now understand how recurrent neural networks work!
Lets go on to the next exercise, where you'll use an RNN to build a character-level language model.
| github_jupyter |

# Python fundamentals
This notebook gives the basics of Python 3.
The best resource for beginners is [The Python Tutorial](https://docs.python.org/3/tutorial/).
***
## Examples
***
You can quickly do lots of things in Python, such as manipulate an image.
Excellent packages exist for almost anything reasonable a computer can do.
```
# You need to install Pillow for this first: conda install -c anaconda pillow
import urllib.request
import io
import PIL.Image
URL = 'http://www.gmit.ie/sites/all/themes/gmitpublic/images/gmit_logo.png'
with urllib.request.urlopen(URL) as url:
imagefile = io.BytesIO(url.read())
image = PIL.Image.open(imagefile)
imagebw = image.convert('L')
display(image, imagebw)
```
***
Many plotting packages exist, such as matplotlib.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
x1 = np.linspace(0, 4 * np.pi, 1000)
y1 = np.sin(x1)
y2 = np.cos(x1)
x2 = np.linspace(0, 4 * np.pi, 9)
y3 = np.sin(x2)
y4 = np.cos(x2)
pl.plot(x1, y1)
pl.plot(x2, y3, 'r.')
pl.plot(x1, y2, 'g')
pl.plot(x2, y4, 'k.')
pl.show()
```
***
Python is an excellent choice for data analytics.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
pl.hist(np.random.normal(10, 2, 1000))
pl.show()
```
***
## Philosophy
***
One reason Python is popular is because of its philosophy.
There's an Easter egg you can find as follows.
```
import this
```
***
## Offside rule
***
Python uses the [*offside rule*](https://en.wikipedia.org/wiki/Off-side_rule) instead of curly braces and semi-colons.
Its purpose is to improve the readability of code.
***
## Comments
***
Comments come after a hash character, #.
```
# This section of code
# does
#### absolutely nothing.
print(1) # Print the number 1.
```
***
## Variables
***
Python doesn't require the declaration of variables or their type.
You can just start using a new variable, and Python won't complain.
***
Whole number literals, like `123`, are of type int.
```
i = 123
i
```
***
You can assign two or more variables at once using commas.
```
m, n = 10, 11
print(m, n)
```
So, you can do this:
```
a = 1
b = 2
print(a, b)
a, b = b, a
print(a, b)
```
***
You can check the type of a variable using the built-in type function.
```
type(i)
```
***
Placing a full stop, followed by optional digits, creates a `float` instead.
```
f = 3.0
g = f / 2.0
print(f, g)
```
***
## Strings and lists
***
Strings can be enclosed in either double or single quotes.
The characters can be indexed as usual.
You can also access slices of strings using colons.
```
s = "Hello, world!"
print(s[0])
print(s[7:12])
```
***
Lists are created using square brackets and commas.
There is a related concept called tuples - they are immutable.
They can be indexed in the same way as strings, even with negative indices!
```
x = [1,3,4,"cow"]
t = (1,2,3,4)
print(x[2])
print(x[-1])
print(x)
print(t)
```
***
Note that it's really the commas that matter.
Here's a tuple without brackets.
```
v = 1,2,3
v
```
***
## Conditions
***
We can make hard decisions using `if`, `elif` and `else`.
```
if 2 == 1 + 1:
print("Yes")
```
Here's the whole shebang.
```
s = "Hello, world!"
if s[0] == "H":
print("H is first letter")
elif s[1] == "e":
print("e is second letter")
else:
print("H is not first letter and e is not second letter")
```
You can write shorthand if statements on a single line as follows.
The `if` comes after the value to return if the condition is true.
```
i = 3
j = 4 if i == 3 else 0
print(i, j)
```
***
## Loops
***
Python likes to loop over lists.
```
for i in [1,2,3]:
print(i**2)
```
***
If you want to loop over an integer you can use the built-in `range` function.
With one argument it returns the integer values from 0, including 0, up to, but not including, that number.
```
for i in range(10):
print(i**2)
```
***
You can create inline lists also, using an inline for loop.
```
squares = [i**2 for i in range(10)]
squares
```
***
Here's an example of using a loop and a conditional together.
```
for i in range(10):
if i % 2 == 0:
continue
elif i == 7:
break
else:
print(i)
```
***
## Functions
***
Functions are defined using the def keyword.
```
def f(x):
return x**2 - (2 * x) + 1
for i in range(10):
print(i, f(i))
```
***
In Python, you can define one-line (anonymous) functions (that you can give a name if you want).
```
g = lambda x: x**3 - 10 * x**2 + x + 5
[g(i) for i in range(10)]
```
***
Python can automatically generate documentation for your code if you include docstrings.
They come in triple quotes just inside your function and should describe the function.
```
def gcd(a, b):
"""Calculate the Greatest Common Divisor of the integers a and b."""
while b:
# a % b is a modulo b.
a, b = b, (a % b)
return a
gcd(-100, 60)
```
***
## Slices
***
You can slice strings and lists as follows.
```
s1 = "Hello, world!"
s2 = 'Goodbye, computer!'
print(s1) # Print s1
print(s1[7]) # Print the 8th characters of s1
print(s1[7:12]) # Print characters 7 to 11 of s1
print(len(s1)) # Print the length of s1
print(s2[::2]) # Print what?
print(s2[::-1]) # Print what?
```
## End
| github_jupyter |
##### Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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.
```
# Linear Mixed-Effect Regression in {TF Probability, R, Stan}
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/probability/examples/HLM_TFP_R_Stan"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/HLM_TFP_R_Stan.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/HLM_TFP_R_Stan.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/probability/tensorflow_probability/examples/jupyter_notebooks/HLM_TFP_R_Stan.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## 1 Introduction
In this colab we will fit a linear mixed-effect regression model to a popular, toy dataset. We will make this fit thrice, using R's `lme4`, Stan's mixed-effects package, and TensorFlow Probability (TFP) primitives. We conclude by showing all three give roughly the same fitted parameters and posterior distributions.
Our main conclusion is that TFP has the general pieces necessary to fit HLM-like models and that it produces results which are consistent with other software packages, i.e.., `lme4`, `rstanarm`. This colab is not an accurate reflection of the computational efficiency of any of the packages compared.
```
%matplotlib inline
import os
from six.moves import urllib
import numpy as np
import pandas as pd
import warnings
from matplotlib import pyplot as plt
import seaborn as sns
from IPython.core.pylabtools import figsize
figsize(11, 9)
import tensorflow.compat.v1 as tf
import tensorflow_probability as tfp
```
## 2 Hierarchical Linear Model
For our comparison between R, Stan, and TFP, we will fit a [Hierarchical Linear Model](https://en.wikipedia.org/wiki/Multilevel_model) (HLM) to the [Radon dataset](http://www.stat.columbia.edu/~gelman/arm/examples/radon/) made popular in [_Bayesian Data Analysis_ by Gelman, et. al.](http://www.stat.columbia.edu/~gelman/book/) (page 559, second ed; page 250, third ed.).
We assume the following generative model:
$$\begin{align*}
\text{for } & c=1\ldots \text{NumCounties}:\\
& \beta_c \sim \text{Normal}\left(\text{loc}=0, \text{scale}=\sigma_C \right) \\
\text{for } & i=1\ldots \text{NumSamples}:\\
&\eta_i = \underbrace{\omega_0 + \omega_1 \text{Floor}_i}_\text{fixed effects} + \underbrace{\beta_{ \text{County}_i} \log( \text{UraniumPPM}_{\text{County}_i}))}_\text{random effects} \\
&\log(\text{Radon}_i) \sim \text{Normal}(\text{loc}=\eta_i , \text{scale}=\sigma_N)
\end{align*}$$
In R's `lme4` "tilde notation", this model is equivalent to:
> `log_radon ~ 1 + floor + (0 + log_uranium_ppm | county)`
We will find MLE for $\omega, \sigma_C, \sigma_N$ using the posterior distribution (conditioned on evidence) of $\{\beta_c\}_{c=1}^\text{NumCounties}$.
For essentially the same model but _with_ a random intercept, see _[Appendix A](#scrollTo=tsXhZ4rtNUXL)_.
For a more general specification of HLMs, see _[Appendix B](#scrollTo=H0w7ofFvNsxi)_.
## 3 Data Munging
In this section we obtain the [`radon` dataset](http://www.stat.columbia.edu/~gelman/arm/examples/radon/) and do some minimal preprocessing to make it comply with our assumed model.
```
# We'll use the following directory to store files we download as well as our
# preprocessed dataset.
CACHE_DIR = os.path.join(os.sep, 'tmp', 'radon')
def cache_or_download_file(cache_dir, url_base, filename):
"""Read a cached file or download it."""
filepath = os.path.join(cache_dir, filename)
if tf.gfile.Exists(filepath):
return filepath
if not tf.gfile.Exists(cache_dir):
tf.gfile.MakeDirs(cache_dir)
url = os.path.join(url_base, filename)
print("Downloading {url} to {filepath}.".format(url=url, filepath=filepath))
urllib.request.urlretrieve(url, filepath)
return filepath
def download_radon_dataset(cache_dir=CACHE_DIR):
"""Download the radon dataset and read as Pandas dataframe."""
url_base = 'http://www.stat.columbia.edu/~gelman/arm/examples/radon/'
# Alternative source:
# url_base = ('https://raw.githubusercontent.com/pymc-devs/uq_chapter/'
# 'master/reference/data/')
srrs2 = pd.read_csv(cache_or_download_file(cache_dir, url_base, 'srrs2.dat'))
srrs2.rename(columns=str.strip, inplace=True)
cty = pd.read_csv(cache_or_download_file(cache_dir, url_base, 'cty.dat'))
cty.rename(columns=str.strip, inplace=True)
return srrs2, cty
def preprocess_radon_dataset(srrs2, cty, state='MN'):
"""Preprocess radon dataset as done in "Bayesian Data Analysis" book."""
srrs2 = srrs2[srrs2.state==state].copy()
cty = cty[cty.st==state].copy()
# We will now join datasets on Federal Information Processing Standards
# (FIPS) id, ie, codes that link geographic units, counties and county
# equivalents. http://jeffgill.org/Teaching/rpqm_9.pdf
srrs2['fips'] = 1000 * srrs2.stfips + srrs2.cntyfips
cty['fips'] = 1000 * cty.stfips + cty.ctfips
df = srrs2.merge(cty[['fips', 'Uppm']], on='fips')
df = df.drop_duplicates(subset='idnum')
df = df.rename(index=str, columns={'Uppm': 'uranium_ppm'})
# For any missing or invalid activity readings, we'll use a value of `0.1`.
df['radon'] = df.activity.apply(lambda x: x if x > 0. else 0.1)
# Remap categories to start from 0 and end at max(category).
county_name = sorted(df.county.unique())
df['county'] = df.county.astype(
pd.api.types.CategoricalDtype(categories=county_name)).cat.codes
county_name = map(str.strip, county_name)
df['log_radon'] = df['radon'].apply(np.log)
df['log_uranium_ppm'] = df['uranium_ppm'].apply(np.log)
df = df[['log_radon', 'floor', 'county', 'log_uranium_ppm']]
return df, county_name
radon, county_name = preprocess_radon_dataset(*download_radon_dataset())
# Save processed data. (So we can later read it in R.)
with tf.gfile.Open(os.path.join(CACHE_DIR, 'radon.csv'), 'w') as f:
radon.to_csv(f, index=False)
```
### 3.1 Know Thy Data
In this section we explore the `radon` dataset to get a better sense of why the proposed model might be reasonable.
```
radon.head()
fig, ax = plt.subplots(figsize=(22, 5));
county_freq = radon['county'].value_counts()
county_freq.plot(kind='bar', color='#436bad');
plt.xlabel('County index')
plt.ylabel('Number of radon readings')
plt.title('Number of radon readings per county', fontsize=16)
county_freq = np.array(zip(county_freq.index, county_freq.values)) # We'll use this later.
fig, ax = plt.subplots(ncols=2, figsize=[10, 4]);
radon['log_radon'].plot(kind='density', ax=ax[0]);
ax[0].set_xlabel('log(radon)')
radon['floor'].value_counts().plot(kind='bar', ax=ax[1]);
ax[1].set_xlabel('Floor');
ax[1].set_ylabel('Count');
fig.subplots_adjust(wspace=0.25)
```
Conclusions:
- There's a long tail of 85 counties. (A common occurrence in GLMMs.)
- Indeed $\log(\text{Radon})$ is unconstrained. (So linear regression might make sense.)
- Readings are most made on the $0$-th floor; no reading was made above floor $1$. (So our fixed effects will only have two weights.)
## 4 HLM In R
In this section we use R's [`lme4`](https://cran.r-project.org/web/packages/lme4/index.html) package to fit probabilistic model described above.
**NOTE: To execute this section, you must switch to an `R` colab runtime.**
```
suppressMessages({
library('bayesplot')
library('data.table')
library('dplyr')
library('gfile')
library('ggplot2')
library('lattice')
library('lme4')
library('plyr')
library('rstanarm')
library('tidyverse')
RequireInitGoogle()
})
data = read_csv(gfile('/tmp/radon/radon.csv'))
head(data)
# https://github.com/stan-dev/example-models/wiki/ARM-Models-Sorted-by-Chapter
radon.model <- lmer(log_radon ~ 1 + floor + (0 + log_uranium_ppm | county), data = data)
summary(radon.model)
qqmath(ranef(radon.model, condVar=TRUE))
write.csv(as.data.frame(ranef(radon.model, condVar = TRUE)), '/tmp/radon/lme4_fit.csv')
```
## 5 HLM In Stan
In this section we use [rstanarm](http://mc-stan.org/users/interfaces/rstanarm) to fit a Stan model using the same formula/syntax as the `lme4` model above.
Unlike `lme4` and the TF model below, `rstanarm` is a fully Bayesian model, i.e., all parameters are presumed drawn from a Normal distribution with parameters themselves drawn from a distribution.
**NOTE: To execute this section, you must switch an `R` colab runtime.**
```
fit <- stan_lmer(log_radon ~ 1 + floor + (0 + log_uranium_ppm | county), data = data)
```
**Note**: The runtimes are from a single CPU core. (This colab is not intended to be a faithful representation of Stan or TFP runtime.)
```
fit
color_scheme_set("red")
ppc_dens_overlay(y = fit$y,
yrep = posterior_predict(fit, draws = 50))
color_scheme_set("brightblue")
ppc_intervals(
y = data$log_radon,
yrep = posterior_predict(fit),
x = data$county,
prob = 0.8
) +
labs(
x = "County",
y = "log radon",
title = "80% posterior predictive intervals \nvs observed log radon",
subtitle = "by county"
) +
panel_bg(fill = "gray95", color = NA) +
grid_lines(color = "white")
# Write the posterior samples (4000 for each variable) to a CSV.
write.csv(tidy(as.matrix(fit)), "/tmp/radon/stan_fit.csv")
```
**Note: Switch back to the Python TF kernel runtime.**
```
with tf.gfile.Open('/tmp/radon/lme4_fit.csv', 'r') as f:
lme4_fit = pd.read_csv(f, index_col=0)
lme4_fit.head()
```
Retrieve the point estimates and conditional standard deviations for the group random effects from lme4 for visualization later.
```
posterior_random_weights_lme4 = np.array(lme4_fit.condval, dtype=np.float32)
lme4_prior_scale = np.array(lme4_fit.condsd, dtype=np.float32)
print(posterior_random_weights_lme4.shape, lme4_prior_scale.shape)
```
Draw samples for the county weights using the lme4 estimated means and standard deviations.
```
with tf.Session() as sess:
lme4_dist = tfp.distributions.Independent(
tfp.distributions.Normal(
loc=posterior_random_weights_lme4,
scale=lme4_prior_scale),
reinterpreted_batch_ndims=1)
posterior_random_weights_lme4_final_ = sess.run(lme4_dist.sample(4000))
posterior_random_weights_lme4_final_.shape
```
We also retrieve the posterior samples of the county weights from the Stan fit.
```
with tf.gfile.Open('/tmp/radon/stan_fit.csv', 'r') as f:
samples = pd.read_csv(f, index_col=0)
samples.head()
posterior_random_weights_cols = [
col for col in samples.columns if 'b.log_uranium_ppm.county' in col
]
posterior_random_weights_final_stan = samples[
posterior_random_weights_cols].values
print(posterior_random_weights_final_stan.shape)
```
[This Stan example](https://github.com/stan-dev/example-models/blob/master/ARM/Ch.16/radon.3.stan) shows how one would implement LMER in a style closer to TFP, i.e., by directly specifying the probabilistic model.
## 6 HLM In TF Probability
In this section we will use low-level TensorFlow Probability primitives (`Distributions`) to specify our Hierarchical Linear Model as well as fit the unkown parameters.
```
# Handy snippet to reset the global graph and global session.
with warnings.catch_warnings():
warnings.simplefilter('ignore')
tf.reset_default_graph()
try:
sess.close()
except:
pass
sess = tf.InteractiveSession()
```
### 6.1 Specify Model
In this section we specify the [radon linear mixed-effect model](#scrollTo=IFC9r-h0XlQ3) using TFP primitives. To do this, we specify two functions which produce two TFP distributions:
- `make_weights_prior`: A multivariate Normal prior for the random weights (which are multiplied by $\log(\text{UraniumPPM}_{c_i})$ to compue the linear predictor).
- `make_log_radon_likelihood`: A batch of `Normal` distributions over each observed $\log(\text{Radon}_i)$ dependent variable.
Since we will be fitting the parameters of each of these distributions we must use TF variables (i.e., [`tf.get_variable`](https://www.tensorflow.org/api_docs/python/tf/get_variable)). However, since we wish to use unconstrained optimzation we must find a way to constrain real-values to achieve the necessary semantics, eg, postives which represent standard deviations.
```
inv_scale_transform = lambda y: np.log(y) # Not using TF here.
fwd_scale_transform = tf.exp
```
The following function constructs our prior, $p(\beta|\sigma_C)$ where $\beta$ denotes the random-effect weights and $\sigma_C$ the standard deviation.
We use `tf.make_template` to ensure that the first call to this function instantiates the TF variables it uses and all subsequent calls _reuse_ the variable's current value.
```
def _make_weights_prior(num_counties, dtype):
"""Returns a `len(log_uranium_ppm)` batch of univariate Normal."""
raw_prior_scale = tf.get_variable(
name='raw_prior_scale',
initializer=np.array(inv_scale_transform(1.), dtype=dtype))
return tfp.distributions.Independent(
tfp.distributions.Normal(
loc=tf.zeros(num_counties, dtype=dtype),
scale=fwd_scale_transform(raw_prior_scale)),
reinterpreted_batch_ndims=1)
make_weights_prior = tf.make_template(
name_='make_weights_prior', func_=_make_weights_prior)
```
The following function constructs our likelihood, $p(y|x,\omega,\beta,\sigma_N)$ where $y,x$ denote response and evidence, $\omega,\beta$ denote fixed- and random-effect weights, and $\sigma_N$ the standard deviation.
Here again we use `tf.make_template` to ensure the TF variables are reused across calls.
```
def _make_log_radon_likelihood(random_effect_weights, floor, county,
log_county_uranium_ppm, init_log_radon_stddev):
raw_likelihood_scale = tf.get_variable(
name='raw_likelihood_scale',
initializer=np.array(
inv_scale_transform(init_log_radon_stddev), dtype=dtype))
fixed_effect_weights = tf.get_variable(
name='fixed_effect_weights', initializer=np.array([0., 1.], dtype=dtype))
fixed_effects = fixed_effect_weights[0] + fixed_effect_weights[1] * floor
random_effects = tf.gather(
random_effect_weights * log_county_uranium_ppm,
indices=tf.to_int32(county),
axis=-1)
linear_predictor = fixed_effects + random_effects
return tfp.distributions.Normal(
loc=linear_predictor, scale=fwd_scale_transform(raw_likelihood_scale))
make_log_radon_likelihood = tf.make_template(
name_='make_log_radon_likelihood', func_=_make_log_radon_likelihood)
```
Finally we use the prior and likelihood generators to construct the joint log-density.
```
def joint_log_prob(random_effect_weights, log_radon, floor, county,
log_county_uranium_ppm, dtype):
num_counties = len(log_county_uranium_ppm)
rv_weights = make_weights_prior(num_counties, dtype)
rv_radon = make_log_radon_likelihood(
random_effect_weights,
floor,
county,
log_county_uranium_ppm,
init_log_radon_stddev=radon.log_radon.values.std())
return (rv_weights.log_prob(random_effect_weights)
+ tf.reduce_sum(rv_radon.log_prob(log_radon), axis=-1))
```
### 6.2 Training (Stochastic Approximation of Expectation Maximization)
To fit our linear mixed-effect regression model, we will use a stochastic approximation version of the Expectation Maximization algorithm (SAEM). The basic idea is to use samples from the posterior to approximate the expected joint log-density (E-step). Then we find the parameters which maximize this calculation (M-step). Somewhat more concretely, the fixed-point iteration is given by:
$$\begin{align*}
\text{E}[ \log p(x, Z | \theta) | \theta_0]
&\approx \frac{1}{M} \sum_{m=1}^M \log p(x, z_m | \theta), \quad Z_m\sim p(Z | x, \theta_0) && \text{E-step}\\
&=: Q_M(\theta, \theta_0) \\
\theta_0 &= \theta_0 - \eta \left.\nabla_\theta Q_M(\theta, \theta_0)\right|_{\theta=\theta_0} && \text{M-step}
\end{align*}$$
where $x$ denotes evidence, $Z$ some latent variable which needs to be marginalized out, and $\theta,\theta_0$ possible parameterizations.
For a more thorough explanation, see [_Convergence of a stochastic approximation version of the EM algorithms_ by Bernard Delyon, Marc Lavielle, Eric, Moulines (Ann. Statist., 1999)](https://projecteuclid.org/euclid.aos/1018031103).
To compute the E-step, we need to sample from the posterior. Since our posterior is not easy to sample from, we use Hamiltonian Monte Carlo (HMC). HMC is a Monte Carlo Markov Chain procedure which uses gradients (wrt state, not parameters) of the unnormalized posterior log-density to propose new samples.
Specifying the unnormalized posterior log-density is simple--it is merely the joint log-density "pinned" at whatever we wish to condition on.
```
# Specify unnormalized posterior.
dtype = np.float32
log_county_uranium_ppm = radon[
['county', 'log_uranium_ppm']].drop_duplicates().values[:, 1]
log_county_uranium_ppm = log_county_uranium_ppm.astype(dtype)
def unnormalized_posterior_log_prob(random_effect_weights):
return joint_log_prob(
random_effect_weights=random_effect_weights,
log_radon=dtype(radon.log_radon.values),
floor=dtype(radon.floor.values),
county=np.int32(radon.county.values),
log_county_uranium_ppm=log_county_uranium_ppm,
dtype=dtype)
```
We now complete the E-step setup by creating an HMC transition kernel.
Notes:
- We use `state_stop_gradient=True`to prevent the M-step from backpropping through draws from the MCMC. (Recall, we needn't backprop through because our E-step is intentionally parameterized at the _previous_ best known estimators.)
- We use [`tf.placeholder`](https://www.tensorflow.org/api_docs/python/tf/placeholder) so that when we eventually execute our TF graph, we can feed the previous iteration's random MCMC sample as the the next iteration's chain's value.
- We use TFP's adaptive `step_size` heuristic, `tfp.mcmc.hmc_step_size_update_fn`.
```
# Set-up E-step.
step_size = tf.get_variable(
'step_size',
initializer=np.array(0.2, dtype=dtype),
trainable=False)
hmc = tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_posterior_log_prob,
num_leapfrog_steps=2,
step_size=step_size,
step_size_update_fn=tfp.mcmc.make_simple_step_size_update_policy(
num_adaptation_steps=None),
state_gradients_are_stopped=True)
init_random_weights = tf.placeholder(dtype, shape=[len(log_county_uranium_ppm)])
posterior_random_weights, kernel_results = tfp.mcmc.sample_chain(
num_results=3,
num_burnin_steps=0,
num_steps_between_results=0,
current_state=init_random_weights,
kernel=hmc)
```
We now set-up the M-step. This is essentially the same as an optimization one might do in TF.
```
# Set-up M-step.
loss = -tf.reduce_mean(kernel_results.accepted_results.target_log_prob)
global_step = tf.train.get_or_create_global_step()
learning_rate = tf.train.exponential_decay(
learning_rate=0.1,
global_step=global_step,
decay_steps=2,
decay_rate=0.99)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss, global_step=global_step)
```
We conclude with some housekeeping tasks. We must tell TF that all variables are initialized. We also create handles to our TF variables so we can `print` their values at each iteration of the procedure.
```
# Initialize all variables.
init_op = tf.initialize_all_variables()
# Grab variable handles for diagnostic purposes.
with tf.variable_scope('make_weights_prior', reuse=True):
prior_scale = fwd_scale_transform(tf.get_variable(
name='raw_prior_scale', dtype=dtype))
with tf.variable_scope('make_log_radon_likelihood', reuse=True):
likelihood_scale = fwd_scale_transform(tf.get_variable(
name='raw_likelihood_scale', dtype=dtype))
fixed_effect_weights = tf.get_variable(
name='fixed_effect_weights', dtype=dtype)
```
### 6.3 Execute
In this section we execute our SAEM TF graph. The main trick here is to feed our last draw from the HMC kernel into the next iteration. This is achieved through our use of `feed_dict` in the `sess.run` call.
```
init_op.run()
w_ = np.zeros([len(log_county_uranium_ppm)], dtype=dtype)
%%time
maxiter = int(1500)
num_accepted = 0
num_drawn = 0
for i in range(maxiter):
[
_,
global_step_,
loss_,
posterior_random_weights_,
kernel_results_,
step_size_,
prior_scale_,
likelihood_scale_,
fixed_effect_weights_,
] = sess.run([
train_op,
global_step,
loss,
posterior_random_weights,
kernel_results,
step_size,
prior_scale,
likelihood_scale,
fixed_effect_weights,
], feed_dict={init_random_weights: w_})
w_ = posterior_random_weights_[-1, :]
num_accepted += kernel_results_.is_accepted.sum()
num_drawn += kernel_results_.is_accepted.size
acceptance_rate = num_accepted / num_drawn
if i % 100 == 0 or i == maxiter - 1:
print('global_step:{:>4} loss:{: 9.3f} acceptance:{:.4f} '
'step_size:{:.4f} prior_scale:{:.4f} likelihood_scale:{:.4f} '
'fixed_effect_weights:{}'.format(
global_step_, loss_.mean(), acceptance_rate, step_size_,
prior_scale_, likelihood_scale_, fixed_effect_weights_))
```
Looks like after ~1500 steps, our estimates of the parameters have stabilized.
### 6.4 Results
Now that we've fit the parameters, let's generate a large number of posterior samples and study the results.
```
%%time
posterior_random_weights_final, kernel_results_final = tfp.mcmc.sample_chain(
num_results=int(15e3),
num_burnin_steps=int(1e3),
current_state=init_random_weights,
kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_posterior_log_prob,
num_leapfrog_steps=2,
step_size=step_size))
[
posterior_random_weights_final_,
kernel_results_final_,
] = sess.run([
posterior_random_weights_final,
kernel_results_final,
], feed_dict={init_random_weights: w_})
print('prior_scale: ', prior_scale_)
print('likelihood_scale: ', likelihood_scale_)
print('fixed_effect_weights: ', fixed_effect_weights_)
print('acceptance rate final: ', kernel_results_final_.is_accepted.mean())
```
We now construct a box and whisker diagram of the $\beta_c \log(\text{UraniumPPM}_c)$ random-effect. We'll order the random-effects by decreasing county frequency.
```
x = posterior_random_weights_final_ * log_county_uranium_ppm
I = county_freq[:, 0]
x = x[:, I]
cols = np.array(county_name)[I]
pw = pd.DataFrame(x)
pw.columns = cols
fig, ax = plt.subplots(figsize=(25, 4))
ax = pw.boxplot(rot=80, vert=True);
```
From this box and whisker diagram, we observe that the variance of the county-level $\log(\text{UraniumPPM})$ random-effect increases as the county is less represented in the dataset. Intutively this makes sense--we should be less certain about the impact of a certain county if we have less evidence for it.
## 7 Side-by-Side-by-Side Comparison
We now compare the results of all three procedures. To do this, we will compute non-parameteric estimates of the posterior samples as generated by Stan and TFP. We will also compare against the parameteric (approximate) estimates produced by R's `lme4` package.
The following plot depicts the posterior distribution of each weight for each county in Minnesota. We show results for Stan (red), TFP (blue), and R's `lme4` (orange). We shade results from Stan and TFP thus expect to see purple when the two agree. For simplicity we do not shade results from R. Each subplot represents a single county and are ordered in descending frequency in raster scan order (i.e., from left-to-right then top-to-bottom).
```
nrows = 17
ncols = 5
fig, ax = plt.subplots(nrows, ncols, figsize=(18, 21), sharey=True, sharex=True)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ii = -1
for r in range(nrows):
for c in range(ncols):
ii += 1
idx = county_freq[ii, 0]
sns.kdeplot(
posterior_random_weights_final_[:, idx] * log_county_uranium_ppm[idx],
color='blue',
alpha=.3,
shade=True,
label='TFP',
ax=ax[r][c])
sns.kdeplot(
posterior_random_weights_final_stan[:, idx] *
log_county_uranium_ppm[idx],
color='red',
alpha=.3,
shade=True,
label='Stan/rstanarm',
ax=ax[r][c])
sns.kdeplot(
posterior_random_weights_lme4_final_[:, idx] *
log_county_uranium_ppm[idx],
color='#F4B400',
alpha=.7,
shade=False,
label='R/lme4',
ax=ax[r][c])
ax[r][c].vlines(
posterior_random_weights_lme4[idx] * log_county_uranium_ppm[idx],
0,
5,
color='#F4B400',
linestyle='--')
ax[r][c].set_title(county_name[idx] + ' ({})'.format(idx), y=.7)
ax[r][c].set_ylim(0, 5)
ax[r][c].set_xlim(-1., 1.)
ax[r][c].get_yaxis().set_visible(False)
if ii == 2:
ax[r][c].legend(bbox_to_anchor=(1.4, 1.7), fontsize=20, ncol=3)
else:
ax[r][c].legend_.remove()
fig.subplots_adjust(wspace=0.03, hspace=0.1)
```
## 8 Conclusion
In this colab we fit a linear mixed-effect regression model to the radon dataset. We tried three different software packages: R, Stan, and TensorFlow Probability. We concluded by plotting the 85 posterior distributions as computed by the three different software packages.
## Appendix A: Alternative Radon HLM (Add Random Intercept)
In this section we describe an alternative HLM which also has a random intercept associated with each county.
$$\begin{align*}
\text{for } & c=1\ldots \text{NumCounties}:\\
& \beta_c \sim \text{MultivariateNormal}\left(\text{loc}=\left[ \begin{array}{c} 0 \\ 0 \end{array}\right] , \text{scale}=\left[\begin{array}{cc} \sigma_{11} & 0 \\ \sigma_{12} & \sigma_{22} \end{array}\right] \right) \\
\text{for } & i=1\ldots \text{NumSamples}:\\
& c_i := \text{County}_i \\
&\eta_i = \underbrace{\omega_0 + \omega_1\text{Floor}_i \vphantom{\log( \text{CountyUraniumPPM}_{c_i}))}}_{\text{fixed effects}} + \underbrace{\beta_{c_i,0} + \beta_{c_i,1}\log( \text{CountyUraniumPPM}_{c_i}))}_{\text{random effects}} \\
&\log(\text{Radon}_i) \sim \text{Normal}(\text{loc}=\eta_i , \text{scale}=\sigma)
\end{align*}$$
In R's `lme4` "tilde notation", this model is equivalent to:
> `log_radon ~ 1 + floor + (1 + log_county_uranium_ppm | county)`
## Appendix B: Generalized Linear Mixed-Effect Models
In this section we give a more general characterization of Hierarchical Linear Models than what is used in the main body. This more general model is known as a [generalized linear mixed-effect model](https://en.wikipedia.org/wiki/Generalized_linear_mixed_model) (GLMM).
GLMMs are generalizations of [generalized linear models](https://en.wikipedia.org/wiki/Generalized_linear_model) (GLMs). GLMMs extend GLMs by incorporating sample specific random noise into the predicted linear response. This is useful in part because it allows rarely seen features to share information with more commonly seen features.
As a generative process, a Generalized Linear Mixed-effects Model (GLMM) is characterized by:
\begin{align}
\text{for } & r = 1\ldots R: \hspace{2.45cm}\text{# for each random-effect group}\\
&\begin{aligned}
\text{for } &c = 1\ldots |C_r|: \hspace{1.3cm}\text{# for each category ("level") of group $r$}\\
&\begin{aligned}
\beta_{rc}
&\sim \text{MultivariateNormal}(\text{loc}=0_{D_r}, \text{scale}=\Sigma_r^{1/2})
\end{aligned}
\end{aligned}\\\\
\text{for } & i = 1 \ldots N: \hspace{2.45cm}\text{# for each sample}\\
&\begin{aligned}
&\eta_i = \underbrace{\vphantom{\sum_{r=1}^R}x_i^\top\omega}_\text{fixed effects} + \underbrace{\sum_{r=1}^R z_{r,i}^\top \beta_{r,C_r(i) }}_\text{random effects} \\
&Y_i|x_i,\omega,\{z_{r,i} , \beta_r\}_{r=1}^R \sim \text{Distribution}(\text{mean}= g^{-1}(\eta_i))
\end{aligned}
\end{align}
where:
\begin{align}
R &= \text{number of random-effect groups}\\
|C_r| &= \text{number of categories for group $r$}\\
N &= \text{number of training samples}\\
x_i,\omega &\in \mathbb{R}^{D_0}\\
D_0 &= \text{number of fixed-effects}\\
C_r(i) &= \text{category (under group $r$) of the $i$th sample}\\
z_{r,i} &\in \mathbb{R}^{D_r}\\
D_r &= \text{number of random-effects associated with group $r$}\\
\Sigma_{r} &\in \{S\in\mathbb{R}^{D_r \times D_r} : S \succ 0 \}\\
\eta_i\mapsto g^{-1}(\eta_i) &= \mu_i, \text{inverse link function}\\
\text{Distribution} &=\text{some distribution parameterizable solely by its mean}
\end{align}
In words, this says that every category of each group is associated with an iid MVN, $\beta_{rc}$. Although the $\beta_{rc}$ draws are always independent, they are only indentically distributed for a group $r$; notice there is exactly one $\Sigma_r$ for each $r\in\{1,\ldots,R\}$.
When affinely combined with a sample's group's features, $z_{r,i}$, the result is sample-specific noise on the $i$-th predicted linear response (which is otherwise $x_i^\top\omega$).
When we estimate $\{\Sigma_r:r\in\{1,\ldots,R\}\}$ we're essentially estimating the amount of noise a random-effect group carries which would otherwise drown out the signal present in $x_i^\top\omega$.
There are a variety of options for the $\text{Distribution}$ and [inverse link function](https://en.wikipedia.org/wiki/Generalized_linear_model#Link_function), $g^{-1}$. Common choices are:
- $Y_i\sim\text{Normal}(\text{mean}=\eta_i, \text{scale}=\sigma)$,
- $Y_i\sim\text{Binomial}(\text{mean}=n_i \cdot \text{sigmoid}(\eta_i), \text{total_count}=n_i)$, and,
- $Y_i\sim\text{Poisson}(\text{mean}=\exp(\eta_i))$.
For more possibilities, see the [`tfp.glm`](https://github.com/tensorflow/probability/tree/master/tensorflow_probability/python/glm) module.
| github_jupyter |
```
%pylab inline
rcParams['savefig.dpi']=100
from scipy import stats
chisq=stats.chi2(1)
fig,ax=subplots()
xi = np.linspace(0.01,10,100)
ax.plot(xi,chisq.pdf(xi),color='k',lw=2)
ax.axis(ymax=1)
ax.set_xlabel('$x$',fontsize=18)
ax.set_ylabel('$f_x(x)$',fontsize=22)
ax.set_title(r'$\chi_1^2$ Probability Density',fontsize=18,fontdict={'family':'serif'})
fig.savefig('../fig-probability/ProbabilityInequalities_001.png')
fig,ax=subplots()
ax.plot(xi,1-chisq.cdf(xi),label=r'$\mathbb{P}(X>\epsilon)$',color='k',linestyle='-',lw=3)
ax.plot(xi,1/xi,label=r'$\mathbb{E}(X)/\epsilon$',lw=3,color='k',ls='--')
ax.fill_between(xi,1-chisq.cdf(xi),1/xi,color='gray',alpha=.3)
ax.axis(ymax=.5)
ax.set_xlabel('$\epsilon$',fontsize=18)
ax.legend(fontsize=18)
ax.set_title("Markov's Inequality",fontsize=18)
fig.savefig('../fig-probability/ProbabilityInequalities_002.png')
chisq.mean()
from scipy.integrate import quad
rv = stats.chi2(1)
# from sympy import init_printing;init_printing()
import sympy
from sympy import stats as ss
t = sympy.symbols('t',real=True,positive=True)
# z = sympy.symbols('z',real=True,positive=True)
x=ss.ChiSquared('x',1)
# v=ss.P((x-1) > t,x>1)+ss.P(-(x-1) > t,x<1)
w=(1-ss.cdf(x)(t+1))+ ss.cdf(x)(1-t)
fig,ax=subplots()
fw=sympy.lambdify(t,w)
ti = np.linspace(.01,5)
fvals = map(fw,ti)
ax.plot(ti,fvals,'k',lw=3,label=r'$\mathbb{P}(\vert X-\mu\vert > \epsilon)$')
ax.plot(ti,4/ti**2,'k--',lw=3,label=r'$\sigma^2/\epsilon^2$')
ax.fill_between(ti,fvals,4/ti**2,color='gray',alpha=.3)
ax.axis(ymax=1)
ax.set_xlabel('$\epsilon$',fontsize=18)
ax.set_title("Chebyshev's Inequality")
ax.legend(fontsize=16)
fig.savefig('../fig-probability/ProbabilityInequalities_003.png',dpi=100)
%qtconsole
# from sympy.interactive import printing
# printing.init_printing(use_latex=True)
from IPython.display import Math
Math(sympy.latex(w))
Math(sympy.latex(ss.cdf(x)(t)))
```
## Hoeffding’s Inequality
```
from scipy.integrate import quad
from scipy.interpolate import interp1d
def pdf(n=3,m=20):
u = np.ones(m)
fv=reduce(lambda i,j:np.convolve(i,j),[u,]*n,u)
xv = np.linspace(0,n,len(fv))
norm = (xv[1]-xv[0])*sum(fv)
xv = xv-np.mean(xv)
return interp1d(xv,fv/norm,fill_value=0,bounds_error=False)
f3=pdf(5)
apdf=interp1d(f3.x[f3.x>=0],f3.y[f3.x>=0]*2,fill_value=0,bounds_error=False)
ti = linspace(0.01,f3.x.max(),50)
plot(f3.x,f3.y,'-')
fig,ax=subplots()
vals = map(lambda t:quad(apdf,t,100)[0],ti)
ax.plot(ti,vals,'-k',label=r'$\mathbb{P}(\vert \overline{X}_n-1/2\vert \geq \epsilon)$',lw=3)
ax.plot(ti,2*np.exp(-2*ti**2),label='Hoeffding',color='k',ls='--',lw=3)
ax.fill_between(ti,vals,2*np.exp(-2*ti**2),color='gray',alpha=0.3)
ax.plot(ti,0.52/ti,label='Markov',color='k',ls=':')
ax.legend(loc=0,fontsize=12)
ax.axis(ymax=2)
ax.set_xlabel('$\epsilon$',fontsize=18)
fig.savefig('../fig-probability/ProbabilityInequalities_004.png',dpi=100)
```
| github_jupyter |
# sympy [1] - Symbolic Python
https://docs.sympy.org/latest/index.html
https://github.com/sympy/sympy/wiki
1. Meurer A, Smith CP, Paprocki M, Čertík O, Kirpichev SB, Rocklin M, Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE, Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry MJ, Terrel AR, Roučka Š, Saboo A, Fernando I, Kulal S, Cimrman R, Scopatz A. (2017) sympy: symbolic computing in Python. PeerJ Computer Science 3:e103 https://doi.org/10.7717/peerj-cs.103
<!-- @article{10.7717/peerj-cs.103,
title = {sympy: symbolic computing in Python},
author = {Meurer, Aaron and Smith, Christopher P. and Paprocki, Mateusz and \v{C}ert\'{i}k, Ond\v{r}ej and Kirpichev, Sergey B. and Rocklin, Matthew and Kumar, AMiT and Ivanov, Sergiu and Moore, Jason K. and Singh, Sartaj and Rathnayake, Thilina and Vig, Sean and Granger, Brian E. and Muller, Richard P. and Bonazzi, Francesco and Gupta, Harsh and Vats, Shivam and Johansson, Fredrik and Pedregosa, Fabian and Curry, Matthew J. and Terrel, Andy R. and Rou\v{c}ka, \v{S}t\v{e}p\'{a}n and Saboo, Ashutosh and Fernando, Isuru and Kulal, Sumith and Cimrman, Robert and Scopatz, Anthony},
year = 2017,
month = jan,
keywords = {Python, Computer algebra system, Symbolics},
abstract = {
sympy is an open source computer algebra system written in pure Python. It is built with a focus on extensibility and ease of use, through both interactive and programmatic applications. These characteristics have led sympy to become a popular symbolic library for the scientific Python ecosystem. This paper presents the architecture of sympy, a description of its features, and a discussion of select submodules. The supplementary material provide additional examples and further outline details of the architecture and features of sympy.
},
volume = 3,
pages = {e103},
journal = {PeerJ Computer Science},
issn = {2376-5992},
url = {https://doi.org/10.7717/peerj-cs.103},
doi = {10.7717/peerj-cs.103}
} -->
```
import sympy
```
## Number representation
```
sympy.sqrt(7)
sympy.Float(9/4)
sympy.Integer(9/4) ## drops the fractional part
sympy.Rational(9/4)
```
## Defining variables (i.e. symbols)
```
x, y, z, t = sympy.symbols('x y z t')
```
## Expresssions
- can type them directly into the cell:
```
x**2+3*x+2
type(x**2+3*x+2)
```
- alternatively, `sympify` will converts a string to a sympy function
```
function_string = 'x**2+3*x+2'
function_string
## Equivalent statement
# function_sympy = sympy.sympify('x**2+3*x+2')
function_sympy = sympy.sympify(function_string, evaluate=False)
function_sympy
```
Let's prove that it took a string and converted it to a sympy object:
```
print(type(function_string))
print(type(function_sympy))
sympy.sympify("2/3 + 1/6", evaluate=False)
```
`simpify` also attempts to simplify a provided forumla:
```
sympy.sympify("2/3 + 1/6", evaluate=True)
```
Also does so for equations with variables.
```
sympy.sympify("(1 + x)*(2 + x**2)*(2 + x**2)*(2 + x**2)", evaluate=False)
```
Let' go back and see what `Rational` would do with $\frac{2}{3} + \frac{1}{6}$:
```
sympy.Rational(2/3 + 1/6)
```
This looks complicated, but it is just the manner tha sympy stores the resulting number:
```
print(3752999689475413/4503599627370496)
print(5/6)
```
#### Evaluate an expression or function
Convert a sympy expressions to a float
The following two are equivalent:
- `evalf()`
- `sympy.N()`
```
test_func = sympy.sqrt(7)*sympy.pi
test_func
test_func.evalf()
sympy.N(test_func)
```
Returning to our fraction above, we could get float value via:
```
sympy.sympify("2/3 + 1/6").evalf()
```
## Polynomials
sympy can also create and work with polynomials.
Recall: 2nd Degree Polynomial (Three coefficients: [M, N, O] --> $Mx^2 + Nx + O$)
One can do this using two approaches, which result in two different object types:
1. A sympy "expression"
1. A sympy Poly
##### Approach 1
Using a sympy "expresssion"
```
polynomial_simple_expr = -4*x**2 + 1*x -2
polynomial_simple_expr
type(polynomial_simple_expr)
```
##### Approach 2
Using sympy's `Poly` function (https://docs.sympy.org/latest/modules/polys/reference.html)
- Efficiently transform an expression into a polynomial
```
polynomial_simple_poly = sympy.Poly(-4*x**2 + 1*x -2)
polynomial_simple_poly
type(polynomial_simple_poly)
```
One can also create a polynomial by providing a list of **ALL** of the coefficients (including those that might be zero).
```
polynomial_simple_poly = sympy.Poly.from_list([-4, 1, -2], x)
polynomial_simple_poly
```
Print the degree:
- of a sympy expression
```
sympy.degree(polynomial_simple_expr)
```
- of a sympy `Poly`
```
sympy.degree(polynomial_simple_poly)
```
#### Evaluating Polynomials
- Use `subs` to substitute values (https://docs.sympy.org/latest/tutorial/basic_operations.html)
- `subs` works for both
- expressions (e.g. sympy.core.add.Add, sympy.core.power.Pow)
- `Poly` (i.e. sympy.polys.polytools.Poly)
##### Evaluating a Single Variable Polynomial
- expression
```
polynomial_simple_expr.subs(x, 2)
```
- Poly
```
polynomial_simple_poly.subs(x, 2)
```
##### Evaluating a Multiple Variable Polynomial
- Using `subs` pass a
- list of tuples
- dictionary
```
polynomial_multi_expr = x**2 + x*y + 3
polynomial_multi_expr
```
**Approach 1**: Substitute the two variables by providing a list:
```
polynomial_multi_expr.subs([(x, 3), (y, 2)])
type(polynomial_multi_expr.subs([(x, 3), (y, 2)]))
```
**Approach 2**: SSubstitute the two variables by providing a dictionary:
```
polynomial_multi_expr.subs({x: 3, y: 2})
```
To obtain a float, use `evalf` (https://docs.sympy.org/latest/modules/evalf.html)
Important: the variable values are passed as a dictionary (i.e. lists don't work as they did for `subs`).
```
polynomial_multi_expr.evalf(subs = {x: 3, y: 2})
type(polynomial_multi_expr.evalf(subs = {x: 3, y: 2}))
```
### Expanding a polynomial
Notice: we are not specifying a Poly object.
```
polynomial_expr = (-4*x**2 + 1*x - 2)**2
polynomial_expr
polynomial_expr.expand()
polynomial_expr
```
sympy `Poly` will expand it automatically:
```
polynomial_poly = sympy.Poly((-4*x**2 + 1*x - 2)**2)
polynomial_poly
```
### Factor a polynomial
```
polynomial_expr = (16*x**4 - 8*x**3 + 17*x**2 - 4*x + 4).factor()
polynomial_expr
type(polynomial_expr)
```
Notice this does not work for sympy Poly:
```
# sympy.Poly((-4*x**2 + 1*x - 2)**2).fractor()
polynomial_poly.factor()
```
### Math with Polynomials
#### Multiply two polynomials together
Expression
```
polynomial_simple_expr
polynomial_simple_expr * polynomial_simple_expr
```
sympy `Poly`
```
polynomial_simple_poly
polynomial_simple_poly * polynomial_simple_poly
```
Recall: `Poly` automatically expands the polynomials.
#### Calculus
#### Taking Derivatives
-`diff()` (https://docs.sympy.org/latest/modules/core.html?highlight=diff#sympy.core.function.diff)
**First derivative** (noted as $f'(x)$ or as $\frac{df}{dx}$, which is the same as $\frac{d}{dx}f$)
Taking the first derivative of a function (e.g. f(x)) tells us:
1. if the function at a given point (ie. x) is increasing or decreasing (i.e. the **direction of change**), and
1. by how much it is increasing or decreasing (i.e. **a rate**)
##### sympy Expressions
```
polynomial_expr = 2 * x**3 + 1
polynomial_expr
```
**Approach 1**
```
sympy.diff(polynomial_expr, x, 1)
```
**Approach 2**
```
polynomial_expr.diff(x)
polynomial_expr.diff(x, 1)
```
##### sympy `Poly`
```
polynomial_poly = sympy.poly(2 * x**3 + 1)
polynomial_poly
```
**Approach 1**
```
polynomial_poly.diff(x)
```
**Approach 2**
```
sympy.diff(polynomial_poly, x)
```
**Note**: that `sympy.diff(polynomial_poly, x, 1)` or `polynomial_poly.diff(x, 1)` does not work for a sympy poly object, as it did using the sympy expression above.
Therefore, it is generally better to have your **functions as sympy expressions** if you plan to preforms some **calculus** on them.
**Second derivative** (noted as $f''(x)$ or as $\frac{d^2f}{dx}$)
Taking the second derivative of a function (e.g. f(x)) tells us:
1. the **shape** of the curve at a specified point (i.e. x)
- **postive** value: the curve is **convex**
- **negative** value: the curve is **concave**
```
polynomial_expr.diff(x, x)
polynomial_expr.diff(x, 2)
sympy.diff(polynomial_expr, x, 2)
```
##### Derivative of Multiple Variable Functions
```
polynomial_multi_expr
```
1st derivative with respect to x:
```
sympy.diff(polynomial_multi_expr, x, 1)
```
1st derivative with respect to y:
```
sympy.diff(polynomial_multi_expr, y, 1)
```
2nd-order mixed derivatives:
Derivative with respect to x **and then** to y:
- i.e. $\frac{d}{dy}(\frac{df}{dx})$
$f(x) = x^2 + xy + 3$
$f'(x) = \frac{df}{dx} = \frac{d}{dx}(x^2 + xy + 3) = 2x + y$
$\frac{df'(x)}{dy} = \frac{d}{dy}(2x + y) = 1$
```
sympy.diff(polynomial_multi_expr, x, y)
```
### Integration
The integral of a function (e.g. f(x)) tells us:
1. the area that resides under the function (e.g. the amount of water in a curve shaped pool).
#### Indefinite integral (i.e. without limits/bounds)
$\int (2x^3+1) \,dx = \frac{x^4}{2} + 1x$
(recall: if you take the derivative of the result, you will get the input)
**Approaches 1**
- sympy expression
- sympy Poly
```
polynomial_expr
sympy.integrate(polynomial_expr, x)
sympy.integrate(polynomial_poly, x)
```
**Approaches 2**
- sympy expression
- sympy Poly
```
polynomial_expr.integrate(x)
polynomial_poly.integrate(x)
```
#### Definate integral (i.e. evaluated between two boundary conditions)
$\int_1^2 (2x^3+1) \,dx = \frac{x^4}{2} + 1x$
Notice: the tuple being passed (i.e. `(x, 1, 2)`)
```
sympy.integrate(polynomial_expr, (x, 1, 2))
polynomial_expr.integrate((x, 1, 2))
```
This is where I personally find some of the logic/consistency breaking down in sympy. It seems like `sympy.integrate` only works with expresssions.
```
sympy.integrate(polynomial_poly, (x, 1, 2))
```
## Visualizing functions (i.e. plotting)
- backend: matplotlib
Plot a function (i.e. f(x)) by its single variable
(doing something like f(x,y) would require a 2D plot)
```
sympy.plot(x**2 + 20)
```
Change the x-axis range:
```
sympy.plot(x**2 + 20, (x, -2, 2))
function = x**4
plot_func = sympy.plot(function)
plot_der1 = sympy.plot(sympy.diff(function, x, 1))
plot_der2 = sympy.plot(sympy.diff(function, x, 2))
```
## Solving equations
- Finding the "roots" of the equation (i.e. what the variable values are that sets the equation to zero).
Equation:
$x^2 = 4$
Rearrange:
$x^2 -4 = 0$
Solve:
Solutions are
1. x = 2
1. x = -2
```
solutions = sympy.solve(x**2 - 4)
solutions
solutions[0]
```
### Misc sympy functions
Lambdify: https://docs.sympy.org/latest/modules/utilities/lambdify.html
- transforms a sympy expression to a lambda function that can be used to evaluate (solve) equations
- https://docs.python.org/3/reference/expressions.html#lambda
Examples of lambda functions
- `lambda x: x+x`
- `lambda a, b: a+b`
And you can directly evaluate a lambda function:
```
(lambda x: x*2)(12)
function = x**2
derivative_function = function.diff(x)
derivative_function
f1 = sympy.lambdify(x, derivative_function)
f1(3)
multi_var_func = (x**2 + y**3 + z**4)
```
List the variables
```
multi_var_func.free_symbols
```
To evaluate the function for when x=1, y=2 and z=3 and return an regular Python `int` type:
```
f = sympy.lambdify([x, y, z], multi_var_func)
f(1, 2, 3)
type(f(1, 2, 3))
```
You can also evalute the function to return a `sympy.core.numbers.Integer` type:
```
multi_var_func.subs([(x, 1), (y, 2), (z, 3)])
type(multi_var_func.subs([(x, 1), (y, 2), (z, 3)]))
```
To obtain a `sympy.core.numbers.Float`:
```
multi_var_func.evalf(subs = {x: 1, y: 2, z: 3})
type(multi_var_func.evalf(subs = {x: 1, y: 2, z: 3}))
```
## Unit Conversions with sympy
```
from sympy.physics.units import convert_to
from sympy.physics.units import speed_of_light
from sympy.physics.units import kilometer, meter, centimeter, millimeter
from sympy.physics.units import second, minute, hour
speed_of_light
speed_of_light.evalf()
```
To obtain a value, you must specify the desired units:
```
convert_to(speed_of_light, [meter, minute])
convert_to(speed_of_light, [millimeter, hour])
#help(sympy.physics.units)
```
#### Constants built into sympy
1. A: ampere
1. Bq: becquerel
1. C: coulomb
1. D: dioptre
1. F: farad
1. G: gravitational_constant
1. Gy: gray
1. H: henry
1. Hz: hertz
1. J: joule
1. K: kelvin
1. N: newton
1. Pa: pascal
1. R: molar_gas_constant
1. S: siemens
1. T: tesla
1. V: volt
1. W: watt
1. Wb: weber
1. Z0: vacuum_impedance
1. __all__: ['Dimension', 'DimensionSystem', 'UnitSystem', 'convert_to',...
1. acceleration: Dimension(acceleration)
1. acceleration_due_to_gravity: acceleration_due_to_gravity
1. action: Dimension(action, A)
1. amount: Dimension(amount_of_substance)
1. amount_of_substance: Dimension(amount_of_substance)
1. ampere: ampere
1. amperes: ampere
1. amu: atomic_mass_constant
1. amus: atomic_mass_constant
1. angular_mil: angular_mil
1. angular_mils: angular_mil
1. anomalistic_year: anomalistic_year
1. anomalistic_years: anomalistic_year
1. astronomical_unit: astronomical_unit
1. astronomical_units: astronomical_unit
1. atm: atmosphere
1. atmosphere: atmosphere
1. atmospheres: atmosphere
1. atomic_mass_constant: atomic_mass_constant
1. atomic_mass_unit: atomic_mass_constant
1. atto: Prefix('atto', 'a', -18)
1. au: astronomical_unit
1. avogadro: avogadro_constant
1. avogadro_constant: avogadro_constant
1. avogadro_number: avogadro_number
1. bar: bar
1. bars: bar
1. becquerel: becquerel
1. bit: bit
1. bits: bit
1. boltzmann: boltzmann_constant
1. boltzmann_constant: boltzmann_constant
1. byte: byte
1. c: speed_of_light
1. candela: candela
1. candelas: candela
1. capacitance: Dimension(capacitance)
1. cd: candela
1. centi: Prefix('centi', 'c', -2)
1. centiliter: centiliter
1. centiliters: centiliter
1. centimeter: centimeter
1. centimeters: centimeter
1. charge: Dimension(charge, Q)
1. cl: centiliter
1. cm: centimeter
1. common_year: common_year
1. common_years: common_year
1. conductance: Dimension(conductance, G)
1. coulomb: coulomb
1. coulomb_constant: coulomb_constant
1. coulombs: coulomb
1. current: Dimension(current, I)
1. dHg0: 13.5951
1. day: day
1. days: day
1. deca: Prefix('deca', 'da', 1)
1. deci: Prefix('deci', 'd', -1)
1. deciliter: deciliter
1. deciliters: deciliter
1. decimeter: decimeter
1. decimeters: decimeter
1. deg: degree
1. degree: degree
1. degrees: degree
1. dioptre: dioptre
1. dl: deciliter
1. dm: decimeter
1. draconic_year: draconic_year
1. draconic_years: draconic_year
1. e0: vacuum_permittivity
1. eV: electronvolt
1. electric_constant: vacuum_permittivity
1. electric_force_constant: coulomb_constant
1. electronvolt: electronvolt
1. electronvolts: electronvolt
1. elementary_charge: elementary_charge
1. energy: Dimension(energy, E)
1. exa: Prefix('exa', 'E', 18)
1. exbi: Prefix('exbi', 'Y', 60, 2)
1. exbibyte: exbibyte
1. exbibytes: exbibyte
1. farad: farad
1. faraday_constant: faraday_constant
1. farads: farad
1. feet: foot
1. femto: Prefix('femto', 'f', -15)
1. foot: foot
1. force: Dimension(force, F)
1. frequency: Dimension(frequency, f)
1. ft: foot
1. full_moon_cycle: full_moon_cycle
1. full_moon_cycles: full_moon_cycle
1. g: gram
1. gaussian_year: gaussian_year
1. gaussian_years: gaussian_year
1. gee: acceleration_due_to_gravity
1. gees: acceleration_due_to_gravity
1. gibi: Prefix('gibi', 'Y', 30, 2)
1. gibibyte: gibibyte
1. gibibytes: gibibyte
1. giga: Prefix('giga', 'G', 9)
1. gram: gram
1. grams: gram
1. gravitational_constant: gravitational_constant
1. gray: gray
1. h: hour
1. hbar: hbar
1. hecto: Prefix('hecto', 'h', 2)
1. henry: henry
1. henrys: henry
1. hertz: hertz
1. hour: hour
1. hours: hour
1. hz: hertz
1. impedance: Dimension(impedance, Z)
1. inch: inch
1. inches: inch
1. inductance: Dimension(inductance)
1. josephson_constant: josephson_constant
1. joule: joule
1. joules: joule
1. julian_year: julian_year
1. julian_years: julian_year
1. kPa: kilopascal
1. kat: katal
1. katal: katal
1. kelvin: kelvin
1. kelvins: kelvin
1. kg: kilogram
1. kibi: Prefix('kibi', 'Y', 10, 2)
1. kibibyte: kibibyte
1. kibibytes: kibibyte
1. kilo: Prefix('kilo', 'k', 3)
1. kilogram: kilogram
1. kilograms: kilogram
1. kilometer: kilometer
1. kilometers: kilometer
1. km: kilometer
1. l: liter
1. length: Dimension(length, L)
1. lightyear: lightyear
1. lightyears: lightyear
1. liter: liter
1. liters: liter
1. luminosity: Dimension(luminous_intensity)
1. luminous_intensity: Dimension(luminous_intensity)
1. lux: lux
1. lx: lux
1. ly: lightyear
1. m: meter
1. magnetic_constant: magnetic_constant
1. magnetic_density: Dimension(magnetic_density, B)
1. magnetic_flux: Dimension(magnetic_flux)
1. magnetic_flux_density: Dimension(magnetic_density, B)
1. mass: Dimension(mass, M)
1. mebi: Prefix('mebi', 'Y', 20, 2)
1. mebibyte: mebibyte
1. mebibytes: mebibyte
1. mega: Prefix('mega', 'M', 6)
1. meter: meter
1. meters: meter
1. mg: milligram
1. mho: siemens
1. mhos: siemens
1. mi: mile
1. micro: Prefix('micro', 'mu', -6)
1. microgram: microgram
1. micrograms: microgram
1. micrometer: micrometer
1. micrometers: micrometer
1. micron: micrometer
1. microns: micrometer
1. microsecond: microsecond
1. microseconds: microsecond
1. mil: angular_mil
1. mile: mile
1. miles: mile
1. milli: Prefix('milli', 'm', -3)
1. milli_mass_unit: milli_mass_unit
1. milligram: milligram
1. milligrams: milligram
1. milliliter: milliliter
1. milliliters: milliliter
1. millimeter: millimeter
1. millimeters: millimeter
1. millisecond: millisecond
1. milliseconds: millisecond
1. minute: minute
1. minutes: minute
1. ml: milliliter
1. mm: millimeter
1. mmHg: mmHg
1. mmu: milli_mass_unit
1. mmus: milli_mass_unit
1. mol: mole
1. molar_gas_constant: molar_gas_constant
1. mole: mole
1. moles: mole
1. momentum: Dimension(momentum)
1. ms: millisecond
1. nano: Prefix('nano', 'n', -9)
1. nanometer: nanometer
1. nanometers: nanometer
1. nanosecond: nanosecond
1. nanoseconds: nanosecond
1. nautical_mile: nautical_mile
1. nautical_miles: nautical_mile
1. newton: newton
1. newtons: newton
1. nm: nanometer
1. nmi: nautical_mile
1. ns: nanosecond
1. ohm: ohm
1. ohms: ohm
1. optical_power: dioptre
1. pa: pascal
1. pascal: pascal
1. pascals: pascal
1. pebi: Prefix('pebi', 'Y', 50, 2)
1. pebibyte: pebibyte
1. pebibytes: pebibyte
1. percent: percent
1. percents: percent
1. permille: permille
1. peta: Prefix('peta', 'P', 15)
1. pico: Prefix('pico', 'p', -12)
1. picometer: picometer
1. picometers: picometer
1. picosecond: picosecond
1. picoseconds: picosecond
1. planck: planck
1. planck_acceleration: planck_acceleration
1. planck_angular_frequency: planck_angular_frequency
1. planck_area: planck_area
1. planck_charge: planck_charge
1. planck_current: planck_current
1. planck_density: planck_density
1. planck_energy: planck_energy
1. planck_energy_density: planck_energy_density
1. planck_force: planck_force
1. planck_impedance: planck_impedance
1. planck_intensity: planck_intensity
1. planck_length: planck_length
1. planck_mass: planck_mass
1. planck_momentum: planck_momentum
1. planck_power: planck_power
1. planck_pressure: planck_pressure
1. planck_temperature: planck_temperature
1. planck_time: planck_time
1. planck_voltage: planck_voltage
1. planck_volume: planck_volume
1. pm: picometer
1. pound: pound
1. pounds: pound
1. power: Dimension(power)
1. pressure: Dimension(pressure)
1. ps: picosecond
1. psi: psi
1. quart: quart
1. quarts: quart
1. rad: radian
1. radian: radian
1. radians: radian
1. s: second
1. second: second
1. seconds: second
1. sidereal_year: sidereal_year
1. sidereal_years: sidereal_year
1. siemens: siemens
1. speed: Dimension(velocity)
1. speed_of_light: speed_of_light
1. sr: steradian
1. stefan: stefan_boltzmann_constant
1. stefan_boltzmann_constant: stefan_boltzmann_constant
1. steradian: steradian
1. steradians: steradian
1. tebi: Prefix('tebi', 'Y', 40, 2)
1. tebibyte: tebibyte
1. tebibytes: tebibyte
1. temperature: Dimension(temperature, T)
1. tera: Prefix('tera', 'T', 12)
1. tesla: tesla
1. teslas: tesla
1. time: Dimension(time, T)
1. torr: mmHg
1. tropical_year: tropical_year
1. tropical_years: tropical_year
1. u0: magnetic_constant
1. ug: microgram
1. um: micrometer
1. us: microsecond
1. v: volt
1. vacuum_impedance: vacuum_impedance
1. vacuum_permeability: magnetic_constant
1. vacuum_permittivity: vacuum_permittivity
1. velocity: Dimension(velocity)
1. volt: volt
1. voltage: Dimension(voltage, U)
1. volts: volt
1. volume: Dimension(volume)
1. von_klitzing_constant: von_klitzing_constant
1. watt: watt
1. watts: watt
1. wb: weber
1. weber: weber
1. webers: weber
1. yard: yard
1. yards: yard
1. yd: yard
1. year: tropical_year
1. years: tropical_year
1. yocto: Prefix('yocto', 'y', -24)
1. yotta: Prefix('yotta', 'Y', 24)
1. zepto: Prefix('zepto', 'z', -21)
1. zetta: Prefix('zetta', 'Z', 21)
# Practicle Usage Example
A particle is moving in space with a velocity that can be defined by the following function:
$v(t) = t^2 - 2t - 8$
where time `t` is in seconds and the velocity `v` is measured in $\frac{\text{meter}}{\text{second}}$:
1. Plot the function.
1. At what time(s) is the particle at rest (i.e. $v(t) = 0$)?
1. What is the acceleration of the particle at a time of 5.3 seconds into its trajectory? (Hint: acceleration is the first derivative of the velocity)
Original source: https://www.georgebrown.ca/sites/default/files/2020-05/Applications%20of%20Derivatives.pdf
First define what our sympy variable is:
```
t = sympy.symbols('t')
velocity_function = t**2 - 2*t - 8
```
1. Plot the function
```
plot_func = sympy.plot(velocity_function)
```
2. At what time(s) is the particle at rest (i.e. $v(t) = 0$)?
- That means we need to solve the equation an find its **roots**.
As learned above, we do this using the `solve` function.
```
solutions = sympy.solve(velocity_function)
solutions
```
However, now it is time to **think** about the solutions.
Since a negative time is not possible in our scenario, the answer to the question can only be 4 seconds.
3. What is the acceleration of the particle at t=3 seconds?
- Recall that acceleration is defined as the first derivative of the velecity with respect to time
$a(t) = \frac{d}{dt} v(t) = \frac{d}{dt} (t^2 - 2t - 8)$
```
first_derivative = velocity_function.diff(t, 1)
first_derivative
```
Now evaluate the first derivative at a time of 5.3 seconds:
```
time = 5.3
acceleration = first_derivative.evalf(subs = {t: time})
acceleration
print(f'The acceleration of the particle at {time} s into its trajectory is '
f' {acceleration:0.1f} m/s^2.')
```
---
Side note about how the unit was obtained:
Derivative can also be expressed mathematically in a different way (i.e. via Leibniz):
$\frac{d}{dx} f(x) = \lim_{x \to x_0} f(x) = \lim_{x \to x_0} \frac{f(x) - f(x_0)}{x - x_0}$
if `f(x)` has units of $\frac{\text{meter}}{\text{second}}$
and `x` has units of $\text{second}$, then we have
$\lim_{x \to x_0} \frac{\frac{\text{meter}}{\text{second}} - \frac{\text{meter}}{\text{second}}}{\text{second} - \text{seconds}}$
$ = \frac{\frac{\text{meter}}{\text{second}}}{\text{second}} = \frac{\text{meter}}{\text{second second}} = \frac{\text{meter}}{\text{second}^2}$
| github_jupyter |
```
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from IPython import display
from scipy.spatial.transform import Rotation as R
import math
from copy import copy
import glob
import random
from scipy.stats import kendalltau
```
# First, we'll load some data
```
flist = sorted(glob.glob('../../demos/perms/order*'))
random.shuffle(flist)
# Load 300 examples
obj_list = []
im_list = []
for i,f in enumerate(flist[0:300]):
run = int(f.split('_')[1][:-4])
im = np.load('../../demos/perms/ims_%04d.npy'%run)
obj_ids = np.load('../../demos/perms/order_%04d.npy'%run)
obj_list.append(obj_ids)
im_list.append(im)
# Force into masked tensor structure
obj_idxs = np.ones((len(obj_list),6))*0
seq_len = []
for j,obj_idx in enumerate(obj_list):
seq_len.append(obj_idx.shape[0]-1)
obj_idxs[j,0:obj_idx.shape[0]] = obj_idx
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
device = torch.device("cuda:1")
```
# Next, we'll define a dataloader and Sinkhorn network
```
# Set up pytorch dataloader
class Sampler(Dataset):
def __init__(self, ims, actions, seq_lens, K=6):
self.ims = torch.FloatTensor(ims.astype('float')).to(device)
self.actions = torch.FloatTensor(actions.astype('float')).to(device)
self.K = K
def __len__(self):
return self.ims.shape[0]
def __getitem__(self, index):
im = self.ims[index,:,:,:]
actions = self.actions[index,:]
return im, actions, torch.FloatTensor(np.arange(self.K).astype('float')).to(device)
dataset = Sampler(np.swapaxes(np.stack(im_list),1,3),obj_idxs,6)
train_dataset,test_dataset = torch.utils.data.random_split(dataset, [200,len(im_list)-200])
batch_size = 32
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class SinkhornNet(nn.Module):
def __init__(self, latent_dim=16, image_channels=3, K=6, n_samples=5, noise_factor=1.0, temp=1.0, n_iters=20):
super(SinkhornNet, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=5),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(64, 128, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(128, 256, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2,2),
Flatten(),
nn.Linear(4096, latent_dim),
nn.ReLU(),
nn.Dropout(p=0.5)
)
# Sinkhorn params
self.latent_dim = latent_dim
self.K = K
self.n_samples = n_samples
self.noise_factor = noise_factor
self.temp = temp
self.n_iters = n_iters
self.criterion = nn.MSELoss()
self.sinknet = nn.Sequential(nn.Linear(self.latent_dim, self.latent_dim),
nn.ReLU(),
nn.Linear(self.latent_dim, K*K))
def permute(self,seq,P):
return torch.matmul(P,seq)
def predict_P(self,im):
latent = self.encoder(im)
log_alpha = self.sinknet(latent)
log_alpha = log_alpha.reshape(-1, self.K, self.K)
soft_perms_inf, log_alpha_w_noise = self.gumbel_sinkhorn(log_alpha)
P = self.inv_soft_pers_flattened(soft_perms_inf,self.K)
return P
def forward(self, seq, im):
latent = self.encoder(im)
log_alpha = self.sinknet(latent)
log_alpha = log_alpha.reshape(-1, self.K, self.K)
soft_perms_inf, log_alpha_w_noise = self.gumbel_sinkhorn(log_alpha)
P = self.inv_soft_pers_flattened(soft_perms_inf,self.K)
seq_tiled = seq.repeat(self.n_samples, 1)
ordered = self.permute(torch.unsqueeze(seq_tiled,dim=-1),P)
return ordered
def loss(self, seq, im, seq_gt):
seq_pred = self.forward(seq_gt,im)
seq_pred = torch.squeeze(seq_pred)
recon_loss = self.criterion(seq_pred,seq.repeat(self.n_samples, 1))
return recon_loss, seq_pred
def inv_soft_pers_flattened(self,soft_perms_inf,n_numbers):
inv_soft_perms = torch.transpose(soft_perms_inf, 2, 3)
inv_soft_perms = torch.transpose(inv_soft_perms, 0, 1)
inv_soft_perms_flat = inv_soft_perms.view(-1, n_numbers, n_numbers)
return inv_soft_perms_flat
def sample_gumbel(self, shape, eps=1e-20):
U = torch.rand(shape).float().to(device)
return -torch.log(eps - torch.log(U + eps))
def gumbel_sinkhorn(self,log_alpha):
n = log_alpha.size()[1]
log_alpha = log_alpha.view(-1, n, n)
batch_size = log_alpha.size()[0]
log_alpha_w_noise = log_alpha.repeat(self.n_samples, 1, 1)
if self.noise_factor == 0:
noise = 0.0
else:
noise = self.sample_gumbel([self.n_samples*batch_size, n, n])*self.noise_factor
log_alpha_w_noise = log_alpha_w_noise + noise
log_alpha_w_noise = log_alpha_w_noise / self.temp
my_log_alpha_w_noise = log_alpha_w_noise.clone()
sink = self.sinkhorn(my_log_alpha_w_noise)
sink = sink.view(self.n_samples, batch_size, n, n)
sink = torch.transpose(sink, 1, 0)
log_alpha_w_noise = log_alpha_w_noise.view(self.n_samples, batch_size, n, n)
log_alpha_w_noise = torch.transpose(log_alpha_w_noise, 1, 0)
return sink, log_alpha_w_noise
def sinkhorn(self,log_alpha, n_iters = 20):
n = log_alpha.size()[1]
log_alpha = log_alpha.view(-1, n, n)
for i in range(n_iters):
log_alpha = log_alpha - (torch.logsumexp(log_alpha, dim=2, keepdim=True)).view(-1, n, 1)
log_alpha = log_alpha - (torch.logsumexp(log_alpha, dim=1, keepdim=True)).view(-1, 1, n)
return torch.exp(log_alpha)
```
# Now, let's train the network
```
sn = SinkhornNet(latent_dim=128, image_channels=3, K=6)
sn.to(device)
optimizer = torch.optim.Adam(sn.parameters(), lr=3e-4)
n_epochs = 5000
losses = []
plt.figure(figsize=(15,7))
for j in range(n_epochs):
batch_losses = []
for im, seq, seq_order in train_loader:
loss, seq_pred = sn.loss(seq, im, seq_order)
batch_losses.append(loss.item())
loss.backward()
optimizer.step()
optimizer.zero_grad()
losses.append(np.mean(batch_losses))
plt.clf()
plt.cla()
plt.subplot(1,3,1)
plt.plot(losses,alpha=0.5)
plt.title('Recon loss')
plt.subplot(2,3,6)
P = sn.predict_P(im)
plt.imshow(P[0,:,:].cpu().detach().numpy())
plt.title('Permutation')
plt.subplot(3,3,2)
plt.imshow(seq_pred[0,:].cpu().detach().numpy().reshape(1,-1))
plt.title('Re-shuffled seq')
plt.subplot(3,3,5)
plt.imshow(seq_order[0,:].cpu().detach().numpy().reshape(1,-1))
plt.title('Ordered seq')
plt.subplot(3,3,8)
plt.imshow(seq[0,:].cpu().detach().numpy().reshape(1,-1))
plt.title('Original seq')
plt.subplot(2,3,3)
plt.imshow(np.swapaxes(im[0,:,:,:].cpu().detach().numpy(),0,2))
display.clear_output(wait=True)
display.display(plt.gcf())
```
# Now evaluate on test set
```
sn.eval()
sn.noise_factor = 0.0
sn.n_samples = 1
sn.n_iters = 100
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
tau_list = []
for im,seq,seq_ordered in test_loader:
P = sn.predict_P(im)
obj_ids = np.argmax(P[0,:,:].cpu().detach().numpy(),1)
tau, _ = kendalltau(obj_ids, seq.cpu().numpy())
tau_list.append(tau)
plt.figure(figsize=(15,5))
plt.plot(tau_list)
plt.ylabel('Kendall\'s $\\tau$')
plt.xlabel('Demonstration')
plt.grid()
plt.show()
```
# Demonstrate in CoppeliaSim
```
from pyrep import PyRep
from pyrep.robots.arms.panda import Panda
from pyrep.robots.end_effectors.panda_gripper import PandaGripper
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from IPython import display
from pyrep.objects.shape import Shape
from pyrep.const import PrimitiveShape
from scipy.spatial.transform import Rotation as R
import math
from copy import copy
pr = PyRep()
pr.launch('../../assets/scene_panda.ttt', headless=False)
agent = Panda()
gripper = PandaGripper()
home_pos = agent.get_tip().get_position()
home_orient = agent.get_tip().get_orientation()
def grasp(grip=False):
if grip:
pos = 0.1
else:
pos = 0.9
actuated = False
ims = []
states = []
while not actuated:
actuated = gripper.actuate(pos,0.1)
im0,im1 = get_image()
ims.append((im0,im1))
states.append(agent.get_tip().get_pose())
return ims,states
def move_above_object(object_name='',offset=0.05):
pos = agent.get_object(object_name).get_position()
pos[2] = pos[2] + offset
orient = [-np.pi,0,np.pi/2]
path = agent.get_path(position=pos,euler=orient)
done = False
ims = []
states = []
while not done:
done = path.step()
im0,im1 = get_image()
ims.append((im0,im1))
states.append(agent.get_tip().get_pose())
return ims,states
def get_image():
cam = agent.get_object('Vision_sensor_front')
im0 = cam.capture_rgb()
cam1 = agent.get_object('Vision_sensor')
im1 = cam1.capture_rgb()
pr.step()
return im0, im1
# Set up a dataloader for testing
tl = iter(train_loader)
# Run this repeatedly to see how the action sequencing works for different images
im,seq,seq_ordered,seq_len = next(tl)
P = sn.predict_P(im)
_,stop_logit = sn(seq_ordered,im)
stop_bin = np.argmax(stop_logit.detach().numpy(),-1)
obj_ids = np.argmax(P[0,:,:].detach().numpy(),1)[0:(stop_bin[0]+1)]
pr.start()
grasp(grip=False)
gripper.release()
ims = []
states = []
for j in range(1,len(obj_ids)):
object_name = 'Cuboid%d'%obj_ids[j]
i,s = move_above_object(object_name,offset=0.08)
ims = ims + i
states = states + s
i,s = move_above_object(object_name,offset=0)
ims = ims + i
states = states + s
i,s = grasp(grip=True)
ims = ims + i
states = states + s
gripper.grasp(agent.get_object(object_name))
i,s = move_above_object(object_name,offset=0.08)
ims = ims + i
states = states + s
object_name = 'Cuboid%d'%obj_ids[j-1]
i,s = move_above_object(object_name,offset=0.15)
ims = ims + i
states = states + s
i,s = move_above_object(object_name,offset=0.05)
ims = ims + i
states = states + s
i,s = grasp(grip=False)
ims = ims + i
states = states + s
gripper.release()
i,s = move_above_object(object_name,offset=0.2)
ims = ims + i
states = states + s
#clear_view()
plt.cla()
plt.clf()
plt.subplot(1,3,1)
plt.imshow(ims[-1][0])
plt.title('Actual')
plt.subplot(1,3,2)
plt.imshow(ims[-1][1])
plt.subplot(1,3,3)
plt.imshow(np.swapaxes(im.numpy()[0,:,:],2,0))
plt.title('Target')
display.clear_output(wait=True)
display.display(plt.gcf())
pr.stop()
pr.shutdown()
```
| github_jupyter |
```
import random
import re
import numpy as np
import psycopg2 as db
import pandas as pd
import geopandas as gpd
from shapely.wkb import loads
from matplotlib import pyplot as plt
from shapely.geometry import Point, LineString
```
# Compare pgRouting Speedup Execution Times
In our tutorial on how to speed up pgRouting queries, we have presented a couple of ways to make dijkstra's algorithm in pgRouting run faster even on large road data sets. In this notebook, we're taking it a little further and instead of just running the queries on one route, we're comparing them across various routes of different lengths.
```
db_creds = {"dbname": "gis", "user": "<user>", "password": "<pass>", "host": "localhost", "port": "5450"}
conn = db.connect(**db_creds)
cur = conn.cursor()
norcal_boundary = gpd.read_file("./data/norcal.geojson")
minx, miny, maxx, maxy = norcal_boundary.geometry.total_bounds
poly_norcal = norcal_boundary.iloc[0].geometry
def random_coordinates(n, min_dist, max_dist):
assert min_dist < max_dist # make sure parameters are valid
coordinates = []
for _ in range(n):
counter = 0
in_poly = False
while not in_poly:
counter += 1
x = random.uniform(minx, maxx)
y = random.uniform(miny, maxy)
p = Point(x, y)
if poly_norcal.contains(p):
# Make sure all route segments are within limits
if coordinates:
if not min_dist < p.distance(Point(coordinates[-1])) < max_dist:
continue
coordinates.append([x, y])
in_poly = True
if counter > 1000:
raise ValueError("Distance settings are too restrictive. Try a wider range and remember it's in degrees.")
return coordinates
coords = gpd.GeoDataFrame(geometry=[Point(x,y) for x,y in random_coordinates(50000, 0.0001, 1)], crs=4326)
geoms = []
data = []
for rix, row in coords.iterrows():
from_geom = row.geometry
to_geom = coords.sample(1).iloc[0].geometry
euclidean = from_geom.distance(to_geom)
if euclidean == 0:
continue
geoms.append(LineString([from_geom, to_geom]))
data.append({"euclidean": euclidean})
from_to = gpd.GeoDataFrame(geometry=geoms, data=data, crs=4326)
from_to["eucl_rounded"] = np.floor(from_to.euclidean)
from_to = from_to.query("euclidean < 10")
#from_to["eucl_rounded"] = from_to["eucl_rounded"].apply(lambda x: x if x < 8 else 7) # group smaller groups together
min_ = min(from_to.groupby("eucl_rounded").size()) # let's get somewhat of a uniform distribution along the eucl. distance
samples = []
for name, group in from_to.groupby("eucl_rounded"):
samples.append(group.sample(min_))
df = pd.concat(samples)
df = df.reset_index(drop=True)
df
queries = {
"baseline": """EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
WITH start AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
),
destination AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
)
SELECT ST_Union(geom_way) as geom
FROM pgr_dijkstra('
SELECT id,
source,
target,
ST_Length(ST_Transform(geom_way, 3857)) AS cost,
ST_Length(ST_Transform(geom_way, 3857)) AS reverse_cost
FROM norcal_2po_4pgr',
array(SELECT source FROM start),
array(SELECT source FROM destination),
directed := true) AS di
JOIN norcal_2po_4pgr AS pt
ON di.edge = pt.id;""",
"fixed_cost": """EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
WITH start AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
),
destination AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
)
SELECT ST_Union(geom_way) as geom
FROM pgr_dijkstra('
SELECT id,
source,
target,
cost,
reverse_cost
FROM norcal_2po_4pgr',
array(SELECT source FROM start),
array(SELECT source FROM destination),
directed := true) AS di
JOIN norcal_2po_4pgr AS pt
ON di.edge = pt.id;""",
"bbox": """EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
WITH start AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
),
destination AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
)
SELECT ST_Union(geom_way) as geom
FROM pgr_dijkstra('
SELECT id,
source,
target,
cost,
reverse_cost
FROM norcal_2po_4pgr as e,
(SELECT ST_Expand(ST_Extent(geom_way),0.1) as box FROM norcal_2po_4pgr as b
WHERE b.source = '|| (SELECT source FROM start) ||'
OR b.source = ' || (SELECT source FROM destination) || ') as box WHERE e.geom_way && box.box'
,
array(SELECT source FROM start),
array(SELECT source FROM destination),
directed := true) AS di
JOIN norcal_2po_4pgr AS pt
ON di.edge = pt.id;""",
"spatial_index": """EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
WITH start AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr_gist as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
),
destination AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr_gist as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
)
SELECT ST_Union(geom_way) as geom
FROM pgr_dijkstra('
SELECT id,
source,
target,
cost,
reverse_cost
FROM norcal_2po_4pgr_gist as e,
(SELECT ST_Expand(ST_Extent(geom_way),0.1) as box FROM norcal_2po_4pgr_gist as b
WHERE b.source = '|| (SELECT source FROM start) ||'
OR b.source = ' || (SELECT source FROM destination) || ') as box WHERE e.geom_way && box.box'
,
array(SELECT source FROM start),
array(SELECT source FROM destination),
directed := true) AS di
JOIN norcal_2po_4pgr_gist AS pt
ON di.edge = pt.id;""",
"clustering": """EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
WITH start AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr_clustered as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
),
destination AS (
SELECT topo.source --could also be topo.target
FROM norcal_2po_4pgr_clustered as topo
ORDER BY topo.geom_way <-> ST_SetSRID(
st_makepoint(%s,%s),
4326)
LIMIT 1
)
SELECT ST_Union(geom_way) as geom
FROM pgr_dijkstra('
SELECT id,
source,
target,
cost,
reverse_cost
FROM norcal_2po_4pgr_clustered as e,
(SELECT ST_Expand(ST_Extent(geom_way),0.1) as box FROM norcal_2po_4pgr_clustered as b
WHERE b.source = '|| (SELECT source FROM start) ||'
OR b.source = ' || (SELECT source FROM destination) || ') as box WHERE e.geom_way && box.box'
,
array(SELECT source FROM start),
array(SELECT source FROM destination),
directed := true) AS di
JOIN norcal_2po_4pgr_clustered AS pt
ON di.edge = pt.id;"""
}
for key in queries:
query = queries[key]
for rix, row in df.reset_index(drop=True).iterrows():
from_x, from_y, to_x, to_y = [
row.geometry.coords[0][0],
row.geometry.coords[0][1],
row.geometry.coords[1][0],
row.geometry.coords[1][1],
]
cur.execute(query, [from_x, from_y, to_x, to_y])
rows = cur.fetchall()
exec_time = float(re.search("Execution Time: (.*) ms", rows[-1][0]).group(1))
df.loc[rix, f"{key}_exec_time"] = exec_time
conn.commit()
df["eu_km"] = df.to_crs(3857).geometry.length / 1000
df = df.sort_values("eu_km")
width = 4
fig, ax = plt.subplots(1,1, figsize=(20,10))
ax.grid(True)
ax.bar(data=df, height="baseline_exec_time", x="eu_km", width=width, color="red")
ax.bar(data=df, height="fixed_cost_exec_time", x="eu_km", width=width, color="salmon")
ax.bar(data=df, height="bbox_exec_time", x="eu_km", width=width, color="orange")
ax.bar(data=df, height="spatial_index_exec_time", x="eu_km", width=width, color="lightgreen")
ax.bar(data=df, height="clustering_exec_time", x="eu_km", width=width, color="green")
ax.legend(["Baseline", "Fixed cost", "Bbox query", "Spatial index", "Spatial clustering"], fontsize=12)
ax.set_xlim(0, max(df["eu_km"])*1.01)
ax.set_ylim(0, max(df["baseline_exec_time"]*1.28))
ax.set_xlabel("Route distance (km)", fontdict={"fontsize": 16})
ax.set_ylabel("Execution time (ms)", fontdict={"fontsize": 16})
ax.tick_params(labelsize = 12)
plt.tight_layout()
plt.savefig("./static/img/pgr_exec_times.jpg", dpi=200)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import string
import random
from datetime import *
def gen_random_email():
domains = [ "hotmail.com", "gmail.com", "aol.com", "mail.com" , "mail.kz", "yahoo.com"]
letters = string.ascii_letters +'.'*5
email = ''.join(np.random.choice(list(letters),10))+'@'+ np.random.choice(domains)
email = email.replace('.@', '@')
return email, "Email"
def gen_random_float():
num = np.random.random()*np.random.randint(2000)
decimal_points = np.random.randint(8)
num = int(num*10**(decimal_points))/10**decimal_points
return str(num), 'Float'
def gen_random_sentence():
nouns = ["The","puppy", "car", "rabbit", "girl", "monkey"]
verbs = ["runs", "hits", "jumps", "drives", "barfs", "has", "is"]
adv = ["crazily", "dutifully", "foolishly", "merrily", "occasionally"]
adj = ["adorable.", "clueless.", "dirty.", "odd.", "stupid."]
random_entry = lambda x: x[random.randrange(len(x))]
random_entry = " ".join([random_entry(nouns), random_entry(verbs),
random_entry(adv), random_entry(nouns), random_entry(nouns), random_entry(adj)])
return random_entry, 'String'
def gen_random_int():
num = np.random.randint(1000000)
return str(num), 'Int'
def generate_phonenum():
first = str('+1')
second = str(random.randint(1, 888)).zfill(3)
last = (str(random.randint(1, 9998)).zfill(7))
return '{} {} {}'.format(first, second, last), 'PhoneNumber'
def generate_creditcard():
first = str(np.random.randint(3,6))
def prefill(numbers):
filled = ""
i=1
while i <= numbers:
filled += str(np.random.randint(1, 9))
i+=1
return filled
return '{}{}-{}-{}-{}'.format(first, prefill(3), prefill(4),prefill(4),prefill(4)), 'CreditCard'
def gen_random_date_yearfirst():
sdate = date(year = np.random.randint(1990,2020),
day = np.random.randint(1,28),
month = np.random.randint(1,12))
return str(sdate), 'DateTime'
def gen_random_date_monthfirst():
sdate = date(year = np.random.randint(1990,2020),
day = np.random.randint(1,28),
month = np.random.randint(1,12))
sdate = sdate.strftime("%m/%d/%y")
return str(sdate), 'DateTime'
def gen_random_date_dayfirst():
sdate = date(year = np.random.randint(1990,2020),
day = np.random.randint(1,28),
month = np.random.randint(1,12))
sdate = sdate.strftime("%d/%m/%Y")
return str(sdate), 'DateTime'
def gen_random_date_monthstring():
sdate = date(year = np.random.randint(1990,2020),
day = np.random.randint(1,28),
month = np.random.randint(1,12))
sdate = sdate.strftime("%d/%B/%y")
return str(sdate), 'DateTime'
def gen_random_datetime_format():
sdate = date(year = np.random.randint(1990,2020),
day = np.random.randint(1,28),
month = np.random.randint(1,12))
sdate = sdate.strftime("%m/%d/%Y %H:%M:%S")
return str(sdate), 'DateTime'
def gen_random_datetime_withoutsec_format():
sdate = date(year = np.random.randint(1990,2020),
day = np.random.randint(1,28),
month = np.random.randint(1,12))
sdate = sdate.strftime("%m/%d/%Y %H:%M")
return str(sdate), 'DateTime'
def gen_dataset(filename, size=5000):
randomizers = [gen_random_email, gen_random_float,
gen_random_int, gen_random_sentence,
gen_random_date_yearfirst,
gen_random_date_monthfirst,
generate_creditcard,
gen_random_date_dayfirst,
gen_random_float,
gen_random_date_monthstring,
gen_random_datetime_format,
gen_random_float,
gen_random_datetime_withoutsec_format,
generate_phonenum]
with open(filename, 'w') as file:
file.write("Text, Type\n")
for _ in range(size):
file.write(",".join(random.choice(randomizers)())+"\n")
gen_dataset('data.csv')
```
| github_jupyter |
```
import psycopg2
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns
import datetime as dt
import seaborn as sns
import datetime
```
## Clean Infielder Datasets
```
#dfinf1 (infielder who played btwn 30 to 100 gms) = clutch_inf_30.csv
#dfinf2 (infielder whe played at least 100gms) = clutch_inf_100.csv
#dfinf3 (infielder who made atleast 5 allstar gms) = allstr_clutch_inf.csv
```
## Data Ingestion
```
import psycopg2 as p2
conn = p2.connect(database = 'player_stats', user ='baseball_master', password = 'georgetowndata',
host = 'georgetown-baseball.cnfqonxqdbry.us-east-1.rds.amazonaws.com',
port = '5432')
```
## Data sets created
```
#dfinf1 = pd.read_csv('clutch_inf_30.csv', index_col=0)
#dfinf2 = pd.read_csv('clutch_inf_100.csv', index_col=0)
dfinf3 = pd.read_csv('allstr_clutch_inf.csv', index_col=0)
#Clear data set of NaN values
#dfinf1 = dfinf1.fillna(0)
#dfinf2 = dfinf2.fillna(0)
dfinf3 = dfinf3.fillna(0)
#dfinf1.head()
#dfinf2.head()
#dfinf3.head()
```
## Summary Statistics
### Infielders who played atleast 30 games
```
dfinf1[["AVG", "HR", "H", "TB", "SLG", "OPS", "OBP","BB","RC"]].describe()
```
### Infielders who played atleast 100 games
```
dfinf2[["AVG", "HR", "H", "TB", "SLG", "OPS", "OBP","BB","RC"]].describe()
```
### All Star Infielders
```
dfinf3[["AVG", "HR", "H", "TB", "SLG", "OPS", "OBP","BB","RC"]].describe()
```
## Data Exploration with Seaborn
#### Leverage Pairplots to id trends in the data
```
import seaborn as sns
import numpy as np
%matplotlib inline
### Measure relationship btwn key stats [AVG, TB, HR, OPS, OBP, SLG, BB, 1B, 2B, 3B, RC]
```
### Infielders who played at least 30 games
```
sns.pairplot(dfinf1, x_vars = ['OPS','1B','3B','2B','SLG'], y_vars = 'RC', height = 3, aspect = 0.7, kind = 'reg')
sns.pairplot(dfinf1, x_vars = ['BB','HR','OBP','TB','AVG'], y_vars = 'RC', height = 3, aspect = 0.7, kind = 'reg')
```
### Infielders who played at least 100 games
```
sns.pairplot(dfinf2, x_vars = ['OPS','1B','3B','2B','SLG'], y_vars = 'RC', height = 3, aspect = 0.7, kind = 'reg')
sns.pairplot(dfinf2, x_vars = ['BB','HR','OBP','TB','AVG'], y_vars = 'RC', height = 3, aspect = 0.7, kind = 'reg')
```
### All Star Infielders
```
sns.pairplot(dfinf3, x_vars = ['OPS','1B','3B','2B','SLG'], y_vars = 'RC', height = 3, aspect = 0.7, kind = 'reg')
sns.pairplot(dfinf3, x_vars = ['BB','HR','OBP','TB','AVG'], y_vars = 'RC', height = 3, aspect = 0.7, kind = 'reg')
```
## Machine Learning: Which Features can predict Runs Created (response)?
### Infielders who played at least 30 games
#### Create X = features and y = response
```
#What are the features? - AVG, HR, OPS, SLG, BB, 1B, 2B, 3B, H
#What is the response? - Runs Created
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
#response = 'RC' (Runs Created)
X = dfinf1[features]
y = dfinf1['RC']
```
#### Splitting X and y into training and testing sets
```
#Evaluate the Models
#from sklearn.cross.validation import train_test_split (Doesnt work)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 4)
#default split is 75% for training and 25% for test
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
```
#### Linear Regression to train Model to learn
```
#import model
from sklearn.linear_model import LinearRegression
#instantiate
linreg = LinearRegression()
#fit the model to the training data(learn the coefficients)
linreg.fit(X_train, y_train)
### Interpreting model coefficents
```
#### Making Predictions
```
#make predictions on the X test data
y_pred = linreg.predict(X_test)
from sklearn import metrics
```
#### Root-Mean Sample Squared Error (Difference btwn Predicted and Test values)
```
#Infielders with at least 30 gms
#Computing the RMSE for Runs Created
print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
#dfinf1 = 2.02 with all 10 features (Outfielders with atleast 30 gms)
```
### Outfielders who played at least 100 games
#### Create X = features and y = response
```
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
#response = 'RC' (Runs Created)
X = dfinf2[features]
y = dfinf2['RC']
```
#### Splitting X and y into training and testing sets
```
#Evaluate the Models
#from sklearn.cross.validation import train_test_split (Doesnt work)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 4)
#default split is 75% for training and 25% for test
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
```
#### Linear Regression to train Model to learn
```
#import model
from sklearn.linear_model import LinearRegression
#instantiate
linreg = LinearRegression()
#fit the model to the training data(learn the coefficients)
linreg.fit(X_train, y_train)
```
#### Making Predictions
```
#make predictions on the X test data
y_pred = linreg.predict(X_test)
from sklearn import metrics
```
#### Root-Mean Sample Squared Error (Difference btwn Predicted and Test values)
```
#Infielders with atleast 100 games
#Computing the RMSE for Runs Created
print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
```
### All Star Infielders
#### Create X = features and y = response
```
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
#response = 'RC' (Runs Created)
X = dfinf3[features]
y = dfinf3['RC']
```
#### Splitting X and y into training and testing sets
```
#Evaluate the Models
#from sklearn.cross.validation import train_test_split (Doesnt work)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 4 )
#default split is 75% for training and 25% for test
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
```
#### Linear Regression to train Model to learn
```
#import model
from sklearn.linear_model import LinearRegression
#instantiate
linreg = LinearRegression()
#fit the model to the training data(learn the coefficients)
linreg.fit(X_train, y_train)
```
#### Making Predictions
```
#make predictions on the X test data
y_pred = linreg.predict(X_test)
from sklearn import metrics
```
#### Root-Mean Sample Squared Error (Difference btwn Predicted and Test values)
```
#All Star Infielders.
#Computing the RMSE for Runs Created
print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
```
## Feature selection - Which are the underperforming features?
### Infielders with atleast 30 games
#### Yellowbrick's Feature Rank Visualizer
```
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
#response = 'RC' (Runs Created)
X = dfinf1[features]
y = ['RC']
from yellowbrick.features import Rank1D
visualizer = Rank1D(features = features, algorithm ='shapiro')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
# Features [HR, 3B, BB, AVG] ranked the worst
```
#### Yellowbrick's Feature Importance to futher verify Feature Importance
```
#Infielders with atleast 30 games
#convert y from float to integer
y = dfinf1.RC.astype(int)
#Infielders with atleast 30 games
#set X value for all 10 features
X = dfinf1[features]
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from yellowbrick.features.importances import FeatureImportances
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot()
#ax = ax
#Infielders with atleast 30 gms
#This model takes over 90 seconds to run
#Features TB, OBP, and OPS are the most important
viz = FeatureImportances(GradientBoostingClassifier(), ax = ax)
viz.fit(X,y)
viz.poof()
```
#### Yellowbrick's Feature Covariance 2D Rank heat map
```
#reset value of y to y = dfin1['RC']
y = dfinf1['RC']
from yellowbrick.features import Rank2D
visualizer = Rank2D(features=features, algorithm = 'covariance')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
### Infielders with atleast 100 games
#### Yellowbrick's Feature Rank Visualizer
```
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
#response = 'RC' (Runs Created)
X = dfinf2[features]
y = ['RC']
from yellowbrick.features import Rank1D
visualizer = Rank1D(features = features, algorithm ='shapiro')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
#### Yellowbrick's Feature Importance to futher verify Feature Importance
```
#Infielders with atleast 100 games
#convert y from float to integer
y = dfinf2.RC.astype(int)
X = dfinf2[features]
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from yellowbrick.features.importances import FeatureImportances
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot()
#ax = ax
#Infielders with atleast 100 gms
#This model takes over 90 seconds to run
#Features TB, OBP, and OPS are the most important
viz = FeatureImportances(GradientBoostingClassifier(), ax = ax)
viz.fit(X,y)
viz.poof()
```
#### Yellowbrick's Feature Covariance 2D Rank heat map
```
#reset value of y to y = dfinf2['RC']
y = dfinf2['RC']
from yellowbrick.features import Rank2D
visualizer = Rank2D(features=features, algorithm = 'covariance')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
### Allstar Outfielders
#### Yellowbrick's Feature Rank Visualizer
```
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
#response = 'RC' (Runs Created)
X = dfin3[features]
y = ['RC']
from yellowbrick.features import Rank1D
visualizer = Rank1D(features = features, algorithm ='shapiro')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
#### Yellowbrick's Feature Importance to futher verify Feature Importance
```
#convert y from float to integer
y = dfin3.RC.astype(int)
X = dfin3[features]
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from yellowbrick.features.importances import FeatureImportances
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot()
#ax = ax
# Features TB, OBP, and OPS are the most important
viz = FeatureImportances(GradientBoostingClassifier(), ax = ax)
viz.fit(X,y)
viz.poof()
```
#### Yellowbrick's Feature Covariance 2D Rank heat map
```
#reset value of y to y = dfin3['RC']
y = dfin3['RC']
from yellowbrick.features import Rank2D
visualizer = Rank2D(features=features, algorithm = 'covariance')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
## Prediction and Error Plotting
### Infielders with atleast 30 games
```
#Reset X and y values
features = ['AVG', 'TB', 'HR', 'OPS', 'OBP', 'SLG', 'BB', '1B','2B','3B']
X = dfinf1[features]
y = dfinf1['RC']
```
#### Ridge Regression - R2 Score
```
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import r2_score
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
#score to high = overfitted. Must remove features and add noise
#removed TB, OPS, OBP, SLG, '2B'
features = ['AVG','HR','BB', '1B','3B']
X= dfinf1[features]
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
#### Retry with adding noise to features
```
#add noise to features
features = ['AVG','HR','BB','1B','3B','W', 'G_x', 'birthYear']
#Re-try with removed features
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
#### Lasso Regression -R2 Score
```
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import r2_score
#Re-set X with reduced features
features = ['AVG','HR','BB', '1B','3B']
X= dfinf1[features]
y = dfinf1['RC']
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
### Re-measure importance of reduced feautures
```
features = ['AVG','HR','BB', '1B','3B']
X = dfinf1[features]
y = dfinf1['RC']
from yellowbrick.features import Rank1D
visualizer = Rank1D(features = features, algorithm ='shapiro')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
#convert y from float to integer
y = dfinf1.RC.astype(int)
X = dfinf1[features]
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from yellowbrick.features.importances import FeatureImportances
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot()
#Model takes over 90 seconds to calculate
viz = FeatureImportances(GradientBoostingClassifier(), ax = ax)
viz.fit(X,y)
viz.poof()
#reset value of y to y = dfinf1['RC']
y = dfinf1['RC']
from yellowbrick.features import Rank2D
visualizer = Rank2D(features=features, algorithm = 'covariance')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
## Data Visualization
### Outfielders with at least 30 gms
#### Visualize Plot Error
```
#Train Model again
from sklearn.model_selection import train_test_split
data = dfinf1
features = ['AVG','HR','BB', '1B','3B']
X = dfinf1[features]
y = dfinf1['RC']
#Create the train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
#### Ridge Regression R2 Score
```
from sklearn.linear_model import Ridge
from yellowbrick.regressor import PredictionError
# Instantiate the linear model and visualizer
Ridge = Ridge()
visualizer = PredictionError(Ridge)#, ##size = (1080,720), legend_size = 3))
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.poof()
```
#### Lasso Regression R2 Score
```
from sklearn.linear_model import Lasso
from yellowbrick.regressor import PredictionError
# Instantiate the linear model and visualizer
Lasso = Lasso()
visualizer = PredictionError(Lasso)#, ##size = (1080,720), legend_size = 3))
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.poof()
```
#### Ridge - Residual Plots
```
from sklearn.linear_model import Ridge
from yellowbrick.regressor import ResidualsPlot
Ridge = Ridge()
visualizer = ResidualsPlot(Ridge)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof()
```
#### Lasso - Resdiual Plots
```
from sklearn.linear_model import Lasso
from yellowbrick.regressor import ResidualsPlot
Lasso = Lasso()
visualizer = ResidualsPlot(Lasso)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof()
```
## Prediction and Error Plotting
### Infielders with atleast 100 games
```
#Reset X and y values
features = ['AVG','HR','BB', '1B','3B']
X = dfinf2[features]
y = dfinf2['RC']
```
#### Ridge Regression -R2 Score
```
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import r2_score
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
#### Lasso Regression -R2 Score
```
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import r2_score
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
### Re-measure importance of reduced feautures
```
features = ['AVG','HR','BB', '1B','3B']
X = dfinf2[features]
y = dfinf2['RC']
from yellowbrick.features import Rank1D
visualizer = Rank1D(features = features, algorithm ='shapiro')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
#convert y from float to integer
y = dfinf2.RC.astype(int)
X = dfinf2[features]
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from yellowbrick.features.importances import FeatureImportances
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot()
#ax = ax
#This takes over 90 seconds to run
#Features TB, OBP, and OPS are the most important
viz = FeatureImportances(GradientBoostingClassifier(), ax = ax)
viz.fit(X,y)
viz.poof()
#reset value of y to y = dfinf2['RC']
y = dfinf2['RC']
from yellowbrick.features import Rank2D
visualizer = Rank2D(features=features, algorithm = 'covariance')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
## Data Visualization
### Infielders with at least 100 gms
#### Visualize Plot Error
```
#Train Model again
from sklearn.model_selection import train_test_split
data = dfinf2
features = ['AVG','HR','BB', '1B','3B']
X = dfinf2[features]
y = dfinf2['RC']
#Create and train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
#### Ridge Regression R2 Score
```
from sklearn.linear_model import Ridge
from yellowbrick.regressor import PredictionError
# Instantiate the linear model and visualizer
Ridge = Ridge()
visualizer = PredictionError(Ridge)#, ##size = (1080,720), legend_size = 3))
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.poof()
```
#### Lasso Regression R2 Score
```
from sklearn.linear_model import Lasso
from yellowbrick.regressor import PredictionError
# Instantiate the linear model and visualizer
Lasso = Lasso()
visualizer = PredictionError(Lasso)#, ##size = (1080,720), legend_size = 3))
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.poof()
```
#### Ridge - Residual Plots
```
from sklearn.linear_model import Ridge
from yellowbrick.regressor import ResidualsPlot
Ridge = Ridge()
visualizer = ResidualsPlot(Ridge)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof()
```
#### Lasso - Residual Plots
```
from sklearn.linear_model import Lasso
from yellowbrick.regressor import ResidualsPlot
Lasso = Lasso()
visualizer = ResidualsPlot(Lasso)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof()
```
## Prediction and Error Plotting
### All Star Infielders
```
#Reset X and y values
features = ['AVG','HR','BB', '1B','3B']
X = dfinf3[features]
y = dfinf3['RC']
```
#### Ridge Regression - R2 Score
```
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import r2_score
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
#### Lasso Regression -R2 Score
```
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import r2_score
X_train, X_test, y_train, y_test = tts(X,y, random_state = 4, test_size = .2)
#want to first train the model on test data because if the model memorizes the training data and then evaluates, it will overfit
model = LinearRegression(fit_intercept=False)
model.fit(X_train, y_train)
y_hat = model.predict(X_test)
r2 = r2_score(y_test, y_hat)
print(r2)
```
### Re-measure importance of reduced feautures
```
features = ['AVG','HR','BB','1B','3B']
X= dfinf3[features]
y = dfinf3['RC']
from yellowbrick.features import Rank1D
visualizer = Rank1D(features = features, algorithm ='shapiro')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
#convert y from float to integer
y = dfinf3.RC.astype(int)
X = dfinf3[features]
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingClassifier
from yellowbrick.features.importances import FeatureImportances
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot()
#ax = ax
#This model takes over 90 seconds to run
viz = FeatureImportances(GradientBoostingClassifier(), ax = ax)
viz.fit(X,y)
viz.poof()
#reset value of y to y = dfinf3['RC']
y = dfinf3['RC']
from yellowbrick.features import Rank2D
visualizer = Rank2D(features=features, algorithm = 'covariance')
visualizer.fit(X,y)
visualizer.transform(X)
visualizer.poof()
```
## Data Visualization
### All Star Infielders
#### Visualize Plot Error
```
#Train Model again
from sklearn.model_selection import train_test_split
data = dfinf3
features = ['AVG','HR','BB', '1B','3B']
X = dfinf3[features]
y = dfinf3['RC']
#Create and train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
#### Ridge Regression R2 Score
```
from sklearn.linear_model import Ridge
from yellowbrick.regressor import PredictionError
# Instantiate the linear model and visualizer
Ridge = Ridge()
visualizer = PredictionError(Ridge)#, ##size = (1080,720), legend_size = 3))
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.poof()
```
#### Lasso Regression R2 Score
```
from sklearn.linear_model import Lasso
from yellowbrick.regressor import PredictionError
# Instantiate the linear model and visualizer
Lasso = Lasso()
visualizer = PredictionError(Lasso)#, ##size = (1080,720), legend_size = 3))
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.poof()
```
#### Ridge - Residual Plots
```
from sklearn.linear_model import Ridge
from yellowbrick.regressor import ResidualsPlot
Ridge = Ridge()
visualizer = ResidualsPlot(Ridge)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof()
```
#### Lasso - Residual Plots
```
from sklearn.linear_model import Lasso
from yellowbrick.regressor import ResidualsPlot
Lasso = Lasso()
visualizer = ResidualsPlot(Lasso)
visualizer.fit(X_train, y_train) # Fit the training data to the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.poof()
```
| github_jupyter |
# Elasticsearch Data Analytics
This notebook provides sample code to fetch Elasticsearch Data into and analyze it.
```
from IPython.display import Image
from IPython.core.display import HTML
Image(url= "https://www.antaresnet.com/wp-content/uploads/2018/07/Elasticsearch-Logo-Color-V.png")
```
## Loading modules and connect to the Elastic Stack
```
import sys
import json
import requests
import numpy as np
import pandas as pd
import seaborn as sns
import pytz
from datetime import datetime, timedelta
from dateutil import tz
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
plt.rcParams["figure.figsize"] = (18,10)
# connect to our cluster
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'elasticsearch', 'port': 9200}])
print('Last run: {} UTC, status: {} %'.format(
datetime.utcnow(),
es.cluster.health()['active_shards_percent_as_number']))
es.info()
```
Display our indices and document types saved in elasticsearch.
## Defining useful functions
```
!pip install "elasticsearch>=7.0.0,<8.0.0"
# %load scroller.py
def scroller(index, quantity, timerange=timedelta(days=0), startdt="", enddt=""):
print("Starting to scroll", end='')
# Retrieve the datetimes, note that timerange has a higher priority
if timerange.total_seconds() > 0:
now = datetime.utcnow().replace(tzinfo=pytz.UTC)
startdt = (now - timerange).isoformat()
enddt = now.isoformat()
# search the first page and write the result to data
response = es.search(
index=index,
body={
"query": {
"bool": {
"must": [
{"range" : {
"phenomenonTime" : {
#"gte": "2018-02-20T09:08:34.230693+00:00",
"gte": startdt,
"lte": enddt,
"time_zone": "+01:00"
}
}},
{
"match_phrase": {
"Datastream.name.keyword": quantity
}
}
]
}
}
},
scroll='10m'
)
data = [[row["_source"]["phenomenonTime"], row["_source"]["result"]] for row in response['hits']['hits']]
# Append new pages until there aren't any left
while len(response['hits']['hits']):
print(".", end='')
# process results
# print([item["_id"] for item in response["hits"]["hits"]])
response = es.scroll(scroll_id=response['_scroll_id'], scroll='10m')
data += [[row["_source"]["phenomenonTime"], row["_source"]["result"]] for row in response['hits']['hits']]
# Convert data to a DataFrame and return it
df = pd.DataFrame(data, columns=["phenomenonTime", quantity])
# df.index = pd.to_datetime(df["phenomenonTime"].map(lambda t: t.split(".")[0]), utc=True)
df.index = pd.to_datetime(df["phenomenonTime"].map(lambda t: roundto(t, 1)), utc=True)
df = df.drop(["phenomenonTime"], axis=1)
print("\nFetched {} tuples.".format(df.shape[0]))
return df
def roundto(string, n):
base = string.split(".")[0]
if n > 0:
base += "." + string.split(".")[1][:n]
return base
```
# Gather data from Elasticsearch
```
# Get data for an index and a quantity between two static timestamps
startdt="2019-08-07T08:58:34+00:00"
enddt="2019-08-07T11:58:34+00:00"
df = scroller("at.srfg.iot-iot4cps-wp5.infraprov.internal-*",
"at.srfg.iot-iot4cps-wp5.CarFleet1.car_1.Air Temperature",
startdt=startdt, enddt=enddt)
df.head()
# Get data for an index and a quantity of the latest timerange
df = scroller("at.srfg.iot-iot4cps-wp5.infraprov.internal-*",
"at.srfg.iot-iot4cps-wp5.CarFleet1.car_1.Air Temperature",
timerange=timedelta(days=10))
df.head()
# Plot the extracted data using pandas and seaborn
df.plot()
plt.show()
# Get multiple quantities and (outer) join them to a single DataFrame.
# There can be a lot of missing values
used_quantities = ["at.srfg.iot-iot4cps-wp5.CarFleet1.car_1.Air Temperature",
"at.srfg.iot-iot4cps-wp5.CarFleet2.car_2.Air Temperature"]
df = scroller("at.srfg.iot-iot4cps-wp5.infraprov.internal-*",
used_quantities[0],
timerange=timedelta(days=10))
for q in used_quantities[1:]:
print(q)
df = df.join(scroller("at.srfg.iot-iot4cps-wp5.infraprov.internal-*", q,
timerange=timedelta(days=10)),
how="outer")
df.head()
```
## Store and retrieve the DataFrame in a csv
```
df.to_csv("elasticsearchdata.csv")
df = pd.read_csv("elasticsearchdata.csv", parse_dates=True, index_col='phenomenonTime')
df.tail()
```
# Pre-processing
## Reduce size and interpolate
```
df = pd.read_csv("elasticsearchdata.csv", parse_dates=True, index_col='phenomenonTime')
df.index.names = ["time"]
col_mapping = {"at.srfg.iot-iot4cps-wp5.CarFleet1.car_1.Air Temperature": "car1_temp",
"at.srfg.iot-iot4cps-wp5.CarFleet2.car_2.Air Temperature": "car2_temp"}
df = df.rename(index=str,
columns=col_mapping)
df.head()
# Interpolate forwards and backwaonly up to
df = df.interpolate(method ='linear', limit_direction ='both', limit=10)
df = df.interpolate(method ='linear', limit_direction ='both', limit=10)
# Keep only the rows with at least 2 non-NA values.
df = df.dropna(thresh=2)
# make Timestamp unique
df = df.reset_index()
df = df.groupby("time").agg({q: "mean" for q in col_mapping.values()})
# Interpolate again to close gaps, use the smalles value
df = df.interpolate(method ='zero', limit_direction ='forward')
df = df.interpolate(method ='zero', limit_direction ='forward')
df.index.min()
df.shape
df.isna().sum()
df.describe()
# Keep only rows with all filled rows
df = df.dropna()
df.to_csv("elasticsearchdata.csv")
```
# Basic Data Analysis
```
df = pd.read_csv("elasticsearchdata.csv", parse_dates=True, index_col='time')
df.tail()
# df.hist()
plt.show()
# pd.plotting.scatter_matrix(df, alpha=0.2)
plt.show()
# corr = df.corr()
cm = sns.light_palette("orange", as_cmap=True)
cm = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
# corr.style.background_gradient(cmap=cm).set_precision(2)
```
# Feature Engineering
This task is very domain-specific and must be done by an expert.
# Data Analytics
```
from IPython.html.widgets import *
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["figure.figsize"] = (18,10)
sns.set(style="darkgrid")
def plot3D(pitch, yaw):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plot = ax.scatter(df['car1_temp'], df['car1_temp'], df['car2_temp'], c=df["car1_temp"], s=60)
fig.colorbar(plot)
ax.view_init(pitch, yaw)
ax.legend(['Vibration for each 3D position'])
ax.set_xlabel("x-Position")
ax.set_ylabel("y-Position")
ax.set_zlabel("z-Position")
interact(plot3D, pitch=(0,90,1), yaw=(0,90,1))
plt.show()
# df[col_mapping.values()].hist()
plt.show()
# pd.plotting.scatter_matrix(df[["vib", "distance", "projection", "v-radial", "v-tang"]], alpha=0.5)
plt.show()
# bins = np.linspace(0, df['v-radial'].max(), 10)
# df["binned-v-radial"] = pd.cut(df['v-radial'], bins)
# df.groupby("binned-v-radial").agg({"vib": {"min", "median", "mean", "max", "count"}})
# corr = df[df.columns.sort_values()].corr()[["vib", "vib-x", "vib-y"]]
# cm = sns.light_palette("orange", as_cmap=True)
# cm = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
# corr.style.background_gradient(cmap=cm).set_precision(2)
from IPython.display import Markdown
Markdown("""
## Inline Description:
It is very nice to describe results using Markdown with dynamic values like: **{pi}**.
""".format(pi=np.pi))
```
# Machine Learning
**Be careful when handling with Artificial Intelligence:**

| github_jupyter |
## 1. Import Data
```
from google.colab import drive
drive.mount('/content/gdrive', force_remount=True)
root_dir = '/content/gdrive/My Drive/Colab Notebooks/Bank Marketing Experiments/'
import os
os.chdir(root_dir)
import warnings
warnings.filterwarnings("ignore")
#reading the accepted loans
import pandas as pd
data = pd.read_csv(r'accepted_2007_to_2018Q4.csv', sep = ',', low_memory=True)
data.head()
```
## 2. Take only the loans that are either 'Fully Paid' or 'Charged Off'
```
#data = data[(data['loan_status']=='Fully Paid') | (data['loan_status']=='Charged Off')]
data = data.loc[data['loan_status'].isin(['Fully Paid', 'Charged Off'])]
data.shape
```
## 3. Limit the Feature Space
### 3.1. Drop features missing more than 30% data
```
missing_fractions = data.isnull().mean().sort_values(ascending=False)
drop_list = sorted(list(missing_fractions[missing_fractions > 0.3].index))
data.drop(labels=drop_list, axis=1, inplace=True)
data.shape
```
### 3.2. Only keep loan features known to potential investors
```
keep_list = ['addr_state', 'annual_inc', 'application_type', 'dti', 'earliest_cr_line', 'emp_length',
'emp_title', 'fico_range_high', 'fico_range_low', 'grade', 'home_ownership', 'id',
'initial_list_status', 'installment', 'int_rate', 'issue_d', 'loan_amnt', 'loan_status',
'mort_acc', 'open_acc', 'pub_rec', 'pub_rec_bankruptcies', 'purpose', 'revol_bal', 'revol_util',
'sub_grade', 'term', 'title', 'total_acc', 'verification_status', 'zip_code']
drop_list = [col for col in data.columns if col not in keep_list]
data.drop(labels=drop_list, axis=1, inplace=True)
data.shape
data.head()
```
## 4. Data Pre-processing
```
import numpy as np
# Id
data.drop('id', axis=1, inplace=True)
# term
data['term'] = data['term'].apply(lambda s: np.int8(s.split()[0]))
# grade
data.drop('grade', axis=1, inplace=True)
# emp_title
data.drop(labels='emp_title', axis=1, inplace=True)
# emp_length
data['emp_length'].replace(to_replace='10+ years', value='10 years', inplace=True)
data['emp_length'].replace('< 1 year', '0 years', inplace=True)
def emp_length_to_int(s):
if pd.isnull(s):
return s
else:
return np.int8(s.split()[0])
data['emp_length'] = data['emp_length'].apply(emp_length_to_int)
# home_ownership
data['home_ownership'].replace(['NONE', 'ANY'], 'OTHER', inplace=True)
# annual_inc
data['log_annual_inc'] = data['annual_inc'].apply(lambda x: np.log10(x+1))
data.drop('annual_inc', axis=1, inplace=True)
# title
data.drop('title', axis=1, inplace=True)
# zip_code
data.drop(labels='zip_code', axis=1, inplace=True)
# earliest_cr_line
data['earliest_cr_line'] = data['earliest_cr_line'].apply(lambda s: int(s[-4:]))
# fico_range_low, fico_range_high
data['fico_score'] = 0.5*data['fico_range_low'] + 0.5*data['fico_range_high']
data.drop(['fico_range_high', 'fico_range_low'], axis=1, inplace=True)
# revol_bal
data['log_revol_bal'] = data['revol_bal'].apply(lambda x: np.log10(x+1))
data.drop('revol_bal', axis=1, inplace=True)
# Convert loan status to 0/1 charge-off indicator
data['charged_off'] = (data['loan_status'] == 'Charged Off').apply(np.uint8)
data.drop('loan_status', axis=1, inplace=True)
# Create dummy variables
data = pd.get_dummies(data, columns=['sub_grade', 'home_ownership', 'verification_status',
'purpose', 'addr_state', 'initial_list_status',
'application_type'], drop_first=True)
data.head()
```
## 5. Train / Test split
### We'll make our modeling problem more realistic by performing the train/test split based on the month that the loan was funded. That is, we'll use loans funded on earlier dates to predict whether future loans will charge-off. The variable issue_d includes the month and year that the loan was funded.
```
data['issue_d'] = pd.to_datetime(data['issue_d'])
# We'll form the test set from the most recent 10% of the loans
data_train = data.loc[data['issue_d'] < data['issue_d'].quantile(0.8)]
data_test = data.loc[data['issue_d'] >= data['issue_d'].quantile(0.8)]
# Delete the data Dataframe
del data
```
### Let's look at the summary statistics of the issue dates in the train and test sets:
```
data_train['issue_d'].describe()
data_test['issue_d'].describe()
```
### Now we need to delete the issue_d variable, because it was not available before the loan was funded.
```
data_train.drop('issue_d', axis=1, inplace=True)
data_test.drop('issue_d', axis=1, inplace=True)
data_train.head()
```
### Do some undersampling on the training data to reduce the computational time
```
data_train_under = data_train[:].loc[data_train['charged_off']==1]
data_train_under = pd.concat([data_train_under, data_train[0:].loc[data_train['charged_off']==0]])
print("Initial training data points: ", data_train.shape[0])
print()
print("Training data after undersampling: ", data_train_under.shape[0])
print("Fully paid loans after undersampling: ", data_train_under.loc[data_train_under['charged_off']==0].shape[0])
print("Charged off loans after undersampling: ", data_train_under.loc[data_train_under['charged_off']==1].shape[0])
```
### Now separate the predictor variables from the response variable:
```
y_train = data_train_under['charged_off']
y_test = data_test['charged_off']
X_train = data_train_under.drop('charged_off', axis=1)
X_test = data_test.drop('charged_off', axis=1)
#del data_train, data_test, data_train_under
X_train.shape
```
## 6. Calculate missing values
```
def null_values(df):
mis_val = df.isnull().sum()
mis_val_percent = 100 * df.isnull().sum() / len(df)
mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)
mis_val_table_ren_columns = mis_val_table.rename(
columns = {0 : 'Missing Values', 1 : '% of Total Values'})
mis_val_table_ren_columns = mis_val_table_ren_columns[
mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(
'% of Total Values', ascending=False).round(1)
print ("Dataframe has " + str(df.shape[1]) + " columns.\n"
"There are " + str(mis_val_table_ren_columns.shape[0]) +
" columns that have missing values.")
return mis_val_table_ren_columns
# Missing values statistics
miss_values = null_values(X_train)
miss_values.head(20)
```
### Fill the missing values
```
# Take the columns
cols = X_train.columns
cols = list(cols)
# Impute missing values
from sklearn.impute import SimpleImputer
imp = SimpleImputer(missing_values=np.nan, strategy='mean', copy=False)
imp.fit(X_train)
X_train = imp.transform(X_train)
X_test = imp.transform(X_test)
X_train = pd.DataFrame(X_train)
X_train.columns = cols
X_test = pd.DataFrame(X_test)
X_test.columns = cols
X_train.head()
```
### Scale the Data
```
# Scale the Data
from sklearn import preprocessing
x = X_train.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
X_train = pd.DataFrame(x_scaled)
X_train.columns = cols
x = X_test.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
X_test = pd.DataFrame(x_scaled)
X_test.columns = cols
X_train.head()
```
## 7. Change Directory
```
root_dir = '/content/gdrive/My Drive/Colab Notebooks/Bank Marketing Experiments/Comparison of GBT and CORELS/Interpretable_GBT/example/'
os.chdir(root_dir)
```
## 8. Create a Validation Set
```
from sklearn.model_selection import train_test_split
'''
creating a 50 / 50 validation, test split
'''
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size = 0.50, random_state = 777)
```
## 9. Train the Neural Network and use F1 score as evaluation metric
```
from keras import backend as K
def f1(y_true, y_pred):
def recall(y_true, y_pred):
"""Recall metric.
Only computes a batch-wise average of recall.
Computes the recall, a metric for multi-label classification of
how many relevant items are selected.
"""
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(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
"""
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
precision = precision(y_true, y_pred)
recall = recall(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
```
### Train the Neural Network
```
import warnings
warnings.filterwarnings("ignore")
from keras import optimizers
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.callbacks import EarlyStopping
from matplotlib import pyplot
model = Sequential()
model.add(Dense(4096, input_shape = (len(X_train.columns),), activation='relu'))
#model.add(Dropout(0.3))
model.add(Dense(2048, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='linear'))
model.add(Dense(1, activation = 'sigmoid'))
opt = optimizers.RMSprop(lr=0.00001) # default is 0.001
model.compile(optimizer = opt,
loss = 'binary_crossentropy',
metrics = ['accuracy', f1])
# Adjust the weights of the classes since your dataset is HIGHLY IMBALANCED!
class_weight = {0: 1.,
1: 4.25}
model.fit(X_train,
y_train,
epochs = 4,
batch_size = 512,
validation_data = (X_val, y_val), class_weight=class_weight,
callbacks=[EarlyStopping(monitor='val_f1', mode='max', patience=30, restore_best_weights=True)])
#let's get the training and validation accuracies for plotting
val_acc = model.history.history['val_acc']
acc = model.history.history['acc']
print(model.summary())
# let's plot the performance curve
import matplotlib.pyplot as plt
plt.figure()
plt.plot(val_acc, label='Validation')
plt.plot(acc, label = 'Training')
plt.gcf().set_size_inches(8.5, 5)
plt.xlabel('Epoch',size=14)
plt.ylabel('Accuracy',size=14)
plt.legend(loc="lower right", prop={'size':11.5})
plt.show()
```
## 10. Check Test Accuracy, Confusion Matrix, Classification report and ROC curve
```
from sklearn.metrics import accuracy_score
y_prediction = model.predict_classes(X_test)
print("The Test Accuracy of the model is: {} %".format(accuracy_score(y_test, y_prediction) * 100.))
print()
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, y_prediction))
print()
from sklearn.metrics import classification_report
target_names = ['Fully Paid', 'Charged Off']
print(classification_report(y_test, y_prediction, target_names=target_names))
import numpy as np
prob = model.predict(X_test)
full_prob = np.zeros((y_test.shape[0],2))
full_prob[:,0] = 1-np.squeeze(prob)
full_prob[:,1] = np.squeeze(prob)
y_test_array = np.asarray(y_test)
y_test_ar = np.zeros((y_test.shape[0],2))
for i in range(0, y_test.shape[0]):
if y_test_array[i] == 0:
y_test_ar[i,0] = 1
else:
y_test_ar[i,1] = 1
from itertools import cycle
from sklearn.metrics import roc_curve, auc
from scipy import interp
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
classes = ["0: The loans were Fully Paid", "1: The loans were Charged Off"]
for i in range(0,2):
fpr[i], tpr[i], _ = roc_curve(y_test_ar[:, i], full_prob[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
plt.figure(figsize=(10,8))
lw = 2
for i in range(2):
plt.plot(fpr[i], tpr[i], lw=2,
label='ROC curve of Class {0} (AUC = {1:0.3f})'
''.format(classes[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate',fontsize=15)
plt.ylabel('True Positive Rate',fontsize=15)
plt.title('Receiver operating characteristic (ROC) curve',fontsize=16)
plt.legend(loc="lower right",fontsize=12)
plt.show()
```
It should be noted that the above result of AUC=0.695 has beaten the result of the Top Voted kernel in Kaggle as shown in the following link [*Kaggle Top Kernel*](https://www.kaggle.com/pileatedperch/predicting-charge-off-from-initial-listing-data).
## 11. Anchors Rule-Based Model-Agnostic Explanations
The below Rule-Based Explanations are based on the results of the paper [*High-Precision Model-Agnostic Explanations*](https://homes.cs.washington.edu/~marcotcr/aaai18.pdf) published in AAAI in 2018.
```
!pip install anchor_exp
from anchor import utils
from anchor import anchor_tabular
```
### Fit the Explainer
```
explainer = anchor_tabular.AnchorTabularExplainer(['Fully Paid','Charged Off'], X_train.columns, X_train.values, categorical_names = {})
explainer.fit(X_train.values, y_train, X_val.values, y_val, discretizer='quartile')
```
### Check Train and Test Accuracy
```
import sklearn
predict_fn = lambda x: model.predict(explainer.encoder.transform(x))
print('Train', sklearn.metrics.accuracy_score(y_train, np.rint(predict_fn(X_train))))
print('Test', sklearn.metrics.accuracy_score(y_test, np.rint(predict_fn(X_test))))
```
### Pick an example and check the prediction of the model for this example
```
def predict(qc):
global model
qc = model.predict(qc)
return qc.reshape(qc.shape[0])
idx = 1008
np.random.seed(1)
print('Prediction: ', explainer.class_names[int(np.rint(predict_fn(X_test.values[idx].reshape(1, -1))[0])[0])])
exp = explainer.explain_instance(X_test.values[idx], predict, threshold=0.80)
print('Anchor: %s' % (' AND '.join(exp.names())))
print('Precision: %.2f' % exp.precision())
print('Coverage: %.2f' % exp.coverage())
```
Note that we set threshold to 0.95, so we guarantee (with high probability) that precision will be above 0.95 - that is, that predictions on instances where the anchor holds will be the same as the original prediction at least 95% of the time. Let's try it out on the test set
```
# Get test examples where the anchor applies
fit_anchor = np.where(np.all(X_test.values[:, exp.features()] == X_test.values[idx][exp.features()], axis=1))[0]
print('Anchor test coverage: %.2f' % (fit_anchor.shape[0] / float(X_test.values.shape[0])))
print('Anchor test precision: %.2f' % (np.mean(predict_fn(X_test.values[fit_anchor]) == predict_fn(X_test.values[idx].reshape(1, -1)))))
```
### Looking at a partial anchor
You can look at just part of the anchor - for example, the first two clauses. Note how these do not have enough precision.
```
print('Partial anchor: %s' % (' AND '.join(exp.names(1))))
print('Partial precision: %.2f' % exp.precision(1))
print('Partial coverage: %.2f' % exp.coverage(1))
fit_partial = np.where(np.all(X_test.values[:, exp.features(1)] == X_test.values[idx][exp.features(1)], axis=1))[0]
print('Partial anchor test precision: %.2f' % (np.mean(predict_fn(X_test.values[fit_partial]) == predict_fn(X_test.values[idx].reshape(1, -1)))))
print('Partial anchor test coverage: %.2f' % (fit_partial.shape[0] / float(X_test.values.shape[0])))
```
| github_jupyter |
# Ecomonitor data converter
This program has been written to convert the available consumption data from the NURI smart meter to the preferred structure for NILM-Eval (https://github.com/beckel/nilm-eval).
The data is received from the EcoMonitor smart meter data collector, made by Hark Tech by downloading a CSV-file from the customer website.
Input: 1 CSV-file from EcoMonitor from the path data/rawdata/smartmeter/ecomonitor.csv.
Output: 16 separated consumption CSV-files in folders based on the data collection in the path per day: /data/powermundsen_data/smartmeter/YYYY-MM-DD
TODO:
- Change plotting so that it also plots the missing values in data. Now it only prints the data available and some days where data is missing will hence have a compressed x-axis. This missing data is smoothed in the Matlab-script so by plotting the data from there is best at the moment.
- Change script so that it iterates through available households. At the moment it only works with one, the one set by the variable "household."
## Removing unwanted columns
```
import csv
import pandas as pd
from pylab import *
import datetime
import time
import os
# Setting variables
mpl.rcParams['agg.path.chunksize'] = 10000 # To avoid error message when plotting
plt.rcParams["figure.dpi"] = 600
plt.rcParams.update({'font.size': 22})
current_directory = os.getcwd()
household = '01'
plotvalues = {'Pi':'Active power in [W]',
'Pe':'Active power out [W]',
'Qi':'Reactive power in [VAr]',
'Qe':'Reactive power out [VAr]',
'I1':'Current phase 1 [A]',
'I2':'Current phase 2 [A]',
'I3':'Current phase 3 [A]',
'U1':'Voltage phase 1 [V]',
'U2':'Voltage phase 2 [V]',
'U3':'Voltage phase 3 [V]',
'powerl1': 'Active power phase 1 [W]',
'powerl2': 'Active power phase 2 [W]',
'powerl3': 'Active power phase 3 [W]',
'Ai':'Accumulated active power in [KW]',
'Ae':'Accumulated active power out [KW]',
'Ri':'Accumulated reactive power in [VArh]',
'Re':'Accumulated reactive power out [VArh]',
'phaseanglevoltagel2l1':'Phase angle voltage l2l1 [Degrees] ',
'phaseanglevoltagel3l1':'Phase angle voltage l3l1 [Degrees]'}
units = {'Pi':'W',
'Pe':'kW',
'Qi':'VAr',
'Qe':'VAr',
'I1':'Amper',
'I2':'Amper',
'I3':'Amper',
'U1':'Volt',
'U2':'Volt',
'U3':'Volt',
'powerl1': 'W',
'powerl2': 'W',
'powerl3': 'W',
'Ai':'KWh',
'Ae':'KWh',
'Ri':'VArh',
'Re':'VArh',
'phaseanglevoltagel2l1':'Degrees',
'phaseanglevoltagel3l1':'Degrees'}
filenames = {'Pi':'powerallphases',
'I1':'currentl1',
'I2':'currentl2',
'I3':'currentl3',
'U1':'voltagel1',
'U2':'voltagel2',
'U3':'voltagel3',
'powerl1': 'powerl1',
'powerl2': 'powerl2',
'powerl3': 'powerl3',
'phaseanglevoltagel2l1':'phaseanglevoltagel2l1',
'phaseanglevoltagel3l1':'phaseanglevoltagel3l1'}
# Import the CSV
df = pd.read_csv('data/rawdata/smartmeter/ecomonitor.csv')
# Renaming columns
df.rename(columns={'DTM':'time'}, inplace=True)
# Converting from kW to W
df.loc[:,'Pi'] *= 1000
df.loc[:,'Pe'] *= 1000
df.loc[:,'Qi'] *= 1000
df.loc[:,'Qe'] *= 1000
df.loc[:,'Ri'] *= 1000
df.loc[:,'Re'] *= 1000
# U1 and U3 are measured against U2, leaving U2 to be 0. U1, U2, and U3 should all have been measured
# against ground to work with NILM-eval. U2 is therefore given the value of (U1+U3)/2 as a quick fix.
df['U2'] = (df['U1']+df['U3'])/2
# Making new columns for date, time, powerl1, powerl2, powerl3, phaseanglevoltagel2l1 and phaseanglevoltagel3l1
df['powerl1'] = df['I1']*df['U1']
df['powerl2'] = df['I2']*df['U2']
df['powerl3'] = df['I3']*df['U3']
df['phaseanglevoltagel2l1'] = 240
df['phaseanglevoltagel3l1'] = 120
df['year'] = df['time'].str.slice(0,4)
df['month'] = df['time'].str.slice(5,7)
df['day'] = df['time'].str.slice(8,10)
df['time_of_day'] = df['time'].str.slice(11,16)
# Adding seconds count
for index, row in df.iterrows():
timestamp = row['time']
time_reduced = timestamp[-8:]
x = time.strptime(time_reduced.split(',')[0],'%H:%M:%S')
second = datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
df.set_value(index,'second',second)
# Finding unique days
unique_years = df.year.unique()
unique_months = df.month.unique()
unique_days = df.day.unique()
print('Unique years: %s, Unique months: %s, Unique days: %s' %(unique_years, unique_months, unique_days))
print('\t\t Staring day iteration')
for year in unique_years:
for month in unique_months:
for day in unique_days:
print('\t\t\t Working on day %s-%s-%s' %(year, month, day))
df_temp = df.loc[(df['day'] == day)] # Locks the rows with this value
# Setting second to be index (First second of day is 00:00:00)
df_temp.set_index("second")
new_index = pd.Index(arange(0,86400), name="second")
df_temp = df_temp.set_index("second").reindex(new_index)
# Plot graphs and save to
print('\t\t\t Making daily plots')
for value in plotvalues:
df_print = df_temp.dropna(subset=[value])
plot = df_print.plot(x = 'time_of_day', y = value, label= plotvalues[value], figsize=[20,10]);
plot.set_xlabel('Smart meter measurements %s-%s-%s' %(year, month, day))
plot.set_ylabel(units[value])
fig = plot.get_figure();
plotpath = current_directory + '/data/plots/smartmeter/'
if not os.path.exists(plotpath):
os.makedirs(plotpath)
filename = year+'-'+month+'-'+day+':'+ value +'-'+plotvalues[value]
fig.savefig(plotpath + filename +'.png')
plt.clf()
plt.close('all')
# Adding value -1 in power to rows with NaN
df_temp[value].fillna('-1', inplace=True)
# Save to file with a filename that includes: date, value, household.
print('\t\t\t Saving to file')
path = current_directory + '/data/powermundsen_data/smartmeter/' + household + '/' + year + '-' + month + '-' + day
if not os.path.exists(path):
os.makedirs(path)
if value in filenames:
df_temp.to_csv(os.path.join(path, r'%s' %(filenames[value]) + '.csv'), columns=[value], index=True, header=False)
# Adding the remaining files the add on uses (These have no value since we dont have the data)
print('Making the empty files...')
path = current_directory + '/data/powermundsen_data/smartmeter/' + household + '/' + year + '-' + month + '-' + day
others = ['currentneutral', 'phaseanglecurrentvoltagel1', 'phaseanglecurrentvoltagel2', 'phaseanglecurrentvoltagel3']
for element in others:
df_temp[element] = -1
df_temp.to_csv(os.path.join(path, r'%s' %element +'.csv'), columns=[element], index=True, header=False)
print('\t\t\t Finished processing day %s ' %day)
print('Finished processing all smart meter data')
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras import Sequential
from keras.layers import Embedding, Conv1D, BatchNormalization, Flatten, Dense, Dropout
from keras.optimizers import Adam
from keras.callbacks import ReduceLROnPlateau, ModelCheckpoint
from sklearn import metrics
from dataUtils import DataUtils
from model_utils import ModelUtils
dset = DataUtils.readData('cleaned_data_emission.tsv', sep='\t')
X, y = DataUtils.get_xy(dset, 9, 8)
word_map = DataUtils.get_wordmap(x_smiles=X)
```
#### Set uniform length
```
uniform_length = DataUtils.get_max_len(X) + 5
X_numeric = DataUtils.numeric_encoding(x_list=X, word_map=word_map, uniform_length=uniform_length)
```
#### Save out wordmap as json file
```
DataUtils.save_wordmap_json(word_map, 'smiles_wordmap.json')
X_train, X_test, y_train, y_test = DataUtils.splitData(x=X_numeric, y=y, ratio=0.2)
y_train = np.reshape(y_train, (-1, 1))
y_test = np.reshape(y_test, (-1, 1))
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
model = Sequential()
model.add(Embedding(len(word_map), 50, input_length=279))
model.add(BatchNormalization())
model.add(Conv1D(192,10,activation='relu'))
model.add(Dropout(0.4))
model.add(Conv1D(192,5,activation='relu'))
model.add(Conv1D(192,3,activation='relu'))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(1, activation='linear'))
model.summary()
def coeff_determination(y_true, y_pred):
from keras import backend as K
SS_res = K.sum(K.square( y_true-y_pred ))
SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) )
return ( 1 - SS_res/(SS_tot + K.epsilon()) )
def get_lr_metric(optimizer):
def lr(y_true, y_pred):
return optimizer.lr
return lr
callbacks_list = [
ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=1e-15, verbose=1, mode='auto',cooldown=0),
ModelCheckpoint(filepath="weights.best.hdf5", monitor='val_loss', save_best_only=True, verbose=1, mode='auto')
]
optimizer = Adam(lr=0.00025)
lr_metric = get_lr_metric(optimizer)
model.compile(loss="mse", optimizer=optimizer, metrics=[coeff_determination, lr_metric])
history = model.fit(x=X_train, y=y_train, batch_size=128, epochs=150, validation_data=(X_test,y_test))
ModelUtils.plot_model_error(X_train,X_test,y_train.reshape(1,-1), y_test.reshape(1,-1),model)
from sklearn import metrics
```
### R square training vs. R square testing
```
metrics.r2_score(y_train, model.predict(X_train))
metrics.r2_score(y_test, model.predict(X_test))
```
a little overfitting
### mean absolute error
```
metrics.mean_absolute_error(y_train, model.predict(X_train))
metrics.mean_absolute_error(y_test, model.predict(X_test))
```
### plot history
```
hist = history.history
plt.figure(figsize=(10, 8))
for label in ['val_coeff_determination','coeff_determination']:
plt.subplot(211)
plt.plot(hist[label], label = label)
plt.legend()
plt.xlabel("Epochs")
plt.ylabel("coeff_determination")
for label in ['val_loss','loss']:
plt.subplot(212)
plt.plot(hist[label], label = label)
plt.legend()
plt.xlabel("Epochs")
plt.ylabel("loss")
plt.subplots_adjust(top=0.8, bottom=0.1, left=0.10, right=0.9, hspace=0.25,
wspace=0.35)
```
Add another 150 epochs
```
history1 = model.fit(x=X_train, y=y_train, batch_size=128, epochs=150, validation_data=(X_test,y_test))
metrics.r2_score(y_train, model.predict(X_train))
metrics.r2_score(y_test, model.predict(X_test))
metrics.mean_absolute_error(y_train, model.predict(X_train))
metrics.mean_absolute_error(y_test, model.predict(X_test))
```
Overfitting
```
hist = history1.history
plt.figure(figsize=(10, 8))
for label in ['val_coeff_determination','coeff_determination']:
plt.subplot(211)
plt.plot(hist[label], label = label)
plt.legend()
plt.xlabel("Epochs")
plt.ylabel("coeff_determination")
for label in ['val_loss','loss']:
plt.subplot(212)
plt.plot(hist[label], label = label)
plt.legend()
plt.xlabel("Epochs")
plt.ylabel("loss")
plt.subplots_adjust(top=0.8, bottom=0.1, left=0.10, right=0.9, hspace=0.25,
wspace=0.35)
```
## BETTER MODEL, with callback checkpointing to save the best weight
```
model = Sequential()
model.add(Embedding(len(word_map), 50, input_length=279))
model.add(BatchNormalization())
model.add(Conv1D(192,10,activation='relu'))
model.add(Dropout(0.4))
model.add(Conv1D(192,5,activation='relu'))
model.add(Conv1D(192,3,activation='relu'))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(1, activation='linear'))
model.summary()
optimizer = Adam(lr=0.00025)
lr_metric = get_lr_metric(optimizer)
model.compile(loss="mse", optimizer=optimizer, metrics=[coeff_determination, lr_metric])
callbacks_list = [
ModelCheckpoint(filepath="weights.best.hdf5", monitor='val_loss', save_best_only=True, verbose=1, mode='auto')
]
history = model.fit(x=X_train, y=y_train, batch_size=128, epochs=250, validation_data=(X_test,y_test), callbacks=callbacks_list)
metrics.r2_score(y_train, model.predict(X_train))
metrics.r2_score(y_test, model.predict(X_test))
metrics.mean_absolute_error(y_train, model.predict(X_train))
metrics.mean_absolute_error(y_test, model.predict(X_test))
hist = history.history
plt.figure(figsize=(8, 10), dpi=100)
for label in ['val_loss','loss']:
plt.subplot(212)
plt.plot(hist[label], label = label)
plt.legend()
plt.xlabel("Epochs",fontsize = 12)
plt.ylabel("loss", fontsize = 12)
plt.subplots_adjust(top=0.8, bottom=0.1, left=0.10, right=0.9, hspace=0.25,
wspace=0.35)
plt.savefig('loss_vs_epochs_smiles_cnn.png')
loss_history = history.history["loss"]
numpy_loss_history = np.array(loss_history)
np_R2_history = np.array(history.history['coeff_determination'])
```
### save the loss and R2 in the history
```
np.savetxt("loss_history_epoch_smiles_cnn.txt", numpy_loss_history, delimiter=",")
np.savetxt("R2_history.txt" ,np_R2_history, delimiter=",")
plt.figure(figsize=(8, 10), dpi=100)
plt.subplot(211)
plt.scatter(y_train, model.predict(X_train), color = 'r', label = 'train')
plt.scatter(y_test, model.predict(X_test), color = 'blue', label = 'test')
plt.xlabel('Actual Absorption Wavelength(nm)', fontsize=12)
plt.ylabel('Predicted Absorption Wavelength(nm)', fontsize=12)
plt.legend(loc='upper center')
plt.subplot(212)
plt.scatter(y_train, model.predict(X_train)-y_train, color = 'r', label = 'train', marker= 'x')
plt.scatter(y_test, model.predict(X_test)-y_test, color = 'blue', label = 'test', marker = 'x')
plt.axhline(0, ls='--')
plt.xlabel('Actual Absorption Wavelength(nm)', fontsize=12)
plt.ylabel('Prediction error(nm)', fontsize=12)
plt.legend(loc='upper center')
plt.savefig('smiles_cnn_metrics_plot.png')
ModelUtils.plot_model_error(X_train,X_test,y_train.reshape(1,-1), y_test.reshape(1,-1),model)
```
### To SAVE model AND Weight
```
model_json = model.to_json()
with open("model_smiles_cnn.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
#model.save_weights("model_smiles_cnn.h5")
print("Saved model to disk")
```
### To LOAD model
```
from keras.models import model_from_json
json_file = open('model_smiles_cnn.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights('weights.best.hdf5')
y_train
plt.figure(figsize=(8, 10), dpi=100)
plt.subplot(211)
plt.scatter(y_train, loaded_model.predict(X_train), color = 'r', label = 'train')
plt.scatter(y_test, loaded_model.predict(X_test), color = 'blue', label = 'test')
plt.xlabel('Actual Absorption Wavelength(nm)', fontsize=12)
plt.ylabel('Predicted Absorption Wavelength(nm)', fontsize=12)
plt.legend(loc='upper center')
plt.subplot(212)
plt.scatter(y_train, loaded_model.predict(X_train)-y_train, color = 'r', label = 'train', marker= 'x')
plt.scatter(y_test, loaded_model.predict(X_test)-y_test, color = 'blue', label = 'test', marker = 'x')
plt.axhline(0, ls='--')
plt.xlabel('Actual Absorption Wavelength(nm)', fontsize=12)
plt.ylabel('Prediction error(nm)', fontsize=12)
plt.legend(loc='upper center')
plt.savefig('smiles_cnn_metrics_plot_loaded_model.png')
rev_wordmap=DataUtils.reverse_wordmap(word_map)
DataUtils.decode_num_smiles(X_train, rev_wordmap)
metrics.r2_score(y_train, loaded_model.predict(X_train))
metrics.r2_score(y_test, loaded_model.predict(X_test))
indivisual_X_string1=X[9]
indivisual_X_string2=X[12]
indivisual_X_code = DataUtils.numeric_encoding(np.array([indivisual_X_string1, indivisual_X_string2]), uniform_length,word_map)
indivisual_X_code.shape
X_train.shape
loaded_wordmap=DataUtils.load_wordmap_from_json('smiles_wordmap.json')
loaded_model.predict(indivisual_X_code)
def predict_abs_wavelength(smiles_string = 'C1=CC=CC=C1', uniform_length_of_model = 279, word_map = None, model = None):
indivisual_X_code = DataUtils.numeric_encoding(np.array([smiles_string]), uniform_length_of_model,word_map)
pred_abs_wl = model.predict(indivisual_X_code)
return pred_abs_wl
predict_abs_wavelength(smiles_string='CC(=O)C1=C(C(=C(C=C1)O)O)O', word_map=loaded_wordmap, model=loaded_model)
```
| github_jupyter |
# Shared Task Submission
### Experimental Settings:
`Twitter word settings:`
* `window = 3 tokens `
* `embeddings -> twitter pre-trained embeddings, Godin`
* `dimensions = 400`
* `LSTM units = 100 -> 200 (Bi-LSTM)`
`Other settings:`
* `Epochs -> 150`
* `Batch size -> 500`
* `Opimizer -> Admax`
* `Seed 1337 for reproducibility`
```
experiment = 'notebook'
# os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=cuda,floatX=float64"
import sys
sys.path += [new_path
for new_path in ['..',
'../embeddings/twitter']
if new_path not in sys.path]
import numpy as np
seed_number = 1337
np.random.seed(seed_number) # for reproducibility
import pycrfsuite as crf
import matplotlib.pyplot as plt
import common.utilities as utils
from settings import *
from pycrfsuite import ItemSequence
from collections import Counter, defaultdict as ddict
from embeddings.twitter.word2vecReader import Word2Vec, Vocab
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.preprocessing import LabelBinarizer
from keras.models import Model
from keras.layers import Embedding
from keras.layers import Conv1D
from keras.layers import Dropout
from keras.layers import Bidirectional
from keras.layers import Flatten
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import Input
from keras.layers.merge import concatenate
from keras.layers.pooling import GlobalAveragePooling1D
from keras.optimizers import Adamax
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.preprocessing import sequence
from keras.preprocessing.sequence import pad_sequences
from keras.initializers import RandomUniform
```
# Loading data
```
tweets_train, labels_train = utils.read_file_as_lists(TRAIN_PREPROC_URL)
tweets_dev, labels_dev = utils.read_file_as_lists(DEV_PREPROC_URL)
tweets_test, labels_test = utils.read_file_as_lists(TEST_PREPROC_URL)
tweets_train += tweets_dev
labels_train += labels_dev
vocabulary = list(set(utils.flatten(tweets_train + tweets_test)))
print("Vocabulary:", len(vocabulary))
```
# Loading POS Tags
```
pos_tweets_train, postags_train = utils.read_file_as_lists(TRAIN_PREPROC_URL_POSTAG)
pos_tweets_dev, postags_dev = utils.read_file_as_lists(DEV_PREPROC_URL_POSTAG)
pos_tweets_test, postags_test = utils.read_file_as_lists(TEST_PREPROC_URL_POSTAG)
pos_tweets_train += pos_tweets_dev
postags_train += postags_dev
utils.sync_postags_and_tweets(tweets_train, pos_tweets_train, postags_train)
utils.sync_postags_and_tweets(tweets_test, pos_tweets_test, postags_test)
```
# Loading Twitter embeddings
```
%%time
w2v_model = Word2Vec.load_word2vec_format(W2V_TWITTER_EMB_GODIN, binary=True)
twitter_vb = {token:v.index for token,v in w2v_model.vocab.items()}
# Using only needed embeddings (faster this way)
twitter_index2word, twitter_embeddings = utils.pick_embeddings_by_indexes(vocabulary, w2v_model.syn0, twitter_vb)
twitter_index2word = [PAD_TOKEN, UNK_TOKEN] + twitter_index2word
twitter_word2index = ddict(lambda: twitter_index2word.index(UNK_TOKEN), {w:i for i,w in enumerate(twitter_index2word)})
twitter_embeddings = np.append(np.zeros((2,twitter_embeddings.shape[1])), twitter_embeddings, axis=0)
```
# Loading Gazetteers embeddings
```
gazetteers = utils.read_file_as_list_of_tuples(GAZET_EMB_ONE_CHECK)[0]
index2gaze, gaze_embeddings = zip(*[(data[0], data[1:]) for data in gazetteers])
index2gaze = [UNK_TOKEN, PAD_TOKEN] + list(index2gaze)
gaze2index = ddict(lambda: index2gaze.index(UNK_TOKEN), {g:i for i,g in enumerate(index2gaze)})
gaze_embeddings = np.append(np.zeros((2,6)), gaze_embeddings, axis=0)
```
# Encoding words and labels
```
window = 1
x_word_twitter_train = utils.build_x_matrix(window, [[twitter_word2index[token] for token in tweet] for tweet in tweets_train], twitter_word2index[PAD_TOKEN])
x_word_twitter_test = utils.build_x_matrix(window, [[twitter_word2index[token] for token in tweet] for tweet in tweets_test], twitter_word2index[PAD_TOKEN])
index2label_cat = [
'B-corporation',
'B-creative-work',
'B-group',
'B-location',
'B-person',
'B-product',
'I-corporation',
'I-creative-work',
'I-group',
'I-location',
'I-person',
'I-product',
'O'
]
y_cat_train, label2index_cat, _ = utils.vectorize_labels(labels_train, index2label_cat)
def map_to_binary(labels):
return [['TRUE' if label != 'O' else 'FALSE' for label in lbls] for lbls in labels]
labels_seg_train = map_to_binary(labels_train)
index2label_seg = ['FALSE', 'TRUE']
label2index_seg = { l:i for i, l in enumerate(index2label_seg) }
lb = LabelBinarizer()
y_seg_train = lb.fit_transform(utils.flatten(labels_seg_train))
```
# Encoding POS tags
```
index2postag = [PAD_TOKEN] + list(set(utils.flatten(postags_train + postags_test)))
postag2index = {w:i for i,w in enumerate(index2postag)}
x_postag_train = utils.build_x_matrix(window, [[postag2index[token] for token in tweet] for tweet in postags_train], postag2index[PAD_TOKEN])
x_postag_test = utils.build_x_matrix(window, [[postag2index[token] for token in tweet] for tweet in postags_test], postag2index[PAD_TOKEN])
```
# Encoding orthography
```
ortho_max_length = 20
index2ortho = ['x', 'c', 'C', 'n', 'p']
ortho2index = ddict(lambda: 0, {o:i for i,o in enumerate(index2ortho)})
x_ortho_twitter_train = pad_sequences(utils.encode_tokens(ortho2index, utils.flatten(utils.orthographic_mapping(tweets_train))), maxlen=ortho_max_length)
x_ortho_twitter_test = pad_sequences(utils.encode_tokens(ortho2index, utils.flatten(utils.orthographic_mapping(tweets_test))), maxlen=ortho_max_length)
```
# Encoding gazetteers
```
encoded_gaze_train = [[gaze2index[token] for token in tweet] for tweet in tweets_train]
encoded_gaze_test = [[gaze2index[token] for token in tweet] for tweet in tweets_test]
x_gaze_train = utils.build_x_matrix(window, encoded_gaze_train, gaze2index[PAD_TOKEN])
x_gaze_test = utils.build_x_matrix(window, encoded_gaze_test, gaze2index[PAD_TOKEN])
```
# Neural Network -- Character Representation
```
def get_input_layer(shape, name):
return Input(shape=shape, dtype='int32', name='{}_input'.format(name))
def pretrained_embedding_layer(embeddings, input_layer, input_len, name):
embed_layer = Embedding(embeddings.shape[0],
embeddings.shape[1],
input_length=input_len,
weights=[embeddings],
trainable=False,
name='{}_embed'.format(name))(input_layer)
embed_layer = Dropout(0.5, name='{}_embed_dropout'.format(name))(embed_layer)
return embed_layer
def rand_uniform_embedding_layer(input_layer, input_dim, output_dim, input_len, name):
uniform = RandomUniform(seed=seed_number,
minval=-np.sqrt(3/output_dim), # Suggested by
maxval= np.sqrt(3/output_dim)) # He et al (2015)
embed_layer = Embedding(input_dim=input_dim,
output_dim=output_dim,
input_length=input_len,
embeddings_initializer=uniform,
trainable=False,
name='{}_embed'.format(name))(input_layer)
embed_layer = Dropout(0.5, name='{}_embed_dropout'.format(name))(embed_layer)
return embed_layer
ortho_dim = 30
char_ortho_input = get_input_layer((ortho_max_length,), 'char_ortho')
char_ortho_embed = rand_uniform_embedding_layer(char_ortho_input,
len(index2ortho),
ortho_dim,
ortho_max_length,
'char_ortho')
```
### CNN Network
```
def get_char_cnn(embedded, name, filters=64, kernel_size=3, dense_units=32, convs=2):
conv_net = embedded
for _ in range(convs):
conv_net = Conv1D(filters=filters, kernel_size=kernel_size, activation='relu')(conv_net)
conv_net = GlobalAveragePooling1D()(conv_net)
conv_net = Dense(dense_units, activation='relu', name='{}_dense'.format(name))(conv_net)
return conv_net
char_encoded = char_ortho_embed
char_encoded = get_char_cnn(char_encoded, 'char_encoded')
char_encoder = Model(inputs=[char_ortho_input], outputs=[char_encoded])
char_encoder.summary()
```
# Neural Network -- Word Representation
```
twitter_input = get_input_layer((window*2+1,), 'word_twitter')
twitter_embed = pretrained_embedding_layer(twitter_embeddings,
twitter_input,
window*2+1,
'word_twitter')
postag_dim = 100
postag_input = get_input_layer((window*2+1,), 'word_postag')
postag_embed = rand_uniform_embedding_layer(postag_input,
len(index2postag),
postag_dim,
window*2+1,
'word_postag')
```
### BLSTM Network
```
word_encoded = concatenate([twitter_embed, postag_embed], axis=2)
word_encoded = Bidirectional(LSTM(100,
return_sequences=False,
dropout=0.2,
recurrent_dropout=0.2),
name='word_encoded_blstm')(word_encoded)
word_encoded = Dropout(0.5, name='word_encoded_blstm_dropout')(word_encoded)
word_encoder = Model(inputs=[twitter_input,
postag_input,
], outputs=[word_encoded])
word_encoder.summary()
```
### Feed-Forward NN
```
gazetteer_input = get_input_layer((window * 2 + 1,), 'gazzetteer')
gazetteer_embed = pretrained_embedding_layer(gaze_embeddings,
gazetteer_input,
window*2+1,
'gazetteer')
gazetteer_dense = Dense(units=32, activation="relu", name='gazetteer_dense')(gazetteer_embed)
gazetteer_dense = Flatten()(gazetteer_embed)
```
### Final Concatenation
```
network = concatenate([gazetteer_dense, char_encoded, word_encoded], name='concat_layer')
network = Dense(100, activation='relu', name='common_dense_layer') (network)
seg_output = Dense(1, activation='sigmoid', name='seg_output')(network)
cat_output = Dense(len(index2label_cat), activation='softmax', name='cat_output')(network)
word_inputs = [twitter_input, postag_input]
char_inputs = [char_ortho_input]
other_input = [gazetteer_input]
model = Model(inputs=other_input + char_inputs + word_inputs,
outputs=[seg_output, cat_output],
name='ne_model')
model.summary()
adamax = Adamax(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(optimizer=adamax,
loss={'seg_output': 'binary_crossentropy',
'cat_output': 'categorical_crossentropy'},
loss_weights={'seg_output': 1.,
'cat_output': 1.},
metrics={'seg_output': [utils.fbeta_score, 'accuracy'],
'cat_output': [utils.fbeta_score, 'accuracy']})
early_stopping = EarlyStopping(patience=20, verbose=1)
# checkpointer = ModelCheckpoint(filepath='{}weights/{}.hdf5'.format(WEIGHTS_DIR, experiment),
# save_best_only=True, verbose=1)
train_word_values = [x_word_twitter_train, x_postag_train]
train_char_values = [x_ortho_twitter_train]
train_other_values = [x_gaze_train]
hist = model.fit(train_other_values + train_char_values + train_word_values,
{'seg_output': y_seg_train, 'cat_output': y_cat_train},
batch_size=500,
epochs=150,
verbose=1,
shuffle=True,
validation_split=0.2,
callbacks=[early_stopping]) # , checkpointer])
train_loss = hist.history["loss"]
val_loss = hist.history["val_loss"]
plt.plot(range(len(train_loss)), train_loss, color="red", label="Train Loss")
plt.plot(range(len(train_loss)), val_loss, color="blue", label="Validation Loss")
plt.xlabel("epochs")
plt.ylabel("loss")
plt.legend(loc="best")
plt.show()
```
# Network Predictions
```
cat_model = Model(inputs=other_input + char_inputs + word_inputs,
outputs=[cat_output],
name='cat_model')
# Predicting test data
test_word_values = [x_word_twitter_test, x_postag_test]
test_char_values = [x_ortho_twitter_test]
test_other_values = [x_gaze_test]
prediction_probs = cat_model.predict(test_other_values +
test_char_values +
test_word_values, batch_size=500, verbose=1)
# Decoding predictions
decoded_predictions = utils.decode_predictions([np.argmax(p) for p in prediction_probs], index2label_cat)
original_test_tweets,_ = utils.read_file_as_lists(TEST)
assert len(original_test_tweets) == len(tweets_test)
assert len(utils.flatten(original_test_tweets)) == len(utils.flatten(tweets_test))
assert len(utils.flatten(original_test_tweets)) == len(decoded_predictions)
utils.save_final_predictions('{}{}.network.tsv'.format(PREDICTIONS_DIR, experiment),
original_test_tweets,
decoded_predictions)
```
#### Prediction insigths
```
# print("Classification Report\n")
# print(classification_report(utils.flatten(labels_test), decoded_predictions))
# print()
# print()
# print("Confusion Matrix\n")
# print(confusion_matrix(utils.flatten(labels_test), decoded_predictions))
```
# CRF-Suite Predictions
```
nn_model = Model(inputs=model.input, outputs=model.get_layer('common_dense_layer').output)
def get_xseq(model, matrix):
xseq = [{'feat{}'.format(i):float(w) for i,w in enumerate(list(features))}
for features
in model.predict(matrix)]
return ItemSequence(xseq)
xseq_train = get_xseq(nn_model, train_other_values + train_char_values + train_word_values)
yseq_train = utils.flatten(labels_train)
trainer = crf.Trainer(verbose=False)
trainer.append(xseq_train, yseq_train)
trainer.set_params({
'c1': 1.0, # L1 penalty
'c2': 1e-3, # L2 penalty
'max_iterations': 100, # stop earlier
'feature.possible_transitions': True # possible transitions, but not observed
})
trainer.train('{}.pycrfsuite'.format(experiment))
trainer.logparser.last_iteration
tagger = crf.Tagger()
tagger.open('{}.pycrfsuite'.format(experiment))
# Predicting test data
decoded_predictions = tagger.tag(get_xseq(nn_model,
test_other_values +
test_char_values +
test_word_values))
# Saving predictions
utils.save_final_predictions('{}{}.crfsuite.tsv'.format(PREDICTIONS_DIR, experiment),
original_test_tweets,
decoded_predictions)
```
#### Prediction insigths
```
# print("Classification Report\n")
# print(classification_report(utils.flatten(labels_test), decoded_predictions))
# print()
# print()
# print("Confusion Matrix\n")
# print(confusion_matrix(utils.flatten(labels_test), decoded_predictions))
from collections import Counter
info = tagger.info()
def print_transitions(trans_features):
for (label_from, label_to), weight in trans_features:
print("%-6s -> %-7s %0.6f" % (label_from, label_to, weight))
print("Top likely transitions:")
print_transitions(Counter(info.transitions).most_common(15))
print("\nTop unlikely transitions:")
print_transitions(Counter(info.transitions).most_common()[-15:])
```
| github_jupyter |
```
import phys.light
import numpy as np
import matplotlib.pyplot as plt
T = 2000
Eg = np.linspace(phys.light.E_from_wavelength(500000e-9), phys.light.E_from_wavelength(500e-9), 10000)
gamma = phys.light.planck_distribution(Eg, T)
plt.plot(Eg, gamma)
plt.xlabel("E")
plt.ylabel("$\zeta(E)$")
plt.show()
E = [phys.light.planck_phot_distribution(phys.light.E_from_wavelength(500000e-9), phys.light.E_from_wavelength(100e-9), T, bins=50000) for x in range(10000)]
phot = phys.light.generate_photons_from_E(E)
plt.hist(E, 100)
plt.xlabel("$E_\gamma$")
plt.ylabel("$N_\gamma$")
plt.title("Frequency of Photons with Energy ")
plt.show()
import phys
import phys.newton
sim = phys.Simulation({"cl_on": True, "exit": lambda cond: cond.t >= 0.200})
sim.add_objs(phot)
sim.add_step(0, phys.UpdateTimeStep(lambda x: 0.0005))
sim.add_step(1, phys.newton.NewtonianKinematicsStep())
sim.add_step(2, phys.light.ScatterSphericalStep(0.00000000000001, 0.000000000000005, wavelength_dep_scattering=True))
sim.add_step(3, phys.light.TracePathMeasureStep(None, id_info_fn = lambda x: str(x.E), trace_dv = True))
sim.add_step(4, phys.light.ScatterMeasureStep(None, measure_n = True, measure_locs = [[x * (phys.light.c) * 0.0005 * 50, 0, 0] for x in range(1, 5)], measure_E = True))
import time
sim.start()
while sim.running:
time.sleep(5)
print(sim.get_state())
xy = []
for z in sim.steps[3].data[1:]:
r = [np.double(z[0])] * z[1]
xy.extend(r)
x = [np.double(z[0]) for z in sim.steps[3].data[1:]]
y = [np.double(z[1]) for z in sim.steps[3].data[1:]]
plt.hist(xy, 75)
plt.xlabel("$E$ (J)")
plt.ylabel("Frequency of Scattering")
plt.title("Frequency of Scattering as a Result of $\lambda$")
plt.show()
for y in range(0, 4):
plt.scatter(range(0, len(sim.steps[4].data)), [len(sim.steps[4].data[x][3 + y * 2]) for x in range(0, len(sim.steps[4].data))])
plt.show()
plt.hist(sim.steps[4].data[49][3], 50)
plt.hist(sim.steps[4].data[99][5], 50)
plt.hist(sim.steps[4].data[150][7], 50)
plt.hist(sim.steps[4].data[200][9], 50)
plt.show()
from matplotlib.animation import FuncAnimation
import matplotlib.animation
fig = plt.figure()
hist = plt.hist([], 100)
def update(frame):
plt.cla()
plt.hist(sim.steps[4].data[frame][3], 50, label="1st")
plt.hist(sim.steps[4].data[frame][5], 50, label="2nd")
plt.hist(sim.steps[4].data[frame][7], 50, label="3rd")
plt.hist(sim.steps[4].data[frame][9], 50, label="4th")
plt.xlim(0, 3.5e-19)
plt.ylim(0, 300)
plt.legend()
plt.ylabel("Frequency of $E_\gamma$")
plt.xlabel("$E_\gamma$")
plt.title("Comparison of Photon Distribution at Given Distances \n ($n = " + str(len(E)) + ", t = " + "{:.4f}".format(0.0005 * frame) + " s$)")
ani = FuncAnimation(fig, update, len(sim.steps[4].data))
ani.save("out.mp4", "ffmpeg", fps=20, dpi=144)
plt.show()
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Egitim donguleri ile tf.distribute.Strategy
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/tr/r1/tutorials/distribute/training_loops.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/tr/r1/tutorials/distribute/training_loops.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
Note: Bu dökümanlar TensorFlow gönüllü kullanıcıları tarafından çevirilmiştir.
Topluluk tarafından sağlananan çeviriler gönüllülerin ellerinden geldiğince
güncellendiği için [Resmi İngilizce dökümanlar](https://www.tensorflow.org/?hl=en)
ile bire bir aynı olmasını garantileyemeyiz. Eğer bu tercümeleri iyileştirmek
için önerileriniz var ise lütfen [tensorflow/docs](https://github.com/tensorflow/docs)
havuzuna pull request gönderin. Gönüllü olarak çevirilere katkıda bulunmak için
[docs-tr@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-tr)
listesi ile iletişime geçebilirsiniz.
Bu rehber egitim donguleri ile [`tf.distribute.Strategy`](https://www.tensorflow.org/r1/guide/distribute_strategy)'nin nasil kullanildigini gosteriyor. Basit bir CNN modelini Fashion MNIST veri seti ile egitecegiz. Bu veri seti icinde 28X28 boyutunda 60000 egitim resmini ve 28X28 boyutunda 10000 test resmini barindirir.
Burada bize esneklik ve daha cok kontrol kazandirmasi icin ozellestirilmis egitim donguleri kullanacagiz. Ustelik, bu ozel donguler modeli ve egitim dongulerindeki hatalari ayiklamamizi da kolaylastiracaktir.
```
# TensorFlow'u yukleyelim
import tensorflow.compat.v1 as tf
# Yardimci kutuphaneler
import numpy as np
import os
print(tf.__version__)
```
## Fashion MNIST veri setini indirelim
```
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# Diziye yeni bir boyut ekleyelim-> new shape == (28, 28, 1)
# Bunu yapmamizin sebebi ise modelimizin ilk katmaninin katlamali olmasi
# ve 4D bir girdiye ihtiyac duyar (batch_size, height, width, channels).
# batch_size boyutunu daha sonra ekleyecegiz.
train_images = train_images[..., None]
test_images = test_images[..., None]
# Resimleri [0, 1] araligina indirgeyelim.
train_images = train_images / np.float32(255)
test_images = test_images / np.float32(255)
train_labels = train_labels.astype('int64')
test_labels = test_labels.astype('int64')
```
## Degiskenleri ve grafigi dagitmak icin bir taktik olusturalim
`tf.distribute.MirroredStrategy` nasil calisir?
* Butun degiskenler ve model grafigi birkac kere kopyalanir.
* Girdi bu kopyalara esit olarak dagitilir.
* Her kopya verilen girdiye gore bir kayip ve degisim tablosu hesaplar.
* Butun degisim verileri toplanir ve kopyalardaki degerler bu toplama gore guncellenir.
* Bu islemden sonra, ayni guncelleme degiskenlerin kopyalarina da uygulanir.
Note: Butun kodu tek bir kapsam icine koyabilirsiniz, fakat biz burada daha aciklayici olmasi icin kodu boluyoruz.
```
# Eger kullanilacak cihazlar `tf.distribute.MirroredStrategy` yapicisinda belirtilmediyse
# otomatik olarak bulunacaktir.
strategy = tf.distribute.MirroredStrategy()
print ('Number of devices: {}'.format(strategy.num_replicas_in_sync))
```
## Girdi hattinin kurulmasi
Eger bir model birden fazla GPU'da egitiliyorsa, grup boyutu buna orantili olarak arttirilmalidir ki fazla bilgisayar gucunu verimli bir sekilde kullanabilelim. Ayrica, egitim hizi da orantili olarak ayarlanmaidir.
```
BUFFER_SIZE = len(train_images)
BATCH_SIZE_PER_REPLICA = 64
BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync
EPOCHS = 10
```
`strategy.make_dataset_iterator`, veriyi kopyalara esit olarak dagitan bir iterator olusturur.
Note: Bu API yakin zamanda degisecektir.
```
with strategy.scope():
train_dataset = tf.data.Dataset.from_tensor_slices(
(train_images, train_labels)).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
train_iterator = strategy.make_dataset_iterator(train_dataset)
test_dataset = tf.data.Dataset.from_tensor_slices(
(test_images, test_labels)).batch(BATCH_SIZE)
test_iterator = strategy.make_dataset_iterator(test_dataset)
```
## Modelin olusturulmasi
`tf.keras.Sequential` ile modelimizi olusturalim. Model Subclassing API'yini da kullanarak bu islemi yapabiliriz.
```
with strategy.scope():
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(64, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
optimizer = tf.train.GradientDescentOptimizer(0.001)
```
## Kayip fonksiyonunu tanimlayalim
Normalde, eger 1 GPU/CPU'lu bir makine kullaniyorsak, kayip girdi grubundaki ornek sayisina bolunur.
*Peki `tf.distribute.Strategy` ile kayip nasil hesaplanir?*
> Ornegin, 4 GPU'muz ve boyutu 64 olan girdimiz oldugunu varsayalim. Bu girdiler esit olarak 4 GPU (4 kopya) ustune bolunur, yani her kopyaya giden girdi grub boyutu 16 idir.
> Her kopyadaki model icindeki girdinin ustunden gecerek kayip degerini hesaplar. Simdi, bu kayip degerini icindeki girdi sayisina (16) bolmek yerine, en bastaki evrensel girdi miktarina (64) boler.
*Neden bu islem boyle yaplir?*
> Cunku degisim degerleri her kopyada hesaplandiktan sonra, butun kopyalardaki degerler butun degisim degerlerinin toplamina esitlenir.
*Bunu TensorFlow'da nasil yapabiliriz?*
Eger ozellestirilmis bir egitim dongusu yaziyorsaniz, her ornekteki kayiplari toplayip butun orneklerin toplamina bolmelisiniz:
```
GLOBAL_BATCH_SIZE:`scale_loss = tf.reduce_sum(loss) * (1. / GLOBAL_BATCH_SIZE)`
```
* `tf.reduce_mean` metodunu kullanmanizi tavsiye etmiyoruz. Bu metod kayip degerini kopyalardaki ornek sayisina boler ki bu her adimda degisebilir.
* Bu indirgeme ve olcekleme keras'ta otomatok olarak yapilir: model.fit ve model.compile ile
* Eger `tf.keras.losses` siniflarini kullaniyorsaniz, kayip indirgemesinin ozellikle `NONE` ya da `SUM` olarak belirtilmesi gerekmektedir. `AUTO` ve `SUM_OVER_BATCH_SIZE` ise `tf.distribute.Strategy` ile birlikte kullanilamaz. Cunku kullanicilarin `AUTO` kullanmadan once yaptiklari indirgemenin o anki dagitim ornegindeki dogrulugundan emin olmalari gerekir. `SUM_OVER_BATCH_SIZE` kullanilamaz cunku su anki haliyle sadece kopyadaki ornek sayisina bolum yapip asil toplam ornek sayisina bolme islemini kullaniciya birakir, ki bu cok kolay gozden kacabilecek bir noktadir. Onun yerine kullanicinin indirgemeyi kendilerinin yapmalarini istiyoruz.
## Egitim dongusu
```
with strategy.scope():
def train_step():
def step_fn(inputs):
images, labels = inputs
logits = model(images)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / BATCH_SIZE)
train_op = optimizer.minimize(loss)
with tf.control_dependencies([train_op]):
return tf.identity(loss)
per_replica_losses = strategy.experimental_run(
step_fn, train_iterator)
mean_loss = strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
with strategy.scope():
iterator_init = train_iterator.initialize()
var_init = tf.global_variables_initializer()
loss = train_step()
with tf.Session() as sess:
sess.run([var_init])
for epoch in range(EPOCHS):
sess.run([iterator_init])
for step in range(10000):
if step % 1000 == 0:
print('Epoch {} Step {} Loss {:.4f}'.format(epoch+1,
step,
sess.run(loss)))
```
## Sirada ne var?
Simdi `tf.distribute.Strategy` API'yini kendi modellerinizde deneyin.
| github_jupyter |
# Dropout
Dropout [1] is a technique for regularizing neural networks by randomly setting some features to zero during the forward pass. In this exercise you will implement a dropout layer and modify your fully-connected network to optionally use dropout.
[1] [Geoffrey E. Hinton et al, "Improving neural networks by preventing co-adaptation of feature detectors", arXiv 2012](https://arxiv.org/abs/1207.0580)
```
# As usual, a bit of setup
from __future__ import print_function
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solver import Solver
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
# Load the (preprocessed) CIFAR10 data.
data = get_CIFAR10_data()
for k, v in data.items():
print('%s: ' % k, v.shape)
```
# Dropout forward pass
In the file `cs231n/layers.py`, implement the forward pass for dropout. Since dropout behaves differently during training and testing, make sure to implement the operation for both modes.
Once you have done so, run the cell below to test your implementation.
```
np.random.seed(231)
x = np.random.randn(500, 500) + 10
for p in [0.25, 0.4, 0.7]:
out, _ = dropout_forward(x, {'mode': 'train', 'p': p})
out_test, _ = dropout_forward(x, {'mode': 'test', 'p': p})
print('Running tests with p = ', p)
print('Mean of input: ', x.mean())
print('Mean of train-time output: ', out.mean())
print('Mean of test-time output: ', out_test.mean())
print('Fraction of train-time output set to zero: ', (out == 0).mean())
print('Fraction of test-time output set to zero: ', (out_test == 0).mean())
print()
```
# Dropout backward pass
In the file `cs231n/layers.py`, implement the backward pass for dropout. After doing so, run the following cell to numerically gradient-check your implementation.
```
np.random.seed(231)
x = np.random.randn(10, 10) + 10
dout = np.random.randn(*x.shape)
dropout_param = {'mode': 'train', 'p': 0.2, 'seed': 123}
out, cache = dropout_forward(x, dropout_param)
dx = dropout_backward(dout, cache)
dx_num = eval_numerical_gradient_array(lambda xx: dropout_forward(xx, dropout_param)[0], x, dout)
# Error should be around e-10 or less
print('dx relative error: ', rel_error(dx, dx_num))
```
## Inline Question 1:
What happens if we do not divide the values being passed through inverse dropout by `p` in the dropout layer? Why does that happen?
## Answer:
If we do not divide the values by p then at test time we will not be considering the average of the training output. Thus, we will be considering only the summation of all possible sub-networks which may lead to large values (exploding gradients). This happens because at test time we require an approximation of the expected output produced by the training phase, due to we only perform a forward call without dropping neurons out.
# Fully-connected nets with Dropout
In the file `cs231n/classifiers/fc_net.py`, modify your implementation to use dropout. Specifically, if the constructor of the net receives a value that is not 1 for the `dropout` parameter, then the net should add dropout immediately after every ReLU nonlinearity. After doing so, run the following to numerically gradient-check your implementation.
```
np.random.seed(231)
N, D, H1, H2, C = 2, 15, 20, 30, 10
X = np.random.randn(N, D)
y = np.random.randint(C, size=(N,))
for dropout in [1, 0.75, 0.5]:
print('Running check with dropout = ', dropout)
model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,
weight_scale=5e-2, dtype=np.float64,
dropout=dropout, seed=123)
loss, grads = model.loss(X, y)
print('Initial loss: ', loss)
# Relative errors should be around e-6 or less; Note that it's fine
# if for dropout=1 you have W2 error be on the order of e-5.
for name in sorted(grads):
f = lambda _: model.loss(X, y)[0]
grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)
print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))
print()
```
# Regularization experiment
As an experiment, we will train a pair of two-layer networks on 500 training examples: one will use no dropout, and one will use a keep probability of 0.25. We will then visualize the training and validation accuracies of the two networks over time.
```
# Train two identical nets, one with dropout and one without
np.random.seed(231)
num_train = 500
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
solvers = {}
dropout_choices = [1, 0.25]
for dropout in dropout_choices:
model = FullyConnectedNet([500], dropout=dropout)
print(dropout)
solver = Solver(model, small_data,
num_epochs=25, batch_size=100,
update_rule='adam',
optim_config={
'learning_rate': 5e-4,
},
verbose=True, print_every=100)
solver.train()
solvers[dropout] = solver
# Plot train and validation accuracies of the two models
train_accs = []
val_accs = []
for dropout in dropout_choices:
solver = solvers[dropout]
train_accs.append(solver.train_acc_history[-1])
val_accs.append(solver.val_acc_history[-1])
plt.subplot(3, 1, 1)
for dropout in dropout_choices:
plt.plot(solvers[dropout].train_acc_history, 'o', label='%.2f dropout' % dropout)
plt.title('Train accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(ncol=2, loc='lower right')
plt.subplot(3, 1, 2)
for dropout in dropout_choices:
plt.plot(solvers[dropout].val_acc_history, 'o', label='%.2f dropout' % dropout)
plt.title('Val accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(ncol=2, loc='lower right')
plt.gcf().set_size_inches(15, 15)
plt.show()
```
## Inline Question 2:
Compare the validation and training accuracies with and without dropout -- what do your results suggest about dropout as a regularizer?
## Answer:
The results show that we are overfitting the model. In the training phase, when we do not use dropout the accuracies are very high (at epoch 25: ~0.99); however, with dropout the accuracies are smaller (at epoch 25: ~0.93). This suggests that with dropout we are learning a simpler model and therefore we are trying to avoid overfitting. In the validation phase, we can see that with dropout we obtained slighly better results. This suggest that effectively with dropout we are regularizing our model and we are reducing overfitting.
## Inline Question 3:
Suppose we are training a deep fully-connected network for image classification, with dropout after hidden layers (parameterized by keep probability p). How should we modify p, if at all, if we decide to decrease the size of the hidden layers (that is, the number of nodes in each layer)?
## Answer:
If we decide to decrease the size of the hidden layers, we are not required to modify p because the number of neurons, which will be dropped out, will be proportional according to the size of the hidden layers. As an example, let's suppose we have n=1024 neurons in a hidden layer and we are using p=0.5. Thus, the expected number of dropped neurons is p\*n=0.5\*1024=512. If we reduce the number of neurons in the hidden layer to n=512 and by using the same p=0.5, the expected number of dropped neurons will be p\*n=0.5\*512=256. Therefore, we do not require to modify the keep probability p when we vary the size of the hidden layers.
| github_jupyter |
```
%matplotlib inline
import pandas as pd
import numpy as np
import cv2 as cv
import h5py
import matplotlib.pyplot as plt
import keras
from keras.layers import Conv2D, MaxPool2D, CuDNNGRU, GlobalMaxPool2D, Reshape, \
concatenate, Input, TimeDistributed, Dense, BatchNormalization, SpatialDropout2D, SpatialDropout1D, Dropout, GlobalAvgPool2D, Flatten
from keras import Model
from keras.applications import Xception
import keras.backend as k
from sklearn.model_selection import train_test_split, KFold
from keras.callbacks import EarlyStopping, ModelCheckpoint
from sklearn.metrics import mean_squared_error
time_history = 1 # how many time steps to look back
hdf5_path = './train_data/train.hdf5'
with h5py.File(hdf5_path, "r") as f:
print("mean intensity of optical flow:" , f["op_flow"][1].mean())
print("mean intensity of frame:", f["frame"][5].mean())
plt.imshow(f["frame"][5]/255)
train_size = len(f["speed"])
speed_data = list(f["speed"])
# for i in range(train_size,train_size - 100):
# frame, axarr = plt.subplots(1,2)
# axarr[0].imshow(f["frame"][i])
# axarr[1].imshow(f["op_flow"][i])
# print(f['speed'][i])
# plt.show()
# plt.plot(speed_data)
hdf5_path_comma = './train_data/comma_train.hdf5'
with h5py.File(hdf5_path_comma, "r") as f:
print("mean intensity of optical flow:" ,f["op_flow"][50].mean())
plt.imshow(f["frame"][6500]/255)
print(len(f["speed"]))
comma_train_size = len(f["speed"])
comma_speed_data = list(f["speed"])
hdf5_path_comma_test = './test_data/comma_test.hdf5'
with h5py.File(hdf5_path_comma_test, "r") as f:
print("mean intensity of optical flow:" ,f["op_flow"][2000].mean())
plt.imshow(f["frame"][2000]/255)
print(len(f["speed"]))
comma_test_size = len(f["speed"])
plt.plot(comma_speed_data)
print(train_size, comma_train_size)
import time
class DataGenerator(keras.utils.Sequence):
def __init__(self, batch_size, history_size, hdf5_path, indexes = None, validation_mode = False):
self.hdf5_path = hdf5_path
if indexes is None:
with h5py.File(self.hdf5_path, "r") as f:
self.indexes = np.arange(len(f["speed"]))
else:
self.indexes = indexes
self.batch_size = batch_size
self.history_size = history_size
self.validation_mode = validation_mode
if self.validation_mode == False:
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.ceil(len(self.indexes) / self.batch_size))
def __getitem__(self, index):
'Generate one batch of data'
# Generate indexes of the batch
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
# Generate data
return self.__data_generation(indexes)
def on_epoch_end(self):
'Updates indexes after each epoch'
if self.validation_mode == False:
np.random.shuffle(self.indexes)
def __data_generation(self, indexes):
'Generates data containing batch_size samples'
indexes = list(indexes)
indexes.sort()
frame = np.zeros((self.batch_size, 224, 224, 3))
op_flow = np.zeros((self.batch_size, 50, 160, 2))
speed = np.zeros((self.batch_size, 1))
with h5py.File(self.hdf5_path, "r") as f:
#self.frame = np.array(f["frame"][indexes])[batch_shuffles]
op_flow = np.array(f["op_flow"][indexes])
speed = np.array(f["speed"][indexes])
return [
#frame,
op_flow], speed
index_array = np.arange(int(train_size))
#correcting for extra element at beginning of comma training data
comma_index_array = np.arange(int(comma_train_size) - 1)
comma_test_index_array = np.arange(int(comma_test_size) - 1)
# comma_train_indexes_no_shuf = np.copy(comma_train_indexes)
# comma_val_indexes_no_shuf = np.copy(comma_val_indexes)
# comma_train_indexes, comma_val_indexes = train_test_split(comma_index_array, shuffle = False, test_size = .2)
def build_model_flat(history_size):
k.clear_session()
#frame_inp = Input(shape=(224, 224, 3))
op_flow_inp = Input(shape=(50, 160, 2))
filters = [3, 5]
op_flows = []
#op_flow = BatchNormalization()(op_flow_inp)
op_flow = (op_flow_inp)
for i, filter_size in enumerate(filters):
int_layer = Dropout(.0)(op_flow)
int_layer = Conv2D(8, (filter_size,filter_size), activation = "relu", data_format = "channels_last")(int_layer)
int_layer = MaxPool2D(pool_size = (1,2))(int_layer)
int_layer = Conv2D(16, (filter_size,filter_size), activation = "relu", data_format = "channels_last")(int_layer)
int_layer = MaxPool2D(pool_size = (1,2))(int_layer)
int_layer = Conv2D(32, (filter_size,filter_size), activation = "relu", data_format = "channels_last")(int_layer)
int_layer = Conv2D(64, (filter_size,filter_size), activation = "relu", data_format = "channels_last")(int_layer)
int_layer = Dropout(.0)(int_layer)
int_layer = Conv2D(128, (filter_size,filter_size), activation = "relu", data_format = "channels_last")(int_layer)
int_layer = MaxPool2D()(int_layer)
int_layer = Conv2D(256, (filter_size,filter_size), activation = "relu", data_format = "channels_last")(int_layer)
int_layer = MaxPool2D()(int_layer)
int_layer = Conv2D(512, (filter_size,filter_size), activation = "relu",
data_format = "channels_last", padding = "same")(int_layer)
int_layer = MaxPool2D()(int_layer)
int_layer_max = GlobalMaxPool2D()(int_layer)
int_layer_avg = GlobalAvgPool2D()(int_layer)
conc = concatenate([int_layer_max, int_layer_avg])
op_flows.append(conc)
conc = concatenate(op_flows)
#conc = BatchNormalization()(conc)
#conc = SpatialDropout1D(.2)(conc)
#conc = CuDNNGRU(256)(conc)
conc = Dropout(.2)(conc)
conc = Dense(500, activation = "relu")(conc)
# conc = Dropout(.2)(conc)
conc = Dense(250, activation = "relu")(conc)
# conc = Dropout(.1)(conc)
result = Dense(1, activation='linear')(conc)
model = Model(inputs=[
#frame_inp,
op_flow_inp], outputs=[result])
model.compile(loss="mse", optimizer='adam')
return model
def runningMeanFast(x, N):
return np.convolve(x, np.ones((N,))/N)[(N-1):]
def evaluate_metrics(y_true, y_pred, title = None, verbose = False):
#print(pd.DataFrame(y_pred).describe())
# plt.figure(figsize=(12,4))
# plt.subplot(1, 2, 1)
# plt.plot(y_true)
# plt.plot(y_pred)
# plt.title("raw "+ title + " predictions")
for j in range(1,21,5):
rolling_preds = runningMeanFast(y_pred, j)
rolling_mse = mean_squared_error(y_true, rolling_preds)
print("unsmoothed mse" , mean_squared_error(y_true, y_pred) , "\t" + str(j), "smoothed mse", str(rolling_mse))
# plt.subplot(1, 2, 2)
# plt.plot(y_true)
# plt.plot(rolling_preds)
# plt.title("smoothed "+ title + " predictions")
# plt.show()
return rolling_mse, rolling_preds
split_count = 5
num_epochs = 10
steps_per_epoch = None
kf = KFold(shuffle = False, n_splits = split_count)
test_preds = np.zeros((split_count, len(comma_test_index_array)))
oof_preds = np.zeros((len(index_array)))
comma_oof_preds = np.zeros((len(comma_index_array)))
custom_splits = list(kf.split(index_array))
comma_splits = list(kf.split(comma_index_array))
for fold in range(split_count):
train_indexes, val_indexes = custom_splits[fold]
comma_train_indexes, comma_val_indexes = comma_splits[fold]
print("training on fold " + str(fold))
print("="*80)
best_comma_mse = 200
best_custom_mse = 200
comma_train_generator = DataGenerator(32, time_history, hdf5_path_comma, indexes = comma_train_indexes)
comma_val_generator = DataGenerator(32, time_history, hdf5_path_comma, indexes = comma_val_indexes, validation_mode = True)
comma_test_generator = DataGenerator(32, time_history, hdf5_path_comma_test, indexes = comma_test_index_array, validation_mode = True)
train_generator = DataGenerator(32, time_history, hdf5_path, indexes = train_indexes)
valid_generator = DataGenerator(32, time_history, hdf5_path, indexes = val_indexes, validation_mode = True)
model_flat = build_model_flat(time_history)
comma_mse = []
custom_mse = []
for i in range(num_epochs):
model_flat.fit_generator(train_generator, epochs = 1, steps_per_epoch=steps_per_epoch)
val_predictions = model_flat.predict_generator(valid_generator)[:, 0]
print("custom valid metrics")
val_roll_mse, val_roll_preds = evaluate_metrics(np.array(speed_data)[val_indexes], val_predictions, title = "custom data")
custom_mse.append(val_roll_mse)
if val_roll_mse < best_custom_mse:
oof_preds[val_indexes] = val_roll_preds
model_flat.fit_generator(comma_train_generator, epochs = 1, steps_per_epoch=steps_per_epoch)
print("comma val metrics")
comma_val_predictions = model_flat.predict_generator(comma_val_generator)[:, 0]
comma_roll_mse, comma_roll_preds = evaluate_metrics(np.array(comma_speed_data)[comma_val_indexes], comma_val_predictions, title = "comma data")
comma_mse.append(comma_roll_mse)
if comma_roll_mse < best_comma_mse:
model_flat.save("best_model" + str(fold) + ".ckpt")
comma_test_predictions = model_flat.predict_generator(comma_test_generator)[:, 0][comma_test_index_array]
comma_test_predictions = runningMeanFast(comma_test_predictions, 21)
test_preds[fold, :] = comma_test_predictions
comma_oof_preds[comma_val_indexes] = comma_roll_preds
best_comma_mse = comma_roll_mse
# plt.plot(comma_test_predictions)
# plt.plot(np.mean(test_preds[:fold+1], axis = 0))
# plt.title("comma test predictions")
# plt.show()
plt.figure(figsize=(12,4))
plt.subplot(1, 2, 1)
plt.plot(custom_mse)
plt.title("smoothed custom validation mse")
plt.subplot(1, 2, 2)
plt.plot(comma_mse)
plt.title("smoothed comma validation mse")
plt.show()
fold_means = np.mean(test_preds[:fold+1], axis = 0)
plt.plot(fold_means)
plt.title("best fold mean predictions")
plt.show()
print("fold mean histograms")
pd.DataFrame(fold_means).hist(bins = 25)
plt.show()
#comma oof performance
print(mean_squared_error(comma_speed_data[1:], comma_oof_preds))
#custom off performance
print(mean_squared_error(speed_data, oof_preds))
pd.DataFrame(speed_data).hist(bins = 25)
pd.DataFrame(comma_speed_data).hist(bins = 25)
pd.DataFrame(fold_means).hist(bins = 25)
with open("test.txt", "w") as f:
for line in [13] + list(fold_means):
f.write(str(line) + "\n")
fold_means
def build_model(history_size):
k.clear_session()
frame_inp = Input(shape=(history_size, 224, 224, 3))
op_flow_inp = Input(shape=(history_size, 224, 224, 3))
filter_size = (3,3)
#frame = TimeDistributed(BatchNormalization())(frame_inp)
frame = TimeDistributed(SpatialDropout2D(.2))(frame_inp)
frame = TimeDistributed(Conv2D(4, filter_size, activation = "relu", data_format = "channels_last"))(frame)
frame = TimeDistributed(MaxPool2D())(frame)
frame = TimeDistributed(Conv2D(4, filter_size, activation = "relu", data_format = "channels_last"))(frame)
frame = TimeDistributed(MaxPool2D())(frame)
frame = TimeDistributed(Conv2D(8, filter_size, activation = "relu", data_format = "channels_last"))(frame)
frame = TimeDistributed(MaxPool2D())(frame)
frame = TimeDistributed(Conv2D(16, filter_size, activation = "relu", data_format = "channels_last"))(frame)
#frame = TimeDistributed(SpatialDropout2D(.2))(frame)
frame = TimeDistributed(MaxPool2D())(frame)
frame = TimeDistributed(Conv2D(32, filter_size, activation = "relu", data_format = "channels_last"))(frame)
frame = TimeDistributed(MaxPool2D())(frame)
frame = TimeDistributed(GlobalMaxPool2D())(frame)
op_flow = TimeDistributed(BatchNormalization())(op_flow_inp)
op_flow = TimeDistributed(Dropout(.3))(op_flow)
op_flow = TimeDistributed(Conv2D(4, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(8, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(32, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(64, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(Dropout(.3))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(128, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow_max = TimeDistributed(GlobalMaxPool2D())(op_flow)
op_flow_avg = TimeDistributed(GlobalAvgPool2D())(op_flow)
conc = concatenate([op_flow_max, op_flow_avg,
#frame
])
#conc = BatchNormalization()(conc)
conc = SpatialDropout1D(.2)(conc)
conc = CuDNNGRU(256)(conc)
conc = Dense(100, activation = "relu")(conc)
conc = Dropout(.2)(conc)
conc = Dense(50, activation = "relu")(conc)
conc = Dropout(.1)(conc)
result = Dense(1, activation='linear')(conc)
model = Model(inputs=[frame_inp, op_flow_inp], outputs=[result])
print(model.summary())
model.compile(loss="mse", optimizer='adam')
return model
model = build_model(time_history)
hist = model.fit_generator(train_generator, validation_data=valid_generator, epochs = 10,
callbacks=[EarlyStopping(patience=3), ModelCheckpoint(filepath="rnn_model.ckpt", save_weights_only=False)])
hist2 = model_flat.fit_generator(train_generator, validation_data=valid_generator, epochs = 10)
hist2 = model_flat.fit_generator(train_generator, validation_data=valid_generator, epochs = 10)
def build_model_frame(history_size):
k.clear_session()
frame_inp = Input(shape=(history_size, 224, 224, 3))
op_flow_inp = Input(shape=(history_size, 224, 224, 3))
filter_size = (3,3)
base_mod = Xception(weights='imagenet', include_top=False, input_shape = (224,224,3))
for l in base_mod.layers:
l.trainable=False
frame = TimeDistributed(BatchNormalization())(frame_inp)
frame = TimeDistributed(base_mod)(frame)
#frame = Reshape(target_shape=(history_size, 2048))(frame)
frame = TimeDistributed(Conv2D(128, (1,1), activation = "relu"))(frame)
frame_max = TimeDistributed(GlobalMaxPool2D())(frame)
frame_avg = TimeDistributed(GlobalAvgPool2D())(frame)
op_flow = TimeDistributed(BatchNormalization())(op_flow_inp)
op_flow = TimeDistributed(Dropout(.3))(op_flow)
op_flow = TimeDistributed(Conv2D(4, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(8, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(32, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(64, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(Dropout(.3))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(128, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow_max = TimeDistributed(GlobalMaxPool2D())(op_flow)
op_flow_avg = TimeDistributed(GlobalAvgPool2D())(op_flow)
conc = concatenate([
#frame_max, frame_avg,
op_flow_max, op_flow_avg
])
conc = BatchNormalization()(conc)
#conc = SpatialDropout1D(.2)(conc)
#conc = CuDNNGRU(256)(conc)
conc = Flatten()(conc)
conc = Dropout(.3)(conc)
conc = Dense(500, activation = "relu")(conc)
conc = Dropout(.2)(conc)
conc = Dense(100, activation = "relu")(conc)
conc = Dropout(.1)(conc)
result = Dense(1, activation='linear')(conc)
model = Model(inputs=[frame_inp, op_flow_inp], outputs=[result])
print(model.summary())
model.compile(loss="mse", optimizer='adam')
return model
model3 = build_model_frame(time_history)
hist3 = model3.fit_generator(train_generator, validation_data=valid_generator, epochs = 10)
def build_model_frame(history_size):
k.clear_session()
frame_inp = Input(shape=(history_size, 224, 224, 3))
op_flow_inp = Input(shape=(history_size, 224, 224, 3))
filter_size = (3,3)
base_mod = Xception(weights='imagenet', include_top=False, input_shape = (224,224,3))
for l in base_mod.layers:
l.trainable=False
#frame = TimeDistributed(BatchNormalization())(frame_inp)
frame = TimeDistributed(base_mod)(frame_inp)
#frame = Reshape(target_shape=(history_size, 2048))(frame)
frame = TimeDistributed(Conv2D(128, (1,1), activation = "relu"))(frame)
frame_max = TimeDistributed(GlobalMaxPool2D())(frame)
frame_avg = TimeDistributed(GlobalAvgPool2D())(frame)
op_flow = TimeDistributed(BatchNormalization())(op_flow_inp)
op_flow = TimeDistributed(Dropout(.3))(op_flow)
op_flow = TimeDistributed(Conv2D(4, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(8, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(32, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(64, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(Dropout(.3))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow = TimeDistributed(Conv2D(128, filter_size, activation = "relu", data_format = "channels_last"))(op_flow)
op_flow = TimeDistributed(MaxPool2D())(op_flow)
op_flow_max = TimeDistributed(GlobalMaxPool2D())(op_flow)
op_flow_avg = TimeDistributed(GlobalAvgPool2D())(op_flow)
conc = concatenate([
frame_max, frame_avg,
#op_flow_max, op_flow_avg
])
conc = BatchNormalization()(conc)
#conc = SpatialDropout1D(.2)(conc)
#conc = CuDNNGRU(256)(conc)
conc = Flatten()(conc)
conc = Dropout(.3)(conc)
conc = Dense(500, activation = "relu")(conc)
conc = Dropout(.2)(conc)
conc = Dense(100, activation = "relu")(conc)
conc = Dropout(.1)(conc)
result = Dense(1, activation='linear')(conc)
model = Model(inputs=[frame_inp, op_flow_inp], outputs=[result])
print(model.summary())
model.compile(loss="mse", optimizer='adam')
return model
model4 = build_model_frame(time_history)
hist4 = model4.fit_generator(train_generator, validation_data=valid_generator, epochs = 10)
```
| github_jupyter |
This notebook contains code that uses **Word2Vec** to generate word embeddings on proxy statements. This model is then trained, saved and can be loaded for future use. For instance, word embeddings can be used to cluster text.
This notebook also contains code to do this. K-Means Clustering is used to cluster excerpts from the proxy statements. Additionally, clusters are visualized using wordclouds to detect most prominent keywords.
```tqdm``` is used to show a progress bar when running a cell.
```
from tqdm import tqdm
tqdm.pandas()
```
Import necessary libraries.
```
import string
import pickle
import joblib
import numpy as np
import pandas as pd
import nltk
import gensim
import re
import os
import math
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
#from nltk.stem.snowball import SnowballStemmer
#from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
#from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
#from sklearn.preprocessing import normalize
###Word Embeddings: Word2Vec
from gensim.models import Word2Vec
###K-Means Clustering
from sklearn.cluster import KMeans
from sklearn.metrics.pairwise import euclidean_distances
from sklearn import metrics
###WordCloud
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
###Word Frequency
from collections import Counter
```
This cell loads the parsed and cleaned csv file into a DataFrame called ```documents``` which contains the proxy statements. Each row is an excerpt/paragraph from a proxy statement. Columns include ```file_name```, ```text```, and ```clean_text```. The ```clean_text``` column includes stemmed words from ```text```.
```
documents = pd.read_csv("def14a_para_clean.csv")
print(documents.shape)
documents.head()
```
The ```preprocess``` function preprocesses the ```text``` column: set to lowercase, removes digits, and whitespace. A new column named ```trial``` is added. The ```token_words``` function tokenizes each word in ```trial``` and removes punctuation. A new column named ```paragraph``` is added.
```
def preprocess(paragraph):
text = re.sub(r'\[[0-9]*\]',' ',paragraph)
text = re.sub(r'\s+',' ',text)
text = text.lower()
text = re.sub(r'\d',' ',text)
text = re.sub(r'\s+',' ',text)
return text
def token_words(sentence_list): #sentence_list is a row in the datframe
punctuation=nltk.word_tokenize(string.punctuation)
paragraph = nltk.word_tokenize(sentence_list)
return [token for token in paragraph if token not in punctuation]
documents['trial'] = documents.progress_apply(lambda x: preprocess(x['text']), axis = 1)
documents['paragraph'] = documents.progress_apply(lambda x: token_words(x['trial']), axis = 1)
```
### Word2Vec needs a list of lists as input.
- Convert the ```paragraph``` column into a list.
```
paragraphs = documents.paragraph.tolist()
```
### Word2Vec
- Instantiate the model. **Skipgram** is used.
```
model = Word2Vec(sentences, size=150, window=10, min_count=2, workers=10, sg = 1)
```
- Train the model
```
model.train(sentences,total_examples=len(sentences),epochs=10)
```
### Word Embedding Vocabulary
- This code shows the vocabulary that was generated by the model.
```
words = model.wv.vocab
words
```
This code shows what you can do with the vocabulary. For instance, you can find a word vector for a specific word. You can also predict the most similar words of a specific word. Moreover, you can check the similarity scores of words.
```
# Finding Word Vectors
vector = model.wv['labor']
# Most similar words i.e. predicted the next words
similar = model.wv.most_similar('coercion')
print(similar)
# #Similarity scores
# model.wv.similarity('trafficking', 'labor')
```
Under the hood, the above three code snippets computes the cosine similarity between the two specified words using word vectors of each. If you do a similarity between two identical words, the score will be 1.0 as the range of the cosine similarity score will always be between [0.0-1.0].
### Save/Load the Trained Word Embeddings
- The code below can be used to save the model.
- There is also code that can be used to load an already saved Word2Vec model.
```
#SAVE
#Uncomment the code below to save the model.
#model.save('word2vec_proxy_docs.model')
#LOAD
model = gensim.models.Word2Vec.load("word2vec_proxy_docs.model")
```
### K Means Clustering
- Word embeddings can be used to cluster text. In this case, paragraphs are clustered.
- Find the Optimal Number of Clusters.
- Fit data into K-Means. Save into a pickle doc.
#### Paragraph Clustering
The function ```paragraph_vectorizer```: For each paragraph from the set of paragraphs, word embedding of each word is summed and in the end divided by number of words in the paragraph. So we are getting average of all word embeddings for each paragraph and use them as we would use embeddings at word level – feeding to machine learning clustering algorithm such as k-means.
```
def paragraph_vectorizer(paragraph, model):
paragraph_vec =[]
numw = 0 #number of word in the paragraph
for w in paragraph:
try:
if numw == 0:
paragraph_vec = model.wv[w]
else:
paragraph_vec = np.add(paragraph_vec, model.wv[w])
numw+=1
except:
pass
if len(paragraph_vec) == 150:
return np.asarray(paragraph_vec) / numw
else:
return None
```
This cell creates the vectorized paragraphs. X is used as the input to K-Means. It also takes note of the paragraphs that do not have vectors based on their index.
```
X=[]
for idx, paragraph in tqdm(enumerate(paragraphs)):
result=paragraph_vectorizer(paragraph, model)
if result is None:
print('No Vector for Paragraph: {a}'.format(a=idx))
else:
X.append(paragraph_vectorizer(paragraph, model))
# empty array rows: 324639, 324640, 324642, 324643, 324645, 324646
```
This cell is used to find the optimal number of clusters. First, within_cluster_variance is found. K-Means minimizes this and maximizes between-cluster variance. The objective is to find the most compact partitioning of the data set into 𝑘 partitions.
```
#OPTIMAL NUMBER OF CLUSTERS: get within cluster variance
within_cluster_variance = []
for k in tqdm(range(2,21)):
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)
within_cluster_variance.append(kmeans.inertia_)
def optimal_number_of_clusters(wcss):
x1, y1 = 2, wcss[0]
x2, y2 = 20, wcss[len(wcss)-1]
distances = []
for i in range(len(wcss)):
x0 = i+2
y0 = wcss[i]
numerator = abs((y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1)
denominator = math.sqrt((y2 - y1)**2 + (x2 - x1)**2)
distances.append(numerator/denominator)
return distances.index(max(distances)) + 2
optimal_number_of_clusters(within_cluster_variance)
```
Using optimal number of clusters, fit data into K-Means.
```
word_emb_kmeans = KMeans(n_clusters=6)
word_emb_kmeans.fit(X)
#Convert labels into a list
labels = word_emb_kmeans.labels_.tolist()
#Centroids
centroids = word_emb_kmeans.cluster_centers_
```
### Save the Clusters into pickle file
```
#Path to folder
data_dir = 'cluster_pkl' #directory name
#name of new file to be pickled, change this every time you run clustering model again
cluster_file = '/word_emb_clust_2_par.pkl'
path = data_dir + cluster_file
#Save the Pickle File
joblib.dump(word_emb_kmeans, open( path, "wb" )) #pickle doc
#LOAD CLUSTER FILE
word_emb_kmeans_load = joblib.load(path)
word_emb_labels = word_emb_kmeans_load.labels_.tolist() #labels
word_emb_clust_centers = word_emb_kmeans_load.cluster_centers_ # centers
```
### Insert "None" into Labels that do not have a Vector.
This means then that these paragraphs do not have a cluster.
If there exists "No vectors For Paragraph No. __" (see above code), then insert ```None``` into ```labels```.
```
word_emb_labels.insert(324639, None)
word_emb_labels.insert(324640, None)
word_emb_labels.insert(324642, None)
word_emb_labels.insert(324643, None)
word_emb_labels.insert(324645, None)
word_emb_labels.insert(324646, None)
```
### Add the K-Means Cluster Labels to the Original DataFrame
This cell adds the column ```cluster``` to the original dataframe. Now, the paragraphs are assigned to a cluster.
```
documents['cluster'] = word_emb_labels #add labels to the original dataframe
documents.head(10)
```
The function ```find_word_by_cluster``` shows you the actual text in each cluster and where you would like to search for a particular word. You can use the **CSAG** terms here to check which cluster the words are in.
```
#CHECK THE WORDS FOUND IN THE PARAGRAPH FOR EACH CLUSTER:
def find_word_by_cluster(word, cluster_num):
"""
Inputs: word is a string
cluster_num is a number from 0 to 5
"""
par_list = []
for i, par in enumerate(documents['text'][documents['cluster']==cluster_num]): #clusters 0-5
if word in par:
par_list.append(par)
print(str(i+1) + '.', par)
print()
if len(par_list) == 0:
print("This cluster does not contain the specific word.")
find_word_by_cluster('trafficking', 1)
```
### Word Cloud: Find top keywords in each paragraph cluster
- If you want to find the most important keywords per cluster, make a WordCloud.
The function ```wordcloud_cluster``` generates a wordcloud for a cluster.
```
def wordcloud_cluster(cluster_num):
cluster_df = documents[documents['cluster']==cluster_num]
cluster_words = ''
stopwords = set(STOPWORDS)
stopwords.update(["executive", "board", "committee", "governance", "company", "accounting", "compensation",
"corporate", "annual", "director", "meeting", "audit", "public", "shareholder", "independent", "member",
"firm", "nominating", "program", "review", "auditor", "officer", "executives"])
# iterate through the csv file
for val in cluster_df.text:
# typecaste each val to string
val = str(val)
# split the value
tokens = val.split()
# Converts each token into lowercase
for i in range(len(tokens)):
tokens[i] = tokens[i].lower()
cluster_words += " ".join(tokens)+" "
wordcloud = WordCloud(width = 800, height = 800,
background_color ='white',
stopwords = stopwords,
min_font_size = 10).generate(cluster_words)
# plot the WordCloud image
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
plt.show()
wordcloud_cluster(2)
```
#### CSAG dictionary of terms and added words from word embeddings
- These are the words from Civil Society Advisory Board. Word embeddings can help seed the list of words to create a dictionary.
- These words are **keywords** that will be used to count how many times they occur in the cluster. We want to know this to get a signal that the cluster contains 'human rights' related risks which would be the **positive** case.
```
csag_terms = ['human', 'capital', 'labor', 'bondage', 'workers',
'health', 'safety', 'diversity', 'inclusion', 'labor', 'relations', 'culture',
'resources', 'contractors', 'fair', 'wage',
'minimum', 'overtime', 'exploitative', 'injuries', 'protective',
'equipment', 'workforce', 'working', 'conditions',
'discrimination', 'contractor', 'strike', 'recruitment', 'hiring', 'forced',
'collective', 'bargaining', 'union', 'organizing', 'pay', 'ratio', 'equity',
'grievance', 'retaliation', 'whistleblowers', 'modern', 'slavery',
'incident', 'harassment', 'compulsion', 'unethical', 'anti-retaliation',
'intolerance', 'anti-corruption','anti-bribery', 'retaliation', 'indentured', 'anti-human', 'trafficking']
```
We can try it first on Cluster 2. Find the top keywords in Cluster 2. The ```top_csag_words_by_cluster``` function shows the frequency of the CSAG words that were found in the Cluster. As an example, Cluster 2 is used.
```
def top_csag_words_by_cluster(cluster_num, num_keywords):
#Join paragraphs from cluster 2 into one string
cluster_text = documents[documents['cluster']==cluster_num]
par = ' '.join(cluster_text['text'])
c = Counter(''.join(char for char in s.lower() if char.isalpha())
for s in par.split())
term_freq = [c[term] for term in csag_terms]
#DataFrame of Word and Term Frequency
word_freq_df = pd.DataFrame({'csag_terms': csag_terms, 'word_freq':term_freq})
#Top 10 CSAG terms in Cluster 2
return word_freq_df.sort_values(by=['word_freq'], ascending=False).head(num_keywords)
top_csag_words_by_cluster(2, 10)
```
This code shows the word frequency in the cluster. As an example. Cluster 2 is used. In order to get more meaningful keywords, stopwords should be used. Creating custom stopwords involves knowing boilerplate language on proxy statements. This would be the next step.
```
for term in c.most_common()[0:10]:
print(term[0])
```
| github_jupyter |
```
import pandas as pd
import numpy as np
data_click = pd.read_csv('../test/click_log.csv')# click_log
# data_user = pd.read_csv('../test/user.csv') # user
data_ad = pd.read_csv('../test/ad.csv') # user
data_click = data_click.merge(data_ad,on = 'creative_id',how = 'left')
del data_ad
#对industry广告行业进行特征提取
industry_click = data_click[['user_id', 'advertiser_id', 'click_times']].sort_values(by = 'user_id')
# industry_click = industry_click[data_click['industry']!='\\N']
industry_click = industry_click.groupby(['user_id','advertiser_id']).agg({'click_times':sum})
industry_click = industry_click.reset_index()
# def func_log(x):
# return np.log(x+1)
# industry_click['advertiser_id'+'_log'] = industry_click['click_times'].transform(func_log)
# 提取头三个点击最高的种类及点击量
head_x = industry_click.sort_values(['click_times'],ascending=False).groupby(['user_id']).head(3)
head_x = head_x.sort_values('user_id')
def fun1(x):
x = list(x.values.reshape([-1]))[:6]
x = x[:6]+[0]*(6-len(x))
return pd.DataFrame([x])
tops = head_x.groupby('user_id')['advertiser_id','click_times'].apply(fun1)
columns = []
for i in range(6):
columns.append('advertiser_id'+str(i))
tops.columns = columns
tops = tops.reset_index()
tops = tops.drop(['level_1'],axis = 1)
tops.to_csv('test_advertiser_id_feat.csv',index=False)
#对industry广告行业进行特征提取
industry_click = data_click[['user_id', 'industry', 'click_times']].sort_values(by = 'user_id')
industry_click = industry_click[data_click['industry']!='\\N']
industry_click['click_times'] = industry_click.groupby(['user_id','industry'])['click_times'].transform(np.sum)
def func_x2(x):
max_click = np.max(x['click_times'])
x = x[x['click_times']==max_click]
return x.iloc[-1,:]
feat = industry_click.groupby(['user_id']).apply(func_x2)
feat.columns = ['user_id','industry','max_click_times']
feat['max_click_times_log'] = feat['max_click_times'].transform(np.log)
feat.to_csv('industry_feat.csv',index=False)
print(max(feat['industry']))
category_click = data_click[['user_id', 'product_category', 'click_times']].sort_values(by = ['user_id'])
# category_click = category_click.iloc[:1000,:]
category_click['click_times'] = category_click.groupby(['user_id','product_category'])['click_times'].transform(np.sum)
def func1(x):
x = x.drop_duplicates('product_category',keep='last')
x = x.set_index('product_category')
data = {}
for i in range(1,19):
if i in list(x.index):
data[i]=[x.loc[i]['click_times']]
else:
data[i] = 0
return pd.DataFrame(data)
feat = category_click.groupby(['user_id']).apply(func1)
feat.reset_index(level=0, inplace=True)
feat.index = range(len(feat))
# feat.to_csv('category_feat.csv',index=False)
columns = ['user_id']
for i in range(1,19):
columns.append('category'+ str(i))
feat.columns = columns
def func_log(x):
return np.log(x+1)
for name in columns[1:]:
feat[name+'_log'] = feat[name].transform(func_log)
feat.to_csv('category_feat_addlog.csv',index=False)
click_feat = pd.read_csv('clicks_feat.csv')
category_feat = pd.read_csv('category_feat_addlog.csv')
industry_feat = pd.read_csv('industry_feat.csv')
#特征合并在一起
features = click_feat.merge(category_feat,on='user_id',how='left').merge(industry_feat,on='user_id',how='left')
#添加label
user = pd.read_csv('../../data/train_preliminary/user.csv')
data = features.merge(user,on='user_id',how='left')
# del data['user_id']
# 添加train_cat_max_id_feat特征
def func_cat (x):
x = x[['category1','category2', 'category3', 'category4', 'category5', 'category6','category7', 'category8', 'category9', 'category10', 'category11','category12', 'category13', 'category14', 'category15', 'category16','category17', 'category18']]
d = {}
d['cat_max_id'] = [np.argmax(x.values)+1]
return pd.DataFrame(d)
cat_max_id_feat = data.groupby('user_id').apply(func_cat)
cat_max_id_feat.reset_index(level=0, inplace=True)
cat_max_id_feat.index = range(len(cat_max_id_feat))
cat_max_id_feat.to_csv('train_cat_max_id_feat.csv',index=False)
data = data.merge(cat_max_id_feat,on='user_id',how='left')
data.to_csv('train_feat_user.csv',index=False)
```
| github_jupyter |
```
# !/usr/bin/env python3
# 百度百科QA数据分析
import json
import os
import numpy as np
import jieba
import json
trainfile = './baike_qa2019/baike_qa_train.json'
valfile = './baike_qa2019/baike_qa_valid.json'
train_list = []
val_list = []
cats_list = []
with open(trainfile, 'r', encoding='utf8') as f:
for line in f.readlines():
if line is None or len(line) == 0:
continue
j_info = json.loads(line)
train_list.append(j_info)
with open(valfile, 'r', encoding='utf8') as f:
for line in f.readlines():
if line is None or len(line) == 0:
continue
j_info = json.loads(line)
val_list.append(j_info)
# 训练QA数据
print('====> 训练QA数据:\t', len(train_list))
print(train_list[0])
print('\n')
print('====> 验证集数据:\t', len(val_list))
print(val_list[0])
# 种类分布
import collections
from collections import Counter
import wordcloud
train_cats_list = []
val_cats_list = []
for elem in train_list:
if 'category' in elem:
train_cats_list.append(elem['category'])
for elem in val_list:
if 'category' in elem:
val_cats_list.append(elem['category'])
train_cats = Counter(train_cats_list)
val_cats = Counter(val_cats_list)
train_cats = sorted(train_cats.items(), key=lambda x: x[1], reverse=True)
val_cats = sorted(val_cats.items(), key=lambda x: x[1], reverse=True)
train_cats
# 检查训练集合和验证集合的数据种类关系
print('训练集合数据种类:\t', len(train_cats))
print('验证集合数据种类:\t', len(val_cats))
# 检查验证集合中是否含有训练集合中没有的种类
val_all_cats = list(val_cats)
train_all_cats = list(train_cats)
for elem in val_all_cats:
if elem not in train_all_cats:
print(elem)
#训练集内的种类包含了验证集内所有的种类
# 绘制种类的云图
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
train_cats_txt = ' '.join(train_cats_list)
val_cats_txt = ' '.join(val_cats_list)
wordcloud1 = WordCloud(background_color='yellow', max_font_size=400, min_font_size=20, mode='RGBA', font_path='/Users/higgs/Library/Fonts/SimHei.ttf')
wordcloud2 = WordCloud(background_color='yellow', max_font_size=400, min_font_size=20, mode='RGBA', font_path='/Users/higgs/Library/Fonts/SimHei.ttf')
train_cats_pic = wordcloud1.generate(train_cats_txt)
val_cats_pic = wordcloud2.generate(val_cats_txt)
f, axs = plt.subplots(1,2,figsize=(20,15))
plt.subplot(121)
plt.imshow(train_cats_pic)
plt.axis('off')
plt.subplot(122)
plt.imshow(val_cats_pic)
plt.axis('off')
plt.show()
train_cats_dict = {}
key2key = {}
for elem in train_cats:
train_cats_dict[elem[0]] = elem[1]
# train_cats_dict
del_list = []
train_cats_l = list(train_cats_dict.items())
for elem in train_cats_l:
if elem[1] < 3000:
pos = elem[0].rfind('-')
if pos == -1:
continue
key = elem[0][:pos]
del_list.append(elem[0])
key2key[elem[0]] = key
if key in train_cats_dict:
train_cats_dict[key] += elem[1]
else:
train_cats_dict[key] = elem[1]
print(del_list)
for l in del_list:
print(l)
train_cats_dict.pop(l)
for key, val in train_cats_dict.items():
if val < 3000:
print(key, '\t', val)
key2key_bk = {}
for key,val in key2key.items():
if val in key2key:
key2key_bk[key] = key2key[val]
else:
key2key_bk[key] = val
key2key_bk
# 将key映射表写入文件
with open('./key2key.txt', 'w', encoding='utf8') as f:
f.write(json.dumps(key2key_bk, ensure_ascii=False))
# generate train/val set for category classification
with open(trainfile, 'r', encoding='utf8') as f:
for line in f.readlines():
if line is None or len(line) == 0:
continue
j_info = json.loads(line)
if j_info['category'] in key2key_bk:
j_info['category'] = key2key_bk[j_info['category']]
train_list.append(j_info)
```
| github_jupyter |
```
import os
os.chdir('/Users/Olivier/anaconda3/envs/guitarsounds')
%load_ext autoreload
%autoreload 2
from guitarsounds import Sound, Signal
import guitarsounds as guit
import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt
from scipy.interpolate import InterpolatedUnivariateSpline, interp1d, make_interp_spline
```
# Get the peaks for an harmonic signal
```
# Get a signal to test
sound = Sound('soundfiles/flax_carbon/Wood_D0_2.wav')
sound.condition()
sound.SP.change('fft_range', 5000) # change the fft range so we get a lot of peaks
sound.signal.plot(kind='peaks')
# Calculer les pics
peaks = sound.signal.peaks()
# Tracer chaque pic
fig, axs = plt.subplots(7,4, figsize=(12,12))
axs = axs.reshape(1, -1)[0]
for ax, peak in zip(axs,peaks):
plt.sca(ax)
freq = sound.signal.fft_frequencies()[peak]
dist = np.where(sound.signal.fft_frequencies()>10)[0][0]
height = sound.signal.fft()[peak]
plt.plot(sound.signal.fft_frequencies()[peak-dist:peak+dist], sound.signal.fft()[peak-dist:peak+dist], c='k')
plt.scatter(sound.signal.fft_frequencies()[peak], sound.signal.fft()[peak], c='r')
plt.ylim((height/10, height*1.1))
plt.yscale('log')
plt.tight_layout()
# Ajouter la valeur d'interception pour 7 pics
indexes = np.arange(0, len(peaks), 4) # 1 pic sur 4
reduced_peaks = peaks[indexes]
fig, axs = plt.subplots(2,4, figsize=(12,6))
axs = axs.reshape(1, -1)[0]
for ax, peak in zip(axs,reduced_peaks):
plt.sca(ax)
freq = sound.signal.fft_frequencies()[peak]
dist = np.where(sound.signal.fft_frequencies()>10)[0][0]
height = sound.signal.fft()[peak]
plt.plot(sound.signal.fft_frequencies()[peak-dist:peak+dist], sound.signal.fft()[peak-dist:peak+dist], c='k')
plt.scatter(sound.signal.fft_frequencies()[peak], sound.signal.fft()[peak], c='r')
plt.ylim((height/10, height*1.1))
plt.hlines(height/np.sqrt(2), sound.signal.fft_frequencies()[peak-dist], sound.signal.fft_frequencies()[peak+dist], color='r')
plt.annotate(r"$\frac{H}{\sqrt{2}}$", (sound.signal.fft_frequencies()[peak+dist//2], height/np.sqrt(2)+(height*1.1 - height/10)/10), fontsize=15)
plt.tight_layout()
axs[-1].set_axis_off()
# Approximer chaque pic avec une spline univariante
indexes = np.arange(0, len(peaks), 4) # 1 pic sur 4
reduced_peaks = peaks[indexes]
fig, axs = plt.subplots(2,4, figsize=(12,6))
axs = axs.reshape(1, -1)[0]
fft = sound.signal.fft()[:len(sound.signal.fft())//2]
fft_freq = sound.signal.fft_frequencies()
signal_spline = InterpolatedUnivariateSpline(fft_freq, fft)
for ax, peak in zip(axs,reduced_peaks):
plt.sca(ax)
freq = fft_freq[peak]
dist = np.where(fft_freq>10)[0][0]
height = fft[peak]
spline_freq = np.linspace(fft_freq[peak-dist], fft_freq[peak+dist], 1000)
plt.plot(fft_freq[peak-dist:peak+dist]+0.2, fft[peak-dist:peak+dist], c='r', alpha=0.5)
plt.plot(spline_freq, signal_spline(spline_freq), c='b', alpha=0.5)
plt.scatter(fft_freq[peak], fft[peak], c='r')
plt.ylim((height/10, height*1.1))
plt.hlines(height/np.sqrt(2), fft_freq[peak-dist], fft_freq[peak+dist], color='r')
annotation_height = height/np.sqrt(2)+(height*1.1 - height/10)/10
plt.annotate(r"$\frac{H}{\sqrt{2}}$", (fft_freq[peak+dist//2], annotation_height), fontsize=15)
axs[-1].set_axis_off()
plt.tight_layout()
# Trouver les valeurs de w1 et w2 et de zeta
indexes = np.arange(0, len(peaks), 4) # 1 pic sur 4
reduced_peaks = peaks[indexes]
fig, axs = plt.subplots(2,4, figsize=(12,6))
axs = axs.reshape(1, -1)[0]
fft = sound.signal.fft()[:len(sound.signal.fft())//2]
fft_freq = sound.signal.fft_frequencies()
for ax, peak in zip(axs, reduced_peaks):
plt.sca(ax)
freq = fft_freq[peak]
dist = np.where(fft_freq>3)[0][0]
height = fft[peak]
root_height = height/np.sqrt(2)
frequency_roots = InterpolatedUnivariateSpline(fft_freq, fft-root_height).roots()
sorted_indexes = np.argsort(np.abs(frequency_roots-freq))
w2, w1 = frequency_roots[sorted_indexes[:2]]
w1, w2 = np.sort([w1, w2])
zeta = (w2 - w1)/(2*freq)
plt.plot(fft_freq[peak-dist:peak+dist], fft[peak-dist:peak+dist], c='k')
plt.scatter([w1, w2], [root_height, root_height], c='b')
plt.ylim((height/3, height*1.1))
plt.hlines(height/np.sqrt(2), fft_freq[peak-dist], fft_freq[peak+dist], color='r')
plt.title(r"$\zeta =$ " + str(np.around(zeta, 6)))
axs[-1].set_axis_off()
plt.tight_layout()
# Courbe damping-fréquence
fft = sound.signal.fft()[:len(sound.signal.fft())//2]
fft_freq = sound.signal.fft_frequencies()
peak_freqs = []
zetas = []
for peak in peaks:
peak_frequency = fft_freq[peak]
peak_height = fft[peak]
root_height = peak_height/np.sqrt(2)
frequency_roots = InterpolatedUnivariateSpline(fft_freq, fft-root_height).roots()
sorted_roots_indexes = np.argsort(np.abs(frequency_roots-peak_frequency))
w2, w1 = frequency_roots[sorted_roots_indexes[:2]]
w1, w2 = np.sort([w1, w2])
zeta = (w2 - w1)/(2*peak_frequency)
zetas.append(zeta)
peak_freqs.append(peak_frequency)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16,6))
# First plot
ax1.scatter(peak_freqs, zetas, c='g')
frequencies = np.linspace(peak_freqs[0], peak_freqs[-1], 300)
spl = InterpolatedUnivariateSpline(peak_freqs, zetas, k=3)
ax1.plot(frequencies, spl(frequencies), c='k', label='spline')
ax1.grid('on')
ax1.set_title('Damping versus Frequency')
ax1.set_xlabel('Frequency (Hz)')
ax1.set_ylabel(r'Damping $\zeta$')
# Second plot
ax2.scatter(peak_freqs, np.array(zetas)*(1/np.array(zetas).max()), c='r')
normalised_damping = spl(frequencies)*1/spl(frequencies).max()
ax2.plot(frequencies, normalised_damping, c='k')
plt.sca(ax2)
sound.signal.plot('fft', c='b')
ax2.set_yscale('linear')
ax2.set_title('Damping and FFT')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Normalised [0,1]')
plt.show()
```
## Implementation
```
sound.signal.plot('damping', c='k')
```
## Testing
### 1. Working with different fundamentals
```
file1 = 'soundfiles/flax_carbon/Wood_A0_1.wav'
file2 = 'soundfiles/flax_carbon/Carbon_D0_2.wav'
file3 = 'soundfiles/flax_carbon/Carbon_E0_1.wav'
file4 = 'soundfiles/flax_carbon/Wood_D0_2.wav'
file5 = 'soundfiles/flax_carbon/Wood_E0_1.wav'
file6 = 'soundfiles/flax_carbon/Wood_E1_1.wav'
files = [file1, file2, file3, file4, file5, file6]
sounds = [Sound(file).condition(return_self=True) for file in files]
fig, axs = plt.subplots(2,3, figsize=(16,12))
axs = axs.reshape(1, -1)[0]
for sound, ax in zip(sounds, axs):
sound.SP.change('fft_range', 4000)
plt.sca(ax)
sound.signal.plot('damping', c='k')
ax.set_title('fundamental : ' + str(int(sound.signal.fundamental())) + ' Hz')
plt.tight_layout()
```
### 2. Comparing two materials
```
carbonfile = 'soundfiles/flax_carbon/Carbon_D0_2.wav'
woodfile = 'soundfiles/flax_carbon/Wood_D0_2.wav'
carbon = Sound(carbonfile, name='carbon').condition(return_self=True)
carbon.SP.change('fft_range', 4000)
wood = Sound(woodfile, name='wood').condition(return_self=True)
wood.SP.change('fft_range', 4000)
plt.figure(figsize=(12,8))
wood.signal.plot('damping', label = wood.name + ' : ' + str(int(wood.signal.fundamental())) + ' Hz')
carbon.signal.plot('damping', label = carbon.name + ' : ' + str(int(carbon.signal.fundamental())) + ' Hz')
plt.legend()
plt.title('Wood vs Carbon frequency damping')
plt.show()
```
### 3. Works for plates ?
```
carbonfile = 'soundfiles/flax_carbon/Carbon.wav'
flaxfile = 'soundfiles/flax_carbon/Flax.wav'
carbon = Sound(carbonfile, name='carbon').condition(return_self=True)
carbon.SP.change('fft_range', 580)
flax = Sound(flaxfile, name='flax').condition(return_self=True)
flax.SP.change('fft_range', 580)
plt.figure(figsize=(12,8))
flax.signal.plot('damping', label = flax.name + ' : ' + str(int(flax.signal.fundamental())) + ' Hz')
carbon.signal.plot('damping', label = carbon.name + ' : ' + str(int(carbon.signal.fundamental())) + ' Hz')
plt.legend()
plt.title('Wood vs Flax Damping (impact on plate)')
plt.show()
```
| github_jupyter |
<a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a>
WARNING: This tutorial has not been updated to work with Landlab 2.0 and is thus not tested to verify that it will run.
### Tutorial For Cellular Automaton Vegetation Model Coupled With Ecohydrologic Model
<hr>
<small>For more Landlab tutorials, click here: <a href="https://landlab.readthedocs.io/en/v2_dev/user_guide/tutorials.html">https://landlab.readthedocs.io/en/v2_dev/user_guide/tutorials.html</a></small>
<hr>
This tutorial demonstrates implementation of the Cellular Automaton Tree-GRass-Shrub Simulator (CATGRaSS) [Zhou et al., 2013] on a flat domain. This model is built using components from the Landlab component library. CATGRaSS is spatially explicit model of plant coexistence. It simulates local ecohydrologic dynamics (soil moisture, transpiration, biomass) and spatial evolution of tree, grass, and shrub Plant Functional Types (PFT) driven by rainfall and solar radiation.
Each cell in the model grid can hold a single PFT or remain empty. Tree and shrub plants disperse seeds to their neighbors. Grass seeds are assumed to be available at each cell. Establishment of plants in empty cells is determined probabilistically based on water stress of each PFT. Plants with lower water stress have higher probability of establishment. Plant mortality is simulated probabilistically as a result of aging and drought stress. Fires and grazing will be added to this model soon.
This model (driver) contains:
- A local vegetation dynamics model that simulates storm and inter-storm water balance and ecohydrologic fluxes (ET, runoff), and plant biomass dynamics by coupling the following components:
- PrecipitationDistribution
- Radiation
- PotentialEvapotranspiration
- SoilMoisture
- Vegetation
- A spatially explicit probabilistic cellular automaton component that simulates plant competition by tracking establishment and mortality of plants based on soil moisture stress:
- VegCA
To run this Jupyter notebook, please make sure that the following files are in the same folder:
- cellular_automaton_vegetation_flat_domain.ipynb (this notebook)
- Inputs_Vegetation_CA.txt (Input parameters for the model)
- Ecohyd_functions_flat.py (Utility functions)
[Ref: Zhou, X, E. Istanbulluoglu, and E.R. Vivoni. "Modeling the ecohydrological role of aspect-controlled radiation on tree-grass-shrub coexistence in a semiarid climate." Water Resources Research 49.5 (2013): 2872-2895]
In this tutorial, we are going to work with a landscape in central New Mexico, USA, where aspect controls the organization of PFTs. The climate in this area is semi-arid with Mean Annual Precipitation (MAP) of 254 mm [Zhou et. al 2013].
We will do the following:
- Import a landscape
- Initialize the landscape with random distribution of PFTs
- Run the coupled Ecohydrology and cellular automata plant competition model for 50 years
- Visualize and examine outputs
#### Let us walk through the code:
Import the required libraries
```
from __future__ import print_function
%matplotlib inline
import time
import numpy as np
from landlab import RasterModelGrid as rmg
from landlab import load_params
from Ecohyd_functions_flat import (Initialize_, Empty_arrays,
Create_PET_lookup, Save_, Plot_)
```
Note: 'Ecohyd_functions_flat.py' is a utility script that contains 'functions', which instantiates components and manages inputs and outputs, and help keep this driver concise. Contents of 'Ecohyd_functions_flat.py' can be a part of this driver (current file), however left out to keep driver concise.
To minimize computation time, we will use two grids in this driver. One grid will represent a flat landscape or domain (i.e., landscape with same elevation), on which the cellular automata plant competition will be simulated at an yearly time step. Another grid, with enough cells to house one cell for each of the plant functional types (PFTs), will be used to simulate soil moisture decay and local vegetation dynamics, in between successive storms (i.e. time step = one storm). Cumulative water stress (stress experienced by plants due to lack of enough soil moisture) will be calculated over an year and mapped to the other grid.
- grid: This grid represents the actual landscape. Each cell can be occupied by a single PFT such as tree, shrub, grass, or can be empty (bare). Initial PFT distribution is randomnly generated from inputs of percentage of cells occupied by each PFT.
- grid1: This grid allows us to calculate PFT specific cumulative water stress (cumulated over each storm in the year) and mapped with 'grid'.
Note: In this tutorial, the physical ecohydrological components and cellular automata plant competition will be run on grids with different resolution. To use grids with same resolution, see the tutorial 'cellular_automaton_vegetation_DEM.ipynb'.
```
grid1 = rmg((100, 100), spacing=(5., 5.))
grid = rmg((5, 4), spacing=(5., 5.))
```
Include the input file that contains all input parameters needed for all components. This file can either be a python dictionary or a text file that can be converted into a python dictionary. If a text file is provided, it will be converted to a Python dictionary. Here we use an existing text file prepared for this exercise.
```
InputFile = 'Inputs_Vegetation_CA_flat.txt'
data = load_params(InputFile) # Create dictionary that holds the inputs
```
Instantiate landlab components to simulate corresponding attributes. In this example, we shall demonstrate the use of seasonal rainfall and PFT-specific potential evapotranspiration. The instantiated objects are:
- PD_D: object for dry season rainfall,
- PD_W: object for wet season rainfall,
- Rad: Radiation object computes radiation factor defined as the ratio of total shortwave radiation incident on a sloped surface to total shortwave radiation incident on a flat surface. Note: in this example a flat domain is considered. Radiation factor returned will be a cellular field of ones. This component is included because potential evaporanspiration (PET) component receives an input of radiation factor as a field.
- PET_PFT: Plant specific PET objects. PET is upper boundary to ET. For long-term simulations PET is represented using a cosine function as a function of day of year. Parameters of this function were obtained from P-M model application at a weather station. PET is spatially distributed by using the radiation factor.
- SM: Soil Moisture object simulates depth-averaged soil moisture at each cell using inputs of potential evapotranspiration, live leaf area index and vegetation cover.
- VEG: Vegetation dynamics object simulates net primary productivity, biomass and leaf area index (LAI) at each cell based on inputs of root-zone average soil moisture.
- vegca: Cellular Automaton plant competition object is run once every year. This object is initialized with a random cellular field of PFT. Every year, this object updates the cellular field of PFT based on probabilistic establishment and mortality of PFT at each cell.
Note: Almost every component in landlab is coded as a 'class' (to harness the advantages of objective oriented programming). An 'object' is the instantiation of the 'class' (for more information, please refer any objective oriented programming book). A 'field' refers to a Landlab field (please refer to the [Landlab documentation](https://github.com/landlab/landlab/wiki/Grid#adding-data-to-a-landlab-grid-element-using-fields) to learn more about Landlab fields).
Now let's instantiate all Landlab components that we are going to use for this tutorial:
```
PD_D, PD_W, Rad, PET_Tree, PET_Shrub, PET_Grass, SM, VEG, vegca = Initialize_(
data, grid, grid1)
```
Lets look at the initial organization of PFTs
```
import matplotlib.pyplot as plt
from landlab.plot import imshow_grid
import matplotlib as mpl
cmap = mpl.colors.ListedColormap(
['green', 'red', 'black', 'white', 'red', 'black'])
bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
description = 'green: grass; red: shrub; black: tree; white: bare'
plt.figure(101)
imshow_grid(grid1,
'vegetation__plant_functional_type',
values_at='cell',
cmap=cmap,
grid_units=('m', 'm'),
norm=norm,
limits=[0, 5],
allow_colorbar=False)
plt.figtext(0.2, 0.0, description, weight='bold', fontsize=10)
```
Specify an approximate number of years for the model to run. For this example, we will run the simulation for 600 years. It might take less than 2+ minutes to run.
```
n_years = 600 # Approx number of years for model to run
# Calculate approximate number of storms per year
fraction_wet = (data['doy__end_of_monsoon'] -
data['doy__start_of_monsoon']) / 365.
fraction_dry = 1 - fraction_wet
no_of_storms_wet = (8760 * (fraction_wet) /
(data['mean_interstorm_wet'] + data['mean_storm_wet']))
no_of_storms_dry = (8760 * (fraction_dry) /
(data['mean_interstorm_dry'] + data['mean_storm_dry']))
n = int(n_years * (no_of_storms_wet + no_of_storms_dry))
```
Create empty arrays to store spatio-temporal data over multiple iterations. The captured data can be used for plotting model outputs.
```
P, Tb, Tr, Time, VegType, PET_, Rad_Factor, EP30, PET_threshold = Empty_arrays(
n, grid, grid1)
```
To reduce computational overhead, we shall create a lookup array for plant-specific PET values for each day of the year.
```
Create_PET_lookup(Rad, PET_Tree, PET_Shrub, PET_Grass, PET_, Rad_Factor, EP30,
grid)
```
Specify current_time (in years). current_time is the current time in the simulation.
```
# # Represent current time in years
current_time = 0 # Start from first day of Jan
# Keep track of run time for simulation - optional
Start_time = time.clock() # Recording time taken for simulation
# declaring few variables that will be used in the storm loop
time_check = 0. # Buffer to store current_time at previous storm
yrs = 0 # Keep track of number of years passed
WS = 0. # Buffer for Water Stress
Tg = 270 # Growing season in days
```
The loop below couples the components introduced above in a for loop until all "n" number of storms are generated. Time is advanced by the soil moisture object based on storm and interstorm durations that are estimated by the strom generator object. The ecohydrologic model is run each storm whereas cellular automaton vegetation component is run once every year.
Note: This loop might take less than 2 minutes (depending on your computer) to run for 600 year simulation. Ignore any warnings you might see.
```
# # Run storm Loop
for i in range(0, n):
# Update objects
# Calculate Day of Year (DOY)
Julian = int(np.floor((current_time - np.floor(current_time)) * 365.))
# Generate seasonal storms
# for Dry season
if Julian < data['doy__start_of_monsoon'] or Julian > data[
'doy__end_of_monsoon']:
PD_D.update()
P[i] = PD_D.storm_depth
Tr[i] = PD_D.storm_duration
Tb[i] = PD_D.interstorm_duration
# Wet Season - Jul to Sep - NA Monsoon
else:
PD_W.update()
P[i] = PD_W.storm_depth
Tr[i] = PD_W.storm_duration
Tb[i] = PD_W.interstorm_duration
# Spatially distribute PET and its 30-day-mean (analogous to degree day)
grid['cell']['surface__potential_evapotranspiration_rate'] = PET_[Julian]
grid['cell']['surface__potential_evapotranspiration_30day_mean'] = EP30[
Julian]
# Assign spatial rainfall data
grid['cell']['rainfall__daily_depth'] = P[i] * np.ones(
grid.number_of_cells)
# Update soil moisture component
current_time = SM.update(current_time, Tr=Tr[i], Tb=Tb[i])
# Decide whether its growing season or not
if Julian != 364:
if EP30[Julian + 1, 0] > EP30[Julian, 0]:
PET_threshold = 1
# 1 corresponds to ETThresholdup (begin growing season)
else:
PET_threshold = 0
# 0 corresponds to ETThresholddown (end growing season)
# Update vegetation component
VEG.update(PETThreshold_switch=PET_threshold, Tb=Tb[i], Tr=Tr[i])
# Update yearly cumulative water stress data
WS += (grid['cell']['vegetation__water_stress']) * Tb[i] / 24.
# Record time (optional)
Time[i] = current_time
# Update spatial PFTs with Cellular Automata rules
if (current_time - time_check) >= 1.:
if yrs % 100 == 0:
print('Elapsed time = {time} years'.format(time=yrs))
VegType[yrs] = grid1['cell']['vegetation__plant_functional_type']
WS_ = np.choose(VegType[yrs], WS)
grid1['cell']['vegetation__cumulative_water_stress'] = WS_ / Tg
vegca.update()
time_check = current_time
WS = 0
yrs += 1
VegType[yrs] = grid1['cell']['vegetation__plant_functional_type']
```
Time_Consumed is an optional variable that gives information about computer running time
```
Final_time = time.clock()
Time_Consumed = (Final_time - Start_time) / 60. # in minutes
print('Time_consumed = {time} minutes'.format(time=Time_Consumed))
```
Save the outputs using ``numpy.save()``. These files have '.nc' extension, which can be loaded using ``numpy.load()``.
```
# # Saving
sim = 'Sim_26Jul16_'
#Save_(sim, Tb, Tr, P, VegType, yrs, Time_Consumed, Time)
```
Let's look at outputs.
Plots of the cellular field of PFT at specified year step can be found below where:
GRASS = green; SHRUB = red; TREE = black; BARE = white;
At the end, percentage cover of each PFT is plotted with respect to time.
```
Plot_(grid1, VegType, yrs, yr_step=100)
```
If you want to explore this model further, open 'Inputs_Vegetation_CA.txt' and change the input parameters (e.g., initial PFT distribution percentages, storm characteristics, etc..).
### Click here for more <a href="https://landlab.readthedocs.io/en/v2_dev/user_guide/tutorials.html">Landlab tutorials</a>
| github_jupyter |
# Profiling BatchFlow code
A profile is a set of statistics that describes how often and for how long various parts of the program executed.
This notebooks shows how to profile various parts of BatchFlow: namely, pipelines and models.
```
import sys
sys.path.append("../../..")
from batchflow import B, V, W
from batchflow.opensets import MNIST
from batchflow.models.torch import ResNet18
dataset = MNIST(bar=True)
```
To collect information about model training times (both on CPU and GPU), one must set `profile` option in the model configuration to `True`:
```
model_config = {
'inputs/labels/classes': 10,
'loss': 'ce',
'profile': True,
}
pipeline = (dataset.train.p
.init_variable('loss_history', [])
.to_array(channels='first', dtype='float32')
.multiply(multiplier=1/255., preserve_type=False)
.init_model('resnet', ResNet18, 'dynamic',
config=model_config)
.train_model('resnet',
B.images, B.labels,
fetches='loss',
save_to=V('loss_history', mode='a'))
)
```
To gather statistics about how long each action takes, we must set `profile` to `True` inside `run` call:
```
BATCH_SIZE = 64
N_ITERS = 50
pipeline.run(BATCH_SIZE, n_iters=N_ITERS, bar=True, profile='detailed')
```
# Pipeline profiling
```
pipeline.profile_info.head()
```
Note that there is a detailed information about exact methods that are called inside each of the actions. That is a lot of data which can give us precise understanding of parts of the code, that are our bottlenecks.
Columns of the `profile_info`:
- `action`, `iter`, `batch_id` and `start_time` are pretty self-explainable
- `id` allows to identify exact method with great details: it is a concatenation of `method_name`, `file_name`, `line_number` and `callee`
- `eval_time` is is a time taken by an action execution
- `total_time` is `eval_time` plus time of processing the profiling table at each iteration
- `action_time` is a time taken by an clear action execution without pipeline under-the-hood stuff
- `tottime` is a time taken by a method inside action
- `cumtime` is a time take by a method and all of the methods that are called inside this method
More often than not, though, we don't need such granularity. Pipeline method `show_profile_info` makes some handy aggregations:
**Note:** by default, results are sorted on `total_time` or `tottime`, depending on level of details.
```
# timings for each action
pipeline.show_profile_info(per_iter=False, detailed=False)
# for each action show 2 of the slowest methods, based on maximum `ncalls`
pipeline.show_profile_info(per_iter=False, detailed=True, sortby=('ncalls', 'max'), limit=2)
# timings for each action for each iter
pipeline.show_profile_info(per_iter=True, detailed=False)
# for each iter each action show 3 of the slowest methods, based on maximum `ncalls`
pipeline.show_profile_info(per_iter=True, detailed=True, sortby='tottime', limit=3)
```
# Model profiling
```
model = pipeline.m('resnet')
```
There is an `info` property that, unsurprisingly, shows a lot of interesting details regarding model itself or the training process:
```
print(model.info())
```
As with pipeline, there is a `profile_info` attribute, as well as `show_profile_info` method. Depending on type of the used device (`CPU` or `GPU`)
```
# one row for every operation inside model; limit at 5 rows
model.show_profile_info(per_iter=False, limit=5)
# for each iteration show 3 of the slowest operations
model.show_profile_info(per_iter=True, limit=3)
```
| github_jupyter |
## Observations and Insights
- The mean tumor valume for Ketapril and Naftisol had the highest standard deviation while Ramicane and Capomulin had the lowest.
- The distribulation of male mouse was a little higher than female mouse.
- Ramicane and Capomulin showed decreasing in tumor volume after treatment while no considerable changed was observed in Infubinol and Ceftamin groups.
- There was a positive correlation between Tumor Volume and Weight loss.
## Dependencies and starter code
```
# Dependencies
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats as st
import numpy as np
import random
from scipy.stats import linregress
# Study data files
mouse_metadata = "data/Mouse_metadata.csv"
study_results = "data/Study_results.csv"
# Read the mouse data and the study results
mouse_metadata = pd.read_csv(mouse_metadata)
study_results = pd.read_csv(study_results)
# Combine the data into a single dataset
combined_data=pd.merge(mouse_metadata, study_results, on ="Mouse ID", how="outer")
# check if there is any null
#combined_data.isnull().sum()
combined_data
```
## Summary statistics
```
# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen
# group by data based on the drug regim
combined_data_grouped = combined_data.groupby(["Drug Regimen"])
#calculate mean, median, variance, standard deviation, and SEM
mean = combined_data_grouped["Tumor Volume (mm3)"].mean()
median = combined_data_grouped["Tumor Volume (mm3)"].median()
variance = combined_data_grouped["Tumor Volume (mm3)"].var()
std= combined_data_grouped["Tumor Volume (mm3)"].std()
standard_errors = combined_data_grouped["Tumor Volume (mm3)"].sem()
#create a summery data frame to hold the results
summary_statistics = pd.DataFrame({"Mean": mean,
"Median":median,
"Variance":variance,
"Standard Deviation": std,
"SEM": standard_errors})
summary_statistics
```
## Bar plots-pandas
```
# Generate a bar plot showing number of data points for each treatment regimen using pandas
#calculate the number of data points using group by on drug regimen and count function
reg_data_points = combined_data_grouped.count()["Mouse ID"]
# Use DataFrame.plot() in order to create a bar chart of the data
reg_data_points.plot(kind="bar", facecolor="pink")
#set chart title
plt.title("Data Points for each treatment regimen ")
plt.xlabel("Drug Regimen")
plt.ylabel("Data Points")
#show chart and set layout
plt.show()
plt.tight_layout()
```
## Bar plots-Matplotlib
```
## Generate a bar plot showing number of data points for each treatment regimen using pyplot
#define a list to hold the number and the value of data points
x_axis = np.arange(len(reg_data_points))+1
y_axis = reg_data_points
#crreat a list to hold the drug regimen
drug_regimen = combined_data["Drug Regimen"].drop_duplicates()
#create a bar plot using pyplot
plt.bar(x_axis, y_axis, color='pink', alpha=1, align="center")
# Tell matplotlib where we would like to place each of our x axis headers
tick_locations = [x for x in x_axis]
plt.xticks(tick_locations, drug_regimen, rotation=90)
# Give our graph axis labels and title
plt.xlabel("Drug Regimen")
plt.ylabel("Data points")
plt.title("Data points for each treatment ")
#show chart and set layout
plt.show()
plt.tight_layout()
```
## Pie plots-pandas
```
# Generate a pie plot showing the distribution of female versus male mice using pandas
#difine a list to hold the sex
list_sex=["Female", "Male"]
#count the number of each sex using value.count
sex_distribution= combined_data.Sex.value_counts()
# Tells matplotlib to seperate the "feemale"and "male" section
explode = (0.1, 0)
#showing pie plot of the sex distribution using pandas.Series.plot.pie
chart_pie = sex_distribution.plot.pie(y= list_sex, explode=explode, colors=["green", "red"], figsize=(5, 5))
# Give our graph axis labels and title
plt.title("The distribution of female versus male mice")
#show chart and set layout
plt.show()
plt.tight_layout()
```
## Pie plots-pyplot
```
# Generate a pie plot showing the distribution of female versus male mice using pyplot
# The values of each section of the pie chart
sizes = sex_distribution
# Labels for the sections of our pie chart
labels = list_sex
# The colors of each section of the pie chart
colors = ["red", "green"]
# Tells matplotlib to seperate the "feemale"and "male" section
explode = (0.1, 0)
# Creates the pie chart based upon the values above
# Automatically finds the percentages of each part of the pie chart
plt.pie(sizes, labels=list_sex, explode=explode, colors=colors, shadow=True, startangle=180)
# Tells matplotlib that we want a pie chart with equal axes
plt.axis("equal")
# Give our graph axis labels and title
plt.title("The distribution of female versus male mice")
#show chart and set layout
plt.show()
plt.tight_layout()
```
## Quartiles, outliers and boxplots
```
# Calculate the final tumor volume of each mouse across four of the most promising treatment regimens. Calculate the
#IQR and quantitatively determine if there are any potential outliers.
# calculate the latest time point for each mouse
last_size = combined_data.groupby(["Mouse ID"]).max()
#reset the index of the previose data frame
last_size_reset = last_size.reset_index()
#Merge this dataframe with the first one to calculate the final tumore valume
merge_last_combined = last_size_reset[["Timepoint", "Mouse ID"]].merge(combined_data, on=["Mouse ID", "Timepoint"], how="left")
# seperate the data of each interested regimen
capumulin_volume = marge_last_combined.loc[merge_last_combined["Drug Regimen"]=="Capomulin"]["Tumor Volume (mm3)"]
ramicane_volume = marge_last_combined.loc[merge_last_combined["Drug Regimen"]=="Ramicane"]["Tumor Volume (mm3)"]
infubinol_volume = marge_last_combined.loc[merge_last_combined["Drug Regimen"]=="Infubinol"]["Tumor Volume (mm3)"]
ceftamin_volume = marge_last_combined.loc[merge_last_combined["Drug Regimen"]=="Ceftamin"]["Tumor Volume (mm3)"]
#calculte the outliers of capmolin
capumulin_qurtiles = capumulin_volume.quantile([0.25,0.5,0.75])
capumulin_lowerq = capumulin_qurtiles[0.25]
capumulin_upperq = capumulin_qurtiles[0.75]
capumulin_iqr = capumulin_upperq - capumulin_lowerq
capumulin_lower_bound = capumulin_lowerq - (1.5*capumulin_iqr)
capumulin_upper_bound = capumulin_upperq + (1.5*capumulin_iqr)
#print out the results for capomulin
print(f'The potential outliers for capomulin: {capumulin_volume.loc[(capumulin_volume<capumulin_lower_bound)|(capumulin_volume> capumulin_upper_bound)]}')
#calculte the outliers of Ramicane
ramicane_qurtiles = ramicane_volume.quantile([0.25,0.5,0.75])
ramicane_lowerq = ramicane_qurtiles[0.25]
ramicane_upperq = ramicane_qurtiles[0.75]
ramicane_iqr = ramicane_upperq - ramicane_lowerq
ramicane_lower_bound = ramicane_lowerq - (1.5*ramicane_iqr)
ramicane_upper_bound = ramicane_upperq + (1.5*ramicane_iqr)
#print out the results for Ramicane
print(f'The potential outliers for ramicane: {ramicane_volume.loc[(ramicane_volume < ramicane_lower_bound)|(ramicane_volume> ramicane_upper_bound)]}')
#calculte the outliers of Infubinol
infubinol_qurtiles = infubinol_volume.quantile([0.25,0.5,0.75])
infubinol_lowerq = infubinol_qurtiles[0.25]
infubinol_upperq = infubinol_qurtiles[0.75]
infubinol_iqr = infubinol_upperq - infubinol_lowerq
infubinol_lower_bound = infubinol_lowerq - (1.5*infubinol_iqr)
infubinol_upper_bound = infubinol_upperq + (1.5*infubinol_iqr)
#print out the results for Infubinol
print(f'The potential outliers for infubinol: {infubinol_volume.loc[(infubinol_volume < infubinol_lower_bound)|(infubinol_volume> infubinol_upper_bound)]}')
#calculte the outliers of Ceftamin
ceftamin_qurtiles = ceftamin_volume.quantile([0.25,0.5,0.75])
ceftamin_lowerq = ceftamin_qurtiles[0.25]
ceftamin_upperq = ceftamin_qurtiles[0.75]
ceftamin_iqr = ceftamin_upperq - ceftamin_lowerq
ceftamin_iqr = ceftamin_upperq - ceftamin_lowerq
ceftamin_lower_bound = ceftamin_lowerq - (1.5*ceftamin_iqr)
ceftamin_upper_bound = ceftamin_upperq + (1.5*ceftamin_iqr)
#print out the results for ceftamin
print(f'The potential outliers for ceftamin: {ceftamin_volume.loc[(ceftamin_volume < ceftamin_lower_bound)|(ceftamin_volume> ceftamin_upper_bound)]}')
# Calculate the final tumor volume of each mouse across four of the most promising treatment regimens. Calculate the
#IQR and quantitatively determine if there are any potential outliers.
#Define a pivot table to find the final tumore volume(final_tumor_volume)
tumor_volume = combined_data.pivot_table(values="Tumor Volume (mm3)", index = "Timepoint", columns="Drug Regimen")
# remove less interested column
tumor_volume_limited = tumor_volume[["Capomulin", "Ramicane", "Infubinol", "Ceftamin"]]
#grap the last column of the previous table as a final volume
final_tumore_valume = tumor_volume_limited.iloc[-1,:]
#make a datafram to make it prety!!!
final_tumore_valume_df = final_tumore_valume.to_frame()
#change the name of column to someting meaningfull
final_tumore_valume_df_final = final_tumore_valume_df.rename(columns={45:"final tumor volume"})
final_tumore_valume_df_final
# Generate a box plot of the final tumor volume of each mouse across four regimens of interest
#outliers = dic(markerface)
labels= ["Capomulin", "Ramicane", "Infubinol", "Ceftamin"]
flierprops = {'markersize' : 10, 'markerfacecolor' : 'red'}
plt.boxplot([capumulin_volume, ramicane_volume, infubinol_volume, ceftamin_volume], labels= labels, flierprops=flierprops)
plt.ylim(0, 80)
plt.ylabel("final tumor volume (mm3)")
plt.show()
```
## Line and scatter plots
```
# Generate a line plot of time point versus tumor volume for a mouse treated with Capomulin
#seperate Capomulin data from the rest of datafram
capomulin_df = combined_data.loc[combined_data["Drug Regimen"]=="Capomulin"]
#Randomly select an mouse ID
capomulin_ID = random.choice(capomulin_df['Mouse ID'].unique().tolist())
#seperate the selcetd capomulin ID from the rest of capomulin_df
selected_capomulin_df = combined_data.loc[combined_data["Mouse ID"]==capomulin_ID,:]
#create a plot
plt.plot(selected_capomulin_df['Timepoint'],
selected_capomulin_df['Tumor Volume (mm3)'],
marker = 'o',
color = 'red')
# Give our graph axis labels and title
plt.title(f'Time point versus tumor volume in {capomulin_ID} treated with capomulin' )
plt.ylabel('tumor volume (mm3)')
plt.xlabel('days')
#show chart and set layout
plt.show()
plt.tight_layout()
# Generate a scatter plot of mouse weight versus average tumor volume for the Capomulin regimen
#calculate the mean of tumor volume and weight
mean_capomulin_df = capomulin_df.groupby('Mouse ID').mean()
#create the scatter plot
plt.scatter(mean_capomulin_df["Weight (g)"],
mean_capomulin_df["Tumor Volume (mm3)"],
facecolors = "black",
edgecolors = "red",
)
# Give our graph axis labels and title
plt.title("scatter plot of mouse weight versus average tumor volume for the Capomulin regimen")
plt.ylabel('average tumor volume')
plt.xlabel('mouse weight (g)')
#describe the limitation for axis
plt.ylim(mean_capomulin_df['Tumor Volume (mm3)'].min() - 1,
mean_capomulin_df['Tumor Volume (mm3)'].max() + 1)
plt.xlim(mean_capomulin_df['Weight (g)'].min() - 1,
mean_capomulin_df['Weight (g)'].max() + 1)
#show chart and set layout
plt.show()
plt.tight_layout()
# Calculate the correlation coefficient and linear regression model for mouse weight and average tumor volume for
#the Capomulin regimen
#creat x and y axis
x_axis = mean_capomulin_df["Weight (g)"]
y_axis = mean_capomulin_df["Tumor Volume (mm3)"]
#calculate inear regression
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
#the equation of linier regression
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
#copy the scatter plot code here!
plt.scatter(mean_capomulin_df["Weight (g)"],
mean_capomulin_df["Tumor Volume (mm3)"],
facecolors = "black",
edgecolors = "green",
)
#Line plot of regrresusion
plt.plot(x_axis, regress_values,"r-")
# Give our graph axis labels and title
plt.title("scatter plot of mouse weight versus average tumor volume for the Capomulin regimen")
plt.ylabel('average tumor volume')
plt.xlabel('mouse weight (g)')
#describe the limitation for axis
plt.ylim(mean_capomulin_df['Tumor Volume (mm3)'].min() - 1,
mean_capomulin_df['Tumor Volume (mm3)'].max() + 1)
plt.xlim(mean_capomulin_df['Weight (g)'].min() - 1,
mean_capomulin_df['Weight (g)'].max() + 1)
#write the equation on the scattered plot
plt.annotate(line_eq, (18,36), fontsize=15,)
```
| github_jupyter |
```
# import sys
!{sys.executable} -m pip install pytesseract
# word_level_df.head()
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
img_width = 128
img_height = 64
images = word_level_df.image_path.values.tolist()[3]
print(images)
img = cv2.imread(images)
# grayscale image
# img = cv2.cvtColor(img, cv2.)
# resize image
img = cv2.resize(img, (img_width, img_height))
# change image type
img = img.astype(np.float32)
# scale image
img /= 255
plt.imshow(img)
# img = cv2.imdecode(img, cv2.CV_LOAD_IMAGE_COLOR)
from io import BytesIO
byte = BytesIO()
img = byte.write(img)
print(type(img))
import cv2
img = cv2.imread(images)
print(pytesseract.image_to_string(img))
# OR explicit beforehand converting
print(pytesseract.image_to_string(Image.fromarray(img)))
from PIL import Image
import pytesseract
# (thresh, bw_img) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
img = Image.open(images)
txt = pytesseract.image_to_string(img)
import pytesseract
from PIL import Image, ImageEnhance, ImageFilter
im = Image.open('../../data/raw/word_level/d05/d05-040/d05-040-00-03.png') # the second one
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save('temp2.jpg')
text = pytesseract.image_to_string(Image.open('temp2.jpg'))
print(text)
# Page segmentation modes:
# 0 Orientation and script detection (OSD) only.
# 1 Automatic page segmentation with OSD.
# 2 Automatic page segmentation, but no OSD, or OCR.
# 3 Fully automatic page segmentation, but no OSD. (Default)
# 4 Assume a single column of text of variable sizes.
# 5 Assume a single uniform block of vertically aligned text.
# 6 Assume a single uniform block of text.
# 7 Treat the image as a single text line.
# 8 Treat the image as a single word.
# 9 Treat the image as a single word in a circle.
# 10 Treat the image as a single character.
# 11 Sparse text. Find as much text as possible in no particular order.
# 12 Sparse text with OSD.
# 13 Raw line. Treat the image as a single text line,
# bypassing hacks that are Tesseract-specific.
import pytesseract
from PIL import Image, ImageEnhance, ImageFilter
img_width = 256
img_height = 100
img = '../../data/raw/word_level/d01/d01-016/d01-016-03-03.png'
im = Image.open(img) # img is the path of the image
im = im.convert("RGBA")
im = im.resize((img_width, img_height))
newimdata = []
datas = im.getdata()
vals = 255
for item in datas:
# print(item)
if item[0] < vals or item[1] < vals or item[2] < vals:
newimdata.append(item)
else:
newimdata.append((255, 255, 255))
im.putdata(newimdata)
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
os
im.save('temp2.jpg')
text = pytesseract.image_to_string(Image.open('temp2.jpg'),
config='-c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyz -psm 13', lang='eng', )
print(text)
Image.open('temp2.jpg')
Image.open('../../data/raw/word_level/d01/d01-016/d01-016-03-03.png')
%%bash
tesseract ../../data/raw/word_level/d05/d05-040/d05-040-00-03.png stdout
from tesserocr import PyTessBaseAPI
with PyTessBaseAPI() as api:
api.SetImageFile(bytes(img))
print(api.GetUTF8Text())
print(api.AllWordConfidences())
# with PyTessBaseAPI() as api:
# for img in images:
# api.SetImageFile(img)
# print(api.GetUTF8Text())
# print(api.AllWordConfidences())
data_path = '../../data/raw/word_level'
meta_data_path = '../../data/preprocessed/meta.csv'
meta_json_data_path = '../../data/preprocessed/meta_json.csv'
import os
import pandas as pd
from collections import defaultdict
from tqdm import tqdm_notebook
import pdb
import dill as pickle
meta = pd.read_json(meta_json_data_path)
meta.sort_index().head()
def duplicate_row(df, col_name):
"""When cell contents are lists, create a row for each element in the list"""
series = df.apply(lambda x: pd.Series(x[col_name]),axis=1).stack().reset_index(level=1, drop=True)
series.name = col_name
return series
def create_word_level_df(df, cols=[]):
"""Combine multiple Series into a pandas DataFrame"""
meta_series = duplicate_row(df, 'meta')
id_series = duplicate_row(df, 'ids')
pos_series = duplicate_row(df, 'pos_tag')
df = df.drop(['meta', 'ids', 'pos_tag'], axis=1).join(pd.concat([meta_series, id_series, pos_series], axis=1))
return df.rename(columns={'meta': 'token', 'ids': 'image_name'}).reset_index()
def absoluteFilePaths(directory):
"""Walk filepaths"""
for dirpath,_,filenames in os.walk(directory):
for f in filenames:
yield os.path.join(dirpath, f)
def create_image_path(df, data_path):
"""Create dictionary for mapping of word to data path"""
all_paths = [i for i in absoluteFilePaths(data_path)]
all_path_endings = [i.split('/')[-1].split('.')[0] for i in all_paths]
all_path_dict = defaultdict(lambda: 0, dict(zip(all_path_endings, all_paths)))
df['image_path'] = df['image_name'].map(lambda x: all_path_dict[x])
return df
word_level_df = create_word_level_df(meta)
word_level_df = create_image_path(word_level_df, data_path)
word_level_df.image_path.values.tolist()[:10]
text = pytesseract.image_to_string(Image.open('../../data/raw/word_level/d01/d01-016/d01-016-03-03.png'),
config='-c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyz -psm 7', lang='eng', )
print(text)
```
| github_jupyter |
```
# Import the necessary dependencies
# Operating System
import os
import gc
# Numpy, Pandas and Scipy
import numpy as np
import pandas as pd
# Scikit-learn
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# LightFM
from lightfm import LightFM
from lightfm.data import Dataset as lfmDataset
# Surprise
from surprise import SVD
from surprise import Dataset as sDataset
from surprise import Reader
# Model Evaluation
from evaluation import evaluate_solution
# RAM control
from ramcontrol import check_memory_limit, memory_circuit_breaker
```
### Attention: The data used in this notebook can be enough to fill your PC's RAM. To prevent you PC from turning to a bonfire, there are some steps that can be taken:
<img src="./media/burning_pc.gif" width="450"/>
- On cells that consume a lot of RAM, stop execution if RAM usage is too high. This can be done with function `memory_circuit_breaker`. This function checks if the total computer RAM usage percentage is above a threshold and if it can't lower it, it stops execution. You can control the percentage with `memory_limit_perc` below.
- Frequently delete useless objects along the notebook. If a dataframe or matrix is not going to be used further below a given cell, then we can delete that object and let the garbage collection clear some RAM.
- Change the data types to lighter alternatives: integer IDs can be converted to strings, numerical values can have smaller "bitness" but be on the lookout for [overflow errors](https://numpy.org/doc/stable/user/basics.types.html#overflow-errors) (for example: using `np.float32` instead of `np.float64`), removed unused features early, etc.
- If RAM is still an issue at this point, we can subset the original dataset to work with a smaller fraction of the data. Of course, this will impact the quality of your models and recommendations, but if it necessary to follow the notebook then subset the data.
- When you execute cells multiple times, there might happen that the memory increases at each execution, even if no new objects or data is generated. If that's the case, you should restart the kernel and re-execute the cells.
- Ultimately, you may need more RAM. ¯\\_(ツ)_/¯
```
# limit of total memory percentage that be used [0.,100.]
memory_limit_perc = 90.
```
# BLU12 - Learning Notebook - Workflow
## Introduction
This week, we are going to simulate the real-life environment of the Hackathon! We will provide you with a dataset, some tips and you are going to train, validate and predict with a Recommender System using all the knowledge acquired throughout this specialization.
## Context
You have finished the Academy and you are hired as a Data Scientist in Recommenu. Recommenu is a disruptive crowdsourcing peer-to-peer mobile app experience developed to deliver an unique environment especially designed for maximum enjoyment by empowering users to engage in recipe sharing and reviewing in a paradigm shift block-chain powered AI platform.
<img src="./media/recommenu_logo.png" width="500"/>
First week on the job and the CEO of the next-unicorn-startup that hired you pitches your first task for the company: build a recommender system to suggest users what they should prepare for their next meals. Your recommendations should be based on their reviews but also on the reviews of other users.
He doesn't care how you do it or how it works, just that you use fancy trendy eye-catching mind-blowing AI *stuff* to promote Recommenu's name in the Data Science industry.
## Technical Task
After the pitch from the CEO, you talk with your Lead Data Scientist and you get the tasks needed to fulfill the job. The company collected some data on the users and recipes, you will need to create the recommender system that is effective enough so that your users will always know what to cook. The main task is to find the best recommendations for each user.
## Evaluation
Your Lead DS will keep some of the data as a test dataset (in which you will estimate production performance) and gives you the remaining data for yourself.
The expected output is 50 recommendations for each user. The recommendations are compared with the test dataset and evaluated using map@50.
Review the `example_out.csv` file to know the expected output format.
## Step -1: Avaliable data
You have available under the `./data/` folder some files that you can use for building the recommender system. As a good scientist, the first step is to validate that the data you have will be good enough to proceed.
The files we have available for the **training** stage are:
* `interactions_train.csv` has the users' review history training data
* `RAW_recipes.csv`: has the all recipes' metadata information
For the **test** stage, we have:
* `test_users.csv`: has the users' ID to recommend recipes
* `example_output.csv`: has an example of an output (just for a couple of users)
The best approach is to look at the raw files and print out the first rows of each file just to get a overall sense of what we have.
*Note*: since the `RAW_recipes.csv` is heavy, it was stored in a zip file which you will need to unzip first.
*Note for Windows users: remember that you need to convert the head command into the Windows equivalent. Tip: you can use what you learned in Data Wrangling Learning Unit!*
```
print("RAW_interactions_train.csv \n")
!head -3 data/RAW_interactions_train.csv
print("RAW_recipes.csv\n")
!head -2 data/RAW_recipes.csv
print("test_users.csv \n")
!head -10 data/test_users.csv
print("example_output.csv \n")
!head -1 data/example_output.csv
```
## Step 0: Load the Data
After validating that the data we have is good enough, we start with building the ratings matrix. Our strategy for the first model is to get a non-personalized system as a baseline. This allows us to both predict for existing users (no cold-start problem) and for new users.
## Step 0.1: Load the interaction file
```
train_path = os.path.join('data', 'RAW_interactions_train.csv')
data = pd.read_csv(train_path)
data.head()
```
## Step 0.2: Load the recipes' metadata file
```
recipe_meta_path = os.path.join('data', 'RAW_recipes.csv')
recipes = pd.read_csv(recipe_meta_path)
recipes.head()
```
## Step 0.3: Load test users file
```
test_user_path = os.path.join('data', 'test_users.csv')
test_users = pd.read_csv(test_user_path)
test_users.head()
```
It will be useful later on to have a list of test data users:
```
users_test = list(test_users["user_id"].unique())
print(f"We are recommending recipes for {len(users_test)} users.")
```
## Step 1: Interaction data exploration
Let's explore the interaction data.
```
# How many ratings do we have in total?
# Tip: The ":," at the end of the f-string adds the thousand separator.
print(f"We have {len(data):,} ratings in total.")
# How many recipes were rated?
print(f" We have {data['recipe_id'].unique().size:,} recipes rated.")
# How many users rated at least one recipe?
print(f" We have {data['user_id'].unique().size:,} users that rated at least one recipe.")
```
Let's plot the rating distribution:
```
# Plotting the rating distribution.
data["rating"].hist();
```
There are ratings with value 0. We expected the values to be between 1 and 5. Let's check these cases.
```
data.loc[data["rating"] == 0][80:120]
```
When rating is 0, it seems that some comments are negative but most are positive. Let's read some examples.
```
data.loc[data["rating"] == 0, "comment"][1917]
data.loc[data["rating"] == 0, "comment"][1732]
data.loc[data["rating"] == 0, "comment"][2054]
data.loc[data["rating"] == 0, "comment"][1768]
data.loc[data["rating"] == 0, "comment"][2192]
```
While some comments are positive, others are negative. Additionally, it appears that some user commented that they didn't rate the recipe. Let's see if there are more cases.
```
data.loc[(data["rating"] == 0) & (data["comment"].str.contains("rate"))].head()
## A particular case
data.loc[data["rating"] == 0, "comment"][1435]
```
All of these comments lead us to believe that zero rating means that the user purposely did not rate the recipe (maybe he/she didn't follow the recipe and feels that they shouldn't rate it) or forgot to rate it regardless of liking the recipe of not.
There isn't a consistent meaning behind zero rating as the other values have. Even considering that ratings are subjective, when a user rates a recipe 3 and another recipe 4, it means that he/she likes the recipe with rating 4 more than the recipe 3. Recipes with rating 0 can be excellent, horrible or something in between.
For this reason, reviews with zero rating should be removed from our data.
Note: In a more advanced approach, one might try to use sentiment analysis (or other techniques) to predict the rating when a user does not rate a recipe.
### Removing Zero Rating Recipes
```
nr_reviews_orig = data.shape[0]
data = data.copy().loc[(data["rating"] != 0)]
nr_reviews_new = data.shape[0]
print(f"{nr_reviews_orig - nr_reviews_new:,} reviews with rating 0 where removed from training data.")
```
### Removing Columns
You might have noticed that the review date range from January 2000 to December 2018. This is a huge time interval!
```
## Training data interval range
print(f"The earliest review was written on {data['review_date'].min()}.")
print(f"The lastest review was written on {data['review_date'].max()}.")
```
For most cases, using old data is a risk. Old data might not reflect accurately the current relationship between features and target. We say that have **[concept drift](https://machinelearningmastery.com/gentle-introduction-concept-drift-machine-learning/)** when the relationship between inputs and outputs changes over time.
In our case, we are going to consider that the userbase's taste do not change significantly over time. In a professional setting, we should back this assumption with data or deal with concept drift.
For the construction of the rating matrix, the comment column is also ignored.
```
data = data.copy().drop(columns=["review_date", "comment"])
```
## Train/Validation Split
We are splitting the available data into training and validation data. The validation data can be used to compare models before submitting the recommendations to the portal.
```
data_train, data_val = train_test_split(data, test_size=0.4, random_state=123)
```
### Training Set
```
# How many ratings do we have in total?
# Tip: The ":," at the end of the f-string adds the thousand separator.
print(f"We have {len(data_train):,} ratings in total.")
# How many recipes were rated?
print(f" We have {data_train['recipe_id'].unique().size:,} recipes rated.")
# How many users rated at least one recipe?
print(f" We have {data_train['user_id'].unique().size:,} users that rated at least one recipe.")
```
### Validation Set
```
# How many ratings do we have in total?
# Tip: The ":," at the end of the f-string adds the thousand separator.
print(f"We have {len(data_val):,} ratings in total.")
# How many recipes were rated?
print(f" We have {data_val['recipe_id'].unique().size:,} recipes rated.")
# How many users rated at least one recipe?
print(f" We have {data_val['user_id'].unique().size:,} users that rated at least one recipe.")
```
To be able to compare our recommendations with actual most liked items we need to find users that have enough actual ratings to compare with. If we are measuring `map@k` with `k=50`, users must have at least 50 actual prefered items and we have to provide at least 50 recommendations. One might argue that we now have selection bias because we are specifically selecting users that have more ratings and ignoring users with fewer ratings. This is a consideration that you should take into account specially if you want to evaluate the performance of recommendations to new users.
Here we are selecting all ratings from users with at least 50 positive reviews as our validation data.
#### Select reviews from users with at least 50 positive ratings.
```
def select_frequent_reviewers(df: pd.DataFrame, min_nr_reviews: int = 50, min_rating: int = 3):
"""
Select reviews from users with at least min_nr_reviews reviews with rating larger than min_rating.
"""
# Select only positive reviews
df_positive = df.copy().loc[df["rating"] >= min_rating]
# Select users with more than min_nr_reviews positive reviews
user_review_count = df_positive.groupby(by=["user_id"])["recipe_id"].count()
test_users_list = list(user_review_count[user_review_count > min_nr_reviews].index)
# Select ratings from users specified above
df_restrict = df_positive.copy().loc[df_positive["user_id"].isin(test_users_list)]
return df_restrict
data_val_final = select_frequent_reviewers(data_val)
data_val_final.head()
```
It will be useful later on to have a list of validation data users:
```
users_val = data_val_final["user_id"].unique().tolist()
print(f"We are validating recommendations with {len(users_val)} users.")
```
Notice that, even thought we selected 40% of the data to be used for validation, are left with a tiny number of users to validate our results. The validation data is too small to have a accurate evaluation of the models. With more data and a more robust cross-validation method this shouldn't be a problem.
Beside the new validation users, we also want the validation predictions to compare our results with.
#### Create the validation recommendations
We will evaluate the outputs of our models with the 50 best rated recipes for each user on the validation data.
```
# nr of recommendations per user
k_top = 50
def top_items_per_user(df: pd.DataFrame, user_col: str, rating_col:str, k_top: int = 50):
df_users_kbest = df.copy().groupby(by=[user_col])[rating_col].nlargest(k_top).reset_index()
df_users_kbest['rank'] = df_users_kbest.groupby(by=[user_col])[rating_col].rank(method="first")
#df_users_kbest['rank'] = df_users_kbest['rank'].astype(int) - 1
df_recommendations = df_users_kbest.pivot(index=user_col, columns="rank", values="level_1")
df_recommendations = df_recommendations.reset_index(drop=False)
df_recommendations.columns = np.arange(len(df_recommendations.columns))
return df_recommendations
val_recommendations = top_items_per_user(data_val_final, "user_id", "rating", k_top=k_top)
val_recommendations.head()
```
#### Saving recommendations
Here we create a function to store the recommendations into a `.csv` file.
```
def save_recommendations(df: pd.DataFrame, file_name: str):
"""
Save recommendation dataframe as .csv.
"""
file_path = os.path.join("data", f"{file_name}.csv")
df.to_csv(file_path, index=False, header=False)
print(f"Recommendations were saved on file {file_name}.csv.")
save_recommendations(val_recommendations, "validation_recommendations")
```
We now have the "ground-truth" that we are going to use to evaluate our recommendations.
---
# Non-Personalized Recommendations
We can directly find the most popular recipes without creating a rating matrix. We'll consider that the most popular recipes are the ones that have the best score but are also rated more. By calculating the average score and the number of times a recipe was rated, we can sort the recipes and select the best 50.
```
def non_pers_reco_order(data: pd.DataFrame,
item_col: str,
rating_col:str,
k_top: int = 50,
aggregation: list() = ["mean", "count"]):
"""
Create an ordered list of non-personalized recommendations, from best rated to worst rated.
"""
non_pers_ratings = data.groupby(by=[item_col])[[rating_col]].agg(aggregation)
non_pers_ratings.columns = non_pers_ratings.columns.get_level_values(1)
#The resulting column names might be different than the specified with the aggregation parameter.
try:
non_pers_ratings = non_pers_ratings.sort_values(by=aggregation, ascending=False).head(k_top)
except KeyError as e:
print(e)
print("Check if aggregation argument results in valid column names.")
print(f"aggregation = {aggregation}\nrating columns = {non_pers_ratings.columns}")
raise e
non_pers_reco_list = non_pers_ratings.index.to_list()
return non_pers_reco_list
non_pers_recommendations = non_pers_reco_order(data_train, "recipe_id", "rating", k_top=k_top)
print(non_pers_recommendations)
```
### Output non-personalized solution
Here we create recommendations for the specified users based on the non-personalized recommendations obtained above.
```
def non_pers_reco_output(user_id_list:list, non_pers_reco_list:list):
"""
Creates a non-personalized recommendation dataframe for specified users.
"""
nr_test_users = len(user_id_list)
user_id_df = pd.DataFrame(user_id_list, columns = ["user_id"], dtype = int)
non_pers_reco_repeated = pd.DataFrame(pd.DataFrame(non_pers_reco_list).T.values.repeat(nr_test_users, axis=0))
non_pers_reco_output = pd.concat([user_id_df, non_pers_reco_repeated], axis=1)
# Reset columns numbering. Useful later.
#non_pers_reco_output.columns = np.arange(len(non_pers_reco_output.columns))
return non_pers_reco_output
```
Let's test for a couple of users
```
non_pers_reco_output([452355, 18540, 2743667], non_pers_recommendations)
```
As you can see we create a recommendation dataframe where each row represents an user and the columns are ordered and numbered from best recommended to least recommended.
For each model and every model, we are going to produce recommendations for the validation set and the test set. So let's start with non-presonalized recommendations.
### Non-personalized recommendations for validation data
We just need to evoke function `non_pers_reco_output` with the validation users and the non-personalized recommendations.
```
non_pers_reco_solution_val = non_pers_reco_output(users_val, non_pers_recommendations)
save_recommendations(non_pers_reco_solution_val, "non_personalized_recommendations_VAL")
```
#### Validation evaluation
After creating the output file, we can compare it with the test recommendations. Use function `evaluate_solution` with the solution file name as the first argument and the ground-truth as the second argument.
```
## Second argument is the recommendation file to compare
evaluate_solution('non_personalized_recommendations_VAL', 'validation_recommendations')
```
### Non-personalized recommendations for test data
This section simulates the scoring done by the portal. Again, we just need to evoke function `non_pers_reco_output` but now with the **test** users and the non-personalized recommendations.
```
non_pers_reco_solution_test = non_pers_reco_output(test_users["user_id"].to_list(), non_pers_recommendations)
save_recommendations(non_pers_reco_solution_test, "non_personalized_recommendations_TEST")
```
#### Test evaluation
To simulate submitting the recommendations to the portal, we use function `evaluate_solution` without a second argument.
```
## When second argument is missing, uses test data set.
## Simulates the portal score.
evaluate_solution('non_personalized_recommendations_TEST')
```
---
# Collaborative filtering
Now that we have a baseline model, we can try collaborative filtering.
We are going to use some open-source libraries to replicate what we did on the previous SLUs.
The first library that we are going to use is *[LightFM](https://making.lyst.com/lightfm/docs/home.html)*. LightFM allows to create the rating matrix (aka interaction matrix) and use that matrix to generate recommendations for our users.
We start by using lightFM `Dataset()` function to create the user and item mapping that defines the vectorial space of the rating matrix.
```
# Notice the alias lfmDataset() instead of the standard Dataset()
# Used to distiguish between lightFM Dataset() and another Dataset() that we use later.
lfmdataset = lfmDataset()
lfmdataset.fit(data_train['user_id'], data_train["recipe_id"])
```
We can check that vectorial space is defined as expected:
```
num_users, num_items = lfmdataset.interactions_shape()
print('Num users: {:,}, num_items {:,}.'.format(num_users, num_items))
```
The mapping between external user IDs (the ones in our data) and the internal user IDs can be obtained with method `.mapping()`. The same applies for items.
```
user_id_map, user_feature_map, item_id_map, item_feature_map = lfmdataset.mapping()
```
Reverses map between external and internal IDs. This is used to get the original IDs from the internal IDs.
```
item_id_map_reverse = {v: k for k, v in item_id_map.items()}
```
We now need to create the rating matrix. The equivalent in lightFM is the interactions matrix. We use the `build_interactions` to create the interaction matrix in the COOrdinate format. The argument is an iterable of (user_id, item_id) or (user_id, item_id, weight)), where weight is what we call rating.
```
(interactions, weights) = lfmdataset.build_interactions((row for row in data_train.values))
print(repr(interactions))
```
We now define the model that we are going to use to produce our recommendations. We select the `warp` loss function as it is [recommended](https://making.lyst.com/lightfm/docs/lightfm.html#id2) for optimizing to top of recommendation list (precision@k), which is our case.
```
lfmodel = LightFM(loss='warp')
```
We fit the model with our interaction data.
```
lfmodel.fit(interactions)
```
With the model trained and the dataset in COO format, we can produce recommendations for a given user.
We can use the method `.predict` to calculate the score (rating) of each item for a given user. We then sort the items' IDs in descending order of rating and select the `k_top` best items.
```
k_top = 50
# external user ID to predict
user_ext_id_example = 85826
# internal user ID to predict
user_id_example = user_id_map[user_ext_id_example]
#item internal ids
item_id_int_list = list(item_id_map.values())
# Calculates the score (rating) of each item
scores = lfmodel.predict(user_id_example, item_id_int_list)
# Sort the items from highest to lowest score
top_items_ids = np.argsort(-scores)
top_items_ids = [item_id_map_reverse[ids] for ids in top_items_ids]
# Individual row. Two steps are necessary for the first column to call "user_id"
user_id_df = pd.DataFrame([user_ext_id_example], columns=["user_id"])
top_items_ids = pd.DataFrame([top_items_ids[:k_top]])
user_reco_df = pd.concat([user_id_df,top_items_ids], axis=1)
user_reco_df
```
We recommended recipes for one user. It's time to predict for a set of users. We'll repeat the previous process for each user in the set if that user is present in the training data. If the user is not present in the training data then we have to use non-personalized recommendations.
We start by separating the users present in training data and the users absent in the training data:
```
# some users
user_id_ext_list = [185401, 1580779, 999999999] #last ID is made up
# Split old users (user_id_int_list) from new users (user_id_ext_excluded)
user_id_int_list = []
user_id_ext_excluded = []
for user_id_ext in user_id_ext_list:
try:
# user internal ID with mapping
user_id_int_list.append(user_id_map[user_id_ext])
except:
# user without mapping
user_id_ext_excluded.append(user_id_ext)
print(f"The INTERNAL ID of users with mapping are: {user_id_int_list}")
print(f"The EXTERNAL ID of users without mapping are: {user_id_ext_excluded}")
```
We then list all the item IDs:
```
# list of item external ids
item_id_ext_list = list(item_id_map.values())
```
Then, for each user present in the training data, we predict the rating of all items. We sort them by descending rating and select the `k_top` best items for that users.
```
#Dataframe with model recommendations
model_reco_df = pd.DataFrame()
##Collaborative recommendations
for user_id in user_id_int_list:
scores = lfmodel.predict(user_id, item_id_ext_list)
top_items_ids = np.argsort(-scores)
top_items_ids = [item_id_map_reverse[ids] for ids in top_items_ids]
user_reco_df = pd.DataFrame([[user_id] + top_items_ids[:k_top]])
#Appending rows
model_reco_df = pd.concat([model_reco_df, user_reco_df])
model_reco_df
```
For the remaining users, we use non-personalized recommendations.
```
## Non-personalized recommendations
non_pers_reco_df = non_pers_reco_output(user_id_ext_excluded, non_pers_recommendations)
non_pers_reco_df
```
At last, we concatenate both recommendations together.
```
final_reco_df = pd.concat([model_reco_df, non_pers_reco_df]).reset_index(drop=True)
final_reco_df
```
Now that we have a working example, we can generalize with a function that outputs predictions for lightFM models.
```
def lightFM_recommendations(dataset,
model,
user_id_ext_list,
non_pers_reco_list,
k_top: int = 50,
item_features = None):
"""
Create output dataframe with recommendations based on dataset, model and list of users.
This function predicts recommendations for users specified in user_id_ext_list that are present in the lightFM dataset.
New users are recommended the items in the non-personalized list non_per_reco_list.
Parameters:
-----------
dataset: lightFM dataset
model: lightFM trained model
user_id_ext_list: list of user external IDs to predict
non_pers_reco: list of non-personalized recommendations ordered from best to worst rated
k_top: number of recommendations to create per user
item_features: lightFM item features
Returns:
--------
final_reco_df: dataframe with users' recommendations
The first column has the users' ID and the remaining columns have the recommendations
"""
assert len(user_id_ext_list) > 0, "User ID list length must be larger than 0."
# Dataset mappings
user_id_map, user_feature_map, item_id_map, item_feature_map = dataset.mapping()
# reverse mapping
item_id_map_reverse = {v: k for k, v in item_id_map.items()}
user_id_map_reverse = {v: k for k, v in user_id_map.items()}
# item internal ids
item_id_int_list = list(item_id_map.values())
# Split old users (user_id_int_list) from new users (user_id_ext_excluded)
# Old users are defined in the ratings vectorial space.
# New users are not defined in the ratings vectorial space.
# New users receive non-personalized recommendations.
user_id_int_list = []
user_id_ext_excluded = []
for user_id_ext in user_id_ext_list:
try:
user_id_int_list.append(user_id_map[user_id_ext])
except:
user_id_ext_excluded.append(user_id_ext)
# Dataframe to store model recommendations
model_reco_df = pd.DataFrame()
# Model recommendations
for user_id in user_id_int_list:
scores = model.predict(user_id, item_id_int_list, item_features)
top_items_ids = np.argsort(-scores)
top_items_ids = [item_id_map_reverse[ids] for ids in top_items_ids]
# Individual row. Two steps are necessary for the first row to call "user_id"
user_id_df = pd.DataFrame([user_id_map_reverse[user_id]], columns=["user_id"], dtype = int)
top_items_ids = pd.DataFrame([top_items_ids[:k_top]])
user_reco_df = pd.concat([user_id_df, top_items_ids], axis=1)
# Concatenating rows
model_reco_df = pd.concat([model_reco_df, user_reco_df])
# Stop execution if memory is almost full
memory_circuit_breaker(memory_limit_perc)
# Non-personalized recommendations
non_pers_reco_df = non_pers_reco_output(user_id_ext_excluded, non_pers_reco_list)
# Concatenating all recommendations
if model_reco_df.shape[0] == 0:
final_reco_df = non_pers_reco_df
elif non_pers_reco_df.shape[0] == 0:
final_reco_df = model_reco_df
else:
final_reco_df = pd.concat([model_reco_df, non_pers_reco_df])
return final_reco_df
```
### Let's test with a couple of users
In the example below the user 123213231 is a new user so it should receive the non-personalized recommendations. The remaining users already exist on the training data so the model should output collaborative-based recommendations.
```
lightFM_recommendations(lfmdataset,
lfmodel,
[1232131231, 1498649, 99136, 83961],
non_pers_recommendations,
k_top=k_top)
```
It works great! It creates recommendations for the specified users!
### Collaborative filtering recommendations for validation data
Now that we checked that `lightFM_recommendations` creates recommendations for the provided users, we create the recommendations for the validations users, store them in a `.csv` file and evaluate the results.
```
collab_reco_val = lightFM_recommendations(lfmdataset, lfmodel, users_val, non_pers_recommendations, k_top=k_top)
save_recommendations(collab_reco_val, "collaborative_recommendations_VAL")
```
#### Validation evaluation
```
evaluate_solution('collaborative_recommendations_VAL', 'validation_recommendations')
```
### Collaborative filtering recommendations for test data
The same can be performed for the test data.
```
collab_reco_test = lightFM_recommendations(lfmdataset, lfmodel, users_test, non_pers_recommendations, k_top=k_top)
save_recommendations(collab_reco_test, "collaborative_recommendations_TEST")
```
#### Test evaluation
```
evaluate_solution('collaborative_recommendations_TEST')
```
#### Clean up
To save some RAM, we are removing some objects that won't be needed later. If you want to keep them, comment the next cell.
```
del (interactions,
non_pers_reco_solution_val,
non_pers_reco_solution_test,
model_reco_df,
final_reco_df,
collab_reco_val,
collab_reco_test)
gc.collect()
```
---
# Content-based Recommendations
We are going to create recommendations that take into account the recipes information. We will use a `lightFM` model and introduce the recipe (item) information. We will explore the recipe information, identify potentially useful features and process some of them to use in the model.
#### Exploring recipe data
```
# recipe information
recipes.head()
# numeric summary
recipes.describe()
```
It appears there are some interesting columns that we can use to characterize each recipe. For this example, we are going to use columns `minutes`, `tags` and `n_ingredients`. You are encouraged to try using other features and different processing steps.
Columns `minutes` and `n_ingredients` are going to be rescaled to a normal standard distribution with `StandardScaler()`. Column `tags` is going to be transformed in an one-hot enconding style of transformation. The column is going to be split into several columns, each representing one of the possible tags. When a recipe has a specific tag, the value of the corresponding feature is given value 1. If the recipe does not have that tag, then the respective feature has value 0.
#### Rescaling `minutes` and `n_ingredients`
Before rescaling, notice that there is one recipe that takes 2147483647 minutes or around 4085 years!
```
recipes.loc[recipes["minutes"] == recipes["minutes"].max()]
```
This is clearly a mistake. To simplify, we are going to remove this recipe manually to prevent the outlier to disrupt the rescaling.
```
recipes_rescale = recipes.copy()
recipes_rescale = recipes_rescale[["id","minutes", "n_ingredients"]]
# remove outlier
recipes_rescale = recipes_rescale.loc[recipes["minutes"] < recipes["minutes"].max()]
min_max_scaler = StandardScaler()
recipes_rescale[["minutes", "n_ingredients"]] = min_max_scaler.fit_transform(recipes_rescale[["minutes", "n_ingredients"]])
recipes_rescale.head()
```
#### Encoding `tags`
As explained before, the `tags` is going to be expanded into a series of columns, each representing a specific tag. For every recipe, if it contains a specific tags, the value of the corresponding column will be 1, otherwise it will be 0.
```
recipes_encoding = recipes.copy()
# convert string of list of strings into list of strings
recipes_encoding["tags"] = recipes_encoding["tags"].apply(eval)
# split each value from list into its own column, one-hot enconding style
tags_exploded = recipes_encoding['tags'].explode()
recipes_encoding = recipes_encoding[['id']].join(pd.crosstab(tags_exploded.index, tags_exploded))
recipes_encoding.head()
```
#### Considerations on tags that appear only once.
There are tags that only appear on a single recipe as we can see in the next cell. These tags won't help us connect similar recipes so they are useless for content-based recommendations. Of course, with time, more recipes may have these tags. These tags may now convey useful information about the relationship between recipe and should be considered when retraining the models.
```
# some examples of tags that only appear on one recipe
pd.Series(recipes_encoding.drop(columns=["id"]).sum()).sort_values()[:20]
# filter out tags associated with a single recipe
recipes_encoding = recipes_encoding[recipes_encoding.columns[recipes_encoding.sum()>1]]
```
#### Joining features
```
recipe_features_df = recipes_rescale.merge(recipes_encoding, on="id")
recipe_features_df.head()
```
#### Formating recipe features
In this step, we format the recipe features dataframe in a way that we can iterate and feed the `lightFM` model.
We define `id` as index and rename the columns to increasing integers formatted as strings. We do this because `lightFM` does not deal well with some of the characters used on the tags. Since identifying the features is not important for our model, we'll leave them as strings of integers.
```
recipe_features_df.set_index("id", drop=True, inplace=True)
recipe_features_df.columns = [str(i) for i in range(len(recipe_features_df.columns))]
recipe_features_df.head()
```
To feed our receipe features we are using the method [build_item_features](https://making.lyst.com/lightfm/docs/lightfm.data.html?highlight=build_item_features#lightfm.data.Dataset.build_item_features) with an iterable of form `(item id, {feature name: feature weight})`. We can create such an iterable with the dataframe method `itertuples`.
```
recipe_generator = recipe_features_df.itertuples(index=True, name=None)
```
We replicate the steps performed for the collaborative filtering with some additions:
1. include `item_features=recipe_generator` while fitting the dataset.
2. create a new object (`item_features`) that will store the item features.
3. include the new `item features` while fitting the model.
```
content_dataset = lfmDataset()
content_dataset.fit(data_train['user_id'], data_train["recipe_id"], item_features=recipe_generator)
item_features = content_dataset.build_item_features(recipe_generator)
(interactions, weights) = content_dataset.build_interactions((row for row in data_train.values))
content_model = LightFM(loss='warp')
content_model.fit(interactions, item_features=item_features)
```
### Content-based recommendations for validation data
Once the dataset is prepared and the model is fitted, we can reuse the function `lightFM_recommendations` by adding the argument `item_features = item_features`.
```
content_reco_val = lightFM_recommendations(content_dataset,
content_model,
users_val,
non_pers_recommendations,
k_top=k_top,
item_features = item_features)
save_recommendations(content_reco_val, "content_recommendations_VAL")
```
#### Validation evaluation
```
evaluate_solution('content_recommendations_VAL', 'validation_recommendations')
```
### Content-based recommendations for test data
```
content_reco_test = lightFM_recommendations(content_dataset,
content_model,
users_test,
non_pers_recommendations,
k_top=k_top,
item_features = item_features)
save_recommendations(content_reco_test, "content_recommendations_TEST")
```
#### Test evaluation
```
evaluate_solution('content_recommendations_TEST')
```
#### Clean up
```
del (recipes_rescale,
recipes_encoding,
recipe_features_df,
interactions,
recipe_generator,
content_dataset,
content_model,
content_reco_val,
content_reco_test)
gc.collect()
```
---
# Collaborative recommendations with Surprise
[Surprise](http://surpriselib.com/) is a [SciKit](https://www.scipy.org/scikits.html), i.e. an add-on package for SciPy, that can be use to build recommender systems for explicit rating data. It doesn't support content-based information though.
We start by preparing the data and the loader. These will be use by method `load_from_df` to load the data into a dataset object. The dataframe to be loaded **must specifically** have the columns `userID`, `itemID` and `rating`. Because of this, we need to rename our columns.
```
data_train_surprise = data_train.copy().rename(columns={"user_id":"userID", "recipe_id":"itemID"})
# a reader is required in load_from_df
reader = Reader(rating_scale=(1, 5))
# The columns must correspond to user id, item id and ratings (in that order).
data_surprise = sDataset.load_from_df(data_train_surprise[['userID', 'itemID', 'rating']], reader)
data_surprise
```
Since we already split the data intro training and validation, we can use all training data as the train set. You can use all data for training with method `build_full_trainset()`. If wanted to split you data with `Surprise`, you could use function [`train_test_split`](https://surprise.readthedocs.io/en/stable/getting_started.html#train-test-split-and-the-fit-method) or with some [cross-validations strategies](https://surprise.readthedocs.io/en/stable/model_selection.html#cross-validation-iterators-api).
```
# Retrieve the trainset.
trainset = data_surprise.build_full_trainset()
```
#### Model
One of the available `Surprise` models is the [`KNNBasic`](https://surprise.readthedocs.io/en/stable/knn_inspired.html) model. This a basic collaborative filtering algorithm. We could say it's an improved version of the algorithm that we developed on BLU10. One issue with this model is that the similarity matrixes generated while training the model are not sparse, but dense. This means that, even for moderately large datasets, the model will use gigabytes of memory which isn't feasible for most consumer PCs.
As an alternative, will use the [`SVD`](https://surprise.readthedocs.io/en/stable/matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.SVD) which is based on matrix factorization to approximate the rating matrix using lower ranking matrixes. [Here's](https://cs.carleton.edu/cs_comps/0607/recommend/recommender/svd.html) a brief summary of usage of SVD. `Surprise's SVD` use stochastic gradient descent to minimize the error between the estimated rating matrix and the actual rating matrix during training.
```
svdmodel = SVD(random_state=123)
svdmodel.fit(trainset)
```
#### Generate all user/item combinations
To make recommendations using the Surprise module, we need to provide the `.predict` method of the model with the user ID / item ID pair of which we want the rating. After having the rating all of items for a given user, we can order the best rated items and select the best to recommend.
The steps followed in the next cell are:
1. Select the users that we want to recommend to.
2. Create 3 lists: one to place user IDs, one to place item IDs and another to place the respective rating. The lists are created empty with size `nr. users * nr. items` to allocate all user/item combinations.
3. For each user/item combination, predict rating.
4. Store user id, item id and rating on increasing indexes on the list.
```
# select a few users
users_surprise = [1232131231, 1498649, 99136, 83961]
recipe_ids = recipes["id"].unique()
# calculate the list size beforehand
test_total_len = len(users_surprise) * len(recipe_ids)
# to avoid appending lists
user_id_pred = [None] * test_total_len
recipe_id_pred = [None] * test_total_len
rating_pred = [None] * test_total_len
index_counter = 0
for user in users_surprise:
for recipe in recipe_ids:
prediction = svdmodel.predict(user, recipe)
user_id_pred[index_counter] = prediction.uid
recipe_id_pred[index_counter] = prediction.iid
rating_pred[index_counter] = prediction.est
index_counter += 1
```
From the lists above we can build a predictive rating dataframe to then select best 50 items per user.
```
collab_pred_dict = {'recipe_id': recipe_id_pred,
'user_id': user_id_pred,
'rating': rating_pred}
collab_pred_df = pd.DataFrame(collab_pred_dict)
collab_pred_df.head()
```
#### Selecting top recommendations
We now use the function that we defined earlier to select the best k recommendations for each user.
```
val_collab_recommendations = top_items_per_user(collab_pred_df, "user_id", "rating")
val_collab_recommendations
```
We now bave recommendations using the `Surprise` package!
We can generalize this whole process with a function.
```
def surprise_recommendations(data,
model,
user_id_ext_list,
item_id_ext_list,
k_top: int = 50,
columns_dict: dict = {"user_id":"userID", "recipe_id":"itemID"}):
"""
Create output dataframe with recommendations based on dataset, Surprise model, list of users and list of items.
This function produces recommendations for users specified in user_id_ext_list
Parameters:
-----------
data: dataframe with ratings for each user-item pair
model: untrained Surprise model
user_id_ext_list: list of user external IDs to predict
user_id_ext_list: list of item external IDs to predict
k_top: number of recommendations to create per user
columns_dict: dictionary that converts old column names into Surprise compatible names.
Returns:
--------
final_reco_df: dataframe with users' recommendations
The first column has the users' ID and the remaining columns have the recommendations
"""
data_surprise = data.copy().rename(columns= columns_dict)
# A reader is still needed but only the rating_scale param is required
reader = Reader(rating_scale=(data_surprise['rating'].min(), data_surprise['rating'].max()))
# The columns must correspond to user id, item id and ratings (in that order).
dataset_surprise = sDataset.load_from_df(data_surprise[['userID', 'itemID', 'rating']], reader)
# Retrieve the trainset
trainset = dataset_surprise.build_full_trainset()
# fit the model
model.fit(trainset)
# calculate the list size beforehand
total_len_pred = len(user_id_ext_list) * len(item_id_ext_list)
# to avoid appending lists
user_id_pred = [None] * total_len_pred
recipe_id_pred = [None] * total_len_pred
rating_pred = [None] * total_len_pred
index_counter = 0
for user in user_id_ext_list:
for recipe in item_id_ext_list:
prediction = model.predict(user, recipe)
user_id_pred[index_counter] = prediction.uid
recipe_id_pred[index_counter] = prediction.iid
rating_pred[index_counter] = prediction.est
index_counter += 1
# Stop execution if memory is almost full
memory_circuit_breaker(memory_limit_perc)
model_pred_dict = {'recipe_id': recipe_id_pred,
'user_id': user_id_pred,
'rating': rating_pred}
model_pred_df = pd.DataFrame(model_pred_dict)
model_recommendations = top_items_per_user(model_pred_df, "user_id", "rating")
return model_recommendations
```
Let's try with some users.
```
users_surprise = [1232131231, 1498649, 99136, 83961]
surprise_recommendations(data_train,
SVD(random_state=123),
users_surprise,
recipes["id"].unique(),
k_top)
```
Excellent! We now can recommend recipes for our validation and test users using `surprise_recommendations`, store our results with `save_recommendations` and evaluate our results.
### Collaborative filtering recommendations for validation data (with Surprise)
Unfortunately, the process that we used for a couple of users is not by any means efficient. It takes a lot of time to compute for the validation and test users. If you can parallelize the executions maybe you can run it in useful time. As it stands, it's not recommended to use `Surprise` for anything other than small datasets and a low number of users.
The codes to make the recommendations are below, but are commented.
```
#collab_reco_surprise_val = surprise_recommendations(data_train,
# SVD(random_state=123),
# users_val,
# recipes["id"].unique(),
# k_top)
#save_recommendations(collab_reco_surprise_val, "collaborative_recommendations_surprise_VAL")
```
#### Validation evaluation
```
#evaluate_solution('collaborative_recommendations_surprise_VAL', 'validation_recommendations')
```
### Collaborative filtering recommendations for test data (with Surprise)
```
#collab_reco_surprise_test = surprise_recommendations(data_train,
# SVD(random_state=123),
# users_test,
# recipes["id"].unique(),
# k_top)
#save_recommendations(collab_reco_surprise_test, "collaborative_recommendations_surprise_TEST")
```
#### Test evaluation
```
#evaluate_solution('collaborative_recommendations_surprise_TEST')
```
### On new users
New users are given the mean rating for all training data ratings. This will probably be worse than non-personalized recommendations.
As an exercise, modify the previous function (or create a new one) to replace the recommendations for users that we don't have any information.
---
# Model Selection
It's the end of the day and we have to deliver a model. To simplify, we are going to select the model with best score on the validation data. Remember that the test data is hidden. We just use it to simulate the portal.
The `map@50` values of other models are:
Non-personalized recommendations:
- Validation: 0.0
- Test: 4.651674179825267e-06
Collaborative recommendations:
- Validation: 9.318796011555306e-05
- Test: 3.583748452090996e-06
Content-based:
- Validation: 6.98909700866648e-05
- Test: 3.2054271072713093e-06
Based on the validation results, we would select the collaborative-filtering model since it has the largest validation`map@50`.
Later, it's a good idea to automatize the model selection process to compare many more models and parameters.
---
# Next steps
We have successfully trained a couple of recommendation models to recommend recipes to our users!
Your boss is happy... for now. There is still a lot to be done. Just like with other machine learning applications, recommendations models are not a "build once and it's done" kind of deal. We won't go in much detail here because most of these considerations were already discussed on previous learning units.
Here are a couple of suggestions that you **should** try to implement (on another notebook):
- Cross-validation: Here we have used out-of-sample validation and selected the best model. Try to implement cross-validation using the module's own methods or create your own pipelines.
- Hyperparameter tuning: We haven't performed any hyperparameter tuning on this workflow. Use hyperparameter tuning to explore more models and find better ones.
- Modify code: It feels like some of the examples in this workflow are not to your liking? Then modify them and make them your own. Make changes to simplify your work.
- Other modules: Try to use other recommender systems modules to see if they are simpler to use, give better results or present other advantages. You can check [this GitHub repo](https://github.com/microsoft/recommenders) with a vast selection of recommender system modules with examples. Remember that you should know, to a certain degree, how the model you are using works and what are its limitations.
- More data: You can try, with this or another dataset, to gradually introduce data to the model to simulate new data streaming in. Make use of methods that allow to directly fit new data (usually called someting like [fit_partial](https://making.lyst.com/lightfm/docs/lightfm.html#lightfm.LightFM.fit_partial), for example) or batch train your model each time.
- Different data: Practice your modelling skills with other data sets. See what changes you need to carry out when the data has different properties.
| github_jupyter |
```
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import ast
import os
from fastparquet import ParquetFile
import time
from time import sleep
import librosa
from vagalume import lyrics
import difflib as di
```
## Evaluation of the organization data
The analysis is done for evaluate the distribution of songs by fold and by time range.
the entire dataset and for the subset of songs evaluated manually.
```
data_GI_FO_AF_AA_L=pd.read_csv('lyrics_preprocessing_spotify_data.csv')
```
### Tempo bins distribution
```
plt.figure()
sns.set()
data_1000 =data_GI_FO_AF_AA_L.copy()
data_1000 = data_GI_FO_AF_AA_L.dropna(subset=['manual_filt'])
ax = sns.histplot(data_GI_FO_AF_AA_L.tempo_bins,
bins = 14,color = "darkorange")
ax = sns.histplot(data_1000.tempo_bins,
bins = 14,color = "purple")
plt.axhline(y=100, color='k', linestyle=':',linewidth=3)
ax.figure.set_size_inches(16, 6)
ax.set_ylabel('Frequência', fontsize=14)
ax.set_xlabel('BPM', fontsize=14)
```
### Folds distribution
```
plt.figure()
sns.set()
data_1000 =data_GI_FO_AF_AA_L.copy()
data_1000 = data_GI_FO_AF_AA_L.dropna(subset=['manual_filt'])
ax = sns.histplot(data_GI_FO_AF_AA_L.folds,
bins = 20,color = "darkorange")
ax = sns.histplot(data_1000.folds,
bins = 20,color = "purple")
plt.axhline(y=50, color='k', linestyle=':',linewidth=3)
ax.figure.set_size_inches(16, 6)
ax.set_ylabel('Frequência', fontsize=14)
ax.set_xlabel('BPM', fontsize=14)
```
### Tempo bins and folds distribution
```
plt.figure()
ax = sns.histplot(data_GI_FO_AF_AA_L, x="tempo_bins", hue='folds',multiple="dodge",palette= "Oranges")
ax = sns.histplot(data_1000, x="tempo_bins", hue='folds',multiple="dodge",palette= "Purples")
ax.figure.set_size_inches(16, 6)
plt.axhline(y=5, color='b', linestyle=':',linewidth=3)
ax.set_ylabel('Count', fontsize=14)
ax.set_xlabel('Tempo bins', fontsize=14)
```
## Evaluation of analysis data
Problem found! Analysis data should be in list format, not string.
```
data_GI_FO_AF_AA_L.columns
data_GI_FO_AF_AA_L.bars[0]
data_GI_FO_AF_AA_L['bars'] = data_GI_FO_AF_AA_L['bars'].apply(ast.literal_eval)
data_GI_FO_AF_AA_L['beats'] = data_GI_FO_AF_AA_L['beats'].apply(ast.literal_eval)
data_GI_FO_AF_AA_L['tatums'] = data_GI_FO_AF_AA_L['tatums'].apply(ast.literal_eval)
data_GI_FO_AF_AA_L.bars[0]
```
### Problem solved
But this problem occurs with the .csv format. So we will save the file in .parq too.
```
data_GI_FO_AF_AA_L.to_parquet('forroset_update1.parq',index = False)
```
### Simplifying access to analysis data.
```
def apeend_data(data,dado):
starts= []
duration = []
confidence = []
for j in range(len(dado)):
starts.append(dado[j]['start'])
duration.append(dado[j]['duration'])
confidence.append(dado[j]['confidence'])
data.append(starts)
data.append(duration)
data.append(confidence)
return data
music_ana = []
for i in range(len(data_GI_FO_AF_AA_L['beats'])):
data = []
beats = data_GI_FO_AF_AA_L['beats'][i]
bars = data_GI_FO_AF_AA_L['bars'][i]
tatums =data_GI_FO_AF_AA_L['tatums'][i]
data.append(data_GI_FO_AF_AA_L['track_id'][i])
data = apeend_data(data,beats)
data = apeend_data(data,bars)
data = apeend_data(data,tatums)
music_ana.append(data)
columns= ['track_id','beats_start','beats_duration','beats_confidence','bars_start','bars_duration','bars_confidence','tatums_start','tatums_duration','tatums_confidence']
data_analises = pd.DataFrame(music_ana,columns =columns)
data_GI_FO_AF_AA_L=data_GI_FO_AF_AA_L.drop(columns=["beats","bars","tatums"])
data_GI_FO_AF_AA_L = data_GI_FO_AF_AA_L.merge(data_analises , how='left',on= "track_id")
data_GI_FO_AF_AA_L.to_parquet('forroset_update1.parq',index = False)
data_GI_FO_AF_AA_L.to_csv('forroset_update1.csv',index = False)
```
### Inserting librosa beats anotation data
#### Downloading the audio files
```
from mp3 import getMusics
tempo_inicial = time.time()
getMusics('forroset_update1.csv', 'files')
tempo_final = time.time()
duracao = tempo_final - tempo_inicial
print(duracao/3600)
forroset = ParquetFile('forroset_update1.parq')
forroset = forroset.to_pandas()
musics = os.listdir("files")
```
#### Librosa beats data
```
## Performing beats detection
beat_frames_obt = []
for music in musics:
filename = ("/files/{}").format(music)
y, sr = librosa.load(filename)
onset_env = librosa.onset.onset_strength(y, sr=sr,aggregate=np.median)
tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr, onset_envelope= onset_env, start_bpm = forroset.loc[forroset['track_id'] == music.split(".")[0]].tempo.tolist()[0])
beat_frames_obt.append([beat_frames, music.split(".")[0]])
## Turning beat frames obtained into time
for i in range(len(beat_frames_obt)):
beat_frames_obt[i][0] = librosa.frames_to_time(beat_frames_obt[i][0], sr=sr)
## Adjusting the decimal digits of the beats obtained by Librosa
for i in range(len(beat_frames_obt)):
for j in range(len(beat_frames_obt[i][0])):
beat_frames_obt[i][0][j] = round(beat_frames_obt[i][0][j], 5)
## Creating a DataFrame containing the list of detected beats and the respective identifier for each song
updates = pd.DataFrame(data = beat_frames_obt, columns = ["librosa_beats_start", "track_id"])
## Adding Updates to the forroset
updated_forroset = forroset.merge(updates, how='left',on='track_id')
## Calculating the discrepancy measure of the beats obtained by Librosa
discrepancies = []
averages_spotify = []
## Listing the average distances of the beats obtained by the spotify API
for beats_list in updated_forroset['beats_start']:
mean = sum(beatsDistances(beats_list))/len(beatsDistances(beats_list))
averages_spotify.append(mean)
## Listing the average distances of the beats obtained by Librosa
averages_librosa = []
for beats_list in updated_forroset["librosa_beats_start"]:
beats_dist = beatsDistances(beats_list)
if len(beats_dist) != 0:
mean = sum(beats_dist)/len(beats_dist)
averages_librosa.append(mean)
else:
averages_librosa.append(None)
## Calculating discrepancy measure
for i in range(len(averages_spotify)):
if averages_librosa[i] == None:
discrepancies.append(None)
else:
discrepancy = abs((averages_librosa[i] - averages_spotify[i]))/averages_spotify[i]
## Adjusting the decimal digits of the discrepancy indices
discrepancies.append(round(discrepancy,5))
## Adding a column of discrepancy indices
updated_forroset['librosa_discrepancy'] = discrepancies
beats_list = []
for i in range(0,len(updated_forroset)):
if updated_forroset['librosa_discrepancy'][i] == None:
beats_list.append(None)
else:
beats_list.append(forroset_up['librosa_beats_start'][i])
updated_forroset['librosa_beats_start'] = beats_list
updated_forroset.to_parquet('forroset_update1.parq',index = False)
updated_forroset.to_csv('forroset_update1.csv',index = False)
```
## Evaluation of lyrics data
Problem found! Lyrics data should be in list format, not string.
```
data_GI_FO_AF_AA_L = ParquetFile('forroset_update1.parq')
data_GI_FO_AF_AA_L = data_GI_FO_AF_AA_L.to_pandas()
data_GI_FO_AF_AA_L.lyrics[1]
lyrics = data_GI_FO_AF_AA_L[["track_id",'lyrics']].dropna()
lyrics['lyrics'] = lyrics['lyrics'].apply(ast.literal_eval)
data_GI_FO_AF_AA_L= data_GI_FO_AF_AA_L.drop(['lyrics','lyrics_confidence'], axis=1)
forroset = data_GI_FO_AF_AA_L.merge(lyrics, how='left',on= "track_id")
```
### Problem solved
Same problem that occurred with the analysis data.
```
print(forroset.lyrics[1][0])
print()
print(forroset.lyrics[1][1])
print()
print(forroset.lyrics[1][2])
```
### FAIR's compilance problems
According to Vagalume API requirements it is necessary to insert the link of the lyrics.
```
lyrics_data = forroset[['lyrics']].values
letra = []
list_error = []
similarity = []
url = []
k=0
j=0
for i in range(0,len(lyrics_data)):
time.sleep(2)
if i%50 ==0:
print("Waiting a little bit.")
print("Lyrics searched: ", i)
print("Downloaded lyrics: ", k)
time.sleep(5)
if lyrics_data[i][0] != None:
artist_name = lyrics_data[i][0][1]
song_name = lyrics_data[i][0][0]
try:
result = lyrics.find(artist_name, song_name)
if result.is_not_found():
letra.append(None)
similarity.append(None)
else:
s_artist = di.SequenceMatcher(None, artist_name.upper(), result.artist.name.upper()).ratio()
s_name = di.SequenceMatcher(None, song_name.upper(), result.song.name.upper()).ratio()
similarity.append({'name_similarity':s_name, 'artist_similarity':s_artist})
if s_name<1 or s_artist<1:
print(s_name, s_artist,song_name.upper(), result.song.name.upper())
letra.append([result.song.name, result.artist.name,result.song.lyric,result.song.url])
url.append(result.song.url)
k+=1
except:
letra.append(None)
similarity.append(None)
url.append(None)
time.sleep(5)
else:
letra.append(None)
similarity.append(None)
url.append(None)
forroset['lyrics']=letra
```
## Final forroset version
```
forroset =forroset[['track_id', 'track', 'artist', 'artist_id', 'popularity', 'album',
'album_id', 'track_year', 'duration_ms', 'uri', 'preview_url',
'energy','liveness', 'tempo', 'speechiness', 'acousticness', 'instrumentalness',
'time_signature', 'danceability', 'key', 'loudness', 'valence', 'mode',
'beats_start', 'beats_duration', 'beats_confidence', 'bars_start',
'bars_duration', 'bars_confidence', 'tatums_start', 'tatums_duration',
'tatums_confidence','librosa_beats_start','librosa_discrepancy',
'tempo_bins', 'tempo_bins_max', 'genre_filt', 'folds','manual_filt',
'lyrics' ]]
forroset.to_parquet('forroset.parq',index = False)
forroset.to_csv('forroset.csv',index = False)
```
| github_jupyter |
# Numpy
##### what's ?
NumPy (Numerical Python) is an open source Python library that’s used in almost every field of science and engineering. It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems.
##### who can use?
NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development
##### Application
The NumPy API is used extensively in Pandas, SciPy, Matplotlib, scikit-learn, scikit-image and most other data science and scientific Python packages.
NumPy can be used to perform a wide variety of mathematical operations on arrays.
#### Why use NumPy?
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.
##### Numpy container
- The NumPy library contains multidimensional array and matrix data structures.
- It provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently operate on it.
- It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.
## What is Numpy array?
1. An array is a central data structure of the NumPy library.
2. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element.
3. It has a grid of elements that can be indexed in various ways. The elements are all of the same type, referred to as the array dtype.
4. An array can be indexed by a tuple of nonnegative integers, by booleans, by another array, or by integers.
5. One way we can initialize NumPy arrays is from Python lists, using nested lists for two- or higher-dimensional data.
- The array object represents a multidimensional, homogeneous array of fixed-size items.
- An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)
Arrays should be constructed using `np.array()`,
To create a NumPy array, you can use the function `np.array()`.
- For example
```
import numpy as np
import math as calc
a = np.array([1, 2, 3, 4, 5, 6])# array with a single list
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])#numpy array with two list
print(a,b)
```
#### What’s the difference between a Python list and a NumPy array?
NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.
#### Parameters of NumpyArray
ndarray(shape, dtype=float, buffer=None, offset=0,
strides=None, order=None)
1. shape : tuple of ints
Shape of created array.
2. dtype : data-type, optional
Any object that can be interpreted as a numpy data type.
3. buffer : object exposing buffer interface, optional
Used to fill the array with data.
4. offset : int, optional
Offset of array data in buffer.
5. strides : tuple of ints, optional
Strides of data in memory.
6. order : {'C', 'F'}, optional
Row-major (C-style) or column-major (Fortran-style) order.
For example
```
a = np.array([1, 2, 3, 4, 5, 6], dtype = int)# array with a single list and a type = int
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])#numpy array with two list
a
```
### Properties
- `ndarray.ndim` will tell you the number of axes, or dimensions, of the array.
- `ndarray.size` will tell you the total number of elements of the array. This is the product of the elements of the array’s shape.
- `ndarray.shape` will display a tuple of integers that indicate the number of elements stored along each dimension of the array. If, for example, you have a 2-D array with 2 rows and 3 columns, the shape of your array is (2, 3).
For example:
```
b = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
dimen = b.ndim
print(dimen)
size = b.size
print(size)
shape = b.shape
print(shape)
```
### Reshaping
- Using arr.reshape() will give a new shape to an array without changing the data. Just remember that when you use the reshape method, the array you want to produce needs to have the same number of elements as the original array. If you start with an array with 12 elements, you’ll need to make sure that your new array also has a total of 12 elements.
For exmaple: We can reshape b from (3,4) to (4,3)
```
a = b.reshape(4,3)
print(a)
```
### Reshaping with optional parameters
numpy.reshape(a, newshape=(1, 6), order='C')
- a is the array to be reshaped.
- newshape is the new shape you want. You can specify an integer or a tuple of integers. If you specify an integer, the result will be an array of that length. The shape should be compatible with the original shape.
- order: C means to read/write the elements using C-like index order, F means to read/write the elements using Fortran-like index order, A means to read/write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. (This is an optional parameter and doesn’t need to be specified.)
```
import numpy as np
newArr = np.reshape(a, newshape=(6,2), order = 'C')
print(newArr)
```
## Other Different ways of creating numpy array list
`np.zeros()`, `np.ones()`, `np.empty()`, `np.arange()`, `np.linspace()`
### np.zeros()
Besides creating an array from a sequence of elements, you can easily create an array filled with 0’s
```
b = np.zeros(2)
b
```
### np.ones()
an array filled with 1’s:
```
c = np.ones(2)
c
```
### np.empty()
Or even an empty array! The function empty creates an array whose initial content is random and depends on the state of the memory. The reason to use empty over zeros (or something similar) is speed - just make sure to fill every element afterwards!
```
# Create an empty array with 2 elements
d = np.empty(2)
d
```
### np.arange()
You can create an array with a range of elements: The code below creates a 1D array from 0-3
```
e = np.arange(4)
e
```
And even an array that contains a range of evenly spaced intervals.
To do this, you will specify the `first number`, `last number`, and the `step size`.
```
a = np.arange(2, 9, 2)
a
```
### np.linspace()
You can also use np.linspace() to create an array with values that are spaced linearly in a specified interval:
```
lin = np.linspace(0, 10, num=3)
lin
```
## Adding, removing, and sorting elements
This section covers np.sort(), np.concatenate()
### Sorting
Sorting an element is simple with np.sort(). You can specify the axis, kind, and order when you call the function.
If you start with this array:
```
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
```
You can quickly sort the numbers in ascending order with:
```
ascending = np.sort(arr)
ascending
```
In addition to sort, which returns a sorted copy of an array, you can use:
- argsort, which is an indirect sort along a specified axis,
- lexsort, which is an indirect stable sort on multiple keys,
- searchsorted, which will find elements in a sorted array, and
- partition, which is a partial sort.
To learn more, see [https://numpy.org/doc/stable/reference/generated/numpy.sort.html#numpy.sort]
### Concatenation
You can concatenate them with np.concatenate((arrs), axis='x or y').
- The arrs are the arrays to be concatenated
- axis are the dimenstion for concatenated arrs:
x = 0, for 1D array, y = 1 nD array
Note: if you choose your axis = 1,then your array rows of a = array colum of b
all the input array dimensions for the concatenation axis must match exactly
For example:
```
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
ab = np.concatenate((a,b), axis = 0)
ab
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6]])
res = np.concatenate((x,y), axis = 0)# adding y to x, so, y will be next array list of x
res
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6], [7,8]])
res = np.concatenate((x,y), axis = 0)# adding y to x, so, y will be next array list of x on 2 rows
res
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6], [7,8]])
res = np.concatenate((x,y), axis = 1)# adding y to x, so, y will be next column array list of x
res
```
### How to convert a 1D array into a 2D array (how to add a new axis to an array)
You can use `np.newaxis` and `np.expand_dims` to increase the dimensions of your existing array.
Using `np.newaxis` will increase the dimensions of your array by one dimension when used once.
This means that a 1D array will become a 2D array, a 2D array will become a 3D array, and so on.
For example:
```
a = np.array([1, 2, 3, 4, 5, 6])
print(a.shape)
```
You can use `np.newaxis` to add a new axis: either row or colum
```
#adding it to a row
a2 = a[np.newaxis,:]
print(a2.shape)
a2
#adding it to column
a2 = a[:, np.newaxis]
print(a2.shape)
a2
```
You can also expand an array by inserting a new axis at a specified position with np.expand_dims.
For example, if you start with this array:
```
a = np.array([1, 2, 3, 4, 5, 6])
#You can use np.expand_dims to add an axis at index position 1 with:
b = np.expand_dims(a, axis=1)
print(b.shape)
# You can use np.expand_dims to add an axis at index position 0 with:
c = np.expand_dims(a, axis=0)
print(c.shape)
```
| github_jupyter |
```
import numpy as np
import tensorflow as tf
from sklearn.utils import shuffle
import re
import time
import collections
import os
def build_dataset(words, n_words, atleast=1):
count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]
counter = collections.Counter(words).most_common(n_words)
counter = [i for i in counter if i[1] >= atleast]
count.extend(counter)
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
index = dictionary.get(word, 0)
if index == 0:
unk_count += 1
data.append(index)
count[0][1] = unk_count
reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reversed_dictionary
with open('english-train', 'r') as fopen:
text_from = fopen.read().lower().split('\n')[:-1]
with open('vietnam-train', 'r') as fopen:
text_to = fopen.read().lower().split('\n')[:-1]
print('len from: %d, len to: %d'%(len(text_from), len(text_to)))
concat_from = ' '.join(text_from).split()
vocabulary_size_from = len(list(set(concat_from)))
data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)
print('vocab from size: %d'%(vocabulary_size_from))
print('Most common words', count_from[4:10])
print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])
concat_to = ' '.join(text_to).split()
vocabulary_size_to = len(list(set(concat_to)))
data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)
print('vocab to size: %d'%(vocabulary_size_to))
print('Most common words', count_to[4:10])
print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])
GO = dictionary_from['GO']
PAD = dictionary_from['PAD']
EOS = dictionary_from['EOS']
UNK = dictionary_from['UNK']
for i in range(len(text_to)):
text_to[i] += ' EOS'
class Chatbot:
def __init__(self, size_layer, num_layers, embedded_size,
from_dict_size, to_dict_size, learning_rate, batch_size):
def cells(size,reuse=False):
return tf.nn.rnn_cell.GRUCell(size,reuse=reuse)
self.X = tf.placeholder(tf.int32, [None, None])
self.Y = tf.placeholder(tf.int32, [None, None])
self.X_seq_len = tf.placeholder(tf.int32, [None])
self.Y_seq_len = tf.placeholder(tf.int32, [None])
batch_size = tf.shape(self.X)[0]
encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))
decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))
encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)
main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])
decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)
decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)
for n in range(num_layers):
(out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(
cell_fw = cells(size_layer // 2),
cell_bw = cells(size_layer // 2),
inputs = encoder_embedded,
sequence_length = self.X_seq_len,
dtype = tf.float32,
scope = 'bidirectional_rnn_%d'%(n))
encoder_embedded = tf.concat((out_fw, out_bw), 2)
bi_state = tf.concat((state_fw,state_bw), -1)
last_state = tuple([bi_state] * num_layers)
with tf.variable_scope("decoder"):
rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])
outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded,
initial_state = last_state,
dtype = tf.float32)
self.logits = tf.layers.dense(outputs,to_dict_size)
masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)
self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,
targets = self.Y,
weights = masks)
self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)
y_t = tf.argmax(self.logits,axis=2)
y_t = tf.cast(y_t, tf.int32)
self.prediction = tf.boolean_mask(y_t, masks)
mask_label = tf.boolean_mask(self.Y, masks)
correct_pred = tf.equal(self.prediction, mask_label)
correct_index = tf.cast(correct_pred, tf.float32)
self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
size_layer = 256
num_layers = 2
embedded_size = 128
learning_rate = 0.001
batch_size = 16
epoch = 20
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from),
len(dictionary_to), learning_rate,batch_size)
sess.run(tf.global_variables_initializer())
def str_idx(corpus, dic):
X = []
for i in corpus:
ints = []
for k in i.split():
ints.append(dic.get(k,UNK))
X.append(ints)
return X
X = str_idx(text_from, dictionary_from)
Y = str_idx(text_to, dictionary_to)
maxlen_question = max([len(x) for x in X]) * 2
maxlen_answer = max([len(y) for y in Y]) * 2
maxlen_question, maxlen_answer
def pad_sentence_batch(sentence_batch, pad_int, maxlen):
padded_seqs = []
seq_lens = []
max_sentence_len = maxlen
for sentence in sentence_batch:
padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))
seq_lens.append(maxlen)
return padded_seqs, seq_lens
for i in range(epoch):
total_loss, total_accuracy = 0, 0
X, Y = shuffle(X, Y)
for k in range(0, len(text_to), batch_size):
index = min(k + batch_size, len(text_to))
batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)
batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)
predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),
model.accuracy, model.cost, model.optimizer],
feed_dict={model.X:batch_x,
model.Y:batch_y,
model.X_seq_len:seq_x,
model.Y_seq_len:seq_y})
total_loss += loss
total_accuracy += accuracy
total_loss /= (len(text_to) / batch_size)
total_accuracy /= (len(text_to) / batch_size)
print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))
for i in range(len(batch_x)):
print('row %d'%(i+1))
print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))
print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))
print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\n')
```
| github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#EDA" data-toc-modified-id="EDA-1"><span class="toc-item-num">1 </span>EDA</a></span><ul class="toc-item"><li><span><a href="#Is-any-question/class-a-nan-?" data-toc-modified-id="Is-any-question/class-a-nan-?-1.1"><span class="toc-item-num">1.1 </span>Is any question/class a nan ?</a></span></li><li><span><a href="#What-is-the-distribution-of-classes-?" data-toc-modified-id="What-is-the-distribution-of-classes-?-1.2"><span class="toc-item-num">1.2 </span>What is the distribution of classes ?</a></span></li></ul></li><li><span><a href="#Data-Cleaning" data-toc-modified-id="Data-Cleaning-2"><span class="toc-item-num">2 </span>Data Cleaning</a></span></li></ul></div>
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import sys
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
# Used to import libraries from an absolute path starting with the project's root
module_path = os.path.abspath(os.path.join('../'))
if module_path not in sys.path:
sys.path.append(module_path)
```
# EDA
```
dataset = pd.read_csv("../data/dataset.csv")
dataset.head()
dataset.shape
dataset.dtypes
```
## Is any question/class a nan ?
```
dataset[dataset["question1"].isnull()]
dataset[dataset["question2"].isnull()]
dataset[dataset["is_duplicate"].isnull()]
```
## What is the distribution of classes ?
```
dataset["is_duplicate"].hist()
```
We notice a slight imbalance of the dataset with around 150k positive similar sequences and 250k dissimilar sequences.
# Data Cleaning
We remove the found nan values.
```
new_dataset = dataset[dataset["question1"].isnull() == False]
new_dataset = new_dataset[new_dataset["question2"].isnull() == False]
new_dataset.to_csv("../data/cleaned_dataset.csv")
```
We remove the questions triggering errors in our Word2Vec modelby first fitting our model to our dataset then iterating over our dataset to transform it, removing buggy values at ther same time.
```
new_dataset = pd.read_csv("../data/cleaned_dataset.csv")
questions = np.concatenate(
(new_dataset["question1"].to_numpy(), new_dataset["question2"].to_numpy())
)
from src.preprocessing.word2Vec import Word2VecModel
word2Vec = Word2VecModel(vector_size = 40, detect_bigrams = False, debug=False)
word2Vec.fit(questions)
from tqdm import tqdm
tqdm.pandas()
def transform_dataset(row):
question1 = row["question1"]
question2 = row["question2"]
question1 = word2Vec.transform(question1)
question2 = word2Vec.transform(question2)
#if the returned vector of word embedding is empty, the sentence is good to be thrown
if (len(question1) == 0 or len(question2) == 0):
print(True)
failed_row = True
else:
failed_row = False
return pd.Series([question1, question2, failed_row])
new_dataset[["question1", "question2", "failed_row"]] = new_dataset.progress_apply(
transform_dataset, axis=1
)
new_dataset.head()
new_dataset[new_dataset["failed_row"] == False].to_pickle("D:/thoma/vectorized_dataset.pkl")
```
| github_jupyter |
This demo contains the following:
* Setting up Python environment - importing libraries and first look at the raw dataset
* Import dataset to ArangoDB
* Preprocessing raw data
* Using ArangoQL
* Connecting with Python using PyArango
* Data exploration with the features of ArangoDB.
* Graph visualization
* ArangoSearch example
* K-shortest path example
* Pruned search
* Machine Learning tasks
* Movie similarity based on plots using Tensorflow.
* Genre classification based on plots using -
* scikit-learn
* Tensorflow
# Import libraries
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
```
We are working with Movie data scraped from Wikipedia: [link](https://www.kaggle.com/jrobischon/wikipedia-movie-plots)
The dataset contains descriptions of 34,886 movies from around the world. Column descriptions are listed below:
1. Release Year - Year in which the movie was released
2. Title - Movie title
3. Origin/Ethnicity - Origin of movie (i.e. American, Bollywood, Tamil, etc.)
4. Director - Director(s) (comma separated, null values)
5. Cast - Main actor and actresses (comma separated, null values)
6. Genre - Movie Genre(s) (unknown values)
7. Wiki Page - URL of the Wikipedia page from which the plot description was scraped
8. Plot - Long form description of movie plot
Read csv file:
```
df = pd.read_csv("wiki_movie_plots_deduped.csv")
df.sample(10)
```
We can see that columns like `Cast` (also `Director` and `Genre`) contain multiple values that might be separated by a comma, space or slash etc. It will require some preprocessing.
First we will learn how to import the data into ArangoDB, preprocess it and build a knowledge graph from it for better interpretation.
# Import data to ArangoDB
Create new databse:
db._createDatabase("arangoml", {}, [{ username: "root", passwd: "", active: true}])
ArangoDB Import data:
1. Go to the directory that contains the dataset.
2. Open terminal and write the following command:
arangoimport --file "wiki_movie_plots_deduped.csv" --type csv --server.database arangoml --create-collection --collection "movies"
# Preprocess dataset
### Using ArangoQL
1. We want store different columns like cast, director etc. as documents in collections as raw data is highly unstructured. But it requires some processing first. For example, if we want to store all Casts in a 'cast' collection, we first need to process the original data (which ideally should contain comma separated cast members) as it contains unwanted characters and stopwords. We handle them and extract unique Actors/Actresses from the raw dataset in following way:
let casts_data = (
for i in movies
filter i['Cast'] != null
let casts = substitute(
i['Cast'],
["'",']','[','"','\r\n',')','(','; ',' and ',' & ','/','Cast: ','.'],
['', '', '',', ', ', ', '', '', ', ', ', ', ', ', ', ', '','']
)
for j in split(casts, ",")
let nj = substitute(trim(j),[' '],['_'])
filter trim(j)!=''
return distinct nj)
for i in casts_data
insert {'_key':i} in cast options {ignoreErrors: true}
We can execute same query for Director, Origin, Genre columns.
Director:
let directors_data = (
for i in movies
filter i['Director'] != null
let director = substitute(
i['Director'],
["'",']','[','"','\r\n',')','(','; ',' and ',' & ','/','Director: ','Directors: ','.'],
['', '', '',', ', ', ', '', '', ', ', ', ', ', ', ', ', '', '','']
)
for j in split(director, ",")
let nj = substitute(trim(j),[' '],['_'])
filter trim(j)!=''
return distinct nj)
for i in directors_data
insert {'_key':i} in director options {ignoreErrors: true}
Origin:
let origin_data = (
for i in movies
filter i['Origin'] != null
let origin = substitute(
i['Origin'],
["'",']','[','"','\r\n',')','(','; ',' and ',' & ','/','-','_',' ','.'],
['', '', '',', ', ', ', '', '', ', ', ', ', ', ', ', ', ',', ',', ',','']
)
)
for j in split(origin, ",")
let nj = substitute(trim(j),[' '],['_'])
filter trim(j)!=''
return distinct nj)
for i in origin_data
insert {'_key':i} in origin options {ignoreErrors: true}
Genre:
let genre_data = (
for i in movies
filter i['Genre'] != null
let genre = substitute(
i['Genre'],
["'",']','[','"','\r\n',')','(','; ',' and ',' & ','/','-','_',' ','.'],
['', '', '',', ', ', ', '', '', ', ', ', ', ', ', ', ', ',', ',', ',','']
)
for j in split(genre, ",")
let nj = substitute(trim(j),[' '],['_'])
filter trim(j)!=''
return distinct nj)
for i in genre_data
insert {'_key':i} in genre options {ignoreErrors: true}
2. We create a 'movie' collection that will store specific info about movies like Release data, Title, Plot. Along with this, we also add an edge between the moveis and its corresponding cast members, director(s), origin and genre (that we created from previous queries). To insert data into 'movie' collection, execute the following query:
for i in movies
let id_split = split(i['Wiki Page'],"/")
let id = substitute(id_split[length(id_split)-1],["#"],["_"])
insert {_key:id, year:i['Release Year'], title:i['Title'], plot:i['Plot']}
into movie
options { overwrite: true, ignoreErrors: true }
For adding edge with Casts/Director append the following query to the above query:
let casts = substitute(
i['Cast'],
["'",']','[','"','\r\n',')','(','; ',' and ',' & ','/','Director: ','Directors: ','Cast: ','.'],
['', '', '',', ', ', ', '', '', ', ', ', ', ', ', ', ', '', '', '','']
)
for j in split(casts, ",")
let nj = substitute(trim(j),[' '],['_'])
filter trim(j)!=''
insert {_from: concat("movie/",id), _to:concat("cast/",nj), label:'had as a cast'}
into conn
options {ignoreErrors: true}
Similarly for adding edge with Genre/Origin:
for i in movies
let id_split = split(i['Wiki Page'],"/")
let id = substitute(id_split[length(id_split)-1],["#"],["_"])
let genre = substitute(
i['Genre'],
["'",']','[','"','\r\n',')','(','; ',' and ',' & ','/','-','_',' ','.'],
['', '', '',', ', ', ', '', '', ', ', ', ', ', ', ', ', ',', ',', ',','']
)
for j in split(genre, ",")
let nj = substitute(trim(j),[' '],['_'])
filter trim(j)!=''
insert {_from: concat("movie/",id), _to:concat("genre/",nj), label:'genre'}
into conn
options {ignoreErrors: true}
### Using Python
Another way to do insert node and edges is by using Python. For this, we connect with ArangoDB using PyArango.
```
from pyArango.connection import Connection
conn = Connection(username="root", password="")
db = conn["arangoml"]
def exec(db, aql):
output = db.AQLQuery(aql, rawResults=True, batchSize=1000)
return np.array(output)
```
Here we just need to use `exec()` and provide database variable `db` with corresponding `aql` query for execution. It’s that easy.
# Data Exploration
### Graph
Create graph named `movies` in ArangoDB with the all the node collections and the edge collection created in the previous section.


Now that we can clearly see the connections with the descriptions, we perform graph exploration techniques that are available in ArangoDB for answering different types of research questions.
### Search movies containing given phrase in its plot
We do this by using new feature in ArangoDB 3.5 called ArangoSearch. We use `PHRASE` function to search for documents containing an exact sentence or phrase. To know how it works, refer to [this](https://www.arangodb.com/arangodb-training-center/search/arangosearch/) blog.
We link the view named `search_` with the `movie` collection to index `Plot` column and execute the following query.
for i in search_
SEARCH PHRASE(i.Plot,'batman and robin', 'text_en')
SORT TFIDF(i) desc
limit 5
return [i.Title, i['Release Year']]
### Search with specific Genre combinations
We use another new feature `K_SHORTEST_PATHS` ([details](https://www.arangodb.com/docs/stable/aql/graphs-kshortest-paths.html)) for this. It allows you to query not just a shortest path between two documents in an ArangoDB database, but the list of paths between them, sorted by the length/weights. Here we try to find shortest paths between two different genres `comedy` and `horror`:
FOR p IN ANY K_SHORTEST_PATHS 'genre/comedy' TO 'genre/horror'
GRAPH 'movies'
LIMIT 3
RETURN [p.vertices[*]._key]
Let’s do a similar search with `war` and `horror`.
FOR p IN ANY K_SHORTEST_PATHS 'genre/war' TO 'genre/horror'
GRAPH 'movies'
LIMIT 3
RETURN [p.vertices[*]._key]
We found that there is just one movie titled `Below` in the database (as the shortest path is 3) which is about `war` + `horror`. But the other two outputs just connects movies through their origin. Other outputs are simply connected through their `American` origin.
### Using pruned traversal on graph
Now we look for `American action` movies using pruning ([detail](https://www.arangodb.com/docs/stable/aql/graphs-traversals.html#pruning)) on `Genre` edges during graph traversal. It improves query performance and reduces the amount of overhead generated by the query.
FOR v, e, p IN 1..3 ANY 'origin/American' GRAPH 'movies'
PRUNE e.label == 'genre'
FILTER v._key=='action'
LIMIT 5
RETURN p.vertices[1]._key
Without the PRUNE command, if we execute the above query, we get the same results in ~5 minutes:
# Machine Learning
We are going to perform mainly two ML tasks:
1. Movie similarity based on plots - using Tensorflow.
- Content-based recommendation of movies.
2. Genre classification based on plots - using scikit-learn and Tensorflow.
- Predicting appropriate genres for data with null/unknown values.
## 1. Movie recommendation based on plots
```
from tqdm import tqdm_notebook
import tensorflow as tf
import tensorflow_hub as hub
from nltk import sent_tokenize
from scipy import spatial
from operator import itemgetter
import re
```
Apply basic regex tools to clean movie plots.
```
def clean_plot(text_list):
clean_list = []
for sent in text_list:
sent = re.sub('[%s]' % re.escape("""!"#$%&'()*+,-.:;<=>?@[\]^`{|}~"""), '',sent)
sent = sent.replace('[]','')
sent = re.sub('\d+',' ',sent)
sent = sent.lower()
clean_list.append(sent)
return clean_list
```
Find plot embeddings: (takes some time ~ 5 minutes)
```
plot_emb_list = []
with tf.Graph().as_default():
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2")
messages = tf.placeholder(dtype=tf.string, shape=[None])
output = embed(messages)
with tf.Session() as session:
session.run([tf.global_variables_initializer(), tf.tables_initializer()])
for plot in tqdm_notebook(df['Plot']):
sent_list = sent_tokenize(plot)
clean_sent_list = clean_plot(sent_list)
sent_embed = session.run(output, feed_dict={messages: clean_sent_list})
plot_emb_list.append(sent_embed.mean(axis=0).reshape(1,512))
df['embeddings'] = plot_emb_list
df.to_pickle('./df_embed.pkl')
def similar_movie(movie_name,topn=5):
plot = df[df['Title']==movie_name]['Plot'].values[0]
with tf.Graph().as_default():
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2")
messages = tf.placeholder(dtype=tf.string, shape=[None])
output = embed(messages)
with tf.Session() as session:
session.run([tf.global_variables_initializer(), tf.tables_initializer()])
sent_list = sent_tokenize(plot)
clean_sent_list = clean_plot(sent_list)
sent_embed2 = (session.run(output, feed_dict={messages: clean_sent_list})).mean(axis=0).reshape(1,512)
similarities, titles = [],[movie_name]
for tensor,title in zip(df['embeddings'],df['Title']):
if title not in titles:
cos_sim = 1 - spatial.distance.cosine(sent_embed2,tensor)
similarities.append((title,cos_sim))
titles.append(title)
return sorted(similarities,key=itemgetter(1),reverse=True)[1:topn+1]
similar_movie('Superman',10)
```
We can see that based on the plots, these are the top movies recommended by the model that are similar to “batman” movie.
## 2. Genre Prediction based on plot
### 2.1 Using simpler tools (scikit-learn)
```
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import f1_score, accuracy_score
```
Use Tokenizer and remove unneccessary symbols/expressions
```
new_plots = []
for plot in tqdm_notebook(df['Plot']):
sent_list = sent_tokenize(plot)
clean_sent_list = clean_plot(sent_list)
new_plots.append(clean_sent_list[0])
df_new = df.copy()
df_new['clean plot'] = new_plots
```
Split data into train and test.
```
train_df = df_new[df_new['Genre']!='unknown'][['Title','clean plot','Genre']]
test_df = df_new[df_new['Genre']=='unknown'][['Title','clean plot','Genre']]
train_df['genre_new'] = [x.replace(' ',',').replace('_',',').replace('-',',').split(',') for x in train_df['Genre'].values]
test_df['genre_new'] = [x.replace(' ',',').replace('_',',').replace('-',',').split(',') for x in test_df['Genre'].values]
```
Remove stopwords from plots.
```
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
# function to remove stopwords
def remove_stopwords(text):
no_stopword_text = [w for w in text.split() if not w in stop_words]
return ' '.join(no_stopword_text)
train_df['clean_plot_new'] = train_df['clean plot'].apply(lambda x: remove_stopwords(x))
test_df['clean_plot_new'] = test_df['clean plot'].apply(lambda x: remove_stopwords(x))
```
Apply binarizer for multi-label classification for Genre.
```
multilabel_binarizer = MultiLabelBinarizer()
multilabel_binarizer.fit(train_df['genre_new'])
# transform target variable
y = multilabel_binarizer.transform(train_df['genre_new'])
```
Find embeddings of plots.
```
tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=10000)
xtrain, xval, ytrain, yval = train_test_split(train_df['clean_plot_new'], y, test_size=0.2, random_state=9)
xtrain_tfidf = tfidf_vectorizer.fit_transform(xtrain)
xval_tfidf = tfidf_vectorizer.transform(xval)
```
Define Logistic Regression model and train it.
```
lr = LogisticRegression()
clf = OneVsRestClassifier(lr)
clf.fit(xtrain_tfidf, ytrain)
```
As Logistic regression is rather simpler model and data is complicated, we modify threshold for predition probabilities from 0.5 to 0.2.
```
y_pred_prob = clf.predict_proba(xval_tfidf)
y_pred_new = (y_pred_prob >= 0.2).astype(int)
print("Accuracy:" ,accuracy_score(yval, y_pred_new))
print("F1-score:" ,f1_score(yval, y_pred_new, average="micro"))
```
Make predictions ...
```
def infer_tags(q):
q_vec = tfidf_vectorizer.transform([q])
q_pred = clf.predict(q_vec)
return multilabel_binarizer.inverse_transform(q_pred)
i=0
while i<5:
k = xval.sample(1).index[0]
if infer_tags(xval[k])!=[()]:
print("Movie:\t\t",train_df['Title'].ix[k])
print("Predicted genre: ", infer_tags(xval[k]))
print("Actual genre: ",train_df['genre_new'].ix[k])
i+=1
xtest_tfidf = tfidf_vectorizer.transform(test_df['clean_plot_new'])
y_test_pred_prob = clf.predict_proba(xtest_tfidf)
y_test_pred_new = (y_test_pred_prob >= 0.2).astype(int)
i=0
while i<5:
k = test_df['clean plot'].sample(1).index[0]
pred = infer_tags(test_df['clean plot'].ix[k])
if pred!=[()]:
print("Movie:\t\t\t",test_df['Title'].ix[k])
print("Predicted genre:\t", pred)
i+=1
```
### 2.2 Using Deep Learning (Tensorflow)
```
from nltk.corpus import stopwords
import nltk
from keras.models import Model
from keras.layers import Dense, Embedding, Input
from keras.layers import Conv1D, GlobalMaxPool1D, Dropout, concatenate
from keras.preprocessing import text, sequence
from keras.callbacks import EarlyStopping, ModelCheckpoint
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
# new_plots = []
# for plot in tqdm_notebook(df['Plot']):
# sent_list = sent_tokenize(plot)
# clean_sent_list = clean_plot(sent_list)
# new_plots.append(clean_sent_list[0])
# df_new = df.copy()
# df_new['clean plot'] = new_plots
```
Apply similar preprocessing as previous case: Remove unnecessary symbols/expressions and stopwords from `clean plot`.
```
# train_df = df_new[df_new['Genre']!='unknown'][['Title','clean plot','Genre']]
# test_df = df_new[df_new['Genre']=='unknown'][['Title','clean plot','Genre']]
# from nltk.corpus import stopwords
# stop_words = set(stopwords.words('english'))
# # function to remove stopwords
# def remove_stopwords(text):
# no_stopword_text = [w for w in text.split() if not w in stop_words]
# return ' '.join(no_stopword_text)
# train_df['clean_plot_new'] = train_df['clean plot'].apply(lambda x: remove_stopwords(x))
# test_df['clean_plot_new'] = test_df['clean plot'].apply(lambda x: remove_stopwords(x))
# train_df['genre_new'] = [x.replace(' ',',').replace('_',',').replace('-',',').split(',') for x in train_df['Genre'].values]
# test_df['genre_new'] = [x.replace(' ',',').replace('_',',').replace('-',',').split(',') for x in test_df['Genre'].values]
maxlen = 200
max_features = 20000
encoder = MultiLabelBinarizer()
encoder.fit_transform(train_df['genre_new'])
y_train = encoder.transform(train_df['genre_new'])
y_test = encoder.transform(test_df['genre_new'])
num_classes = len(encoder.classes_)
```
Train tokenizer on movie plots of training data.
```
tokenizer = text.Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(train_df['clean_plot_new']))
# train data
list_tokenized_train = tokenizer.texts_to_sequences(train_df['clean_plot_new'])
X_t = sequence.pad_sequences(list_tokenized_train, maxlen=200)
# test data
list_tokenized_test = tokenizer.texts_to_sequences(test_df['clean_plot_new'])
X_te = sequence.pad_sequences(list_tokenized_test, maxlen=200)
```
Define 1D-CNN Model here
```
def build_model(conv_layers = 2, max_dilation_rate = 3):
embed_size = 128
inp = Input(shape=(maxlen, ))
x = Embedding(max_features, embed_size)(inp)
x = Dropout(0.25)(x)
x = Conv1D(2*embed_size,
kernel_size = 3)(x)
prefilt_x = Conv1D(2*embed_size,
kernel_size = 3)(x)
out_conv = []
for dilation_rate in range(max_dilation_rate):
x = prefilt_x
for i in range(3):
x = Conv1D(32*2**(i),
kernel_size = 3,
dilation_rate = dilation_rate+1)(x)
out_conv += [Dropout(0.5)(GlobalMaxPool1D()(x))]
x = concatenate(out_conv, axis = -1)
x = Dense(50, activation="relu")(x)
x = Dropout(0.1)(x)
x = Dense(num_classes, activation="sigmoid")(x)
model = Model(inputs=inp, outputs=x)
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
model = build_model()
model.summary()
batch_size = 128
epochs = 5
file_path="weights.hdf5"
checkpoint = ModelCheckpoint(file_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
early = EarlyStopping(monitor="val_loss", mode="min", patience=4)
callbacks_list = [checkpoint, early]
model.fit(X_t, y_train,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2)
y_pred = model.predict(X_t)
y_pred_new = (y_pred >= 0.5).astype(int)
y_pred_genre = multilabel_binarizer.inverse_transform(y_pred_new)
for ind,i in enumerate(train_df.index[:20]):
print("\nMovie:\t\t",train_df['Title'].ix[i])
print("Predicted genre: ", y_pred_genre[ind])
print("Actual genre: ",train_df['genre_new'].ix[i])
```
As we can see, this model performs much better than the previous one. The `Genre`s of a movie is identifiable using the plot summaries provided in the data. We can use these predictions in place of `unknown` or missing Genre informatiosn of a movie.
| github_jupyter |
```
import json
import pandas as pd
import os
from collections import defaultdict
import numpy as np
pd.set_option('display.float_format', '{:.5g}'.format)
file_list = ['turbo-155-7_basic.2021-12-18.22-28-54.json', 'turbo-155-7_basic.2021-12-18.23-53-40.json', 'turbo-155-7_basic.2021-12-19.00-47-21.json', 'turbo-155-7_hazzys.2021-12-19.21-17-41.json', 'turbo-155-7_hazzys.2021-12-19.21-34-21.json', 'turbo-155-7_hazzys.2021-12-19.21-44-31.json', 'turbo-155-7_hazzys.2021-12-19.21-54-25.json', 'turbo-155-7_hazzys.2021-12-19.22-22-08.json', 'turbo-155-7_hazzys.2021-12-19.22-28-27.json', 'turbo-155-7_hazzys.2021-12-19.23-08-45.json', 'turbo-155-7_hazzys.2021-12-19.23-48-12.json', 'turbo-155-7_hazzys.2021-12-18.17-34-15.json', 'turbo-155-7_hazzys.2021-12-18.17-45-54.json', 'turbo-155-7_hazzys.2021-12-18.17-56-56.json', 'turbo-155-7_hazzys.2021-12-19.21-17-41.json', 'turbo-755-0_basic.2021-12-18.20-49-10.json', 'turboae-approximated-nonsys_basic.2021-12-19.10-17-15.json', 'turboae-approximated-nonsys_basic.2021-12-19.15-38-12.json', 'turboae-approximated-rsc_hazzys.2021-12-19.07-10-46.json', 'turboae-binary-exact_basic.2021-12-19.04-17-58.json', 'turboae-binary-exact_basic.2021-12-20.04-07-49.json', 'turboae-binary-exact_basic.2021-12-20.05-31-02.json', 'turboae-binary-exact_basic.2021-12-20.05-57-51.json', 'turboae-binary-exact_basic.2021-12-20.06-54-08.json', 'turboae-binary-exact_basic.2021-12-20.07-13-52.json', 'turboae-binary-exact_basic.2021-12-20.08-17-40.json', 'turboae-binary-exact_basic.2021-12-20.08-29-11.json', 'turboae-binary-exact_basic.2021-12-20.09-44-06.json', 'turboae-binary-exact-rsc_hazzys.2021-12-19.22-56-02.json', 'turboae-binary-exact-rsc_hazzys.2021-12-19.23-59-23.json', 'turboae-binary-exact-rsc_hazzys.2021-12-20.00-27-38.json', 'turboae-binary-exact-rsc_hazzys.2021-12-20.01-16-27.json', 'turboae-binary-exact-rsc_hazzys.2021-12-20.01-50-01.json', 'turboae-binary-exact-rsc_hazzys.2021-12-20.02-42-40.json', 'turboae-binary-exact-rsc_hazzys.2021-12-20.03-12-48.json', 'turboae-binary-exact-rsc_hazzys.2021-12-20.04-35-27.json']
filedir = '/code/turbo-codes/results'
cpu_model_ids = ['turbo-155-7_hazzys.2021-12-19.21-44-31', 'turbo-155-7_hazzys.2021-12-19.22-28-27', 'turbo-155-7_hazzys.2021-12-19.23-08-45', 'turbo-155-7_hazzys.2021-12-19.23-48-12', 'turboae-binary-exact-rsc_hazzys.2021-12-20.00-27-38', 'turboae-binary-exact-rsc_hazzys.2021-12-20.01-50-01', 'turboae-binary-exact-rsc_hazzys.2021-12-20.03-12-48', 'turboae-binary-exact-rsc_hazzys.2021-12-20.04-35-27', 'turboae-binary-exact_basic.2021-12-20.05-57-51', 'turboae-binary-exact_basic.2021-12-20.07-13-52', 'turboae-binary-exact_basic.2021-12-20.08-29-11', 'turboae-binary-exact_basic.2021-12-20.09-44-06', ]
json_list = []
for filename in file_list:
with open(os.path.join(filedir, filename), 'r') as f:
json_list.append(json.load(f))
test_runs = [test for jsondict in json_list for test in jsondict]
snrs = [test["test_run_settings"]["encoder_decoder_settings"]["channel"]["snr"] for test in test_runs]
bers = [test["stats"]["ber"] for test in test_runs]
blers = [test["stats"]["bler"] for test in test_runs]
num_blocks = [test["stats"]["num_blocks"] for test in test_runs]
num_iters = [test["test_run_settings"]["encoder_decoder_settings"]["num_iter"] for test in test_runs]
model_ids = [test["model_id"] for test in test_runs]
assert all(1000000 == i for i in num_blocks)
assert all(6 == i for i in num_iters)
model_names = [model_id.split('.')[0] for model_id in model_ids]
model_names
ber_data = defaultdict(list)
bler_data = defaultdict(list)
for i in range(len(test_runs)):
model_name = model_names[i]
model_id = model_ids[i]
if model_id not in cpu_model_ids:
snr = snrs[i]
ber = bers[i]
bler = blers[i]
ber_data[model_name].append({'SNR (BER)': snr, model_id: ber})
bler_data[model_name].append({'SNR (BLER)': snr, model_id: bler})
ber_dataframes = {}
bler_dataframes = {}
for model_name in ber_data:
ber_dataframes[model_name] = pd.DataFrame.from_records(ber_data[model_name], index='SNR (BER)').sum(level=0).replace(0, np.nan).sort_index()
bler_dataframes[model_name] = pd.DataFrame.from_records(bler_data[model_name], index='SNR (BLER)').sum(level=0).replace(0, np.nan).sort_index()
for model_name in ber_dataframes:
print(model_name)
display(ber_dataframes[model_name])
for model_name in bler_dataframes:
print(model_name)
display(bler_dataframes[model_name])
gpu_estimates = {}
for model_name in ber_dataframes:
gpu_stddev = np.sqrt(ber_dataframes[model_name].var(axis=1) / ber_dataframes[model_name].count(axis=1))
gpu_mean = ber_dataframes[model_name].mean(axis=1)
gpu_lower = gpu_mean - 2* gpu_stddev
gpu_upper = gpu_mean + 2 * gpu_stddev
gpu_estimates[model_name] = pd.concat([gpu_mean, gpu_lower, gpu_upper], axis=1)
print(model_name)
display(gpu_estimates[model_name])
cpu_ber_data = defaultdict(list)
cpu_bler_data = defaultdict(list)
for i in range(len(test_runs)):
model_name = model_names[i]
model_id = model_ids[i]
if model_id in cpu_model_ids:
print('hello')
snr = snrs[i]
ber = bers[i]
bler = blers[i]
cpu_ber_data[model_name].append({'SNR (BER)': snr, model_id: ber})
cpu_bler_data[model_name].append({'SNR (BLER)': snr, model_id: bler})
cpu_ber_dataframes = {}
cpu_bler_dataframes = {}
for model_name in cpu_ber_data:
cpu_ber_dataframes[model_name] = pd.DataFrame.from_records(cpu_ber_data[model_name], index='SNR (BER)').sum(level=0).replace(0, np.nan).sort_index()
cpu_bler_dataframes[model_name] = pd.DataFrame.from_records(cpu_bler_data[model_name], index='SNR (BLER)').sum(level=0).replace(0, np.nan).sort_index()
for model_name in cpu_ber_dataframes:
print(model_name)
display(cpu_ber_dataframes[model_name])
for model_name in cpu_bler_dataframes:
print(model_name)
display(cpu_bler_dataframes[model_name])
cpu_estimates = {}
for model_name in cpu_ber_dataframes:
# display(cpu_ber_dataframes['turbo-155-7_hazzys'].count(axis=1))
cpu_stddev = np.sqrt(cpu_ber_dataframes[model_name].var(axis=1) / cpu_ber_dataframes[model_name].count(axis=1))
cpu_mean = cpu_ber_dataframes[model_name].mean(axis=1)
cpu_lower = cpu_mean - 2 * cpu_stddev
cpu_upper = cpu_mean + 2 * cpu_stddev
cpu_estimates[model_name] = pd.concat([cpu_mean, cpu_lower, cpu_upper], axis=1)
print(model_name)
display(cpu_estimates[model_name])
for model_name in cpu_estimates:
print(model_name)
print('cpu')
display(cpu_estimates[model_name])
print('gpu')
display(gpu_estimates[model_name])
ber_data = defaultdict(list)
bler_data = defaultdict(list)
for i in range(len(test_runs)):
model_name = model_names[i]
model_id = model_ids[i]
snr = snrs[i]
ber = bers[i]
bler = blers[i]
ber_data[model_name].append({'SNR (BER)': snr, model_id: ber})
bler_data[model_name].append({'SNR (BLER)': snr, model_id: bler})
ber_dataframes = {}
bler_dataframes = {}
for model_name in ber_data:
ber_dataframes[model_name] = pd.DataFrame.from_records(ber_data[model_name], index='SNR (BER)').sum(level=0).replace(0, np.nan).sort_index()
bler_dataframes[model_name] = pd.DataFrame.from_records(bler_data[model_name], index='SNR (BLER)').sum(level=0).replace(0, np.nan).sort_index()
for model_name in ber_dataframes:
print(model_name)
display(ber_dataframes[model_name])
for model_name in bler_dataframes:
print(model_name)
display(bler_dataframes[model_name])
estimates = {}
for model_name in ber_dataframes:
stddev = np.sqrt(ber_dataframes[model_name].var(axis=1) / ber_dataframes[model_name].count(axis=1))
mean = ber_dataframes[model_name].mean(axis=1)
lower = mean - 2* stddev
upper = mean + 2 * stddev
estimates[model_name] = pd.concat([mean, lower, upper], axis=1)
print(model_name)
display(estimates[model_name])
```
| github_jupyter |
## Exploring folium with co-locating of TIMS and jamcam data as test case
01 July 2019, Jack Hensley
```
import folium
import boto3
import pandas as pd
import operator
import numpy as np
from scipy.spatial.distance import cdist
import json
% matplotlib inline
```
import tims data and explore how the detectors look on a node level
```
# import tims and jam cam locations
# tims
session = boto3.Session(profile_name='dssg')
s3 = session.client('s3')
bucket_name = 'air-pollution-uk'
obj = s3.get_object(Bucket=bucket_name, Key='raw/tims_data/detdata01032019-204523.csv')
tims_df = pd.read_csv(obj['Body']) # 'Body' is a key word
tims_df.head()
```
how many nodes have just one detector?
```
tims_df.DETECTOR_NO.unique()
tims_df.groupby('TOTAL_DETECTOR_NO')['NODE'].nunique()
tims_df.shape
tims_df[tims_df.TOTAL_DETECTOR_NO == 1].shape
```
the desire is to have one detector nodes within central london that could possibly have a jamcam nearby.
```
central_london_easting = 530034
central_london_northing = 180381
tims_df.loc[(operator.and_(
tims_df.EASTING > central_london_easting-5000, tims_df.EASTING < central_london_easting+5000)) &
(operator.and_(
tims_df.NORTHING > central_london_northing-5000, tims_df.NORTHING < central_london_northing+5000)) &
tims_df.TOTAL_DETECTOR_NO == 1
].shape
tims_eval_df = tims_df.loc[(operator.and_(
tims_df.EASTING > central_london_easting-5000, tims_df.EASTING < central_london_easting+5000)) &
(operator.and_(
tims_df.NORTHING > central_london_northing-5000, tims_df.NORTHING < central_london_northing+5000)) &
tims_df.TOTAL_DETECTOR_NO == 1
]
tims_eval_df.head()
```
df of tims locations in central london with only one detector per node selected. let's see if they're near jam cams.
```
session = boto3.Session(profile_name='dssg')
s3 = session.client('s3')
bucket_name = 'air-pollution-uk'
obj = s3.get_object(Bucket=bucket_name, Key='processed_data/tims/node_coords.csv')
tims_df_locs = pd.read_csv(obj['Body'])
tims_df_locs.head()
# find tims_df_locs that are same as the ones selected, so that longitude and latitude can be selected out
common = tims_eval_df.merge(tims_df_locs, on=['NODE'])
common.head()
tims_eval_df_locs = tims_df_locs[tims_df_locs.NODE.isin(common.NODE)]
tims_eval_df_locs.shape
tims_locations = tims_eval_df_locs[['LATITUDE', 'LONGITUDE']]
tims_location_list = tims_locations.values.tolist()
tims_location_list[0:10]
```
plot on city of london map
```
London = [51.506949, -0.122876]
londonmap = folium.Map(
width=500, height=500,
location = London,
zoom_start = 12,
tiles = 'stamentoner')
for point in range(0, len(tims_location_list)):
folium.CircleMarker(tims_location_list[point],
radius=1,
color='red',
fill_color='red',
fill_opacity=0.2
).add_to(londonmap)
londonmap
```
find jamcams that are in similar locations
```
obj = s3.get_object(Bucket=bucket_name, Key='processed_data/jamcams/jamcam_coords.csv')
jc_df = pd.read_csv(obj['Body'])
jc_df.head()
jc_files = pd.read_json('C:/Users/joh3146/Downloads/cam_file.json')
jc_df = jc_files.T
list(jc_df.columns.values)
jc_df = jc_df.rename(index=str, columns={"lat": "LATITUDE", "lon": "LONGITUDE"})
jc_locations = jc_df[['LATITUDE', 'LONGITUDE']]
jc_location_list = jc_locations.values.tolist()
jc_location_list[0:10]
```
find the 20 nearest neighbors, and then report their indices
```
jc_tims_locs = cdist(jc_location_list, tims_location_list)
jc_tims_locs.shape
nearest_tims_to_jc_locs = jc_tims_locs.min(axis=1)
nearest_tims_to_jc_locs.shape
jc_nearest_tims_idx = np.argsort(nearest_tims_to_jc_locs)[0:20]
jc_nearest_tims_idx
jc_nearest_tims_locs = np.take(jc_tims_locs, jc_nearest_tims_idx, axis=0)
jc_nearest_tims_locs.shape
tims_nearest_jc_idx = np.argmin(jc_nearest_tims_locs, axis=1)
tims_nearest_jc_idx
tims_df_out = tims_eval_df_locs.take(tims_nearest_jc_idx)
tims_df_out = tims_df_out.drop("Unnamed: 0", axis=1)
tims_df_out.head()
tims_df_out.to_csv(path_or_buf='C:/Users/joh3146/Downloads/scoot_nodes_for_dssg.csv', sep=',', index=False)
```
select of jc_df the indices corresponding to the 20 nearest neighbors and export to csv
```
jc_df_out = jc_df.take(jc_nearest_tims_idx)
jc_df_out.index
jc_df_out.to_csv(path_or_buf='C:/Users/joh3146/Downloads/jamcams_near_tims.csv', sep=',', index=False)
```
plot to evaluate
```
jc_out_locations = jc_df_out[['LATITUDE', 'LONGITUDE']]
jc_out_location_list = jc_out_locations.values.tolist()
jc_out_location_list
tims_out_locations = tims_df_out[['LATITUDE', 'LONGITUDE']]
tims_out_location_list = tims_out_locations.values.tolist()
tims_out_location_list
London = [51.506949, -0.122876]
londonmap = folium.Map(
width=500, height=500,
location = London,
zoom_start = 12,
tiles = 'stamentoner')
for point in range(0, len(tims_out_location_list)):
folium.CircleMarker(tims_out_location_list[point],
radius=10,
color='red',
fill_color='red',
fill_opacity=0
).add_to(londonmap)
for point in range(0, len(jc_out_location_list)):
folium.CircleMarker(jc_out_location_list[point],
radius=5,
color='blue',
fill_color='blue',
fill_opacity=0
).add_to(londonmap)
londonmap.save("C:/Users/joh3146/Documents/dssg/jamcams_tims_selected_for_eval.html")
londonmap
```
| github_jupyter |
# Analysis of First Year Semester-1 Result
The data used in this analysis is extracted from the Institute website. The data can be used to show various patterns in the results in relation to Section, Gender, Branch and other factors.
## Importing the libraries
```
#Importing the libraries
import numpy as np
import pandas as pd
import seaborn as sns
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
```
## Importing the dataset
```
#Importing the dataset
dataset = pd.read_csv("/kaggle/input/manit-201923-batch-sem1-result/first_year.csv")
dataset
```
### The Dataset contains entries of 954 students across the following parameters:
* Section
* Branch
* Name
* Gender
* Result
* GPA
## Removing Students who did not appear for exam
```
#Removing Students with 0 GPA who didn't appear for exam
students_absent = dataset[dataset.GPA == 0]
dataset = dataset[dataset.GPA != 0]
students_absent.head()
```
# Plotting Section wise students who didn't appear for exams
```
# Plotting Section wise students who didn't appear for exams
sns.catplot(x="Section", data=students_absent, kind='count', order='ABCDEFGHIJ')
```
# Students who did not clear the Semester
```
#Students who did not clear the semester
not_clear = dataset[dataset.Result == 'Not Clear']
sns.catplot(x = "Section", data=not_clear, kind='count', aspect=2, order="ABCDEFGHIJ")
```
# Total student strength sectionwise
```
#Total student strength sectionwise
sec_plt = sns.catplot(x='Section', data=dataset, aspect=2, kind='count', order="ABCDEFGHIJ")
sec_plt.set(ylim=(80, 105))
sns.catplot(x='Section', data=dataset, aspect=2, kind='count', hue='Gender', order="ABCDEFGHIJ")
```
# Branchwise Strength in different sections
```
#Branchwise Strength in different sections
sns.catplot(x='Section', data=dataset, kind='count', col='Branch', col_wrap=4, order="ABCDEFGHIJ")
```
# Kernel Density Extimates for GPA
```
#Kernel Density Extimate for GPA
sns.kdeplot(data=dataset['GPA'], bw=0.1, shade=True)
#Kernel Density Extimate Gender wise
m_gpa = dataset[dataset.Gender=='M']
f_gpa = dataset[dataset.Gender=='F']
sns.kdeplot(m_gpa['GPA'], bw=0.12, shade = True, label='Males')
sns.kdeplot(f_gpa['GPA'], bw=0.12, shade = True, label='Females')
```
# GPA across all Sections
```
#Section wise GPA
sns.catplot(x='Section', y='GPA', data=dataset, kind='box')
```
# Sectionwise GPA by Gender
```
#Sectionwise GPA by Gender
sns.lineplot(x='Section', y='GPA', hue='Gender', data=dataset)
```
# GPA Across all Branches
```
#Branchwise GPA
sns.catplot(x='Branch', y='GPA', data=dataset, kind='boxen')
```
# Branchwise GPA for Males and Females
```
#Branchwise GPA for Males and Females
sns.catplot(x='Branch', y='GPA', data=dataset, kind='point', hue='Gender')
```
# Branchwise GPA across all sections
```
#Branchwise GPA across all sections
sns.catplot(x='Section', y='GPA', data=dataset, hue='Branch', kind='box', aspect=3)
```
## Adding new Feature: Second year section
```
#Adding new feature: second year section
pd.set_option('mode.chained_assignment', None)
x = dataset['Scholar No'].copy() % 1000
sec=[]
for temp in x:
if temp // 200 == 0:
sec.append(1)
elif temp // 200 == 1:
sec.append(2)
else:
sec.append(3)
dataset['Section-Sem3'] = sec
```
# Plotting Second year section wise GPA
```
#Plotting Second year section wise GPA
sns.catplot(x='Section-Sem3', y='GPA', col='Branch', data=dataset, kind='point', aspect=0.6, col_wrap=7)
```
## Extracting initials
```
#Extracting initials
x = dataset.Name
d=[]
for i in dataset.Name:
d.append(i[0])
dataset['Initials']=d
```
# Plotting count of students with same initials
```
#Plotting count of students with same initials
sns.catplot(x='Initials', kind='count', data=dataset)
```
| github_jupyter |
# Latent Factor Analysis (LFA) using SGD
1. Load data
- Prepocessing
- Drop 0
- Convert to Sparse
- Define error function
- Using SGD to minmize error function
- Prediction for user already in database
- References
# Libraries
```
import numpy as np
import pandas as pd
import seaborn as sns
import time
from numpy.linalg import norm
from scipy.sparse import coo_matrix
```
# Load Data
```
def loadingData(dataFile,nrows=None):
# if nrows =-1
df = pd.read_csv(dataFile,
sep=";",
header=0,
names=["user","isbn","rating"],
encoding='iso-8859-1',
nrows=nrows
)
return df
```
# Preprocess
```
# does not work on whole data set coz its too large
# R = df.pivot(index='user',columns='isbn',values='rating')
def covertToSparse(df):
# sparse matrix works more efficiently
df['rating'] = df['rating'].astype(float)
df['user'] = df['user'].astype("category")
df['isbn'] = df['isbn'].astype("category")
# convert str to catergory codes because spare matrix cannot contain string
isbn_code = df['isbn'].cat.codes.copy()
user_code = df['user'].cat.codes.copy()
R = coo_matrix((df['rating'],(user_code, isbn_code)))
return R
def filterBooks(df, book_threshold = 0, user_threshold = 0):
books_ratings_count = df.isbn.value_counts() # count number of review of each book
users_ratings_count = df.user.value_counts() # count number of review of each book
# filtering ,obtain index
books_tokeep = books_ratings_count[books_ratings_count >= book_threshold]
users_tokeep = users_ratings_count[users_ratings_count >= user_threshold]
# filtering
df_clean = df[df.isbn.isin(books_tokeep.index)]
df_clean = df_clean[df_clean.user.isin(users_tokeep.index)]
def cal_size(df):
r,c = df.shape
size = r*c
return size
pc = cal_size(df_clean)/cal_size(df) * 100
print(f"Book, User Threshold: {(book_threshold, user_threshold )}")
print(f"INPUT SIZE: {df.shape}")
print(f"OUTPUT SIZE: {df_clean.shape}")
print(f"Data size reduced to: {pc:.2f}%")
return df_clean
```
# Error Function

```
def cal_error(R,P,Q,lambda_=0.02):
# error function to be minimized
ratings = R.data
rows = R.row
cols = R.col
error = 0
for ui in range(len(ratings)):
rui = ratings[ui]
u= rows[ui]
i= cols[ui]
# adding bias
mean = np.mean(R.data) # mean score of all rating
ui = np.mean(P[u,:]) # mean rating given by that user
bi = np.mean(Q[:,i]) # mean rating give to that movie
bui = mean + ui + bi
if rui > 0:
rui_hat = P[u,:]@Q[:,i] + mean + ui + bi # adding bias
terms = [ui,bi,norm(P[u,:],2),norm(Q[:,i],2)]
error = error + (rui - rui_hat)**2 + \
lambda_ * sum([i**2 for i in terms])
return error
```
# SGD Function

```
def SGD_bias(R,K=5,lambda_=0.02,steps=10,gamma=0.001,rmse_target=1,
initialize=True,P_hat=None,Q_hat=None,
verbose=False):
# lambda_: regularization
# gamma :learning rate
if P_hat ==None and Q_hat==None:
# initialise matrix P and Q
M,N = R.shape
P = np.random.rand(M,K)
Q = np.random.rand(K,N)
# load pretrained weights, used for predicting new user
elif P_hat !=None and Q_hat!=None:
P = P_hat
Q = Q_hat
#initial RMSE
rmse = np.sqrt(cal_error(R,P,Q,lambda_)/len(R.data))
print(f"STARTING RMSE: {rmse:.2f}")
for step in range(steps):
for ui in range(len(R.data)):
rui = R.data[ui] # serialize matrix
u = R.row[ui] # get user index (row)
i = R.col[ui] # get item index (col)
# adding bias
mean = np.mean(R.data) # mean score of all rating
ui = np.mean(P[u,:]) # mean rating given by that user
bi = np.mean(Q[:,i]) # mean rating give to that movie
bui = mean + ui + bi
# update P,Q matrix
rui_hat = P[u,:]@Q[:,i] + mean + ui + bi
eui = rui - rui_hat
P[u,:] = P[u,:] + gamma * (eui * Q[:,i] - lambda_ * P[u,:])
Q[:,i] = Q[:,i] + gamma * (eui * P[u,:] - lambda_ * Q[:,i])
rmse = np.sqrt(cal_error(R,P,Q,lambda_)/len(R.data))
if verbose:
print(f"STEP NO: {step+1} - CURRENT RMSE: {rmse:.2f}")
if rmse < rmse_target:
break
print(f"STEP NO: {step+1} - FINAL RMSE: {rmse:.2f}")
return P,Q,rmse
```
# Production
```
starttime = time.time()
nrows = None
# nrows= 5000
dataFile='data\BX-Book-Ratings.csv'
df = loadingData(dataFile,nrows)
#filtering
book_threshold,user_theshold = 10,10
df = filterBooks(df,book_threshold,user_theshold)
# block for dropping 0 values
print(f"DF size: {df.shape}")
df = df[df.rating!=0]
print(f"DF size after dropping 0: {df.shape}")
# convert df to sparse matrix
R = covertToSparse(df)
print(f"Rating matrix shape: {R.shape}")
# sanity check
print(f"Number of unique users in df: {len(df.user.unique())}")
print(f"Number of unique books in df: {len(df.isbn.unique())}")
print(f"Number of rows and cols,i.e. unique users,books in R matrix: {R.shape}")
#SGD
params = {'R':R,
'K':5,
'lambda_':0.02,
'steps':500,
'gamma':0.01,
'verbose':True,
'rmse_target':1
}
P,Q,rmse = SGD_bias(**params)
duration = time.time() - starttime
print(f"Process time: {duration:.2f}")
import sys
sys.exit()
```
# how to input new user?
layer 1: user demographic, bio
user content based filtering to generate
layer 2: punch in social media account, obtain social graph
recommend using colaborative filtering
layer 3: rate some movies to cold start the LFA process
old user, look up updated R matrix
new user, give random 10 movies to rate, , upate P matrix, reclculate PQ matrix by SGD
```
test_users = [94100, 173415, 116122, 55490, 108950, 148898, 133706, 36299, 262070, 106849]
P.shape
Q.shape
A = np.array(np.mat('1 2; 3 4'), subok=True)
A
np.indices?
#prediction block
R_hat = P@Q
R_hat.shape
max(R_hat[0,:])
min(R_hat[0,:])
sns.heatmap(R_hat,annot=False,cmap='plasma',vmax=0)
```
if oldd user read 10 books, how to prevent system from reocmmending the same 10 books
save and load trained weiights, PQ
save and display rating matrix
load rating matrix to predicut user behaviour
# References
Yehuda Koren, Robert Bell and Chris Volinsky (2019). Matrix Factorization Techniques for Recommender Systems - IEEE Journals & Magazine. [online] Ieeexplore.ieee.org. Available at: https://ieeexplore.ieee.org/document/5197422 [Accessed 10 Jan. 2019];
https://datajobs.com/data-science-repo/Recommender-Systems-[Netflix].pdf[Accessed 10 Jan. 2019].
# SS Misc code
```
P.conc([0,0,0,0,0])
new_user = np.array([0,0,0,0,0])
P_prime = np.append((P,new_user),axis=0)
P
P,Q,rmse = SGD_bias(**params)
new_user = np.array([[0,7,10,0,0]])
P_prime = np.concatenate((P,new_user))
P_prime.shape
P2,Q2, rmse = SGD_bias(**params,P_hat=P_prime,Q_hat=Q)
R.shape
P.shape
P2.shape
P_prime.shape
A = np.array([[1,2,3],[4,5,6]])
A
B = np.array([[1,1,1]])
np.append(A,B)
np.concatenate((A,B))
P.shape
P_prime.shape
df.head()
# query spare matrix
df[df.user == 276726]
R.data
R.col
R_hat[0,:]
R_hat.shape
# sparse matrix works more efficiently
df['rating'] = df['rating'].astype(float)
df['user'] = df['user'].astype("category")
df['isbn'] = df['isbn'].astype("category")
# convert str to catergory codes because spare matrix cannot contain string
isbn_code = df['isbn'].cat.codes.copy()
user_code = df['user'].cat.codes.copy()
R = coo_matrix((df['rating'],(user_code, isbn_code)))
R.shape
print(df.shape)
df = df[df.rating!=0]
df.shape
np.any(np.isnan(df))
dataFile='data\BX-Book-Ratings.csv'
df = pd.read_csv(dataFile,sep=";",
header=0,
names=["user","isbn","rating"],
encoding='iso-8859-1',
nrows=1000
)
df.head()
# R = np.array([[3,0,2],[4,1,9],[9,2,1]])
M,N = R.shape
K=10
P = np.random.rand(M,K)
Q = np.random.rand(K,N)
cal_error(R,P,Q,0.02)
import os
os.startfile(os.getcwd())
# # WRONG,NO REGULARIZATION TERMS
# def SGD(R,K=5,lambda_=0.02,steps=10,gamma=0.001,verbose=False,rmse_target=1):
# # lambda_: regularization
# # gamma :learning rate
# # initialise matrix P and Q
# M,N = R.shape
# P = np.random.rand(M,K)
# Q = np.random.rand(K,N)
# #initial RMSE
# rmse = np.sqrt(mean_squared_error(R.toarray(), P@Q))
# print(f"STARTING RMSE: {rmse:.2f}")
# for step in range(steps):
# for ui in range(len(R.data)):
# rui = R.data[ui] # serialize matrix
# u = R.row[ui] # get user index (row)
# i = R.col[ui] # get item index (col)
# # # adding bias
# # mean = np.mean(R.data) # mean score of all rating
# # ui = np.mean(P[u,:]) # mean rating given by that user
# # bi = np.mean(Q[:,i]) # mean rating give to that movie
# # bui = mean + ui + bi
# # rui_hat = P[u,:] @ Q[:,i] + mean + ui + bi
# rui_hat = P[u,:] @ Q[:,i] # sum(row x col)
# error = rui - rui_hat
# # update P,Q matrix
# P[u,:] = P[u,:] + gamma * (error * Q[:,i] - lambda_ * P[u,:])
# Q[:,i] = Q[:,i] + gamma * (error * P[u,:] - lambda_ * Q[:,i])
# rmse = np.sqrt(mean_squared_error(R.toarray(), P@Q))
# if verbose:
# print(f"STEP NO: {step+1} - CURRENT RMSE:{rmse:.2f}")
# if rmse < rmse_target:
# break
# if verbose:
# print(f"STEP NO: {step+1} - CURRENT RMSE:{rmse:.2f}")
# return P,Q,rmse
# # THE ERROR FUNCTION IS WRONG
# # bias are not accounted for in SGD
# def SGD_bias_old(R,K=5,lambda_=0.02,steps=10,gamma=0.001,verbose=False,rmse_target=1):
# # lambda_: regularization
# # gamma :learning rate
# # initialise matrix P and Q
# M,N = R.shape
# P = np.random.rand(M,K)
# Q = np.random.rand(K,N)
# #initial RMSE
# rmse = np.sqrt(mean_squared_error(R.toarray(), P@Q))
# print(f"STARTING RMSE: {rmse:.2f}")
# for step in range(steps):
# for ui in range(len(R.data)):
# rui = R.data[ui] # serialize matrix
# u = R.row[ui] # get user index (row)
# i = R.col[ui] # get item index (col)
# # adding bias
# mean = np.mean(R.data) # mean score of all rating
# ui = np.mean(P[u,:]) # mean rating given by that user
# bi = np.mean(Q[:,i]) # mean rating give to that movie
# bui = mean + ui + bi
# rui_hat = P[u,:] @ Q[:,i] + mean + ui + bi
# error = rui - rui_hat
# # update P,Q matrix
# P[u,:] = P[u,:] + gamma * (error * Q[:,i] - lambda_ * P[u,:])
# Q[:,i] = Q[:,i] + gamma * (error * P[u,:] - lambda_ * Q[:,i])
# rmse = np.sqrt(mean_squared_error(R.toarray(), P@Q))
# if verbose:
# print(f"STEP NO: {step+1} - CURRENT RMSE:{rmse:.2f}")
# if rmse < rmse_target:
# break
# if verbose:
# print(f"STEP NO: {step+1} - CURRENT RMSE:{rmse:.2f}")
# return P,Q,rmse
# # element by element approach
# def SGD_old(R,K=5,lambda_=0.02,steps=10,gamma=0.001,verbose=False,rmse_target=1):
# # def SGD(R,K,lambda_,steps,gamma,verbose,rmse_target):
# # lambda_: regularization
# # gamma :learning rate
# # initialise matrix P and Q
# M,N = R.shape
# P = np.random.rand(M,K)
# Q = np.random.rand(K,N)
# #initial RMSE
# rmse = np.sqrt(mean_squared_error(R.toarray(), P@Q))
# print(f"STARTING RMSE: {rmse:.2f}")
# for step in range(steps):
# for ui in range(len(R.data)):
# rui = R.data[ui] # serialize matrix
# u = R.row[ui] # get user index (row)
# i = R.col[ui] # get item index (col)
# rui_hat = P[u,:] @ Q[:,i] # sum(row x col)
# error = rui - rui_hat
# # update P,Q matrix
# P[u,:] = P[u,:] + gamma * (error * Q[:,i] - lambda_ * P[u,:])
# Q[:,i] = Q[:,i] + gamma * (error * P[u,:] - lambda_ * Q[:,i])
# rmse = np.sqrt(mean_squared_error(R.toarray(), P@Q))
# if rmse < rmse_target:
# break
# if verbose == True:
# print(f"FINAL RMSE: {rmse:.2f}")
# return P,Q,rmse
```
# Inspection , EDA
```
sns.distplot(df.rating,
bins=range(10),
hist_kws={"histtype": "step",
"linewidth": 3,
"alpha": 1,
"color": "r"},
kde=False,
)
sns.distplot(df[df.rating!=0].rating,
bins=range(10),
hist_kws={"histtype": "step",
"linewidth": 3,
"alpha": 1,
"color": "r"},
kde=False,
)
sns.heatmap(df==0,cmap='plasma_r')
```
norm?
```
a= [1,2,3]
np.mean(a)**2
norm(a,2)
norm(42,2)
df.head()
df.groupby('user').count().head()
df_user = df.groupby('user').count().sort_values('rating',ascending=False).isbn
df_user
# def filterBooks(df, rating_threshold = 10):
# books_ratings_count = df.isbn.value_counts() # count number of review of each book
# users_ratings_count = df.user.value_counts() # count number of review of each book
# # filtering ,obtain index
# books_tokeep = books_ratings_count[books_ratings_count >= rating_threshold]
# users_tokeep = users_ratings_count[users_ratings_count >= rating_threshold]
# # filtering
# df_clean = df[df.isbn.isin(books_tokeep.index)]
# df_clean = df_clean[df_clean.user.isin(users_tokeep.index)]
# print(f"INPUT SIZE: {df.shape}")
# print(f"OUTPUT SIZE: {df_clean.shape}")
# def cal_size(df):
# r,c = df.shape
# size = r*c
# return size
# pc = cal_size(df_clean)/cal_size(df) * 100
# print(f"Data size reduced to: {pc:.2f}%")
# return df_clean
df_test = filterBooks(df,2)
df_test.shape
books_ratings_count = df.isbn.value_counts()
type(books_ratings_count)
books_ratings_count.head()
df.isin?
```
| github_jupyter |
# Using array_ops module in naplib
This notebook demonstrates some of the ways the array_ops module can be used to efficiently process data.
```
import numpy as np
import matplotlib.pyplot as plt
import naplib as nl
filepath = '../out_structs/out_struct_sample.mat'
out = nl.io.import_outstruct(filepath)
print(f'This out struct has data for {len(out)} trials')
print(f"Each trial has {out['resp'][0].shape[1]} channels.")
```
### Quickly perform operations across trials
In many cases, we may want to perform some array operation on all of our data, such as performing PCA or TSNE to reduce the 30 channels down to 2 dimensions. However, we want to fit these models using all of the trials' data, and then take the 2-dimensional data and split it back into the same trial lengths. To quickly do this, we can use the ```concat_apply``` function in naplib, which concatenates data across trials, performs some function on it, and then returns the result as a list of trials once again.
```
from naplib.array_ops import concat_apply
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca_resps = concat_apply(out['resp'], pca.fit_transform)
# Print the shapes of the first four trials before and after PCA
for n in range(4):
print(f"Response shape: {out['resp'][n].shape}, PCA shape: {pca_resps[n].shape}")
```
### Include a sliding window in the operations
Above we reduced 30 channels down to 2 at each time instant, but what if we want to consider a small time window of the responses, for example a 3-sample window of each electrode's response, and then reduce this 90 dimensions down to 2? To do this, we can combine the ```concat_apply``` with ```sliding_window```.
```
from naplib.array_ops import sliding_window
# The sliding_window function can be used to generate sliding windows of data
window_len = 3
window_key_idx = 1 # This produces a noncausal window centered around the given point. Note: window_key_idx=0 -> causal, window_key_idx=window_len-1 -> anticausal, 0<window_key_idx<window_len-1 -> noncausal
windowed_resps = [sliding_window(trial, window_len, window_key_idx=window_key_idx) for trial in out['resp']]
for n in range(4):
print(f"Response shape: {out['resp'][n].shape}, windowed response shape: {windowed_resps[n].shape}")
# now we can use concat_apply on the windowed responses to TSNE the 3*30 dimensions down to 2
windowed_resps = [x.reshape(x.shape[0], -1) for x in windowed_resps] # put the 3*30 dimensions together
pca = PCA(n_components=2)
pca_resps = concat_apply(windowed_resps, pca.fit_transform)
# Print the shapes of the first four trials before and after PCA
for n in range(4):
print(f"Windowed response shape: {windowed_resps[n].shape}, PCA shape: {pca_resps[n].shape}")
```
### Using custom functions with concat_apply
The ```concat_apply``` function takes as an argument a Callable function which can be called on an array to produce another array. If we want to do more complicated things, we can define the callable function ourselves. For example, we may want to perform PCA on a window of each channel independently, reducing the window_len dimensions of data for a single channel down to 2 dimensions.
```
# first, get the windowed responses for each channel, which are of shape (time, window_len, channels) for each trial
window_len = 10 # use a window size of 10 samples (100 ms in our data)
window_key_idx = 0 # here we are using a causal window
windowed_resps = [sliding_window(trial, window_len, window_key_idx=window_key_idx) for trial in out['resp']]
print(f'First trial windowed response shape: {windowed_resps[0].shape}\n')
# Define our custom Callable
# It must take a np.ndarray of shape (time, ...) as input and produce a np.ndarray with the same first dimension shape.
# Behind the scenes, the concat_apply with concatenate all the trials across the first dimension, pass them to this
# function, and then split the result back into the separate trials
def single_channel_PCA(arr):
# base on our windowing, the input arr will be of shape (time, 10, num_channels)
output_shape = (arr.shape[0], 2, arr.shape[-1])
results = np.empty(output_shape)
for channel in range(arr.shape[-1]):
pca = PCA(n_components=2)
results[:,:,channel] = pca.fit_transform(arr[:,:,channel])
return results
pca_resps_singlechannel = concat_apply(windowed_resps, single_channel_PCA)
# Print the shapes of the first four trials before and after PCA
for n in range(4):
print(f"Windowed response shape: {windowed_resps[n].shape}, PCA shape: {pca_resps_singlechannel[n].shape}")
```
| github_jupyter |
```
tanh_dropout = [0,0,0,0.1,0.1,0.1,0.25,0.25,0.25]
#filter_no = 10
tanh_kernel_size = [2,3,4,2,3,4,2,3,4]
tanh_highest_acc = [0.54,0.62,0.55,0.54,0.63,0.62,0.56,0.51,0.55]
relu_highest_acc = [0.45,0.47,0.55,0.56,0.57,0.58,0.53,0.51,0.6]
# the Wilcoxon signed-rank test
from scipy import stats
assert len(tanh_highest_acc)==len(relu_highest_acc)
difference=[t-r for t, r in zip(tanh_highest_acc,relu_highest_acc)]
stats.wilcoxon(difference)
print(difference)
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('CNN activation function')
ax.set_ylabel('Accuracy')
# Create the boxplot
bp = ax.boxplot([tanh_highest_acc,relu_highest_acc])
ax.set_xticklabels(['tanh','ReLU'])
plt.title('Highest accuracy obtained when using tanh or ReLU\nas the CNN activation function\n')
plt.show()
# non-parametric
#stats.ttest_rel(tanh_highest_acc, relu_highest_acc)
%matplotlib inline
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random
import numpy as np
fig = pyplot.figure()
ax = Axes3D(fig)
ax.set_xlabel('Dropout rate')
ax.set_ylabel('Kernel size')
ax.set_zlabel('Accuracy')
pyplot.yticks(np.arange(2, 4, step=1))
ax.scatter(tanh_dropout, tanh_kernel_size, tanh_highest_acc,color='blue',label='tanh')
ax.scatter(tanh_dropout, tanh_kernel_size, relu_highest_acc,color='red',label='relu')
pyplot.legend() #loc='upper right'
plt.title('Highest accuracy obtained when using tanh or ReLU\nas the CNN activation function\n')
pyplot.show()
#hyp_search_numbers.txt
dropout = [0, 0.1, 0, 0.1, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 0, 0, 0, 0, 0, 0, 0, 0.1, 0.1, 0, 0.1, 0, 0.25, 0.1, 0.25, 0.1, 0.25, 0.1, 0.5, 0.5, 0.1, 0.5, 0.1, 0.75, 0.1, 0.75, 0.75, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5, 0.5, 0, 0.1, 0.1, 0, 0.1, 0, 0.1, 0, 0.1, 0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
filter_number = [10, 10, 25, 25, 10, 25, 25, 10, 25, 10, 50, 10, 10, 100, 10, 150, 10, 50, 100, 10, 150, 10, 50, 10, 100, 10, 150, 10, 50, 100, 10, 150, 10, 50, 10, 100, 150, 10, 10, 10, 10, 10, 10, 10, 10, 10, 100, 100, 100, 100, 100, 100, 150, 150, 150, 150, 150, 150, 150, 150, 100, 100, 100, 150, 150, 100, 150, 100, 100, 150, 150, 150, 100, 150, 150, 150, 100, 150]
kernel_size = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 3, 1, 3, 1, 1, 4, 1, 4, 1, 2, 1, 2, 1, 3, 1, 1, 3, 1, 4, 1, 4, 1, 1, 2, 2, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 3, 4, 4, 2, 2, 3, 4, 3, 4, 4, 2, 1, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2, 4, 2, 3, 2, 4, 2, 3]
cnn_activation = ["relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "tanh", "relu", "relu", "tanh", "relu", "relu", "relu", "relu", "tanh", "relu", "relu", "relu", "tanh", "relu", "relu", "relu", "tanh", "relu", "relu", "relu", "relu", "tanh", "relu", "relu", "relu", "relu", "tanh", "relu", "tanh", "relu", "tanh", "relu", "tanh", "relu", "tanh", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu", "relu"]
neg_count = [29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 1, 1, 1, 1, 9, 1, 9, 99, 9, 9, 999, 9, 99, 99, 99, 99, 999, 999, 999, 999]
names = ["20190503-100500.txt","20190503-144659.txt","20190503-161737.txt","20190503-181718.txt","20190503-191543.txt","20190503-202330.txt","20190503-233729.txt","20190504-011613.txt","20190504-021727.txt","20190504-052808.txt","20190505-153800.txt","20190505-153848.txt","20190505-174116.txt","20190505-181113.txt","20190505-201227.txt","20190505-211215.txt","20190506-000553.txt","20190506-002611.txt","20190506-030043.txt","20190506-033335.txt","20190506-052442.txt","20190506-070225.txt","20190506-082520.txt","20190506-103247.txt","20190506-110322.txt","20190506-124709.txt","20190506-135549.txt","20190506-162308.txt","20190506-165926.txt","20190506-185601.txt","20190506-203018.txt","20190506-232331.txt","20190507-000743.txt","20190507-015531.txt","20190507-025310.txt","20190507-041624.txt","20190507-063626.txt","20190507-080430.txt","20190507-105559.txt","20190507-145039.txt","20190507-180441.txt","20190507-203954.txt","20190508-011409.txt","20190508-062339.txt","20190508-082824.txt","20190508-112229.txt","20190510-192416.txt","20190510-192418.txt","20190510-220925.txt","20190510-234729.txt","20190511-012228.txt","20190511-030541.txt","20190511-042412.txt","20190511-061436.txt","20190511-071111.txt","20190511-100527.txt","20190511-110112.txt","20190511-144241.txt","20190511-203101.txt","20190511-203302.txt","20190511-203510.txt","20190512-001031.txt","20190512-004813.txt","20190512-010725.txt","20190512-021918.txt","20190512-035405.txt","20190512-041920.txt","20190512-065329.txt","20190512-071937.txt","20190512-072417.txt","20190512-103829.txt","20190512-105919.txt","20190512-145035.txt","20190512-164841.txt","20190512-181335.txt","20190512-215815.txt","20190512-235957.txt","20190513-043637.txt"]
accuracy = [0.51, 0.55, 0.61, 0.65, 0.57, 0.63, 0.61, 0.5, 0.48, 0.2, 0.66, 0.54, 0.45, 0.76, 0.62, 0.72, 0.47, 0.71, 0.71, 0.55, 0.72, 0.55, 0.66, 0.54, 0.68, 0.56, 0.7, 0.63, 0.59, 0.68, 0.57, 0.63, 0.62, 0.55, 0.58, 0.57, 0.61, 0.56, 0.53, 0.51, 0.51, 0.55, 0.6, 0.41, 0.47, 0.45, 0.75, 0.72, 0.73, 0.74, 0.69, 0.72, 0.73, 0.75, 0.69, 0.7, 0.76, 0.75, 0.73, 0.68, 0.72, 0.66, 0.7, 0.69, 0.71, 0.73, 0.69, 0.69, 0.76, 0.72, 0.71, 0.76, 0.75, 0.77, 0.75, 0.79, 0.79, 0.78]
assert len(dropout)==len(filter_number) and len(kernel_size)==len(cnn_activation) and len(neg_count)==len(names)
assert len(dropout)==len(kernel_size) and len(kernel_size)==len(names)
plots = []
for i, name in enumerate(names):
if kernel_size[i]==1 and cnn_activation[i]=='relu' and neg_count[i]==29:
plots.append((dropout[i],filter_number[i],accuracy[i]))
%matplotlib inline
import matplotlib.pyplot as plt
# show that low dropout works better
plt.ylim(0,1)
plot_dropout = sorted(plots, key=lambda x: x[1])
colors = ['red','orange','green','blue','purple']
for num,colour in zip(sorted(list(set(filter_number))),colors):
plt.plot([do for do, fil, acc in plot_dropout if fil==num],[acc for do, fil, acc in plot_dropout if fil==num],color=colour,label=str(num)+' filters')
plt.xlabel('Dropout rate')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Highest accuracy obtained for various dropout rates\n')
plt.show()
%matplotlib inline
import matplotlib.pyplot as plt
# show that low dropout works better
plt.ylim(0,1)
plot_filter = sorted(plots, key=lambda x: x[0])
colors = ['red','orange','green','blue','purple']
for drpot,colour in zip(sorted(list(set(dropout))),colors):
plt.plot([fil for do, fil, acc in plot_dropout if do==drpot],[acc for do, fil, acc in plot_dropout if do==drpot],color=colour,label=str(int(drpot*100))+'% dropout')
plt.xlabel('Filter size')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Highest accuracy obtained for various number of filters\n')
plt.show()
plots_2 = []
for i, name in enumerate(names):
if dropout[i] in [0,0.1] and filter_number[i] in [100,150] and cnn_activation[i]=='relu' and neg_count[i]==29:
plots_2.append((dropout[i],filter_number[i],accuracy[i],kernel_size[i]))
%matplotlib inline
import matplotlib.pyplot as plt
# kernel size, x=kernel size, y=acc, lines=(dropout rate, filter number)
plt.xticks(np.arange(1, 4.2, step=1))
plt.ylim(0.65,0.80)
colors = ['red','orange','green','blue','purple']
count=0
print(plots_2)
for k in [100,150]:
for d in [0,0.1]:
pplot = sorted([(ks,acc) for do,fil,acc,ks in plots_2 if do==d if fil==k], key=lambda x: x[0])
plt.plot([ks for ks,acc in pplot],[acc for ks,acc in pplot],color=colors[count],label=str(int(d*100))+'% dropout, '+ str(k)+' kernels')
count += 1
plt.xlabel('Filter number')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Highest accuracy obtained by varying sizes of filter\n')
plt.show()
plots_2
%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
import random
import numpy as np
fig = plt.figure()
ax = Axes3D(fig)
ax.set_xlabel('Dropout rate')
ax.set_ylabel('Filter number size')
ax.set_zlabel('Accuracy')
plt.yticks(np.arange(2, 4, step=1))
#
ax.scatter(tanh_dropout, tanh_kernel_size, tanh_highest_acc,color='blue',label='tanh')
ax.scatter(tanh_dropout, tanh_kernel_size, relu_highest_acc,color='red',label='relu')
plt.legend() #loc='upper right'
plt.show()
!echo dropout
!cat ../gitig/hyp_search_numbers_all.txt | egrep dropout| grep -Po 'dropout=\S+'| perl -pe 's/dropout=//;s/\n//'
!echo
!echo filter_number
!cat ../gitig/hyp_search_numbers_all.txt | egrep dropout| grep -Po 'number=\S+'| perl -pe 's/number=//;s/\n//'
!echo
!echo kernel_size
!cat ../gitig/hyp_search_numbers_all.txt | egrep dropout| grep -Po 'size=\S+'| perl -pe 's/size=//;s/\n//'
!echo
!echo cnn_activation
!cat ../gitig/hyp_search_numbers_all.txt | egrep dropout| grep -Po 'activation=\S+'| perl -pe 's/activation=//;s/^/\"/;s/$/\"/;s/\n/,/'
!echo 'file name:'
!cat ../gitig/hyp_search_numbers_all.txt | egrep '.txt'| perl -pe 's/^/\"/;s/$/\"/;s/\n/,/'
!echo
!echo 'highest accuracy:'
!cat ../gitig/hyp_search_numbers_all.txt | egrep -B 1 '.txt'| grep -Po '^\d.\d+$'| perl -pe 's/\n/,/'
!echo neg_count
!cat ../gitig/hyp_search_numbers_all.txt | egrep neg_count | perl -pe 's/neg_count = //;s/^//;s/$/,/;s/\n//'
#hyp_search_numbers.txt
print('Manually add the last accuracy from the file!')
dropout = [0,0.1,0,0.1,0.25,0.25,0.5,0.5,0.75,0.75,0,0,0,0,0,0,0,0.1,0.1,0,0.1,0,0.25,0.1,0.25,0.1,0.25,0.1,0.5,0.5,0.1,0.5,0.1,0.75,0.1,0.75,0.75,0.25,0.25,0.25,0.25,0.25,0.25,0.5,0.5,0.5,0,0.1,0.1,0,0.1,0,0.1,0,0.1,0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
filter_number = [10,10,25,25,10,25,25,10,25,10,50,10,10,100,10,150,10,50,100,10,150,10,50,10,100,10,150,10,50,100,10,150,10,50,10,100,150,10,10,10,10,10,10,10,10,10,100,100,100,100,100,100,150,150,150,150,150,150,150,150,100,100,100,150,150,100,150,100,100,150,150,150,100,150,150,150,100,150,100,150,150,100,150,100,150,100,150,100,100,150,100,150,100,150]
kernel_size = [1,1,1,1,1,1,1,1,1,1,1,2,2,1,3,1,3,1,1,4,1,4,1,2,1,2,1,3,1,1,3,1,4,1,4,1,1,2,2,3,3,4,4,2,2,3,2,2,3,3,4,4,2,2,3,4,3,4,4,2,1,2,1,3,2,1,4,2,1,3,2,4,2,3,2,4,2,3,1,1,2,2,3,3,4,4,1,1,2,2,3,3,4,4]
cnn_activation = ["relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","tanh","relu","relu","tanh","relu","relu","relu","relu","tanh","relu","relu","relu","tanh","relu","relu","relu","tanh","relu","relu","relu","relu","tanh","relu","relu","relu","relu","tanh","relu","tanh","relu","tanh","relu","tanh","relu","tanh","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","relu","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh","tanh"]
neg_count = [29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,1,1,1,1,9,1,9,99,9,9,999,9,99,99,99,99,999,999,999,999,99,99,99,99,99,99,99,99,999,999,999,999,999,999,999,999]
names = ["20190503-100500.txt","20190503-144659.txt","20190503-161737.txt","20190503-181718.txt","20190503-191543.txt","20190503-202330.txt","20190503-233729.txt","20190504-011613.txt","20190504-021727.txt","20190504-052808.txt","20190505-153800.txt","20190505-153848.txt","20190505-174116.txt","20190505-181113.txt","20190505-201227.txt","20190505-211215.txt","20190506-000553.txt","20190506-002611.txt","20190506-030043.txt","20190506-033335.txt","20190506-052442.txt","20190506-070225.txt","20190506-082520.txt","20190506-103247.txt","20190506-110322.txt","20190506-124709.txt","20190506-135549.txt","20190506-162308.txt","20190506-165926.txt","20190506-185601.txt","20190506-203018.txt","20190506-232331.txt","20190507-000743.txt","20190507-015531.txt","20190507-025310.txt","20190507-041624.txt","20190507-063626.txt","20190507-080430.txt","20190507-105559.txt","20190507-145039.txt","20190507-180441.txt","20190507-203954.txt","20190508-011409.txt","20190508-062339.txt","20190508-082824.txt","20190508-112229.txt","20190510-192416.txt","20190510-192418.txt","20190510-220925.txt","20190510-234729.txt","20190511-012228.txt","20190511-030541.txt","20190511-042412.txt","20190511-061436.txt","20190511-071111.txt","20190511-100527.txt","20190511-110112.txt","20190511-144241.txt","20190511-203101.txt","20190511-203302.txt","20190511-203510.txt","20190512-001031.txt","20190512-004813.txt","20190512-010725.txt","20190512-021918.txt","20190512-035405.txt","20190512-041920.txt","20190512-065329.txt","20190512-071937.txt","20190512-072417.txt","20190512-103829.txt","20190512-105919.txt","20190512-145035.txt","20190512-164841.txt","20190512-181335.txt","20190512-215815.txt","20190512-235957.txt","20190513-043637.txt","20190513-175218.txt","20190513-175234.txt","20190513-210335.txt","20190513-213039.txt","20190514-005043.txt","20190514-022326.txt","20190514-045647.txt","20190514-063729.txt","20190514-085109.txt","20190514-102224.txt","20190514-152646.txt","20190514-163244.txt","20190514-195438.txt","20190514-233956.txt","20190515-001919.txt","20190515-073842.txt"]
accuracy = [0.51,0.55,0.61,0.65,0.57,0.63,0.61,0.5,0.48,0.2,0.66,0.54,0.45,0.76,0.62,0.72,0.47,0.71,0.71,0.55,0.72,0.55,0.66,0.54,0.68,0.56,0.7,0.63,0.59,0.68,0.57,0.63,0.62,0.55,0.58,0.57,0.61,0.56,0.53,0.51,0.51,0.55,0.6,0.41,0.47,0.45,0.75,0.72,0.73,0.74,0.69,0.72,0.73,0.75,0.69,0.7,0.76,0.75,0.73,0.68,0.72,0.66,0.7,0.69,0.71,0.73,0.69,0.69,0.76,0.72,0.71,0.76,0.75,0.77,0.75,0.79,0.79,0.78,0.76,0.75,0.76,0.76,0.79,0.78,0.73,0.78,0.8,0.8,0.76,0.75,0.76,0.8,0.78,0.78]
assert len(dropout)==len(filter_number) and len(kernel_size)==len(cnn_activation) and len(neg_count)==len(names)
assert len(dropout)==len(kernel_size) and len(kernel_size)==len(names)
plots = []
for i, name in enumerate(names):
#if neg_count[i]==29:
if cnn_activation[i]=='relu' and filter_number[i]==100 and kernel_size[i]==1 and dropout[i]==0:
plots.append((dropout[i],filter_number[i],kernel_size[i],cnn_activation[i],neg_count[i],accuracy[i]))
print(plots)
# and cnn_activation[i]=='relu' and neg_count[i]==29
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# negative count
# kernel size = 1
plots = []
for i, name in enumerate(names):
#if neg_count[i]==29:
if cnn_activation[i]=='relu' and filter_number[i]==100 and kernel_size[i]==1 and dropout[i]==0:
plots.append((dropout[i],filter_number[i],kernel_size[i],cnn_activation[i],neg_count[i],accuracy[i]))
print(plots)
#plt.xticks(np.arange(1, 4.2, step=1))
plt.ylim(0.65,0.80)
colors = ['red','orange','green','blue','purple']
count=0
print(plots)
pplot = sorted(plots, key=lambda x: x[4])
import math
plt.plot([math.log(neg) for do,f_no,f_size,act,neg,acc in pplot],[acc for do,f_no,f_size,act,neg,acc in pplot],color='orange',label='filter size=1')
# kernel size = 2
plots = []
for i, name in enumerate(names):
#if neg_count[i]==29:
if cnn_activation[i]=='relu' and filter_number[i]==100 and kernel_size[i]==2 and dropout[i]==0:
plots.append((dropout[i],filter_number[i],kernel_size[i],cnn_activation[i],neg_count[i],accuracy[i]))
print(plots)
pplot = sorted(plots, key=lambda x: x[4])
plt.plot([math.log(neg) for do,f_no,f_size,act,neg,acc in pplot],[acc for do,f_no,f_size,act,neg,acc in pplot],color='blue',label='filter size=2')
plt.xlabel('$Log_{10}$ (No. of negative instances sampled)')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Highest accuracy obtained by varying number of \nnegative instances sampled\n')
plt.show()
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plots = []
for i, name in enumerate(names):
#if neg_count[i]==29:
if cnn_activation[i]=='relu' and filter_number[i]==100 and kernel_size[i]==2 and dropout[i]==0:
plots.append((dropout[i],filter_number[i],kernel_size[i],cnn_activation[i],neg_count[i],accuracy[i]))
print(plots)
# and cnn_activation[i]=='relu' and neg_count[i]==29
#plt.xticks(np.arange(1, 4.2, step=1))
plt.ylim(0.65,0.80)
colors = ['red','orange','green','blue','purple']
count=0
print(plots)
pplot = sorted(plots, key=lambda x: x[4])
import math
plt.plot([math.log(neg) for do,f_no,f_size,act,neg,acc in pplot],[acc for do,f_no,f_size,act,neg,acc in pplot],color='blue')
plt.xlabel('$Log_10$ (No. of negative instances sampled)')
plt.ylabel('Accuracy')
plt.title('Highest accuracy obtained varying sizes of filter\n')
plt.show()
```
| github_jupyter |
People always ask: "can you randomize several times and use the proportion of selection, instead of
just one randomization"?
Let's try to figure this out.
```
import numpy as np
import regreg.api as rr
import seaborn as sns
%matplotlib inline
%load_ext rpy2.ipython
import matplotlib.pyplot as plt
import scipy.stats
import statsmodels.api as sm
from selection.distributions.discrete_family import discrete_family
ntries, sigma, q = 21, 0.5, 0.3
def algorithm(Z, ntries=ntries, q=q):
proportion = 0
for _ in range(ntries):
proportion += (Z + sigma * np.random.standard_normal() > 0)
proportion /= ntries
return proportion > q
def fit_algorithm(algorithm, B=10000, ntries=ntries, q=q):
Z = np.random.standard_normal(B) * 2
Y = np.array([algorithm(z, ntries=ntries, q=q) for z in Z])
%R -i Y,Z M = glm(Y ~ Z, family=binomial(link=probit))
coefM = %R coef(M)
return coefM
coefM = fit_algorithm(algorithm)
print(coefM)
def simulate(n=100, ntries=ntries, sigma=sigma, truth=0):
while True:
Z = np.random.standard_normal() + truth
if algorithm(Z, ntries, q=q):
return Z
simulate()
def weight(Z, ntries=ntries, sigma=0.5, q=q):
piZ = scipy.stats.norm.sf(-Z/sigma)
return scipy.stats.binom.sf(ntries * q, ntries, piZ)
def weight_fit(Z, coef=coefM):
linpred = coefM[0] + coefM[1] * Z
return scipy.stats.norm.cdf(linpred)
def weight_LD(Z, ntries=ntries, sigma=0.5, q=q):
phiZ = scipy.stats.norm.sf(-Z/sigma)
return np.exp(-ntries * (q * np.log(q / phiZ) + (1 - q) * np.log((1 - q) / (1 - phiZ)))) * (phiZ < q) + (phiZ >= q)
weight(0.2)
Z = np.linspace(-4, 4, 1001)
W = [weight_LD(z) for z in Z]
W0 = [weight(z) for z in Z]
W1 = [weight_fit(z) for z in Z]
plt.plot(Z, np.log(W))
plt.plot(Z, np.log(W0))
plt.plot(Z, np.log(W1))
selective_law = discrete_family(Z, W * scipy.stats.norm.pdf(Z))
selective_law0 = discrete_family(Z, W0 * scipy.stats.norm.pdf(Z))
selective_law1 = discrete_family(Z, W1 * scipy.stats.norm.pdf(Z))
def pivot(z, truth=0):
return 1 - selective_law.cdf(truth, z)
def pivot0(z, truth=0):
return 1 - selective_law0.cdf(truth, z)
def pivot1(z, truth=0):
return 1 - selective_law0.cdf(truth, z)
pivot(simulate())
P0 = []
for _ in range(1000):
P0.append((pivot(simulate()), pivot0(simulate()), pivot1(simulate())))
P0 = np.array(P0)
U = np.linspace(0, 1, 101)
plt.plot(U, sm.distributions.ECDF(P0[:,1])(U), 'r', label='True')
plt.plot(U, sm.distributions.ECDF(P0[:,0])(U), 'g', label='LD')
plt.plot(U, sm.distributions.ECDF(P0[:,2])(U), 'c', label='fit')
plt.plot([0, 1], [0, 1], 'k--')
plt.legend()
PA = []
for _ in range(1000):
PA.append((pivot(simulate(truth=1), truth=1),
pivot0(simulate(truth=1), truth=1),
pivot1(simulate(truth=1), truth=1)))
PA = np.array(PA)
U = np.linspace(0, 1, 101)
plt.plot(U, sm.distributions.ECDF(PA[:,1])(U), 'r', label='True')
plt.plot(U, sm.distributions.ECDF(PA[:,0])(U), 'g', label='LD')
plt.plot(U, sm.distributions.ECDF(P0[:,2])(U), 'c', label='fit')
plt.plot([0, 1], [0, 1], 'k--')
selective_law.equal_tailed_interval(-1)
Z0 = np.linspace(-2,2,501)
selective_law = discrete_family(Z, W * scipy.stats.norm.pdf(Z))
LU = []
for z in Z0:
selective_law = discrete_family(Z, W * scipy.stats.norm.pdf(Z))
LU.append(selective_law.equal_tailed_interval(z))
LU = np.array(LU)
LU0 = []
for z in Z0:
selective_law = discrete_family(Z, W0 * scipy.stats.norm.pdf(Z))
LU0.append(selective_law.equal_tailed_interval(z))
LU0 = np.array(LU0)
LU = []
for z in Z0:
selective_law = discrete_family(Z, W * scipy.stats.norm.pdf(Z))
LU.append(selective_law.equal_tailed_interval(z))
LU = np.array(LU)
LU1 = []
for z in Z0:
selective_law = discrete_family(Z, W1 * scipy.stats.norm.pdf(Z))
LU1.append(selective_law.equal_tailed_interval(z))
LU1 = np.array(LU1)
plt.plot(Z0, LU[:,0], 'g', label='LD')
plt.plot(Z0, LU[:,1], 'g')
plt.plot(Z0, LU0[:,0], 'r', label='true')
plt.plot(Z0, LU0[:,1], 'r')
plt.plot(Z0, LU1[:,0], 'c', label='fit')
plt.plot(Z0, LU1[:,1], 'c')
plt.legend()
coverage, ncover, truth = 0, 500, 0
lengths = []
for _ in range(ncover):
z = simulate(truth=truth)
selective_law = discrete_family(Z, W1 * scipy.stats.norm.pdf(Z))
L, U = selective_law.equal_tailed_interval(z)
coverage += (L < truth) * (U > truth)
lengths.append(U-L)
coverage / ncover, np.mean(lengths), np.std(lengths)
coverage, ncover, truth = 0, 500, 0.5
lengths = []
for _ in range(ncover):
z = simulate(truth=truth)
selective_law = discrete_family(Z, W1 * scipy.stats.norm.pdf(Z))
L, U = selective_law.equal_tailed_interval(z)
coverage += (L < truth) * (U > truth)
lengths.append(U-L)
coverage / ncover, np.mean(lengths), np.std(lengths)
coverage, ncover, truth = 0, 500, -3.
lengths = []
for _ in range(ncover):
z = simulate(truth=truth)
selective_law = discrete_family(Z, W1 * scipy.stats.norm.pdf(Z))
L, U = selective_law.equal_tailed_interval(z)
coverage += (L < truth) * (U > truth)
lengths.append(U-L)
coverage / ncover, np.mean(lengths), np.std(lengths)
```
# Increasing number of tries
```
ntries, sigma, q = 31, 1, 0.65
Z = np.linspace(-4, 4, 1001)
W = [weight_LD(z, ntries=ntries, sigma=sigma, q=q) for z in Z]
W0 = [weight(z, ntries=ntries, sigma=sigma, q=q) for z in Z]
selective_law = discrete_family(Z, W * scipy.stats.norm.pdf(Z))
selective_law0 = discrete_family(Z, W0 * scipy.stats.norm.pdf(Z))
def pivot(z, truth=0):
return 1 - selective_law.cdf(truth, z)
def pivot(z, truth=0):
return 1 - selective_law0.cdf(truth, z)
def algorithm(Z, ntries=ntries, q=q):
proportion = 0
for _ in range(ntries):
proportion += (Z + sigma * np.random.standard_normal() > 0)
proportion /= ntries
return proportion > q
def fit_algorithm(algorithm, B=10000, ntries=ntries, q=q):
Z = np.random.standard_normal(B) * 2
Y = np.array([algorithm(z, ntries=ntries, q=q) for z in Z])
%R -i Y,Z M = glm(Y ~ Z, family=binomial(link=probit))
coefM = %R coef(M)
return coefM
def weight_fit(Z, coef=coefM):
linpred = coefM[0] + coefM[1] * Z
return scipy.stats.norm.cdf(linpred)
coefM = fit_algorithm(algorithm)
def weight_fit(Z, coef=coefM):
linpred = coefM[0] + coefM[1] * Z
return scipy.stats.norm.cdf(linpred)
W1 = [weight_fit(z) for z in Z]
selective_law1 = discrete_family(Z, W1 * scipy.stats.norm.pdf(Z))
pivot(simulate())
P0 = []
truth = 0
for _ in range(1000):
P0.append((pivot(simulate(ntries=ntries, sigma=sigma, truth=truth)),
pivot0(simulate(ntries=ntries, sigma=sigma, truth=truth)),
pivot1(simulate(ntries=ntries, sigma=sigma, truth=truth)),
1-scipy.stats.norm.cdf(simulate(ntries=ntries, sigma=sigma, truth=truth) - truth)))
P0 = np.array(P0)
U = np.linspace(0, 1, 101)
plt.plot(U, sm.distributions.ECDF(P0[:,1])(U), 'r', label='True')
plt.plot(U, sm.distributions.ECDF(P0[:,0])(U), 'g', label='LD')
plt.plot(U, sm.distributions.ECDF(P0[:,2])(U), 'c', label='fit')
plt.plot(U, sm.distributions.ECDF(P0[:,3])(U), 'y', label='naive')
plt.plot([0, 1], [0, 1], 'k--')
plt.legend()
truth = -1
PA = []
for _ in range(1000):
PA.append((pivot(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
pivot0(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
pivot1(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
1-scipy.stats.norm.cdf(simulate(ntries=ntries, sigma=sigma, truth=truth) - truth)))
PA = np.array(PA)
U = np.linspace(0, 1, 101)
plt.plot(U, sm.distributions.ECDF(PA[:,1])(U), 'r', label='True')
plt.plot(U, sm.distributions.ECDF(PA[:,0])(U), 'g', label='LD')
plt.plot(U, sm.distributions.ECDF(PA[:,2])(U), 'c', label='fit', linewidth=2)
plt.plot(U, sm.distributions.ECDF(PA[:,3])(U), 'y', label='naive')
plt.plot([0, 1], [0, 1], 'k--')
plt.legend()
truth = -2
PA = []
for _ in range(1000):
PA.append((pivot(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
pivot0(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
pivot1(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
1-scipy.stats.norm.cdf(simulate(ntries=ntries, sigma=sigma, truth=truth) - truth)))
PA = np.array(PA)
U = np.linspace(0, 1, 101)
plt.plot(U, sm.distributions.ECDF(PA[:,1])(U), 'r', label='True')
plt.plot(U, sm.distributions.ECDF(PA[:,0])(U), 'g', label='LD')
plt.plot(U, sm.distributions.ECDF(PA[:,2])(U), 'c', label='fit', linewidth=2)
plt.plot(U, sm.distributions.ECDF(PA[:,3])(U), 'y', label='naive')
plt.plot([0, 1], [0, 1], 'k--')
plt.legend()
truth = 1
PA = []
for _ in range(1000):
PA.append((pivot(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
pivot0(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
pivot1(simulate(ntries=ntries, sigma=sigma, truth=truth), truth=truth),
1-scipy.stats.norm.cdf(simulate(ntries=ntries, sigma=sigma, truth=truth) - truth)))
PA = np.array(PA)
U = np.linspace(0, 1, 101)
plt.plot(U, sm.distributions.ECDF(PA[:,1])(U), 'r', label='True')
plt.plot(U, sm.distributions.ECDF(PA[:,0])(U), 'g', label='LD')
plt.plot(U, sm.distributions.ECDF(PA[:,2])(U), 'c', label='fit', linewidth=2)
plt.plot(U, sm.distributions.ECDF(PA[:,3])(U), 'y', label='naive')
plt.plot([0, 1], [0, 1], 'k--')
plt.legend()
```
##
| github_jupyter |
# Modelling the Epidemic Using SIR Model
The simples model for describing an epidemic is called **[SIR model][SIR]**, because it contains three variables:
* $S(t)$ - **Susceptible** - number of people who have the potential to be infected
* $I(t)$ - **Infected** - number of infected people
* $R(t)$ - **Recovered** - number of people who are non susceptible to infection (this includes the number of deceased people as well).
In this model, each variable is a function of time, and we can formulate the following differential equations that describe the behaviour of the model:
$$
\begin{array}{ll}
\frac{dS}{dt} & = -\frac{\beta SI}{N} \cr
\frac{dI}{dt} & = \frac{βSI}{N}−γI \cr
\frac{dR}{dt} & =γI
\end{array}
$$
This model depends on two parameters:
* β is the **contact rate**, and we assume that in a unit time each infected individual will come into contact with βN people. From those people, the proportion of susceptible people is S/N, thus the speed at which new infections occur is defined as $-\frac{βSI}{N}$.
* γ is the **recovery rate**, and the number 1/γ defines the number of days during which a person stays infected. Thus the term γI defines the speed, at which infected individuals are moved from being infected to recovered.
To model the epidemic, we need to solve those differential equations numerically with some initial conditions $S(0)$, $I(0)$ and $R(0)$. We will use the example from the followig book:
*Christian Hill. Learning Scientific Programming with Python. -- Cambridge University Press, ISBN: 9781107428225*, [available online](https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/)
```
import sys
!{sys.executable} -m pip install --user --quiet -r ../requirements.txt
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
```
## Modelling the Abstract Epidemic
First, we define parameters of a city:
```
# Population, N.
N = 12000000
# Initial Number of infected and recovered, I0 and R0.
I0, R0 = 100, 0
# The rest (S0) are potentially susceptible
S0 = N - I0 - R0
# Transmission coefficient beta and inverse mean time to recovery gamma (in 1/day).
beta, gamma = 0.2, 1./20
# Number of days to compute:
days = 160
```
Let's define compuational grid:
```
t = np.linspace(0, days, days)
```
First, let's define the right-hand-side of the differential equations. We assume that the vector `y` contains three values (S, I and R):
```
# The SIR model differential equations.
def deriv(y, t, N, beta, gamma):
S, I, R = y
dSdt = -beta * S * I / N
dIdt = beta * S * I / N - gamma * I
dRdt = gamma * I
return dSdt, dIdt, dRdt
```
We define the initial vector (boundary conditions) and solve the equation using `odeint`:
```
# Initial Vector
y0 = S0, I0, R0
# Solve SIR equations on time grid t
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T
```
Now let's plot the graph:
```
fig = plt.figure()
ax = fig.add_subplot(111, axisbelow=True)
ax.plot(S,label='Susceptible')
ax.plot(I,label='Infected')
ax.plot(R,label='Recovered')
ax.set_xlabel('Time /days')
ax.set_ylabel('Number (1000s)')
ax.yaxis.set_tick_params(length=0)
ax.xaxis.set_tick_params(length=0)
ax.grid(b=True, which='major', c='w', lw=2, ls='-')
legend = ax.legend()
legend.get_frame().set_alpha(0.5)
for spine in ('top', 'right', 'bottom', 'left'):
ax.spines[spine].set_visible(False)
plt.show()
print("R0={}".format(beta/gamma))
```
Below is the function that allows us to easily experiment with different parameters:
```
def experiment(beta, gamma, days):
t = np.linspace(0, days, days)
y0 = N-10000, 10000, 0
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T
plt.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible')
plt.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected')
plt.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered')
plt.title('R0={}'.format(beta/gamma))
plt.show()
experiment(0.085,1/20,720)
```
## Modelling Epidemic in Moscow
Let's try to model the epidemic in a real city of Moscow. We start by getting the real data:
```
import pandas as pd
df = pd.read_csv('../data/Data_Moscow.csv')
df[["Delta_Infected", "Delta_Recovered","Delta_Fatalities"]] = df[["Delta_Infected", "Delta_Recovered","Delta_Fatalities"]].apply(pd.to_numeric)
df["Date"] = pd.to_datetime(df["Date"],format="%d.%m.%Y")
df.head(5)
df["Infected"] = df["Delta_Infected"].cumsum()
df["Recovered"] = df["Delta_Recovered"].cumsum()
df["Fatalities"] = df["Delta_Fatalities"].cumsum()
df["Removed"] = df["Recovered"] + df["Fatalities"]
df["Active"] = df["Infected"] - df["Removed"]
df.plot('Date',['Infected','Removed'])
df.head(20)
```
Let's start with the date of 100 infected people. We create separate dataframe that starts from that date:
```
I0 = df.iloc[18]["Infected"]
start_date = df.iloc[18]["Date"]
df["Day"] = (df["Date"]-start_date).apply(lambda d : d.days)
ndf = df.iloc[18:].copy()
days = df['Day'].max()
ndf.head(1000)
```
Now let's create a function that will model the epidemic with given parameters and then return the value of loss:
```
t = np.linspace(0,days+1,days+1)
def sol(ndf,beta=beta,gamma=gamma,ndays=20):
y0 = N-I0,I0,0
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T
ndf.loc[:,"Infected_Pre"] = list(I+R)
ndf["Delta_Infected_Pre"] = ndf["Infected_Pre"].rolling(2).apply(lambda x: x.iloc[1]-x.iloc[0])
ndf["Diff"] = np.square(ndf["Delta_Infected"]-ndf["Delta_Infected_Pre"])
return ndf.iloc[:ndays]["Diff"].sum()
err = sol(ndf)
print("Error = ",err)
print("Beta = ",beta)
print("R0 = ",beta/gamma)
ndf.head()
```
## Optimize Loss to Get the Parameters of the Model
To get the actual parameters of the model, we need to optimize this function to minimize loss.
```
from scipy.optimize import minimize
from functools import partial
res = minimize(lambda x:sol(ndf,x[0],x[1],ndays=10),x0=[beta,gamma],method='powell')
print(res)
the_beta, the_gamma = res.x[0],res.x[1]
print("Computed values: beta={},1/gamma={},R0={}".format(the_beta,1/the_gamma,the_beta/the_gamma))
sol(ndf,the_beta,the_gamma)
ndf.plot('Date',['Delta_Infected','Delta_Infected_Pre'])
```
| github_jupyter |
# Quick Event analysis
Just to check the events and maybe delete some of them we will analyse it a bit
```
import pandas as pd
import dask.dataframe as dd
from dask.diagnostics import ProgressBar
import numpy as np
from pprint import pprint
from IPython.display import display
from typing import Dict, Union, List, Callable
from pathlib import Path
import lib.util
import lib.data_preparation
import lib.event_detection
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
from tqdm.notebook import tqdm
tqdm.pandas()
sns.set_style('darkgrid')
sns.set_context('notebook')
pd.set_option('max_columns', None)
folderpath = Path('data/UAH-DRIVESET-v1/')
df = lib.util.read_parquet_and_prepare(
filepath=Path(folderpath, 'data_event.parquet'),
col_reindex=None
)
display(df.head())
df.known_divisions
```
I test how to aggregrate with multilple columns and functions and make a util function for it:
"lib.util.agg_multilple()"
```
gb_corner = df.groupby('corner_event')
extent = lib.util.dask_agg_extent()
largest = lib.util.dask_agg_largest()
gb_corner_dyn = gb_corner[['speed', 'yr', 'gy', 'gx', 'beta']].agg(
[largest, extent, 'mean', 'max', 'min']
)
gb_corner_meta = gb_corner[['distance', 'dtime']].sum()
corner = gb_corner_dyn.join(gb_corner_meta)
corner = corner.rename(columns=lambda x: '_'.join(x) if isinstance(x, tuple) else x)
display(corner.head())
corner = lib.util.agg_multilple(
df.groupby('corner_event')[['speed', 'yr', 'gy', 'beta', 'gx', 'dtime', 'distance']],
{('speed', 'yr', 'gy', 'beta', 'gx'):[largest, extent, 'mean', 'max', 'min'],
('dtime', 'distance'):'sum'}
).compute()
display(corner.head())
straight = lib.util.agg_multilple(
df.groupby('straight_event')[['speed', 'gx', 'dtime', 'distance']],
{
('speed', 'gx'):[largest, extent, 'mean', 'max', 'min'],
('dtime', 'distance'):'sum'
}
).compute()
display(straight.head())
```
Some corner event statistics
```
sns.jointplot(x="yr_largest", y="speed_largest", data=corner, kind='hex')
sns.jointplot(x="gy_largest", y="speed_largest", data=corner, kind='hex')
sns.jointplot(x="gy_largest", y="gx_largest", data=corner, kind='hex')
```
Some straight event statistics
```
sns.jointplot(x="speed_mean", y="gx_largest", data=straight, kind='hex');
```
I will compress the data with their change point and trace the average corner event shape in YR
```
with ProgressBar():
df_corner_compress = df.map_partitions(
lambda x: lib.event_detection.change_points_event(x, 'corner_event')
).reset_index(drop=True).compute()
display(df_corner_compress.head())
df_corner_plot = df_corner_compress[['gy', 'dtime', 'corner_event']]\
.groupby('corner_event')\
.progress_apply(lib.event_detection.normalize_index, col='dtime')
plt.figure()
df_corner_plot.set_index('idx_norm')\
.groupby('corner_event')['gy']\
.plot(alpha=0.02, style='k', title='same_time')
plt.figure()
df_corner_plot.set_index('idx')\
.groupby('corner_event')['gy']\
.plot(alpha=0.02, style='k', title='each_time')
df_corner_plot = df_corner_compress[['gy', 'distance', 'corner_event']]\
.groupby('corner_event')\
.progress_apply(lib.event_detection.normalize_index, col='distance')
plt.figure()
df_corner_plot.set_index('idx_norm')\
.groupby('corner_event')['gy']\
.plot(alpha=0.02, style='k', title='same distance')
plt.figure()
df_corner_plot.set_index('idx')\
.groupby('corner_event')['gy']\
.plot(alpha=0.02, style='k', title='each distance')
```
## Application
Let's select some data for the GAN study now
```
df = lib.util.read_parquet_and_prepare(
filepath=Path(folderpath, 'data_event.parquet'),
col_reindex=None
)
df = df.categorize(columns=['corner_event', 'straight_event'])
absmax = lib.util.dask_agg_absmax()
corner_feature = df.groupby('corner_event')\
.agg({'dtime':'sum','gy':absmax})\
.compute()
plt.figure()
corner_feature['gy'].plot(kind='hist', title='GY abs max');
plt.figure()
corner_feature['dtime'].plot(kind='hist', title='time length', logy=True, bins=100);
```
So from previous 2D plots and the lineplot of all corner event, I select those with more movement and which their length/duration is not an outlier.
```
corner_select = (corner_feature['gy'] > 1) & (corner_feature['dtime'] < 20)
display(f'{corner_select.sum()} / {corner_select.shape[0]} events selected')
corner_feature[corner_select]['dtime'].plot(kind='hist', title='time length');
```
To avoid issues, I converted categorical data into known categorical (with static categories) with "df.categorize"
see [Dask Categorical](https://docs.dask.org/en/latest/dataframe-categoricals.html)
```
rem_cat = corner_select.index[~corner_select]
df['corner_select'] = df['corner_event'].cat.remove_categories(rem_cat)
df.head()
```
## Compression for each corner event selected
```
def get_compression(df):
compression = lib.data_preparation.calculate_change_point(
df=df.dropna(subset=['corner_select']),
groupby='corner_select',
col=['gy', 'gx']
)
df = df.join(compression.rename('compression'))
df['compression'] = df['compression'].fillna(False)
return df
with ProgressBar():
df = df.map_partitions(
get_compression,
meta=get_compression(df.head())
).compute()
df = df.dropna(subset=['corner_select'])
df = df.reset_index(drop=True)
df = df.sort_values(['corner_select', 'timestamp'])
df = df\
.groupby('corner_select')\
.progress_apply(lambda x: x.assign(
time_event=lambda df: df['dtime'].cumsum() - df['dtime'].iloc[0],
time_event_norm=lambda df: df['time_event'] / df['time_event'].iloc[-1],
dist_event=lambda df: df['distance'].cumsum() - df['distance'].iloc[0],
dist_event_norm=lambda df: df['dist_event'] / df['dist_event'].iloc[-1]
))
display(df.head())
display(f"{df['corner_select'].unique().shape[0]} events")
display(f"compression: {df['compression'].sum()/df['compression'].shape[0]}%")
display(f'{df.memory_usage(deep=True).sum()/10**6}MB of memory')
```
## Quick Sanity plots
```
plt.figure()
corner_select_time = df.groupby('corner_select')['dtime'].sum()
corner_select_time.plot(kind='hist')
plt.title('event time length')
plt.figure()
corner_select_time = df.groupby('corner_select')['compression'].agg(lambda x: x.sum() / x.shape[0])
corner_select_time.plot(kind='hist')
plt.title('compression per event')
df_analysis = df.groupby('corner_select')\
[['gx', 'gy']]\
.agg(['max', 'min'])\
.stack()
display(df_analysis.head())
display('min & max for GX/GY in each event')
sns.jointplot('gy', 'gx', df_analysis, kind='hex', cmap='jet')
def absmax(x):
return abs(max(x))
def extent(x):
return x.max() - x.min()
df_analysis_speed = df.groupby('corner_select').agg({
'gy':[absmax, extent],
'speed':'max'
})
df_analysis_speed.columns = df_analysis_speed.columns.to_flat_index()
df_analysis_speed = df_analysis_speed.rename(columns=lambda x: '_'.join(x))
display(df_analysis_speed.head(1))
display('speed and 2 values of GY, its extent or its absolute max')
_, axes = plt.subplots(1,2, figsize=(14, 8))
for k, x in enumerate(['gy_absmax', 'gy_extent']):
df_analysis_speed.plot.hexbin(x=x, y='speed_max', cmap='jet', gridsize=30, ax=axes[k])
```
The 2D histogram have been encapsulated under:
- "lib.analysis.plot_gx_gy()"
- "lib.analysis.plot_gy_speed()"
```
plt.figure()
df.set_index('time_event_norm')\
.groupby('corner_select')['gy']\
.plot(style='k', alpha=0.02)
plt.figure()
df.set_index('dist_event_norm')\
.groupby('corner_select')['gy']\
.plot(style='k', alpha=0.02)
df = df.groupby('corner_select')\
.progress_apply(
lambda x: lib.data_preparation.add_vd_signal(x, x['time_event'], method='integral')
)
display(df.head())
```
## Example of trajectory plot
```
n_example = 10
group_select = df['corner_select'].unique()
fig, axes = plt.subplots(ncols=n_example, figsize=(30, 10))
for k, group in enumerate(group_select[:n_example]):
df.query(f'corner_select=="{group}"')\
[['distx', 'disty']]\
.plot(x='disty', y='distx', ax=axes[k])
axes[k].set_aspect('equal')
df.to_parquet(Path(folderpath, 'data_ready.parquet'))
```
| github_jupyter |
This notebook uses the kdot accidents layer and AADT from the KDOT Khub publication database to calaulate crash rates using the equation
$$R = \frac{C x 100,000,000}{V x 365 x N x L}$$
The variables in this equation are:
R = crash rate for the road segment expressed as crashes per 100 million vehicle-miles of travel,
C = Total number of crashes in the study period
V = Traffic volumes using Average Annual Daily Traffic (AADT) volumes
N = Number of years of data
L = Length of the roadway segment in miles
https://safety.fhwa.dot.gov/local_rural/training/fhwasa1109/app_c.cfm
https://wfs.ksdot.org/arcgis_web_adaptor/rest/services/Transportation/Accidents/FeatureServer
```
projdb =r"C:\Users\kgonterwitz\OneDrive - City of Lawrence KS\Documents\ArcGIS\Projects\KDOT_CrashMaps\KDOT_CrashMaps.gdb"
#copy local Accidents data from KDOT Wfs for Douglas County to project database
with arcpy.EnvManager(scratchWorkspace=projdb, outputCoordinateSystem="PROJCS['NAD_1983_2011_KS_RCS_Zone_11',GEOGCS['GCS_NAD_1983_2011',DATUM['D_NAD_1983_2011',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],PARAMETER['False_Easting',11500000.0],PARAMETER['False_Northing',600000.0],PARAMETER['Central_Meridian',-95.25],PARAMETER['Standard_Parallel_1',39.1],PARAMETER['Scale_Factor',1.000033],PARAMETER['Latitude_Of_Origin',39.1],UNIT['Foot_US',0.3048006096012192]]", workspace=projdb):
arcpy.conversion.FeatureClassToFeatureClass("Accidents", projdb, "Accidents_DG", "ACC_COUNTY = 'DOUGLAS'", '#', '')
#copy local AADT data from Khub publiation geodatabase to project database
#selected are assigned routes to douglas county and routes longer than ten feet
#the minimum length threshold should be reviewed and possible raised
#if the minimum lenth threshod rises above 30 feet, raise spatial join parameter accordingly
arcpy.management.SelectLayerByAttribute("ev_AADT", "NEW_SELECTION", "RouteID LIKE '023%' And Shape_Length > 35", None)
with arcpy.EnvManager(outputCoordinateSystem="PROJCS['NAD_1983_2011_KS_RCS_Zone_11',GEOGCS['GCS_NAD_1983_2011',DATUM['D_NAD_1983_2011',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],PARAMETER['False_Easting',11500000.0],PARAMETER['False_Northing',600000.0],PARAMETER['Central_Meridian',-95.25],PARAMETER['Standard_Parallel_1',39.1],PARAMETER['Scale_Factor',1.000033],PARAMETER['Latitude_Of_Origin',39.1],UNIT['Foot_US',0.3048006096012192]]"):
arcpy.conversion.FeatureClassToFeatureClass("ev_AADT", projdb, "AADT_2019", "RouteID LIKE '023%'", '#', '')
#this cell outputs the calculated crash rate for mapping and review with ten years of crash history plus the current year
arcpy.analysis.SpatialJoin("AADT_2019", "Accidents_DG", "SJ_Acc_AADT_2019", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "36 Feet", '')
arcpy.management.CalculateField("SJ_Acc_AADT_2019", "CrashRateVolumetric", "!Join_Count! * 100000000/(!AADTCount! * 365 * 10 * (!ToMeasure!-!FromMeasure!))", "PYTHON3", '', "DOUBLE")
#pedestrian (and bicycle) related crashes included, 10 year average
arcpy.management.MakeFeatureLayer("Accidents_DG", "Accidents_BikePed", "ALL_PEDESTRIANS > 0 Or PEDESTRIAN_ACCS > 0 Or PEDAL_CYCLIST_ACCS > 0", None, "#")
arcpy.analysis.SpatialJoin("AADT_2019", "Accidents_BikePed", "SJ_AccBP_AADT_2019", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "36 Feet", '')
arcpy.management.CalculateField("SJ_AccBP_AADT_2019", "PedCrashRateVolumetric", "!Join_Count! * 100000000/(!AADTCount! * 365 * 10 * (!ToMeasure!-!FromMeasure!))", "PYTHON3", '', "DOUBLE")
```
compare rates to Kansas State Highway Safety Report
https://www.fhwa.dot.gov/tpm/reporting/state/safety.cfm?state=Kansas
the Performance measures in the HSIP are total fataility rate, and total serious injury rate, and non-motorized fatalities and serious injuries
The same calculate as above will calculate the rates with modfication of the input crash data and the modification of the rate unit to per hundred million vmt. The fatality rate will be the rate of fatality crashes not the number of fatalities per fatal crash.
```
#nonmotorized severe and fatal crash rates - 5 year history
arcpy.management.MakeFeatureLayer("Accidents_DG", "NonMotorized_Severe", "(ALL_PEDESTRIANS > 0 Or PEDESTRIAN_ACCS > 0 Or PEDAL_CYCLIST_ACCS > 0) AND ACC_YEAR IN ('2020', '2019', '2017', '2018', '2016') AND MOST_SERIOUS_INJURY IN ('D', 'F')", None, "#")
arcpy.analysis.SpatialJoin("AADT_2019", "NonMotorized_Severe", "SJ_AccNM_DF_AADT_2019", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "36 Feet", '')
arcpy.management.CalculateField("SJ_AccNM_DF_AADT_2019", "NonMotorized_Severe_P100M", "!Join_Count! * 100000000/(!AADTCount! * 365 * 5 * (!ToMeasure!-!FromMeasure!))", "PYTHON3", '', "DOUBLE")
# fatality crash rate per 100 Million VMT - 5 year
arcpy.management.MakeFeatureLayer("Accidents_DG", "FatalCrash", "MOST_SERIOUS_INJURY IN ('F') AND ACC_YEAR IN ('2020', '2019', '2017', '2018', '2016')", None, "#")
arcpy.analysis.SpatialJoin("AADT_2019", "FatalCrash", "SJ_AccF_AADT_2019", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "36 Feet", '')
arcpy.management.CalculateField("SJ_AccF_AADT_2019", "FatalityRate100VMT", "!Join_Count! * 100000000/(!AADTCount! * 365 * 5 * (!ToMeasure!-!FromMeasure!))", "PYTHON3", '', "DOUBLE")
# Serious Injury rate per 100 Million VMT (not including fatalities) - 5 year
arcpy.management.MakeFeatureLayer("Accidents_DG", "SeriousInjury", "MOST_SERIOUS_INJURY IN ('D') AND ACC_YEAR IN ('2020', '2019', '2017', '2018', '2016')", None, "#")
arcpy.analysis.SpatialJoin("AADT_2019", "SeriousInjury", "SJ_AccD_AADT_2019", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "36 Feet", '')
arcpy.management.CalculateField("SJ_AccD_AADT_2019", "SeriousInjuryRate100VMT", "!Join_Count! * 100000000/(!AADTCount! * 365 * 5 * (!ToMeasure!-!FromMeasure!))", "PYTHON3", '', "DOUBLE")
```
KDOT Numbers
to gain context about average crash rates based on KDOT data,
the following reports can be referenced:
https://www.ksdot.org/Assets/wwwksdotorg/bureaus/burTransPlan/prodinfo/Mileage_Travel/CountyMiles2017.pdf
1391 Miles of highway in douglas county in 2017
https://www.ksdot.org/Assets/wwwksdotorg/bureaus/burTransPlan/prodinfo/Mileage_Travel/CountyDVMT2017.pdf
daily VMT in douglas county (2017)- 2,983,274
https://www.ksdot.org/bureaus/burTransPlan/prodinfo/Mileage_Travel/MileTravel2017.asp
Total Highway Miles in Kansas (2017) - 142,054 miles
Average Daily Travel in Kansas (2017) = 88,248,910 Vehicle Miles
from KDOT Crash data online -
Douglas County:
Fatal Crashes - 43 between 2016-2020
Severe Injury Crashes - 108 between 2016-2020
Statewide there are about 380 fatal crashes per year
Statewide there are about 1000 serious injury crashes per year
```
print("DG Co Average AADT is " + str(2983274/1391))
print("Statewide Average AADT is " + str(88248910/142054))
print("DG Co Average 5 yr fatality rate is " + str(43*100000000/(2144*365*5*1391)))
print("DG Co Average 5 yr severe injury rate is " + str(108*100000000/(2144*365*5*1391)))
print("Statewide Average 5 yr fatality rate is " + str(380*5*100000000/(142054*365*5*621.25)))
print("Statewide Average 5 yr severe injury rate is " + str(1000*5*100000000/(142054*365*5*621.25)))
```
| github_jupyter |
# ES Module 4
Welcome back! As a reminder, last week, we went over creating and filtering tables. If you don't feel comfortable with tables yet, please go back and review them, as we'll continue to use them for this module.
This week, we'll be reviewing filtering and going over data visualizations.
For this module, please continue to work in pairs.
Before starting, run the cell below to load the data science libraries.
```
from datascience import *
import numpy as np
# These lines set up graphing capabilities.
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import warnings
warnings.simplefilter('ignore', FutureWarning)
```
## Filtering
As a reminder, here is the general form for filtering:
`some_table.where('column_name', predicate(arg))`
* `some_table` refers to the name of your table.
* `column_name` is the column you're referring to
* `predicate` is the predicate you're using (you can find the list of predicates by running the cell below).
* `arg` is the argument your predicate takes. More details about this too when you run the below cell.
```
functions = make_array('are.equal_to(Z)', 'are.above(x)', 'are.above_or_equal_to(x)', 'are.below(x)',
'are.below_or_equal_to(x)', 'are.between(x, y)', 'are.strictly_between(x, y)',
'are.between_or_equal_to(x, y)', 'are.containing(S)')
descriptions = make_array('Equal to Z', 'Greater than x', 'Greater than or equal to x', 'Below x',
'Less than or equal to x', 'Greater than or equal to x, and less than y',
'Greater than x and less than y', 'Greater than or equal to x, and less than or equal to y',
'Contains the string S')
predicates = Table().with_columns('Predicate', functions,
'Description', descriptions)
predicates
```
Below, load the data table `state_incarceration.csv`. We'll primarily be working with this data set.
```
# clean me
state_incarceration = Table.read_table('state_incarceration.csv')
state_incarceration
```
Now, run the following cell to clean the data.
```
# filtering
def string_to_int(val):
return int(val.replace(',', ''))
state_incarceration = state_incarceration.with_columns('State', state_incarceration.column('State'),
'Population', state_incarceration.column('Population'),
'Total Incarcerated', state_incarceration.apply(string_to_int, 'Total Incarcerated'),
'Incarcerated Males', state_incarceration.apply(string_to_int, 'Incarcerated Males'),
'Incarcerated Females', state_incarceration.apply(string_to_int, 'Incarcerated Females'))
state_incarceration
```
Now, in the following cell, filter `state_incarceration` so it only has states for which the total incarcerated population exceeds 50,000 and save it to `incarcerated_above_50000`.
```
#clean
incarcerated_above_50000 = state_incarceration.where('Total Incarcerated', are.above(50000))
incarcerated_above_50000.show()
```
What proportion (percentage) of states have a total incarcerated population of above 50000? Write your answer in the following cell.
```
incarcerated_above_50000.num_rows/state_incarceration.num_rows
```
Now, filter the data so it only has states where the population is below 5,000,000.
```
#clean
low_population = state_incarceration.where('Population', are.below(5000000))
low_population
```
Lastly, filter the data so it only contains states where the proportion of the incarcerated population over the population is more than 0.006.
(Hint: You may need to add another column to your table. To add another column to your table, use the following command:
`some_table.with_column('Column Name', corresponding_array)`
where `some_table` is a table that already exists).
```
# clean me
new_table = state_incarceration.with_column('Proportion', state_incarceration.column('Total Incarcerated') / state_incarceration.column('Population'))
new_table.where('Proportion', are.above(0.006)).set_format('Proportion', PercentFormatter)
```
Now, find the states in which the proportion of incarcerated females to incarcerated males is between 0.1 and 0.12, inclusive.
```
#clean me
f_to_m = state_incarceration.with_column('Proportion', state_incarceration.column('Incarcerated Females') / state_incarceration.column('Incarcerated Males'))
f_to_m.where('Proportion', are.between_or_equal_to(0.1, 0.12)).set_format('Proportion', PercentFormatter)
```
Good job! We have learned how to filter our data. Filtering is quite important since without it we wouldn't be able to work on our data. The datascience library gives you a tool to efficiently clean and convert your data, don't take it for granted (it's really a pain without it).
## Visualizations
Hurray for Visualizations! Now we'll be working on the showy part of data sciece.
Visualisation is a cruicial component of data science for great many reasons, but probably the most important reason is - It is the easiest way for humans to detect patterns and trends. We will start off with basic graphs such as bar charts and scatter plots, and advance to more complex graphs in the following modules so hang tight.
### Bar Charts
Bar charts are useful tools for visualizing categorical data. For example, the following bar chart shows information about the incarcerated population per state.
```
state_incarceration.bar('State', 'Total Incarcerated')
```
This visualization give us a lot of informations, for example we can instantly see here that there are 3 states with over 100000 incarcerated people, and all three of them rise above the 150000 lines too, which could indicate a much stricter policy than all other states.
Lets try to make this bar chart slightly more informative by focusin on specific states. Please plot a bar chart using the variable you created earlier `incarcerated_above_50000` so we can see some more trends.
```
incarcerated_above_50000.bar('State', 'Total Incarcerated')
```
This is slightly more convenient to the eye, but we are still overpopulating the graph. Lets try again, please make a new variable 'incarcerated_above_100000' which will hold all the states with more than 100,000 people.
```
incarcerated_above_100000 = state_incarceration.where('Total Incarcerated', are.above(100000))
```
Now lets plot and see. Plot a bar chart with the above variable in the next cell.
```
incarcerated_above_100000.bar('State', 'Total Incarcerated')
```
Now we can see all the states of interest. Were you suprised to see California as the second highest (by 3%) incarcerated state? So were we. Lets investigate!
### Scatter Plots
Scatter plots are useful in order to see the distribution of the data (If you don't know what that means exactly, don't worry you'll find out quite soon). Essentially, we wish to see how the data is `scattered`, thus we plot the every data point as a real point on a graph! Let's try:
```
state_incarceration.scatter('Population', 'Total Incarcerated')
```
Ain't that a beaute? The data is distributed in such a way (line) that allows us to comfortably infer that the increase in size correlates with increase in increase of incarcerated.
Let's try to get some more focused information. Please plot the scatter plot of `incarcerated_above_50000`.
```
incarcerated_above_50000.scatter('Population', 'Total Incarcerated')
```
In this case, plotting a more focused view of the data doesn't give us much more information. It is important to notice that scatter plots are good for getting intuition about a larger quantities of data or the total distribution of some data set you work on. Thus, we need another type of graph so really understand what's going on!
### Line Graph
Line graphs are great, they let you see exactly how the data points connect, implying how the information 'develops'. Here, as we already statee, there is a steady increase of inmates reltive to population size. Let's see how it develops more precisely:
```
state_incarceration.plot('Population', 'Total Incarcerated')
```
This is slightly weird shape indeed, but it still moves in a clear trend which assures our assertions. Still, we haven't gotten to the bottom of our previously stated conundrum, why is California up there? Please line plot the variable `incarcerated_above_50000` to get a more focused view once more.
```
incarcerated_above_50000.plot('Population', 'Total Incarcerated')
```
Huh, an interesting shape! What do you think it implies? Maybe a different approach could help.
Let's make a new variable called `high_population` with states that contain above 15000000 people and line plot the population against the total incarcerated!
```
high_population = state_incarceration.where('Population', are.above(15000000))
high_population.plot('Population', 'Total Incarcerated')
```
Well, the plot hasn't really changed much. Sometimes this happens, we can't deduct too much information with the tools we currently have, that's why we must learn more advanced tools in the next modules!
Before we finish, it is important that you notice one thing, if you look at the last `subline`, the one that has a negative slope (decrease in total incarcerated population), you can see that compared to Florida and Texas, California is relatively shy on the numbers of incarcerated people. Keep in mind though that it is only compared to those two states. We will investigate more in the following modules, see you next time!
| github_jupyter |
## Семинар 4
Всем привет и добро пожаловать на наш семинар по сбору новостей. Сегодня мы ставим себе следующие цели:
1. Собрать все заголовки статей на определенную тему, отфильтровав по дате с сайта делового издания "Коммерсант"
2. Узнать про хитрости, которые могут помочь в сборе данных
3. Провести самостоятельную практику с похожими заданиями
Для этого мы воспользуемся уже знакомыми Вам библиотеками requests и BeautifulSoup, а также познакомимся с новой – Selenium.
*Материал подготовила Анастасия Максимовская, хитрости позаимствованы у Филиппа Ульянкина. Вопросы по материалам можно писать мне в телеграм @anastasiyamaxx*
<img src="https://avatars.mds.yandex.net/get-zen_doc/3892121/pub_5f7ab7fb8d3ae5589bb054aa_5f7ab85061e6d41ef5615d94/scale_1200" width=700>
## Забираем заголовки с Коммерсанта
```
import requests
from bs4 import BeautifulSoup
```
Итак, начнем с простого – проверим, соберется ли у нас информация с главной страницы Коммерсанта или нужно искать специальные примочки.
```
url = 'https://www.kommersant.ru/'
response = requests.get(url)
response
```
`<Response [200]>` выглядит хорошо. Но имейте в виду – это не всегда значит, что мы получили нужную информацию. Например, когда я пишу этот семинар, главная страница выглядит так:
<img src='imgs/pic1.png' width=800>
Однако, если бы нам вылетел баннер (например, какое-нибудь предложение о скидке) или запрос в духе "уточните Ваше местоположение", или капча, то некоторый нужный текст с главной страницы в собранный html мог бы не попасть. Для этого можно либо глазами посмотреть на `response.content` или попробовать найти нужный элемент с помощью методов `.find()` (находит первый элемент, отвечающий условиям в скобочках) или `.find_all()` (находит все нужные элементы) из библиотеки `bs4`.
Сделаем деревце, по которому можно искать нужные элементы с помощью `bs4`:
```
tree = BeautifulSoup(response.content, 'html.parser')
```
Найдем главную новость в тексте. Для этого я перехожу на сайт Коммерсанта, навожу мышкой на заголовок "Роспотребнадзор сократил до суток максимальный срок выполнения исследования на коронавирус", щелкаю правой кнопкой мыши и нажимаю "Просмотреть код элемента". Вижу что-то такое:
<img src="imgs/pic2.png">
Попробуем найти этот элемент в нашем дереве!
```
tree.find_all('a', {'class': 'top_news_main__link link'})
```
Достанем только текст:
```
tree.find('a', {'class': 'top_news_main__link link'}).text.strip()
```
Однако, если Вы впервые заходите на сайт или откроете окно в режиме инкогните, то увидите, что при первом визите на сайт вылетает такой баннер:
<img src="imgs/pic3.png">
Также это можно заметить, полистав содержимое `tree`.
Конкретно в этом примере нам это не мешает вытащить заголовок. Однако, иногда такие всплывающие окна мешют собрать html с нужной информацией со страницы. Что же делать? Нам на помощь придет библиотека selenium – специальный инструмент для автоматизации действий браузера.
### Добавляем селениум :)
Библиотека `selenium` – набор инструментов для интерактивной работы в браузере средствами Python. Вообще Selenium ‒ это целый проект, в котором есть разные инструменты. Мы рассмотрим один из самых распространенных ‒ Selenium WebDriver, модуль, который позволяется Python встраиваться в браузер и работать в нем как пользователь: кликать на ссылки и кнопки, заполнять формы, выбирать опции в меню и прочее.
```
# через восклицательный знак обращемся к командной строке (на маке называется terminal)
# pip – менеджер пакетов для питона, который позволяет нам поставить библиотеку
!pip install selenium
!pip install webdriver-manager
```
Для того, чтобы воспользоваться библиотекой, нужно загрузить вебдрайвер для Вашего браузера. Подробнее можно почитать [в пункте 1.5 документации про установку](https://selenium-python.readthedocs.io/installation.html). План действий такой: качате драйвер – прописываете путь в переменной PATH – используете.
Но мы воспользуемся лайфхаком, чтобы не мучиться долго с установкой. Это библиотека `webdriver-manager`, которая скачает вебдрайвер за Вас. Подробнее в [документации](https://pypi.org/project/webdriver-manager/) (там же можно посмотреть код для других браузеров).
```
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
```
На Вашем компьютере откроется пустая страничка. Давайте перейдем на сайт Коммерсанта.
```
driver.get('https://www.kommersant.ru/')
```
Откройте эту страничку – теперь она не пустая :)
Следующим шагом, нам надо понять, как кликнуть на баннер так, чтобы он закрылся. Для этого нужно определить пусть к кнопке. Как и раньше, наводим мышку и кликаем "Просмотреть код".
<img src="imgs/pic4.png">
Теперь нужно сделать 2 действия кодом:
1. Помочь драйверу найти элемент
2. Кликнуть на него
Есть несколько способов указать пусть к элементу, они описаны [здесь](https://selenium-python.readthedocs.io/locating-elements.html) (попросите Вашего семинариста вкратце прокомментировать каждый).
Принципиальной разницы нам сейчас нет, предлагаю воспользоваться методом `driver.find_element_by_css_selector()`. Правой кнопокой мыши щелкните по коду нужной кнопки (принять или отклонить), выберите copy – copy selector.
<img src="imgs/pic5.png" width=500>
Сохраним селектор в переменную, найдем нужный элемент и кликнем. Иногда работает не с первого раза.
```
selector = "body > div.subscription-popup-v2.subscription-popup-v2_push-popup > div.subscription-popup-v2__inner-container > div.subscription-popup-v2__controls > div.subscription-popup-v2__reject"
ss = driver.find_elements_by_css_selector(selector)[0]
ss
ss.click()
```
Обновим страничку на всякий случай:
```
driver.refresh()
```
Давайте найдем главный заголовок еще одним способом. Сначала найдем элемент, помня имя класса (см. скрины выше), потом достанем его html код.
```
main_news = driver.find_element_by_class_name("top_news_main__name")
main_news
main_news.get_attribute('innerHTML')
small_tree = BeautifulSoup(main_news.get_attribute('innerHTML'), 'html.parser')
small_tree
small_tree.text.strip()
```
Ура, получили заголовок главной новости. Если он отличается от того, что на скрине, то нестрашно – новостные сайты быстро меняют статьи на главных страницах. Остальное можно достать по аналогии :)
Перейдем к более интересному – соберем все новости на определенную тему и срок.
Предлагаю попробовать собрать все новости, содержащие фразу "центральный банк" за период с 24 августа 2021 по текущий день. То есть, переводя это на программистский, нам нужно проделать следующие действия:
1. Найти окно поиска, кликнуть
2. Ввести в него ключевую фразу, нажать кнопку поиска
3. Нажать кнопку расширенный поиск
4. Найти кнопку, где изменяем дату начала поиска, выставить нужную нам
5. Собрать информацию
Давайте начнем :) В прошлый раз мы воспользовались поиском с помощью селектора `.find_element_by_css_selector()`. Теперь добавим немного разнообразия и сделаем поиском через XPath. Получить ее можно по старой схеме: наводим мышь на окно поиска – кликаем посмотреть код – правой кнопкой кликаем по мыши на выделенном коде – выбираем copy – copy xpath.
По шагам:
1. наводим мышь на окно поиска – кликаем посмотреть код
<img src="imgs/pic6.png" width=800 alt="aa">
2. правой кнопкой мыши кликаем на выделенном коде – выбираем copy – copy xpath
<img src="imgs/pic7.png" width=500>
```
"Гарик "Бульдог" Харламов"
"Гарик \"Бульдог\" Харламов"
'Гарик "Бульдог" Харламов'
# найденный по инструкции выше xpath к лупе
xpath_query = '//*[@id="js-navsearch-submit"]'
# находим окно поиска
search = driver.find_element_by_xpath(xpath_query)
# кликаем на него
search.click()
# найденный по инструкции выше xpath к окну поиска
xpath_query = '//*[@id="js-navsearch-query"]'
# находим окно поиска
search = driver.find_element_by_xpath(xpath_query)
# кликаем на него
search.click()
search_term = "центральный банк"
# печатаем фразу для поиска в окне для поиска
search.send_keys(search_term)
# нажимаем кнопку enter
search.send_keys(Keys.RETURN)
```
Если Вы посмотрите, что происходит в окне браузера, которым управляет селениум, то увидите, что окно поменялось и мы теперь в разделе поиска :)
<img src="imgs/pic8.png" width=500>
Нажимаем на кнопку расширенный поиск и выбираем дату.
Дальше мы все уже знаем. Откройте в соседней с ноутбуком вкладке сайт коммерсанта и доставайте оттуда нужные селекторы / xpath (неважно).
```
# находим селектор для кнопки расширенный поиск и нажимаем ее
selector2 = "body > main > div > div > section > div.grid-col.grid-col-s3 > form > div.ui-field_pack > label"
ext_search = driver.find_element_by_css_selector(selector2)
ext_search.click()
# находим селектор для поля ввода даты
selector3 = "body > main > div > div > section > div.grid-col.grid-col-s3 > form > div.ui-collapse.js-toggle-collapse.js-toggle-item.ui-collapse--show > section.simple_page_section.simple_page_section--form.js-search-settings > div.grid.ui-collapse.js-toggle-collapse.js-toggle-item.ui-collapse--show > div:nth-child(1) > div > input"
date = driver.find_element_by_css_selector(selector3)
```
Обратите внимание на картинку ниже – дата начала поиска по дефолту вбита в окошко, надо ее удалить.
<img src="imgs/pic9.png" width=500>
```
# удаляем введеный по дефолту текст в ячейке
date.send_keys(Keys.SHIFT, Keys.END, Keys.BACK_SPACE)
# вводим нужную дату и надижимаем enter
date_start = "24.08.2021"
date.send_keys(date_start)
date.send_keys(Keys.RETURN)
```
Ура, получили нужную выдачу! Попробуем перейти на следующую страничку.
```
# путь к кнопке следующая страница
xpath3 = "/html/body/main/div/div/section/div[1]/div[3]/a"
second_page = driver.find_element_by_xpath(xpath3)
second_page.click()
```
Посмотрим на адрес нашей странички:
```
driver.current_url
# driver.page_source
```
Обратите внимание на параметр `page=2`. Если мы будем менять номера, то будем перемещаться по всем страницам с заголовками, удовлетворяющим нашим условиям. Осталось написать функцию, которая будет доставать нужную информацию с одной странички, и запустить ее циклом для всех.
Начнем с того, как задать url. Обратите внимание на обратный слэш, это так называемый line continuation character. Он означает, что код продолжится на следующей строке. Также обратите внимание на букву f перед продолжением url-адреса на 3 строчке – она позваоляет мне подставить значение переменной `{page_num}` в середину строки.
```
page_num = 1
url = 'https://www.kommersant.ru/search/results?search_query='\
'%D1%86%D0%B5%D0%BD%D1%82%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9+%D0%B1'\
'%D0%B0%D0%BD%D0%BA&sort_type=1&search_full=1&time_range=2&'\
f'dateStart=2021-08-24&dateEnd=2021-10-15&page={page_num}'
url
```
Как обычно забираем HTML-разметку и делаем деревце бьютифул супом.
```
response2 = requests.get(url)
response2
tree_search = BeautifulSoup(response2.content, 'html.parser')
```
Уже знакомый по лекциям механизм поиска элемента по html разметке.
```
# находим заголовки
headers = tree_search.find_all('h2', {'class': 'uho__name rubric_lenta__item_name'})
len(headers)
headers[0]
```
Если достать из тега текст, то можно заметить, что есть пробелы / переходы на новые строки в начале и конце. Метод `.strip()` избавится от них.
```
headers[0].text
headers[0].text.strip()
# находим подзаголовки
subheaders = tree_search.find_all('h3', \
{'class': 'uho__subtitle rubric_lenta__item_subtitle'})
len(subheaders)
```
Подзаголовки есть не у всех новостей!
```
subheaders[0]
subheaders[0].text
subheaders[0].text.strip()
# напишем функцию, которая будет выдавать список из словарей
# в каждом словаре заголовок и описание
def get_page_info(page_num):
url = 'https://www.kommersant.ru/search/results?search_query='\
'%D1%86%D0%B5%D0%BD%D1%82%D1%80%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9+%D0%B1'\
'%D0%B0%D0%BD%D0%BA&sort_type=1&search_full=1&time_range=2&'\
f'dateStart=2021-08-24&dateEnd=2021-10-15&page={page_num}'
response = requests.get(url)
tree_search = BeautifulSoup(response.content, 'html.parser')
headers = tree_search.find_all('h2', \
{'class': 'uho__name rubric_lenta__item_name'})
subheaders = tree_search.find_all('h3', \
{'class': 'uho__subtitle rubric_lenta__item_subtitle'})
result = []
for i in range(len(headers)):
header = headers[i]
try:
subheader = subheaders[i]
d = {'article_header': header.text.strip(),
'article_subheader': subheader.text.strip()}
except:
d = {'article_header': header.text.strip(),
'article_subheader': ''}
result.append(d)
return result
all_data = []
for n in range(1, 14):
all_data.extend(get_page_info(n))
len(all_data)
```
Пока не очень знакомая библиотека сделает табличку из списка и позволит сохранить ее в файл.
```
import pandas as pd
df = pd.DataFrame(all_data)
df.head()
# сохранить в csv формат
# index=False сделает так, чтобы колонка с индексами не вогла в итоговый файл
df.to_csv('all_data.csv', index=False)
# сохранить в xlsx формат
df.to_excel('all_data.xlsx', index=False)
# не забываем закрыть браузер драйвером после завершения работы :)
driver.close()
```
## Что делать, если сервер разозлился?
* Вы решили собрать себе немного данных
* Сервер не в восторге от ковровой бомбардировки автоматическими запросами
* Error 403, 404, 504, $\ldots$
* Капча, требования зарегистрироваться
* Заботливые сообщения, что с вашего устройства обнаружен подозрительный трафик
<center>
<img src="https://raw.githubusercontent.com/hse-econ-data-science/eds_spring_2020/master/sem05_parsing/image/doge.jpg" width="450">
### а) быть терпеливым
* Слишком частые запросы раздражают сервер
* Ставьте между ними временные задержки
```
import time
time.sleep(3) # и пусть весь мир подождёт 3 секунды
```
### б) быть похожим на человека
Запрос нормального человека через браузер выглядит так:
<center>
<img src="https://raw.githubusercontent.com/hse-econ-data-science/eds_spring_2020/master/sem05_parsing/image/browser_get.png" width="600">
С ним на сервер попадает куча информации! Запрос от питона выглядит так:
<center>
<img src="https://raw.githubusercontent.com/hse-econ-data-science/eds_spring_2020/master/sem05_parsing/image/python_get.jpg" width="250">
Заметили разницу? Очевидно, что нашему скромному запросу не тягаться с таким обилием мета-информации, которое передается при запросе из обычного браузера. К счастью, никто нам не мешает притвориться человечными и пустить пыль в глаза сервера при помощи генерации фейкового юзер-агента. Библиотек, которые справляются с такой задачей, существует очень и очень много, лично мне больше всего нравится [fake-useragent.](https://pypi.org/project/fake-useragent/) При вызове метода из различных кусочков будет генерироваться рандомное сочетание операционной системы, спецификаций и версии браузера, которые можно передавать в запрос:
```
from fake_useragent import UserAgent
UserAgent().chrome
```
Например, https://knowyourmeme.com/ не захочет пускать к себе python и выдаст ошибку 403. Она выдается сервером, если он доступен и способен обрабатывать запросы, но по некоторым личным причинам отказывается это делать.
```
url = 'https://knowyourmeme.com/'
response = requests.get(url)
response
```
А если сгенерировать User-Agent, вопросов у сервера не возникнет.
```
response = requests.get(url, headers={'User-Agent': UserAgent().chrome})
response
```
__Другой пример:__ если захотите спарсить ЦИАН, он начнет вам выдавать капчу. Один из вариантов обхода: менять ip через тор. Однако на практически каждый запрос из-под тора, ЦИАН будет выдавать капчу. Если добавить в запрос `User_Agent`, то капча будет вылезать намного реже.
### в) общаться через посредников
<center>
<img src="https://raw.githubusercontent.com/hse-econ-data-science/eds_spring_2020/master/sem05_parsing/image/proxy.jpeg" width="400">
Посмотрим на свой ip-адрес без прокси.
```
r = requests.get('https://httpbin.org/ip')
print(r.json())
```
А теперь попробуем посмотреть, что будет если подключить прокси.
```
proxies = {
'http': '182.53.206.47:47592',
'https': '182.53.206.47:47592'
}
r = requests.get('https://httpbin.org/ip', proxies=proxies)
print(r.json())
```
Запрос работал немного подольше, ip адрес сменился. Большая часть проксей, которые вы найдёте работают криво. Иногда запрос идёт очень долго и выгоднее сбросить его и попробовать другую проксю. Это можно настроить опцией `timeout`. Например, так если сервер не будет отвечать секунду, код упадёт.
```
import requests
requests.get('http://www.google.com', timeout=1)
```
У requests есть довольно много разных интересных примочек. Посмотреть на них можно в [гайде из документации.](https://requests.readthedocs.io/en/master/user/advanced/)
__Где можно попытаться раздобыть списки прокси:__
* https://qna.habr.com/q/591069
* https://getfreeproxylists.blogspot.com/
* Большая часть бесплатных прокси обычно не работает. Пишите парсер, который будет собирать списки из проксей и пытаться применить их.
### г) уходить глубже
<center>
<img src="https://raw.githubusercontent.com/hse-econ-data-science/eds_spring_2020/master/sem05_parsing/image/tor.jpg" width="600">
Можно попытаться обходить злые сервера через тор. Есть аж несколько способов, но мы про это говорить не будем. Лучше подробно почитать в нашей статье на Хабре. Ссылка на неё в конце тетрадки. Ещё в самом начале была. А ещё в середине [наверняка есть.](https://habr.com/ru/company/ods/blog/346632/)
### Совместить всё?
1. Начните с малого
2. Если продолжает банить, накидывайте новые примочки
3. Каждая новая примочка бьёт по скорости
4. [Разные примочки для requests](http://docs.python-requests.org/en/v0.10.6/user/advanced/)
## Хитрости для парсинга :)
### Хитрость 1: Не стесняйтесь пользоваться `try-except`
Эта конструкция позволяет питону в случае ошибки сделать что-нибудь другое либо проигнорировать её. Например, мы хотим найти логарифм от всех чисел из списка:
```
from math import log
a = [1,2,3,-1,-5,10,3]
for item in a:
print(log(item))
```
У нас не выходит, так как логарифм от отрицательных чисел не берётся. Чтобы код не падал при возникновении ошибки, мы можем его немного изменить:
```
from math import log
a = [1,2,3,-1,-5,10,3]
for item in a:
try:
print(log(item)) # попробуй взять логарифм
except:
print('я не смог') # если не вышло, сознайся и работай дальше
```
__Как это использовать при парсинге?__ Интернет создаёт человек. У многих людей руки очень кривые. Предположим, что мы на ночь поставили парсер скачивать цены, он отработал час и упал из-за того, что на како-нибудь одной странице были криво проставлены теги, либо вылезло какое-то редкое поле, либо вылезли какие-то артефакты от старой версии сайта, которые не были учтены в нашем парсере. Гораздо лучше, чтобы код проигнорировал эту ошибку и продолжил работать дальше.
### Хитрость 2: pd.read_html
Если на странице, которую вы спарсили, среди тэгов `<tr>` и `<td>` прячется таблица, чаще всего можно забрать её себе без написания цикла, который будет перебирать все стобцы и строки. Поможет в этом `pd.read_html`. Например, вот так можно забрать себе [табличку с сайта ЦБ](https://cbr.ru/currency_base/daily/)
```
import pandas as pd
df = pd.read_html('https://cbr.ru/currency_base/daily/', header=-1)[0]
df.head()
```
Команда пытается собрать в массив все таблички c веб-страницы. Если хочется, можно сначала через bs4 найти нужную таблицу, а потом уже распарсить её:
```
resp = requests.get('https://cbr.ru/currency_base/daily/')
tree = BeautifulSoup(resp.content, 'html.parser')
# нашли табличку
table = tree.find_all('table', {'class' : 'data'})[0]
# распарсили её
df = pd.read_html(str(table), header=-1)[0]
df.head()
```
### Хитрость 3: используйте пакет tqdm
> Код уже работает час. Я вообще без понятия когда он закончит работу. Было бы круто узнать, сколько ещё ждать...
Если в вашей голове возникла такая мысль, пакет `tqdm` ваш лучший друг. Установите его: ```pip install tqdm```
```
from tqdm import tqdm_notebook
a = list(range(30))
# 30 раз будем спать по секунде
for i in tqdm_notebook(a):
time.sleep(1)
```
Мы обмотали тот вектор, по которому идёт цикл в `tqdm_notebook`. Это даёт нам красивую зелёную строку, которая показывает насколько сильно мы продвинулись по коду. Обматывайте свои самые большие и долгие циклы в `tqdm_notebook` и всегда понимайте сколько осталось до конца.
### Хитрость 4: распаралеливание
Если сервер не очень настроен вас банить, можно распаралелить свои запросы к нему. Самый простой способ сделать это — библиотека `joblib`.
```
from joblib import Parallel, delayed
from tqdm import tqdm_notebook
def simple_function(x):
return x**2
nj = -1 # паралель на все ядра
result = Parallel(n_jobs=nj)(
delayed(simple_function)(item) # какую функцию применяем
for item in tqdm_notebook(range(10))) # к каким объектам применям
# tqdm_notebook в последней строчке будет создавать зелёный бегунок с прогрессом
```
На самом деле это не самый эффективный способ паралелить в python. Он жрёт много памяти и работает медленнее, чем [стандартный multiprocessing.](https://docs.python.org/3/library/multiprocessing.html) Но зато две строчки, КАРЛ! Две строчки!
### Хитрость 5: selenium без браузера
Селениум можно настроить так, чтобы физически браузер не открывался.
```
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)
ref = 'http://google.com'
driver.get(ref)
driver.close()
```
### Ещё хитрости:
* __Сохраняйте то, что парсите по мере скачки!__ Прямо внутрь цикла запихните код, который сохраняет файл!
* Когда код упал в середине списка для скачки, не обязательно запускать его с самого начала. Просто сохраните тот кусок, который уже скачался и дозапустите код с места падения.
* Засовывать цикл для обхода ссылок внутрь функции - не самая хорошая идея. Предположим, что надо обойти $100$ ссылок. Функция должна вернуть на выход объекты, которые скачались по всему этому добру. Она берёт и падает на $50$ объекте. Конечно же то, что уже было скачано, функция не возвращает. Всё, что вы накачали - вы теряете. Надо запускать заново. Почему? Потому что внутри функции своё пространство имён. Если бы вы делали это циклом влоб, то можно было бы сохранить первые $50$ объектов, которые уже лежат внутри листа, а потом продолжить скачку.
* Можно ориентироваться на html-страничке с помощью `xpath`. Он предназначен для того, чтобы внутри html-странички можно было быстро находить какие-то элементы. [Подробнее можно почитать тут.](https://devhints.io/xpath)
* Не ленитесь листать документацию. Из неё можно узнать много полезных штук.
### Почиташки
* [Парсим мемы в python](https://habr.com/ru/company/ods/blog/346632/) - подробная статья на Хабре, по которой можно научиться ... парсить (ВНЕЗАПНО)
* [Тетрадки Ильи Щурова](https://github.com/ischurov/pythonhse) про python для анализа данных. В [лекции 9](https://nbviewer.jupyter.org/github/ischurov/pythonhse/blob/master/Lecture%209.ipynb) и [лекции 10](https://nbviewer.jupyter.org/github/ischurov/pythonhse/blob/master/Lecture%2010.ipynb) есть про парсеры.
* [Книга про парсинг](https://github.com/FUlyankin/Parsers/blob/master/Ryan_Mitchell_Web_Scraping_with_Python-_Collecting_Data_from_the_Modern_Web_2015.pdf) на случай если вам совсем скучно и хочется почитать что-то длинное и на английском
* [Продвинутое использование requests](https://2.python-requests.org/en/master/user/advanced/)
* [Перевод документации по selenium на русский на хабре](https://habr.com/ru/post/248559/)
* [Страничка с парсерами Филиппа Ульянкина](https://fulyankin.github.io/Parsers/) (на материалах которого основан список лайфхаков – спасибо!):
* [Более подробно про selenium](https://nbviewer.jupyter.org/github/FUlyankin/Parsers/blob/master/sems/3_Selenium_and_Tor/4.1%20Selenium%20.ipynb)
* [Немного устаревший гайд по парсинг вконтакте](https://nbviewer.jupyter.org/github/FUlyankin/ekanam_grand_research/blob/master/0.%20vk_parser_tutorial.ipynb)
* [Немного устаревший гайд про google maps](https://nbviewer.jupyter.org/github/FUlyankin/Parsers/blob/master/Parsers%20/Google_maps_API.ipynb)
## Практика
Основная цель практики – убедиться, что Вам понятен код с семинара. Попробуйте собрать информацию по аналогии с сайта Коммерсанта. Фразу для поиска оставляем на Ваш выбор, срок – за последний месяц.
| github_jupyter |
# Dirichlet
This notebook illustrates the classification of the nodes of a graph by the [Dirichlet problem](https://en.wikipedia.org/wiki/Dirichlet_problem), based on the labels of a few nodes.
```
from IPython.display import SVG
import numpy as np
from sknetwork.data import karate_club, painters, movie_actor
from sknetwork.classification import DirichletClassifier, BiDirichletClassifier
from sknetwork.visualization import svg_graph, svg_digraph, svg_bigraph
```
## Graphs
```
graph = karate_club(metadata=True)
adjacency = graph.adjacency
position = graph.position
labels_true = graph.labels
```
**Classification**
```
seeds = {i: labels_true[i] for i in [0, 33]}
diffusion = DirichletClassifier()
labels_pred = diffusion.fit_transform(adjacency, seeds)
precision = np.round(np.mean(labels_pred == labels_true), 2)
precision
image = svg_graph(adjacency, position, labels=labels_pred, seeds=seeds)
SVG(image)
```
**Soft classification**
```
membership = diffusion.membership_
scores = membership[:,1].toarray().ravel()
image = svg_graph(adjacency, position, scores=scores, seeds=seeds)
SVG(image)
```
## Digraphs
```
graph = painters(metadata=True)
adjacency = graph.adjacency
position = graph.position
names = graph.names
```
**Classification**
```
rembrandt = 5
klimt = 6
cezanne = 11
seeds = {cezanne: 0, rembrandt: 1, klimt: 2}
diffusion = DirichletClassifier()
labels = diffusion.fit_transform(adjacency, seeds)
image = svg_digraph(adjacency, position, names, labels, seeds=seeds)
SVG(image)
```
**Soft classification**
```
membership = diffusion.membership_
scores = membership[:,0].toarray().ravel()
image = svg_digraph(adjacency, position, names=names, scores=scores, seeds=[cezanne])
SVG(image)
```
## Bigraphs
```
graph = movie_actor(metadata=True)
biadjacency = graph.biadjacency
names_row = graph.names_row
names_col = graph.names_col
```
**Classification**
```
inception = 0
drive = 3
budapest = 8
seeds_row = {inception: 0, drive: 1, budapest: 2}
bidiffusion = BiDirichletClassifier()
bidiffusion.fit(biadjacency, seeds_row)
labels_row = bidiffusion.labels_row_
labels_col = bidiffusion.labels_col_
image = svg_bigraph(biadjacency, names_row, names_col, labels_row, labels_col, seeds_row=seeds_row)
SVG(image)
```
**Soft classification**
```
membership_row = bidiffusion.membership_row_
membership_col = bidiffusion.membership_col_
scores_row = membership_row[:,1].toarray().ravel()
scores_col = membership_col[:,1].toarray().ravel()
image = svg_bigraph(biadjacency, names_row, names_col, scores_row=scores_row, scores_col=scores_col,
seeds_row=seeds_row)
SVG(image)
```
| github_jupyter |
# Huggingface SageMaker-SDK - BERT Japanese example
1. [Introduction](#Introduction)
2. [Development Environment and Permissions](#Development-Environment-and-Permissions)
1. [Installation](#Installation)
2. [Permissions](#Permissions)
3. [Processing](#Preprocessing)
1. [Tokenization](#Tokenization)
2. [Uploading data to sagemaker_session_bucket](#Uploading-data-to-sagemaker_session_bucket)
4. [Fine-tuning & starting Sagemaker Training Job](#Fine-tuning-\&-starting-Sagemaker-Training-Job)
1. [Creating an Estimator and start a training job](#Creating-an-Estimator-and-start-a-training-job)
2. [Estimator Parameters](#Estimator-Parameters)
3. [Download fine-tuned model from s3](#Download-fine-tuned-model-from-s3)
4. [Attach to old training job to an estimator ](#Attach-to-old-training-job-to-an-estimator)
5. [_Coming soon_:Push model to the Hugging Face hub](#Push-model-to-the-Hugging-Face-hub)
# Introduction
このnotebookは[HuggingFaceのSageMaker example](https://github.com/huggingface/notebooks/tree/master/sagemaker)内の以下3つのnotebookの内容を統合し、日本語データで動作する様に変更を加えたものです。
- 01_getting_started_pytorch
- 05_spot_instances
- 06_sagemaker_metrics
このデモでは、AmazonSageMakerのHuggingFace Estimatorを使用してSageMakerのトレーニングジョブを実行します。
トレーニングジョブ(`./scripts/train.py`)では`HuggingFace transformers`の`Trainer`クラスを使用してテキストの二値分類を実行します。
トレーニングジョブの実行にはスポットインスタンスを使用します。
_**NOTE: このデモは、SagemakerNotebookインスタンス、Sagemaker Studio、ローカル環境で実行できます**_
# Development Environment and Permissions
## Installation
このNotebookはSageMakerの`conda_pytorch_p36`カーネルを利用しています。
日本語処理のため、`transformers`ではなく`transformers[ja]`をインスールします。
_Note: 異なるカーネルを使用する場合はpytorchのインストールも必要になります。_
```
!pip install --upgrade pip
!pip install "sagemaker>=2.48.1" "transformers[ja]==4.6.1" "datasets[s3]==1.6.2" --upgrade
```
## Permissions
ローカル環境でSagemakerを使用する場合はSagemakerに必要な権限を持つIAMロールにアクセスする必要があります。[こちら](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html)を参照してください
```
import sagemaker
sess = sagemaker.Session()
# sagemaker session bucket -> used for uploading data, models and logs
# sagemaker will automatically create this bucket if it not exists
sagemaker_session_bucket=None
if sagemaker_session_bucket is None and sess is not None:
# set to default bucket if a bucket name is not given
sagemaker_session_bucket = sess.default_bucket()
role = sagemaker.get_execution_role()
sess = sagemaker.Session(default_bucket=sagemaker_session_bucket)
print(f"sagemaker role arn: {role}")
print(f"sagemaker bucket: {sess.default_bucket()}")
print(f"sagemaker session region: {sess.boto_region_name}")
```
# データの準備
Amazon の商品レビューデータセットは[Registry of Open Data on AWS](https://registry.opendata.aws/)で公開されており、 以下からダウンロード可能です。
このノートブックでは、日本語のデータセットをダウンロードします。
- データセットの概要
https://registry.opendata.aws/amazon-reviews/
- 日本語のデータセット(readme.htmlからたどることができます)
https://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_multilingual_JP_v1_00.tsv.gz
以下では、データをダウンロードして解凍 (unzip) します。
```
import urllib.request
import os
import gzip
import shutil
download_url = "https://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_multilingual_JP_v1_00.tsv.gz"
dir_name = "data"
file_name = "amazon_review.tsv.gz"
tsv_file_name = "amazon_review.tsv"
file_path = os.path.join(dir_name,file_name)
tsv_file_path = os.path.join(dir_name,tsv_file_name)
os.makedirs(dir_name, exist_ok=True)
if os.path.exists(file_path):
print("File {} already exists. Skipped download.".format(file_name))
else:
urllib.request.urlretrieve(download_url, file_path)
print("File downloaded: {}".format(file_path))
if os.path.exists(tsv_file_path):
print("File {} already exists. Skipped unzip.".format(tsv_file_name))
else:
with gzip.open(file_path, mode='rb') as fin:
with open(tsv_file_path, 'wb') as fout:
shutil.copyfileobj(fin, fout)
print("File uznipped: {}".format(tsv_file_path))
```
# Preprocessing
ダウンロードしたデータには学習に不要なデータや直接利用できないデータもあります。以下の前処理で利用できるようにします。
1. ダウンロードしたデータには不要なデータも含まれているので削除し、2クラス分類 (positive が 1, negative が 0)となるようにデータを加工します。
2. 学習データ、テストデータに分けます。
今回利用しないデータは以下の2つです。必要なデータだけ選んで保存します。
- star_rating (評価)とreview_body (レビューのテキストデータ)以外のデータ
- star_rating が 3 のデータ (positive でも negative でもないデータ)
また、評価が1, 2 のデータはラベル 0 (negative) に、評価が4, 5 のデータはラベル 1 (positive) にします。
```
import pandas as pd
df = pd.read_csv(tsv_file_path, sep ='\t')
df_pos_neg = df.loc[:, ["star_rating", "review_body"]]
df_pos_neg = df_pos_neg[df_pos_neg.star_rating != 3]
df_pos_neg.loc[df_pos_neg.star_rating < 3, "star_rating"] = 0
df_pos_neg.loc[df_pos_neg.star_rating > 3, "star_rating"] = 1
print(df_pos_neg.shape)
df_pos_neg.head()
# デモ用にサンプリングしてデータを小さくします
df_pos_neg = df_pos_neg.sample(20000, random_state=42)
from sklearn.model_selection import train_test_split
train, test = train_test_split(df_pos_neg, test_size=0.2, random_state=42)
train = train.reset_index(drop=True)
test = test.reset_index(drop=True)
# 後の加工のため、データをDataFrameからHuggingface Datasetsクラスに変換します
import datasets
train = datasets.Dataset.from_pandas(train)
test = datasets.Dataset.from_pandas(test)
print(train)
print(test)
```
## Tokenization
`review_body`は文章テキストのままだとモデルの学習ができないため、テキストを意味のある単位で分割(トークナイズ)した上で機械学習モデルで扱える様に数値に変換します。
HuggingFaceのTransformersでは、東北大学が公開している[日本語BERT](https://github.com/cl-tohoku/bert-japanese)の学習済みモデル、トークナイザが使用できるため、このデモではこちらを使用します。
```
#from transformers import BertJapaneseTokenizer
from transformers import AutoTokenizer
tokenizer_name = 'cl-tohoku/bert-base-japanese-whole-word-masking'
# download tokenizer
#tokenizer = BertJapaneseTokenizer.from_pretrained(tokenizer_name)
# download tokenizer
tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
# tokenizer helper function
def tokenize(batch):
return tokenizer(batch['review_body'], max_length=256, padding='max_length', truncation=True)
```
試しに一つのテキストでトークナイズと数値変換(エンコード)してみます。
このデモで使用している`cl-tohoku/bert-base-japanese-whole-word-masking`は32,000個の単語と数値のマッピングがあり、[CLS] = 2, 'ハワイ' = 6166, '##アン' = 1028..., [SEP] = 3などとテキストを数値に変換します。
```
print('Original: ', train[0]['review_body'])
print('\nTokenize: ', tokenizer.tokenize(train[0]['review_body']))
print('\nEncode: ', tokenizer.encode(train[0]['review_body']))
```
この処理をデータ全体に適用します
```
# tokenize dataset
train_dataset = train.map(tokenize, batched=True, batch_size=len(train))
test_dataset = test.map(tokenize, batched=True, batch_size=len(test))
print(train_dataset)
print(test_dataset)
train_dataset[0]
```
train_dataset, test_datasetをトレーニングに使用できる様に少し修正します。
- `star_rating`を`labels`に変更します(`Trainer`クラスのデフォルトでは`labels`をターゲットカラム名として認識します)。
- 学習に使用するカラムをpytorchのフォーマットにします。
```
# set format for pytorch
train_dataset.rename_column_("star_rating", "labels")
train_dataset.set_format('torch', columns=['input_ids', 'attention_mask', 'token_type_ids', 'labels'])
test_dataset.rename_column_("star_rating", "labels")
test_dataset.set_format('torch', columns=['input_ids', 'attention_mask', 'token_type_ids', 'labels'])
```
## Uploading data to `sagemaker_session_bucket`
`datasets`の`FileSystem` [Integration](https://huggingface.co/docs/datasets/filesystems.html)を使用してS3へデータをアップロードします。
```
import botocore
from datasets.filesystems import S3FileSystem
s3_prefix = 'samples/datasets/amazon-review'
s3 = S3FileSystem()
# save train_dataset to s3
training_input_path = f's3://{sess.default_bucket()}/{s3_prefix}/train'
train_dataset.save_to_disk(training_input_path, fs=s3)
# save test_dataset to s3
test_input_path = f's3://{sess.default_bucket()}/{s3_prefix}/test'
test_dataset.save_to_disk(test_input_path, fs=s3)
training_input_path = f's3://{sess.default_bucket()}/{s3_prefix}/train'
test_input_path = f's3://{sess.default_bucket()}/{s3_prefix}/test'
# 以下のpathにdatasetがuploadされました
print(training_input_path)
print(test_input_path)
```
# Fine-tuning & starting Sagemaker Training Job
`HuggingFace`のトレーニングジョブを作成するためには`HuggingFace` Estimatorが必要になります。
Estimatorは、エンドツーエンドのAmazonSageMakerトレーニングおよびデプロイタスクを処理します。 Estimatorで、どのFine-tuningスクリプトを`entry_point`として使用するか、どの`instance_type`を使用するか、どの`hyperparameters`を渡すかなどを定義します。
```python
huggingface_estimator = HuggingFace(
entry_point='train.py',
source_dir='./scripts',
base_job_name='huggingface-sdk-extension',
instance_type='ml.p3.2xlarge',
instance_count=1,
transformers_version='4.4',
pytorch_version='1.6',
py_version='py36',
role=role,
hyperparameters={
'epochs': 1,
'train_batch_size': 32,
'model_name':'distilbert-base-uncased'
}
)
```
SageMakerトレーニングジョブを作成すると、SageMakerは`huggingface`コンテナを実行するために必要なec2インスタンスの起動と管理を行います。
Fine-tuningスクリプト`train.py`をアップロードし、`sagemaker_session_bucket`からコンテナ内の`/opt/ml/input/data`にデータをダウンロードして、トレーニングジョブを実行します。
```python
/opt/conda/bin/python train.py --epochs 1 --model_name distilbert-base-uncased --train_batch_size 32
```
`HuggingFace estimator`で定義した`hyperparameters`は、名前付き引数として渡されます。
またSagemakerは、次のようなさまざまな環境変数を通じて、トレーニング環境に関する有用なプロパティを提供しています。
* `SM_MODEL_DIR`:トレーニングジョブがモデルアーティファクトを書き込むパスを表す文字列。トレーニング後、このディレクトリのアーティファクトはモデルホスティングのためにS3にアップロードされます。
* `SM_NUM_GPUS`:ホストで使用可能なGPUの数を表す整数。
* `SM_CHANNEL_XXXX`:指定されたチャネルの入力データを含むディレクトリへのパスを表す文字列。たとえば、HuggingFace estimatorのfit呼び出しで`train`と`test`という名前の2つの入力チャネルを指定すると、環境変数`SM_CHANNEL_TRAIN`と`SM_CHANNEL_TEST`が設定されます。
このトレーニングジョブをローカル環境で実行するには、`instance_type='local'`、GPUの場合は`instance_type='local_gpu'`で定義できます。
_Note:これはSageMaker Studio内では機能しません_
```
!pygmentize ./scripts/train.py
```
## Creating an Estimator and start a training job
```
from sagemaker.huggingface import HuggingFace
num_labels = 2
# hyperparameters, which are passed into the training job
hyperparameters={
'epochs': 3,
'train_batch_size': 32,
'learning_rate' : 5e-5,
'model_name':'cl-tohoku/bert-base-japanese-whole-word-masking',
'output_dir':'/opt/ml/checkpoints',
'num_labels': num_labels,
}
# s3 uri where our checkpoints will be uploaded during training
job_name = "using-spot"
checkpoint_s3_uri = f's3://{sess.default_bucket()}/{job_name}/checkpoints'
print(checkpoint_s3_uri)
```
トレーニングジョブのメトリック抽出に使用する正規表現ベースの定義を作成します。
```
# metric definition to extract the results
metric_definitions=[
{'Name': 'loss', 'Regex': "'loss': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'learning_rate', 'Regex': "'learning_rate': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_loss', 'Regex': "'eval_loss': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_accuracy', 'Regex': "'eval_accuracy': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_f1', 'Regex': "'eval_f1': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_precision', 'Regex': "'eval_precision': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_recall', 'Regex': "'eval_recall': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_runtime', 'Regex': "'eval_runtime': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'eval_samples_per_second', 'Regex': "'eval_samples_per_second': ([0-9]+(.|e\-)[0-9]+),?"},
{'Name': 'epoch', 'Regex': "'epoch': ([0-9]+(.|e\-)[0-9]+),?"}
]
huggingface_estimator = HuggingFace(
entry_point='train.py',
source_dir='./scripts',
instance_type='ml.p3.2xlarge',
instance_count=1,
base_job_name=job_name,
#checkpoint_s3_uri=checkpoint_s3_uri,
#use_spot_instances=True,
#max_wait=7200, # This should be equal to or greater than max_run in seconds'
#max_run=3600, # expected max run in seconds
role=role,
transformers_version='4.6',
pytorch_version='1.7',
py_version='py36',
hyperparameters=hyperparameters,
metric_definitions=metric_definitions,
)
# starting the train job with our uploaded datasets as input
huggingface_estimator.fit({'train': training_input_path, 'test': test_input_path})
# データ数: 20,000, 3epochでの実行時間の目安
# Training seconds: 1289
# Billable seconds: 1289
```
## Estimator Parameters
```
# container image used for training job
print(f"container image used for training job: \n{huggingface_estimator.image_uri}\n")
# s3 uri where the trained model is located
print(f"s3 uri where the trained model is located: \n{huggingface_estimator.model_data}\n")
# latest training job name for this estimator
print(f"latest training job name for this estimator: \n{huggingface_estimator.latest_training_job.name}\n")
# access the logs of the training job
huggingface_estimator.sagemaker_session.logs_for_job(huggingface_estimator.latest_training_job.name)
```
## Accessing Training Metrics
トレーニングジョブは、メトリックをすぐには出力しません。 たとえば、最初にトレーニングインスタンスをプロビジョニングし、トレーニングイメージをダウンロードし、データをダウンロードする必要があります。 さらに、このデモでは、最初の評価ログは500ステップ後に取得されます(Hugging Face Trainerクラスのlogging_stepsの[デフォルト](https://huggingface.co/transformers/main_classes/trainer.html#transformers.TrainingArguments)。
したがって、**トレーニングを開始してから15〜20分後に以下のセクションを実行してください。そうしないと、まだ利用可能な指標がなく、エラーが返される可能性があります**
`TrainingJobAnalytics` API callで正確なトレーニングジョブ名を指定することで、このコードをコピーして別の場所から実行することもできます(クラウドに接続され、APIの使用が許可されている場合)。
```
from sagemaker import TrainingJobAnalytics
# Captured metrics can be accessed as a Pandas dataframe
df = TrainingJobAnalytics(training_job_name=huggingface_estimator.latest_training_job.name).dataframe()
df
!pip install seaborn
from matplotlib import pyplot as plt
import seaborn as sns
plt.rcParams['figure.figsize'] = [15,5]
evals = df[df.metric_name.isin(['eval_accuracy','eval_precision'])]
losses = df[df.metric_name.isin(['loss', 'eval_loss'])]
sns.lineplot(
x='timestamp',
y='value',
data=evals,
hue='metric_name',
palette=['blue', 'purple'])
ax2 = plt.twinx()
sns.lineplot(
x='timestamp',
y='value',
data=losses,
hue='metric_name',
palette=['orange', 'red'],
ax=ax2)
```
## Download-fine-tuned-model-from-s3
```
from sagemaker.s3 import S3Downloader
# 学習したモデルのダウンロード
S3Downloader.download(
s3_uri=huggingface_estimator.model_data, # s3 uri where the trained model is located
local_path='.', # local path where *.targ.gz is saved
sagemaker_session=sess # sagemaker session used for training the model
)
```
## Attach to old training job to an estimator
Sagemakerでは、古いトレーニングジョブをEstimatorにアタッチして、トレーニングを続けたり、結果を取得したりできます。
```
from sagemaker.estimator import Estimator
# job which is going to be attached to the estimator
old_training_job_name=''
# attach old training job
huggingface_estimator_loaded = Estimator.attach(old_training_job_name)
# get model output s3 from training job
huggingface_estimator_loaded.model_data
```
| github_jupyter |
# Chemical-Disease Relation (CDR) Tutorial
In this example, we'll be writing an application to extract *mentions of* **chemical-induced-disease relationships** from Pubmed abstracts, as per the [BioCreative CDR Challenge](http://www.biocreative.org/resources/corpora/biocreative-v-cdr-corpus/). This tutorial will show off some of the more advanced features of Snorkel, so we'll assume you've followed the Intro tutorial.
### Task Description
The CDR task is comprised of three sets of 500 documents each, called training, development, and test. A document consists of the title and abstract of an article from [PubMed](https://www.ncbi.nlm.nih.gov/pubmed/), an archive of biomedical and life sciences journal literature. The documents have been hand-annotated with
* Mentions of chemicals and diseases along with their [MESH](https://meshb.nlm.nih.gov/#/fieldSearch) IDs, canonical IDs for medical entities. For example, mentions of "warfarin" in two different documents will have the same ID.
* Chemical-disease relations at the document-level. That is, if some piece of text in the document implies that a chemical with MESH ID `X` induces a disease with MESH ID `Y`, the document will be annotated with `Relation(X, Y)`.
The goal is to extract the document-level relations on the test set (without accessing the entity or relation annotations). For this tutorial, we make the following assumptions and alterations to the task:
* We discard all of the entity mention annotations and assume we have access to a state-of-the-art entity tagger (see Part I) to identify chemical and disease mentions, and link them to their canonical IDs.
* We shuffle the training and development sets a bit, producing a new training set with 900 documents and a new development set with 100 documents. We discard the training set relation annotations, but keep the development set to evaluate our labeling functions and extraction model.
* We evaluate the task at the mention-level, rather than the document-level. We will convert the document-level relation annotations to mention-level by simply saying that a mention pair `(X, Y)` in document `D` if `Relation(X, Y)` was hand-annotated at the document-level for `D`.
In effect, the only inputs to this application are the plain text of the documents, a pre-trained entity tagger, and a small development set of annotated documents. This is representative of many information extraction tasks, and Snorkel is the perfect tool to bootstrap the extraction process with weak supervision. Let's get going.
## Part 0: Initial Prep
In your shell, download the raw data by running:
```bash
cd tutorials/cdr
./download_data.sh
```
Note that if you've previously run this tutorial (using SQLite), you can delete the old database by running (in the same directory as above):
```bash
rm snorkel.db
```
# Part I: Corpus Preprocessing
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
from snorkel import SnorkelSession
session = SnorkelSession()
```
### Configuring a `DocPreprocessor`
We'll start by defining a `DocPreprocessor` object to read in Pubmed abstracts from [Pubtator]([Pubtator](http://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/PubTator/index.cgi). There some extra annotation information in the file, while we'll skip for now. We'll use the `XMLMultiDocPreprocessor` class, which allows us to use [XPath queries](https://en.wikipedia.org/wiki/XPath) to specify the relevant sections of the XML format.
Note that we are newline-concatenating text from the title and abstract together for simplicity, but if we wanted to, we could easily extend the `DocPreprocessor` classes to preserve information about document structure.
```
import os
from snorkel.parser import XMLMultiDocPreprocessor
# The following line is for testing only. Feel free to ignore it.
file_path = 'data/CDR.BioC.small.xml' if 'CI' in os.environ else 'data/CDR.BioC.xml'
doc_preprocessor = XMLMultiDocPreprocessor(
path=file_path,
doc='.//document',
text='.//passage/text/text()',
id='.//id/text()'
)
```
### Creating a `CorpusParser`
Similar to the Intro tutorial, we'll now construct a `CorpusParser` using the preprocessor we just defined. However, this one has an extra ingredient: an entity tagger. [TaggerOne](https://www.ncbi.nlm.nih.gov/pubmed/27283952) is a popular entity tagger for PubMed, so we went ahead and preprocessed its tags on the CDR corpus for you. The function `TaggerOneTagger.tag` (in `utils.py`) tags sentences with mentions of chemicals and diseases. We'll use these tags to extract candidates in Part II. The tags are stored in `Sentence.entity_cids` and `Sentence.entity_types`, which are analog to `Sentence.words`.
Recall that in the wild, we wouldn't have the manual labels included with the CDR data, and we'd have to use an automated tagger (like TaggerOne) to tag entity mentions. That's what we're doing here.
```
from snorkel.parser import CorpusParser
from utils import TaggerOneTagger
tagger_one = TaggerOneTagger()
corpus_parser = CorpusParser(fn=tagger_one.tag)
corpus_parser.apply(list(doc_preprocessor))
from snorkel.models import Document, Sentence
print("Documents:", session.query(Document).count())
print("Sentences:", session.query(Sentence).count())
```
# Part II: Candidate Extraction
With the TaggerOne entity tags, candidate extraction is pretty easy! We split into some preset training, development, and test sets. Then we'll use PretaggedCandidateExtractor to extract candidates using the TaggerOne entity tags.
```
from six.moves.cPickle import load
with open('data/doc_ids.pkl', 'rb') as f:
train_ids, dev_ids, test_ids = load(f)
train_ids, dev_ids, test_ids = set(train_ids), set(dev_ids), set(test_ids)
train_sents, dev_sents, test_sents = set(), set(), set()
docs = session.query(Document).order_by(Document.name).all()
for i, doc in enumerate(docs):
for s in doc.sentences:
if doc.name in train_ids:
train_sents.add(s)
elif doc.name in dev_ids:
dev_sents.add(s)
elif doc.name in test_ids:
test_sents.add(s)
else:
raise Exception('ID <{0}> not found in any id set'.format(doc.name))
from snorkel.models import Candidate, candidate_subclass
ChemicalDisease = candidate_subclass('ChemicalDisease', ['chemical', 'disease'])
from snorkel.candidates import PretaggedCandidateExtractor
candidate_extractor = PretaggedCandidateExtractor(ChemicalDisease, ['Chemical', 'Disease'])
```
We should get 8268 candidates in the training set, 888 candidates in the development set, and 4620 candidates in the test set.
```
for k, sents in enumerate([train_sents, dev_sents, test_sents]):
candidate_extractor.apply(sents, split=k)
print("Number of candidates:", session.query(ChemicalDisease).filter(ChemicalDisease.split == k).count())
```
### Candidate Recall
We will briefly discuss the issue of candidate recall. The end-recall of the extraction is effectively upper-bounded by our candidate set: any chemical-disease pair that is present in a document but not identified as a candidate cannot be extracted by our end extraction model. Below are some example reasons for missing a candidate<sup>1</sup>.
* The tagger is imperfect, and may miss a chemical or disease mention.
* The tagger is imperfect, and may attach an incorrect entity ID to a correctly identified chemical or disease mention. For example, "stomach pain" might get attached to the entity ID for "digestive track infection" rather than "stomach illness".
* A relation occurs across multiple sentences. For example, "**Artery calcification** is more prominient in older populations. It can be induced by **warfarin**."
If we just look at the set of extractions at the end of this tutorial, we won't be able to account for some false negatives that we missed at the candidate extraction stage. For simplicity, we ignore candidate recall in this tutorial and evaluate our extraction model just on the set of extractions made by the end model. However, when you're developing information extraction applications in the future, it's important to keep candidate recall in mind.
<sup>1</sup>Note that these specific issues can be combatted with advanced techniques like noun-phrase chunking to expand the entity mention set, or coreference parsing for cross-sentence candidates. We don't employ these here in order to focus on weak supervision.
| github_jupyter |
```
import torch
import torch.nn as nn
import torchvision.models as models
from torchvision.transforms import transforms
import cv2
import numpy as np
import matplotlib.pyplot as plt
def readAndPreprocess(img_path):
# Read and convert from BGR to RGB
img = cv2.imread(img_path)[..., ::-1]
# Resize
img = cv2.resize(img, (224, 224))
# Convert to tensor, normalize and flatten
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # From ImageNet
])
img = transform(img).unsqueeze_(0)
return img
def getDeconvModel(model, input_img, last_layer_index):
layer_list = []
unpool_indices_list = []
x = input_img
for idx, layer in enumerate(model.features):
if isinstance(layer, torch.nn.Conv2d):
B, C, H, W = x.shape
x = layer(x)
deconv_layer = nn.ConvTranspose2d(layer.out_channels, C, layer.kernel_size, layer.stride, layer.padding)
deconv_layer.weight = layer.weight
layer_list.append(deconv_layer)
if isinstance(layer, torch.nn.ReLU):
x = layer(x)
layer_list.append(layer)
if isinstance(layer, torch.nn.MaxPool2d):
layer.return_indices = True
x, unpool_index = layer(x)
unpool_indices_list.append(unpool_index)
unpool_layer = torch.nn.MaxUnpool2d(kernel_size=layer.kernel_size, stride=layer.stride,
padding=layer.padding)
layer_list.append(unpool_layer)
layer.return_indices = True
if idx == last_layer_index:
break
def deconvNet(y):
for layer in reversed(layer_list):
if isinstance(layer, nn.MaxUnpool2d):
y = layer(y, unpool_indices_list.pop())
else:
y = layer(y)
return y
return x, deconvNet
model = models.vgg16(pretrained=True).eval()
def getImg(img):
npimg = img[0].data.numpy()
npimg = ((npimg - npimg.min()) * 255 / (npimg.max() - npimg.min())).astype('uint8')
npimg = np.transpose(npimg, (1, 2, 0))
return npimg
input_img = readAndPreprocess("../../experiments/data/imgs/steth.JPEG")
model = models.vgg16(pretrained=True).eval()
model(input_img)
visualize_layer_indices = []
for i, layer in enumerate(model.features):
if isinstance(layer, torch.nn.MaxPool2d):
visualize_layer_indices.append(i)
layerImgs = {}
for layer_max_count in visualize_layer_indices:
print("layer...%s" % layer_max_count)
y, deconvNet = getDeconvModel(model, input_img, layer_max_count)
reproducted_img = deconvNet(y)
layerImgs[layer_max_count] = getImg(reproducted_img)
fig = plt.figure(figsize=(10, 12))
cnt = 1
for key in layerImgs:
fig.add_subplot(3, 3, cnt)
cnt += 1
plt.title('layer: ' + str(key))
plt.imshow(layerImgs[key])
plt.show()
```
| github_jupyter |
```
import pandas as pd
import numpy as np
import os
import pickle
import platform
from sklearn.preprocessing import StandardScaler
from mabwiser.mab import MAB, LearningPolicy
from mabwiser.linear import _RidgeRegression, _Linear
class LinTSExample(_RidgeRegression):
def predict(self, x):
if self.scaler is not None:
x = self._scale_predict_context(x)
covar = np.dot(self.alpha**2, self.A_inv)
beta_sampled = rng.multivariate_normal(self.beta, covar)
return np.dot(x, beta_sampled)
class LinearExample(_Linear):
factory = {"ts": LinTSExample}
def __init__(self, rng, arms, n_jobs=1, backend=None, l2_lambda=1, alpha=1, regression='ts', arm_to_scaler = None):
super().__init__(rng, arms, n_jobs, backend, l2_lambda, alpha, regression)
self.l2_lambda = l2_lambda
self.alpha = alpha
self.regression = regression
# Create ridge regression model for each arm
self.num_features = None
if arm_to_scaler is None:
arm_to_scaler = dict((arm, None) for arm in arms)
self.arm_to_model = dict((arm, LinearExample.factory.get(regression)(rng, l2_lambda,
alpha, arm_to_scaler[arm])) for arm in arms)
```
# Red Hat
```
platform.platform()
print(np.__version__)
users = pd.read_csv('movielens_users.csv')
responses = pd.read_csv('movielens_responses.csv')
train = users[users['set']=='train']
test = users[users['set']=='test']
train = train.merge(responses, how='left', on='user id')
context_features = [c for c in users.columns if c not in ['user id', 'set']]
decisions = MAB._convert_array(train['item id'])
rewards = MAB._convert_array(train['rated'])
contexts = MAB._convert_matrix(train[context_features]).astype('float')
test_contexts = MAB._convert_matrix(test[context_features]).astype('float')
scaler = pickle.load(open('movielens_scaler.pkl', 'rb'))
contexts = scaler.transform(contexts)
test_contexts = scaler.transform(test_contexts)
rng = np.random.RandomState(seed=11)
arms = list(responses['item id'].unique())
mab = LinearExample(rng=rng, arms=arms, l2_lambda=10, alpha=1, regression='ts', n_jobs=1, backend=None)
mab.arm_to_model[1]
mab.fit(decisions, rewards, contexts)
expectations = mab.predict_expectations(test_contexts)
expectations[0][1]
pickle.dump(mab, open(os.path.join('output', 'rh_ml_mab2.pkl'), 'wb'))
pickle.dump(expectations, open(os.path.join('output', 'rl_ml_expectations2.pkl'), 'wb'))
```
# Cholesky
```
arms = list(responses['item id'].unique())
mab = MAB(arms=arms, learning_policy=LearningPolicy.LinTS(l2_lambda=10, alpha=1), n_jobs=1, backend=None, seed=11)
mab._imp.arm_to_model[1]
mab.fit(decisions, rewards, contexts)
expectations = mab.predict_expectations(test_contexts)
expectations[0][1]
pickle.dump(mab, open(os.path.join('output', 'rh_ml_ch_mab2.pkl'), 'wb'))
pickle.dump(expectations, open(os.path.join('output', 'rh_ml_ch_expectations2.pkl'), 'wb'))
mab._imp.arm_to_model[1].beta
```
| github_jupyter |
```
import networkx as nx
import matplotlib.pyplot as plt
from operator import itemgetter
%matplotlib inline
```
# 1. (1/1)
```
g = nx.Graph()
g.add_edges_from([('A', 'F'), ('F', 'E'), ('F', 'C'), ('A', 'C'), ('C', 'E'),
('B', 'A'), ('B', 'C'), ('B', 'E'), ('B', 'D'), ('D', 'E'), ])
pos = nx.kamada_kawai_layout(g)
nx.draw_networkx(g, pos)
degrees = dict(g.degree())
degree_sum = sum(dict(g.degree()).values())
degrees, degree_sum, len(g.nodes())
p_2 = 1/6
p_3 = 2/6
q1 = p_2 + p_3
q1
```
# 2. (0/1)
```
g = nx.DiGraph()
g.add_edges_from([('A', 'B'), ('A', 'C'), ('A', 'D'),
('B', 'A'), ('B', 'C'),
('C', 'A'),
('D', 'E'),
('E', 'C')])
pos = nx.kamada_kawai_layout(g)
nx.draw_networkx(g, pos)
nx.number_of_nodes(g), g.in_degree()
```
```k = 1``` is the most common degree
since our denominator is a fixed value ```nx.number_of_nodes(g)```
```3/nx.number_of_nodes(g)``` is the highest we can achieve
```
q2 = 1
q2
```
# 3. (1/1)
[x] If we draw a power law distribution...
[x] The Preferential Attachment Model generates...
# 4. (1/1)
[x] In the small-world model starting with k...
[x] Some small-world networks...
# 5. (1/1)
[x] Average local clustering will increase and average shortest path will decrease
# 6. (1/1)
```
g = nx.Graph()
g.add_edges_from(
[
('C', 'G'), ('C', 'A'), ('A', 'D'), ('A', 'E'), ('G', 'D'),
('D', 'E'), ('D', 'B'), ('E', 'H'), ('D', 'H'), ('H', 'F')
])
pos = nx.kamada_kawai_layout(g)
nx.draw_networkx(g, pos)
comm_neig = sorted([(e[0], e[1], len(list(nx.common_neighbors(g, e[0], e[1])))) for e in nx.non_edges(g)],
key=itemgetter(2),
reverse=True)
pairs_H = [(node, h, common) for (node, h, common) in comm_neig if (node == 'H' or h == 'H')]
q6 = pairs_H[0][0]
q6
```
# 7. (1/1)
```
# Number of neighbors normalized by the total number of neighbors
jacc = list(nx.jaccard_coefficient(g))
# jacc
q7_ = [wanted for wanted in jacc if (wanted[0] == 'D' and wanted[1] == 'C')]
q7 = q7_[0][2]
q7
```
# 8. (1/1)
```
rai = list(nx.resource_allocation_index(g))
q3_ = [wanted for wanted in rai if (wanted[0] == 'D' and wanted[1] == 'C')]
q3 = q3_[0][2]
q3
```
# 9. (1/1)
```
pref = sorted(list(nx.preferential_attachment(g)), key=itemgetter(2), reverse=True)
q9_ = [wanted for wanted in pref if (wanted[0] == 'D' and wanted[1] == 'C')]
q9 = q9_[0][2]
q9
```
# 10. (1/1)
```
g_comm = g.copy()
comm0 = 'A B C D G'.split()
comm1 = 'E F H'.split()
comm0, comm1
for node in comm0:
g_comm.node[node]['community'] = 0
for node in comm1:
g_comm.node[node]['community'] = 1
# Acknowledge the community value
g_comm.node(data=True)
cn_soun_hop = list(nx.cn_soundarajan_hopcroft(g_comm))
# cn_soun_hop
item1 = [wanted for wanted in cn_soun_hop if (wanted[0] == 'D' and wanted[1] == 'C')]
item1 # False
item2 = [wanted for wanted in cn_soun_hop if (wanted[0] == 'A' and wanted[1] == 'G')]
item2 # True
ra_sound_hop = list(nx.ra_index_soundarajan_hopcroft(g_comm))
# ra_sound_hop
item3 = [wanted for wanted in ra_sound_hop if (wanted[0] == 'E' and wanted[1] == 'F')]
item3 # False
item3 = [wanted for wanted in ra_sound_hop if (wanted[0] == 'A' and wanted[1] == 'G')]
item3 # True
```
[x] The **Commom** ... of node 'A' and node 'G' is 4
[x] The **Resource** ... of node 'A' and node 'G' is 0.7
EOF
| github_jupyter |
# Politician Activity on Wikipedia by Political Affiliation
The parameters in the cell below can be adjusted to explore other political affiliations and time frames.
### How to explore other political affiliation?
The ***affiliation*** parameter can be use to aggregate politicians by their political affiliations. The column `affiliation` in this [this other notebook](../politicians.ipynb?autorun=true) show the politicians that belong each political affiliation.
***Alternatively***, you can direcly use the [politicians API](http://mediamonitoring.gesis.org/api/politicians/swagger/), or access it with the [SMM Wrapper](https://pypi.org/project/smm-wrapper/).
## A. Set Up parameters
```
# Parameters:
affiliation = 'CSU'
from_date = '2017-09-01'
to_date = '2018-12-31'
aggregation = 'week'
```
## B. Using APIs
### B.1 Using the SMM Politician API
```
import pandas as pd
from smm_wrapper import SMMPoliticians
# Create an instance to the smm wrapper
smm = SMMPoliticians()
# Request the politicians from the API
df = smm.dv.get_politicians()
# Filter the accounts by party, and valid ones (the ones that contain wp_ids)
party_df = df[(df['affiliation']==affiliation) & (df['wp_ids'].notnull())]
# query the Social Media Monitoring API
wiki_chobs = pd.concat(smm.dv.wikipedia(_id=politician_id, from_date=from_date, to_date=to_date, aggregate_by=aggregation)
for politician_id in party_df.index)
wiki_chobs = wiki_chobs.groupby('date').agg({'chobs': 'sum'}).reset_index()
```
### B.2 Using the Wikiwho API
```
from wikiwho_wrapper import WikiWho
#using wikiwho to extract conflicts and revisions
ww = WikiWho(lng='de')
edit_persistance_gen = (
ww.dv.edit_persistence(page_id=wp_id , start=from_date, end=to_date)
for wp_ids in party_df['wp_ids'] for wp_id in wp_ids)
wiki_data = pd.concat(df for df in edit_persistance_gen if len(df) > 0)
wiki_data['undos'] = wiki_data['dels'] + wiki_data['reins']
wiki_data['date'] = pd.to_datetime(wiki_data['year_month'])
wiki_data = wiki_data.groupby('date')['conflict','elegibles','undos'].sum().reset_index()
wiki_data['conflict_score'] = wiki_data['conflict'] / wiki_data['elegibles']
wiki_data.fillna(0, inplace=True)
```
### B.3 Using the Wikimedia API
```
import requests
import urllib.parse
# open a session
session = requests.Session()
session.headers.update({'User-Agent': 'mediamonitoring.gesis.org'})
# prepare url
vurl = ("https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article"
"/de.wikipedia.org/all-access/user/{wp_title}/daily/"
f"{from_date.replace('-','')}/{to_date.replace('-','')}")
# use the wikimedia API to download the views
views = pd.concat([pd.DataFrame(session.get(url=vurl.format(
wp_title=urllib.parse.quote(wp_title, safe=''))).json()['items'])
for wp_titles in party_df['wp_titles'] for wp_title in wp_titles])
views['timestamp']=pd.to_datetime(views['timestamp'], format='%Y%m%d%H')
# weekly or monthly aggregation of the data
if aggregation == 'week':
views = views.groupby([pd.Grouper(key='timestamp', freq='W-SUN')])['views'].sum().reset_index().sort_values('timestamp')
views['timestamp'] = views['timestamp'] - pd.Timedelta(days=6)
elif aggregation == 'month':
views = views.groupby([pd.Grouper(key='timestamp', freq='MS')])['views'].sum().reset_index().sort_values('timestamp')
```
## C. Plotting
### C.1 Plot Wikipedia Activity
```
import plotly
from plotly import graph_objs as go
plotly.offline.init_notebook_mode(connected=True)
plotly.offline.iplot({
"data": [go.Scatter(x=views['timestamp'], y=views['views'], name='Views'),
go.Scatter(x=wiki_chobs['date'], y=wiki_chobs['chobs'], name='Changes', yaxis='y2')],
"layout": go.Layout( title='Wikipedia Activity', yaxis=dict(title='Views'),
yaxis2=dict(title='Changes', overlaying='y', side='right'))
})
```
### C.2 Plot Wikipedia Disagreement
```
plotly.offline.iplot({
"data": [go.Scatter(x=wiki_data['date'], y=wiki_data['undos'], name='Undos', line_shape='spline'),
go.Scatter(x=wiki_data['date'], y=wiki_data['conflict_score'], name='Conflict', line_shape='spline', yaxis='y2')],
"layout": go.Layout(title='Wikipedia Disagreement', yaxis=dict(title='Undos'),
yaxis2=dict(title='Conflict', overlaying='y',side='right'))
})
```
| github_jupyter |
```
import os
import time
import datetime
import warnings
import tqdm
import IPython
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
tf.__version__
```
The following may be helpful:
https://github.com/tensorflow/tensorflow/issues/6271#issuecomment-266893850
https://arxiv.org/pdf/1807.03146.pdf
```
# Makes it so any changes in pymedphys is automatically
# propagated into the notebook without needing a kernel reset.
from IPython.lib.deepreload import reload
%load_ext autoreload
%autoreload 2
GRID_SIZE = 1024
PIXELS_PER_UNIT = 4
# reverse
tf.keras.backend.clear_session()
initializer = tf.random_normal_initializer(0., 0.02)
def down_block(x, depth, num_convs, channels, pool):
convolution_sequence = tf.keras.Sequential(name=f'down-convolution-d{depth}')
convolution_sequence.add(
tf.keras.layers.ReLU()
)
for i in range(num_convs):
convolution_sequence.add(
tf.keras.layers.Conv2D(
channels, (3, 3), strides=1, padding='same',
kernel_initializer=initializer, use_bias=True)
)
if i != num_convs - 1:
convolution_sequence.add(
tf.keras.layers.ReLU()
)
short_circuit_sequence = tf.keras.Sequential(name=f'down-short-circuit-d{depth}')
short_circuit_sequence.add(
tf.keras.layers.Conv2D(
channels, (1, 1), strides=1, padding='same',
kernel_initializer=tf.ones_initializer(),
use_bias=True, trainable=False)
)
x = tf.keras.layers.Add()(
[convolution_sequence(x), short_circuit_sequence(x)]
)
unet_short_circuit = x
if pool != 0:
x = tf.keras.layers.AveragePooling2D((pool, pool), strides=None, padding='valid')(x)
return x, unet_short_circuit
def fully_connected_block(x, input_size, internal_channels, output_channels):
x = tf.keras.layers.Conv2D(
internal_channels,
(input_size, input_size),
strides=1,
padding='valid',
kernel_initializer=initializer,
use_bias=True
)(x)
repeats = 2
for _ in range(repeats):
short_circuit = x
x = tf.keras.layers.ReLU()(x)
x = tf.keras.layers.Dense(internal_channels)(x)
x = tf.keras.layers.Add()([x, short_circuit])
x = tf.keras.layers.ReLU()(x)
x = tf.keras.layers.Dense(input_size * input_size * output_channels)(x)
x = tf.keras.layers.Reshape((input_size, input_size, output_channels))(x)
return x
def up_block(x, unet_short_circuit, depth, num_convs, channels, up_scale):
if up_scale != 0:
x = tf.keras.layers.UpSampling2D(size=(up_scale, up_scale))(x)
x = tf.keras.layers.Add()([x, unet_short_circuit])
convolution_sequence = tf.keras.Sequential(name=f'up-convolution-d{depth}')
convolution_sequence.add(
tf.keras.layers.ReLU()
)
for i in range(num_convs):
convolution_sequence.add(
tf.keras.layers.Conv2D(
channels, (3, 3), strides=1, padding='same',
kernel_initializer=initializer, use_bias=True)
)
if i != num_convs - 1:
convolution_sequence.add(
tf.keras.layers.ReLU()
)
internal_short_circuit = tf.keras.Sequential(name=f'up-short-circuit-d{depth}')
internal_short_circuit.add(
tf.keras.layers.Conv2D(
channels, (1, 1), strides=1, padding='same',
kernel_initializer=tf.ones_initializer(),
use_bias=True, trainable=False)
)
x = tf.keras.layers.Add()(
[convolution_sequence(x), internal_short_circuit(x)]
)
return x
def Model(grid_size=GRID_SIZE):
down_block_params = [
(0, (3, 12, 2)), # BS, 1024, 1024, 3 --> BS, 512, 512, 12
(1, (3, 12, 4)), # BS, 512, 512, 12 --> BS, 128, 128, 12
(2, (3, 12, 4)), # BS, 128, 128, 12 --> BS, 32, 32, 12
(3, (3, 12, 4)), # BS, 32, 32, 12 --> BS, 8, 8, 12
(4, (4, 24, 0)), # BS, 8, 8, 12 --> BS, 8, 8, 24
]
fully_connected_params = (8, 96, 24)
up_block_params = [
(4, (4, 12, 0)),
(3, (4, 12, 4)),
(2, (3, 12, 4)),
(1, (3, 12, 4)),
(0, (3, 2, 2)),
]
inputs = tf.keras.layers.Input(shape=[grid_size,grid_size,1], batch_size=None)
x = inputs
unet_short_circuits = []
for depth, down_block_param in down_block_params:
x, unet_short_circuit = down_block(x, depth, *down_block_param)
unet_short_circuits.append(unet_short_circuit)
x = fully_connected_block(x, *fully_connected_params)
unet_short_circuits = reversed(unet_short_circuits)
for unet_shot_circuit, (depth, up_block_param) in zip(unet_short_circuits, up_block_params):
x = up_block(x, unet_shot_circuit, depth, *up_block_param)
return tf.keras.Model(inputs=inputs, outputs=x)
model = Model()
model.compile(
optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.MeanAbsoluteError(),
metrics=['accuracy']
)
tf.keras.utils.plot_model(model, show_shapes=True, dpi=64)
model.summary()
from pymedphys._mocks import wlutz, profiles
from pymedphys._wlutz import reporting, interppoints
def create_gaussian(x_pos, y_pos, sigma):
variance = sigma**2
norm = 1 / (2*np.pi*variance)
def gaussian(x, y):
return norm * np.exp(-((x - x_pos)**2 + (y - y_pos)**2)/(2*variance))
return gaussian
def create_single_dataset(grid_size, pixels_per_unit, include_params=True):
bounding_pixel_centre_val = (grid_size / 2 - 0.5) / pixels_per_unit
field_centre = np.random.uniform(-60, 60, size=2)
field_side_lengths = np.exp(np.random.uniform(np.log(15), np.log(150), size=2))
field_penumbra = np.random.uniform(1, 5)
field_rotation = np.random.uniform(-180, 180)
transform = interppoints.translate_and_rotate_transform(field_centre, field_rotation)
field_corners_before_transform = [
(-field_side_lengths[0]/2, -field_side_lengths[0]/2, field_side_lengths[0]/2, field_side_lengths[0]/2),
(-field_side_lengths[1]/2, field_side_lengths[1]/2, -field_side_lengths[1]/2, field_side_lengths[1]/2),
]
bb_centre_before_transform = [
np.random.uniform(
-field_side_lengths[0]/2, field_side_lengths[0]/2),
np.random.uniform(
-field_side_lengths[1]/2, field_side_lengths[1]/2)
]
bb_centre = interppoints.apply_transform(*bb_centre_before_transform, transform)
field_corners = np.array(interppoints.apply_transform(*field_corners_before_transform, transform))
bb_diameter = tf.random.uniform((), 0.5, 10).numpy()
bb_max_attenuation = tf.random.uniform((), 0.1, 0.5).numpy()
field = profiles.create_rectangular_field_function(
field_centre, field_side_lengths, field_penumbra, field_rotation
)
bb_penumbra = field_penumbra / 3
bb_attenuation_map = wlutz.create_bb_attenuation_func(
bb_diameter, bb_penumbra, bb_max_attenuation
)
x = np.linspace(
-bounding_pixel_centre_val,
bounding_pixel_centre_val,
grid_size
)
xx, yy = np.meshgrid(x, x)
without_bb = field(xx, yy)
def field_with_bb(x, y):
return field(x, y) * bb_attenuation_map(x - bb_centre[0], y - bb_centre[1])
img = field_with_bb(xx, yy)
parameters = tf.concat([field_centre, field_side_lengths, [field_rotation], bb_centre, [bb_diameter]], 0)
xx = tf.convert_to_tensor(xx, dtype=tf.float32)
yy = tf.convert_to_tensor(yy, dtype=tf.float32)
img = tf.convert_to_tensor(img, dtype=tf.float32)
model_input = tf.stack([xx, yy, img], axis=-1)
sigma = 1.5 / PIXELS_PER_UNIT
bb_heatmap = tf.convert_to_tensor(create_gaussian(*bb_centre, sigma)(xx, yy), dtype=tf.float32)
field_corner_heatmap = np.zeros_like(bb_heatmap)
for field_corner in field_corners.T:
field_corner_heatmap += create_gaussian(*field_corner, sigma)(xx, yy)
field_corner_heatmap = tf.convert_to_tensor(field_corner_heatmap, dtype=tf.float32)
model_output = tf.stack([bb_heatmap, field_corner_heatmap], axis=-1)
if include_params:
return model_input, model_output, parameters
return model_input[:,:,2::], model_output
model_input, model_output, parameters = create_single_dataset(GRID_SIZE, PIXELS_PER_UNIT)
plt.figure(figsize=(10,10))
plt.contourf(model_input[:,:,0], model_input[:,:,1], model_input[:,:,2], 100)
plt.contourf(model_input[:,:,0], model_input[:,:,1], model_output[:,:,0], levels=np.linspace(0.5,1.2,100), cmap='magma')
plt.contourf(model_input[:,:,0], model_input[:,:,1], model_output[:,:,1], levels=np.linspace(0.5,1.2,100), cmap='cividis')
plt.axis('equal')
def create_pipeline_dataset(batch_size, grid_size=GRID_SIZE, pixels_per_unit=PIXELS_PER_UNIT, include_params=True):
def dataset_generator():
yield create_single_dataset(grid_size, pixels_per_unit, include_params=include_params)
if include_params:
generator_params = (
(tf.float32, tf.float32, tf.float32),
(tf.TensorShape([grid_size, grid_size, 3]), tf.TensorShape([grid_size, grid_size, 2]), tf.TensorShape([8]))
)
else:
generator_params = (
(tf.float32, tf.float32),
(tf.TensorShape([grid_size, grid_size, 1]), tf.TensorShape([grid_size, grid_size, 2]))
)
dataset = tf.data.Dataset.from_generator(
dataset_generator, *generator_params
)
dataset = dataset.repeat().batch(batch_size)
return dataset
def plot_raw_images(model_input, model_output):
dim = model_input.shape
for i in range(dim[0]):
plt.figure(figsize=(10,10))
plt.contourf(model_input[i,:,:,0], model_input[i,:,:,1], model_input[i,:,:,2], 100)
plt.contourf(
model_input[i,:,:,0], model_input[i,:,:,1], model_output[i,:,:,0],
levels=np.linspace(np.mean(model_output[i,:,:,0]),np.max(model_output[i,:,:,0]), 20),
cmap='magma',
alpha=0.3,
linestyles=None,
)
plt.contourf(
model_input[i,:,:,0], model_input[i,:,:,1], model_output[i,:,:,1],
levels=np.linspace(np.mean(model_output[i,:,:,1]),np.max(model_output[i,:,:,1]), 20),
cmap='cividis',
alpha=0.3,
linestyles=None,
)
plt.axis('equal')
plt.show()
for model_input, model_output, parameters in create_pipeline_dataset(1).take(2):
plot_raw_images(model_input, model_output)
def extract_parameters(parameters):
parameters = {
'field_centre': (parameters[0], parameters[1]),
'field_side_lengths': (parameters[2], parameters[3]),
'field_rotation': parameters[4],
'bb_centre': (parameters[5], parameters[6]),
'bb_diameter': parameters[7]
}
return parameters
def create_figure(image, field_centre, field_side_lengths, field_rotation, bb_centre, bb_diameter):
dim = image.shape
return reporting.image_analysis_figure(
np.array(image[0,:,0]), np.array(image[:,0,1]), np.array(image[:,:,2]),
np.array(bb_centre), np.array(field_centre), np.array(field_rotation),
bb_diameter, field_side_lengths, penumbra=0.03, units=''
)
def results_figures(model, batch_model_inputs, batch_model_outputs, batch_parameters, predicted):
batch_dim = batch_model_inputs.shape
num_batches = batch_dim[0]
for i in range(num_batches):
parameters = extract_parameters(batch_parameters[i, :])
ground_truth_bb_centre = (
np.sum(model_input[i,:,:,0] * batch_model_outputs[i,:,:,0]) / np.sum(batch_model_outputs[i,:,:,0]),
np.sum(model_input[i,:,:,1] * batch_model_outputs[i,:,:,0]) / np.sum(batch_model_outputs[i,:,:,0]),
)
ground_truth_field_centre = (
np.sum(model_input[i,:,:,0] * batch_model_outputs[i,:,:,1]) / np.sum(batch_model_outputs[i,:,:,1]),
np.sum(model_input[i,:,:,1] * batch_model_outputs[i,:,:,1]) / np.sum(batch_model_outputs[i,:,:,1]),
)
ground_truth_parameters = {
**parameters,
'bb_centre': ground_truth_bb_centre,
'field_centre': ground_truth_field_centre
}
predicted_bb_centre = (
np.sum(model_input[i,:,:,0] * predicted[i,:,:,0]) / np.sum(predicted[i,:,:,0]),
np.sum(model_input[i,:,:,1] * predicted[i,:,:,0]) / np.sum(predicted[i,:,:,0]),
)
predicted_field_centre = (
np.sum(model_input[i,:,:,0] * predicted[i,:,:,1]) / np.sum(predicted[i,:,:,1]),
np.sum(model_input[i,:,:,1] * predicted[i,:,:,1]) / np.sum(predicted[i,:,:,1]),
)
predicted_parameters = {
**parameters,
'bb_centre': predicted_bb_centre,
'field_centre': predicted_field_centre
}
fig, axs = create_figure(batch_model_inputs[i,:,:,:], **ground_truth_parameters)
axs[0,0].set_title("Ground Truth")
fig, axs = create_figure(batch_model_inputs[i,:,:,:], **predicted_parameters)
axs[0,0].set_title("Predicted")
plt.show()
def show_predictions():
for model_input, model_output, parameters in create_pipeline_dataset(1).take(1):
predicted = model(model_input[:,:,:,2::], training=True)
plot_raw_images(model_input, predicted)
results_figures(model, model_input, model_output, parameters, predicted)
show_predictions()
# optimizer = tf.keras.optimizers.Adam()
# checkpoint_dir = './training_checkpoints'
# checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
# checkpoint = tf.train.Checkpoint(optimizer=optimizer,
# model=model)
class DisplayCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
IPython.display.clear_output(wait=True)
show_predictions()
logdir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir)
```
```bash
poetry run tensorboard --logdir examples/site-specific/cancer-care-associates/production/Winston\ Lutz/prototyping/tf_model/logs/
```
```
BATCH_SIZE = 10
EPOCHS = 10000
STEPS_PER_EPOCH = 2
VALIDATION_STEPS = 1
test_dataset = create_pipeline_dataset(1, include_params=False)
train_dataset = create_pipeline_dataset(BATCH_SIZE, include_params=False)
model_history = model.fit(
train_dataset, epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
validation_steps=VALIDATION_STEPS,
validation_data=test_dataset,
callbacks=[DisplayCallback(), tensorboard_callback],
use_multiprocessing=True,
shuffle=False,
)
```
| github_jupyter |
# Using SVM to predict Grainsize
TL;DR, RBF is best kernal. Poly does not work.
Put together by Thomas Martin, thomasmartin@mines.edu, all errors are mine
If you are interested in graident boosting, here is a good place to start: https://xgboost.readthedocs.io/en/latest/tutorials/model.html
This is a supervised machine learning method.
```
!pip install sklearn --upgrade
# If you have installation questions, please reach out
import pandas as pd # data storage
import numpy as np # math and stuff
import sklearn
import datetime
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score, KFold
from sklearn.metrics import mean_squared_error
from sklearn.utils.class_weight import compute_sample_weight
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import median_absolute_error, max_error, mean_squared_error
from sklearn import svm
from sklearn.svm import SVR
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt # plotting utility
from google.colab import drive
drive.mount('/content/drive')
df = pd.read_csv('drive/My Drive/1_lewis_research/core_to_wl_merge/Merged_dataset_inner_imputed_12_21_2020.csv')
df = df.drop(['Unnamed: 0', 'Unnamed: 0.1', 'LiveTime2','ScanTime2', 'LiveTime1','ScanTime1',
'ref_num', 'API', 'well_name', 'sample_num' ], axis=1)
print(df.columns.values)
df.describe()
df = df[df['perm_klink_md']>0]
df = df[df.USGS_ID != 'E997']
df.describe()
```
## Loading in Dataset
```
dataset = df[[
'CAL', 'GR', 'DT', 'SP', 'DENS', 'PE',
'RESD', 'PHIN', 'PHID', 'GR_smooth', 'PE_smooth',
'perm_klink_md'
]]
dataset.head(3)
X = dataset[[ 'CAL', 'GR', 'DT', 'SP', 'DENS', 'PE',
'RESD', 'PHIN', 'PHID', 'GR_smooth', 'PE_smooth']]
Y = dataset[['perm_klink_md']]
Y_array = np.array(Y.values)
```
## Starting to set up the ML model params
```
seed = 7 # random seed is only used if you want to compare exact answers with friends
test_size = 0.25 # how much data you want to withold, .15 - 0.3 is a good starting point
X_train, X_test, y_train, y_test = train_test_split(X.values, Y_array, test_size=test_size)
svm_rbf = svm.SVR(kernel='rbf')
svm_rbf.fit(X_train, y_train)
preds = svm_rbf.predict(X_test)
rmse2 = mean_squared_error(y_test, preds, squared=False)
print("Mean Squared Error: %f" % (rmse2))
max1 = np.sqrt(max_error(y_test, preds))
print("Max Error: %f" % (max1))
MAE = median_absolute_error(y_test, preds)
print("Median Abs Error: %f" % (MAE))
```
# RBF Kernal Hyperparameter Tune
```
parameters = {
'C': [ 300, 500, 750, 1000, 1250, 1500, 2000],
'tol':[0.001, 0.01, 0.02, 0.4, 0.8],
'gamma': [ 'auto', 'scale', 0.1, 1, 10],
'max_iter': [25, 50, 100, 300, 500],
'epsilon': [0.05, 0.1, 0.15, 0.2, 0.4],
'degree': [1, 2,3,4,5]
}
estimator = svm.SVR(kernel='rbf')
grid_search = GridSearchCV(
estimator=estimator,
param_grid=parameters,
n_jobs = 6,
cv = 3,
verbose = True
)
grid_search.fit(X_train, y_train)
grid_search.best_estimator_
svm_reg_rbf = svm.SVR(kernel='rbf',
C=grid_search.best_estimator_.C,
max_iter=grid_search.best_estimator_.max_iter,
tol=grid_search.best_estimator_.tol,
gamma= grid_search.best_estimator_.gamma,
degree = grid_search.best_estimator_.degree )
svm_reg_rbf.fit(X_train, y_train)
preds_rbf = svm_reg_rbf.predict(X_test)
rmse3 = mean_squared_error(y_test, preds_rbf, squared=False)
print("Mean Squared Error: %f" % (rmse3))
max3 = np.sqrt(max_error(y_test, preds_rbf))
print("Max Error: %f" % (max3))
MAE2 = median_absolute_error(y_test, preds_rbf)
print("Median Abs Error: %f" % (MAE2))
x = datetime.datetime.now()
d = {'target': [Y.columns.values, Y.columns.values],
'MSE': [rmse2, rmse3],
'MAE': [MAE, MAE2],
'MaxError': [max1, max3],
'day': [x.day, x.day],
'month':[x.month, x.month],
'year':[x.year, x.year],
'model':['SVM-RBF', 'SVM-RBF'],
'version':[sklearn.__version__, sklearn.__version__]}
results = pd.DataFrame(data=d)
results.to_csv('drive/My Drive/1_lewis_research/analysis/experiments/svm/svm_results/perm_SVM.csv')
results
```
| github_jupyter |
> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.
# 5.5. Ray tracing: Cython with structs
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import cython
#%load_ext cythonmagic
%load_ext Cython
```
We now use a pure C structure to represent a 3D vector. We also implement all operations we need by hand in pure C.
```
%%cython
cimport cython
import numpy as np
cimport numpy as np
DBL = np.double
ctypedef np.double_t DBL_C
from libc.math cimport sqrt
cdef int w, h
cdef struct Vec3:
double x, y, z
cdef Vec3 vec3(double x, double y, double z):
cdef Vec3 v
v.x = x
v.y = y
v.z = z
return v
cdef double dot(Vec3 x, Vec3 y):
return x.x * y.x + x.y * y.y + x.z * y.z
cdef Vec3 normalize(Vec3 x):
cdef double n
n = sqrt(x.x * x.x + x.y * x.y + x.z * x.z)
return vec3(x.x / n, x.y / n, x.z / n)
cdef double max(double x, double y):
return x if x > y else y
cdef double min(double x, double y):
return x if x < y else y
cdef double clip_(double x, double m, double M):
return min(max(x, m), M)
cdef Vec3 clip(Vec3 x, double m, double M):
return vec3(clip_(x.x, m, M), clip_(x.y, m, M), clip_(x.z, m, M),)
cdef Vec3 add(Vec3 x, Vec3 y):
return vec3(x.x + y.x, x.y + y.y, x.z + y.z)
cdef Vec3 subtract(Vec3 x, Vec3 y):
return vec3(x.x - y.x, x.y - y.y, x.z - y.z)
cdef Vec3 minus(Vec3 x):
return vec3(-x.x, -x.y, -x.z)
cdef Vec3 multiply(Vec3 x, Vec3 y):
return vec3(x.x * y.x, x.y * y.y, x.z * y.z)
cdef Vec3 multiply_s(Vec3 x, double c):
return vec3(x.x * c, x.y * c, x.z * c)
cdef double intersect_sphere(Vec3 O,
Vec3 D,
Vec3 S,
double R):
# Return the distance from O to the intersection of the ray (O, D) with the
# sphere (S, R), or +inf if there is no intersection.
# O and S are 3D points, D (direction) is a normalized vector, R is a scalar.
cdef double a, b, c, disc, distSqrt, q, t0, t1
cdef Vec3 OS
a = dot(D, D)
OS = subtract(O, S)
b = 2 * dot(D, OS)
c = dot(OS, OS) - R * R
disc = b * b - 4 * a * c
if disc > 0:
distSqrt = sqrt(disc)
q = (-b - distSqrt) / 2.0 if b < 0 else (-b + distSqrt) / 2.0
t0 = q / a
t1 = c / q
t0, t1 = min(t0, t1), max(t0, t1)
if t1 >= 0:
return t1 if t0 < 0 else t0
return 1000000
cdef Vec3 trace_ray(Vec3 O, Vec3 D,):
cdef double t, radius, diffuse, specular_k, specular_c, DF, SP
cdef Vec3 M, N, L, toL, toO, col_ray, \
position, color, color_light, ambient
# Sphere properties.
position = vec3(0., 0., 1.)
radius = 1.
color = vec3(0., 0., 1.)
diffuse = 1.
specular_c = 1.
specular_k = 50.
# Light position and color.
L = vec3(5., 5., -10.)
color_light = vec3(1., 1., 1.)
ambient = vec3(.05, .05, .05)
# Find first point of intersection with the scene.
t = intersect_sphere(O, D, position, radius)
# Return None if the ray does not intersect any object.
if t == 1000000:
col_ray.x = 1000000
return col_ray
# Find the point of intersection on the object.
M = vec3(O.x + D.x * t, O.y + D.y * t, O.z + D.z * t)
N = normalize(subtract(M, position))
toL = normalize(subtract(L, M))
toO = normalize(subtract(O, M))
DF = diffuse * max(dot(N, toL), 0)
SP = specular_c * max(dot(N, normalize(add(toL, toO))), 0) ** specular_k
return add(ambient, add(multiply_s(color, DF), multiply_s(color_light, SP)))
def run(int w, int h):
cdef DBL_C[:,:,:] img = np.zeros((h, w, 3))
cdef Vec3 img_
cdef int i, j
cdef double x, y
cdef Vec3 O, Q, D, col_ray
cdef double w_ = float(w)
cdef double h_ = float(h)
col_ray = vec3(0., 0., 0.)
# Camera.
O = vec3(0., 0., -1.) # Position.
# Loop through all pixels.
for i in range(w):
Q = vec3(0., 0., 0.)
for j in range(h):
x = -1. + 2*(i)/w_
y = -1. + 2*(j)/h_
Q.x = x
Q.y = y
col_ray = trace_ray(O, normalize(subtract(Q, O)))
if col_ray.x == 1000000:
continue
img_ = clip(col_ray, 0., 1.)
img[h - j - 1, i, 0] = img_.x
img[h - j - 1, i, 1] = img_.y
img[h - j - 1, i, 2] = img_.z
return img
w, h = 200, 200
img = run(w, h)
plt.imshow(img);
plt.xticks([]); plt.yticks([]);
%timeit run(w, h)
```
> You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
> [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).
| github_jupyter |
# Algorithms: low-level interface
Once we have data for GST, there are several *algorithms* we can run on it to produce tomographic estimates. Depending on the amount of data you have, and time available for running LinearOperator Set Tomography, one algorithm may be preferable over the others. **What is typically thought of as "standard GST" is the iterative maximum-likelihood optimization implemented by `do_iterative_mlgst`** which uses a combination of minimum-$\chi^2$ GST and maximum-likelihood GST.
`pygsti` provides support for the following "primary" GST algorithms:
* **Linear LinearOperator Set Tomography (LGST)**: Uses short operation sequences to quickly compute a rough (low accuracy) estimate of a model by linear inversion.
* **Extended Linear LinearOperator Set Tomography (eLGST or EXLGST)**: Minimizes the sub-of-squared errors between independent LGST estimates and the estimates obtained from a single model to find a best-estimate model. This is typically done in an interative fashion, using LGST estimates for longer and longer sequences.
* **Minimum-$\chi^2$ LinearOperator Set Tomography (MC2GST)**: Minimizes the $\chi^{2}$ statistic of the data frequencies and model probabilities to find a best-estimate model. Typically done in an interative fashion, using successively larger sets of longer and longer operation sequences.
* **Maximum-Likelihood LinearOperator Set Tomography (MLGST)**: Maximizes the log-likelihood statistic of the data frequencies and model probabilities to find a best-estimate model. Typically done in an interative fashion similar to MC2GST. This maximum likelihood estimation (MLE) is very well-motivated from a statistics standpoint and should be the **most accurate among the algorithms**.
If you're curious, the implementation of the algorithms for LGST, EXLGST, MC2GST, and MLGST may be found in the `pygsti.algorithms.core` module. In this tutorial, we'll show how to invoke each of these algorithms.
Additionally, `pygsti` contains **gauge-optimization** algorithms. Because the outcome data (the input to the GST algorithms above) only determines a model up to some number of un-physical "gauge" degrees of freedom, it is often desirable to optimize the `Model` estimate obtained from a GST algorithm within the space of its gauge freedoms. This process is called "gauge-optimization" and the final part of this tutorial demonstrates how to gauge-optimize a model using various criteria.
## Primary GST Algorithms
The ingredients needed to as input to the "primary" GST algorithms are:
- a "target" `Model` which defines the desired gates. This model is used by LGST to specify the various gate, state preparation, POVM effect, and SPAM labels, as well as to provide an initial guess for the *gauge* degrees of freedom.
- a `DataSet` containing the data that GST attempts to fit using the probabilities generated by a single `Model`. This data set must at least contain the data for the operation sequences required by the algorithm that is chosen.
- for EXLGST, MC2GST, and MLGST, a list-of-lists of `Circuit` objects, which specify which operation sequences are used during each iteration of the algorithm (the length of the top-level list defines the number of interations). Note that which operation sequences are included in these lists is different for EXLGST than it is for MC2GST and MLGST.
```
import pygsti
import json
#We'll use the standard I, X(pi/2), Y(pi/2) model that we generated data for in the DataSet tutorial
from pygsti.modelpacks import smq1Q_XYI
target_model = smq1Q_XYI.target_model()
prep_fiducials = smq1Q_XYI.prep_fiducials()
meas_fiducials = smq1Q_XYI.meas_fiducials()
germs = smq1Q_XYI.germs()
maxLengthList = [1,2,4,8,16] #for use in iterative algorithms
ds = pygsti.io.load_dataset("../../tutorial_files/Example_Dataset.txt", cache=True)
dsLowCounts = pygsti.io.load_dataset("../../tutorial_files/Example_Dataset_LowCnts.txt", cache=True)
depol_model = target_model.depolarize(op_noise=0.1)
print("Loaded target model with operation labels: ", target_model.operations.keys())
print("Loaded fiducial lists of lengths: ", (len(prep_fiducials),len(meas_fiducials)))
print("Loaded dataset of length: ", len(ds))
```
### Using LGST to get an initial estimate
An important and distinguising property of the LGST algorithm is that it does *not* require an initial-guess `Model` as an input. It uses linear inversion and short sequences to obtain a rough model estimate. As such, it is very common to use the LGST estimate as the initial-guess starting point for more advanced forms of GST.
```
#Run LGST to get an initial estimate for the gates in target_model based on the data in ds
#run LGST
mdl_lgst = pygsti.do_lgst(ds, prep_fiducials, meas_fiducials, targetModel=target_model, verbosity=1)
#Gauge optimize the result to match the target model
mdl_lgst_after_gauge_opt = pygsti.gaugeopt_to_target(mdl_lgst, target_model, verbosity=1)
#Contract the result to CPTP, guaranteeing that the gates are CPTP
mdl_clgst = pygsti.contract(mdl_lgst_after_gauge_opt, "CPTP", verbosity=1)
print(mdl_lgst)
```
### Extended LGST (eLGST or EXLGST)
EXLGST requires a list-of-lists of operation sequences, one per iteration. The elements of these lists are typically repetitions of short "germ" strings such that the final strings does not exceed some maximum length. We created such lists in the operation sequence tutorial. Now, we just load these lists from the text files they were saved in.
```
#Get rho and E specifiers, needed by LGST
elgstListOfLists = pygsti.construction.make_elgst_lists(target_model, germs, maxLengthList)
#run EXLGST. The result, mdl_exlgst, is a Model containing the estimated quantities
mdl_exlgst = pygsti.do_iterative_exlgst(ds, mdl_clgst, prep_fiducials, meas_fiducials, elgstListOfLists,
targetModel=target_model, verbosity=2)
```
### Minimum-$\chi^2$ GST (MC2GST)
MC2GST and MLGST also require a list-of-lists of operation sequences, one per iteration. However, the elements of these lists are typically repetitions of short "germ" strings *sandwiched between fiducial strings* such that the repeated-germ part of the string does not exceed some maximum length. We created such lists in the operation sequence tutorial. Now, we just load these lists from the text files they were saved in.
```
#Get lists of operation sequences for successive iterations of LSGST to use
lsgstListOfLists = pygsti.construction.make_lsgst_lists(target_model, prep_fiducials, meas_fiducials, germs, maxLengthList)
#run MC2GST. The result is a Model containing the estimated quantities
mdl_mc2 = pygsti.do_iterative_mc2gst(ds, mdl_clgst, lsgstListOfLists, verbosity=2)
#Write the resulting EXLGST and MC2GST results to model text files for later reference.
pygsti.io.write_model(mdl_exlgst, "../../tutorial_files/Example_eLGST_Gateset.txt","# Example result from running eLGST")
pygsti.io.write_model(mdl_mc2, "../../tutorial_files/Example_MC2GST_Gateset.txt","# Example result from running MC2GST")
#Run MC2GST again but use a DataSet with a lower number of counts
mdl_mc2_lowcnts = pygsti.do_iterative_mc2gst(dsLowCounts, mdl_clgst, lsgstListOfLists, verbosity=2)
```
### Maximum Likelihood GST (MLGST)
Executing MLGST is very similar to MC2GST: the same operation sequence lists can be used and calling syntax is nearly identitcal.
```
#run MLGST. The result is a Model containing the estimated quantities
mdl_mle = pygsti.do_iterative_mlgst(ds, mdl_clgst, lsgstListOfLists, verbosity=2)
#Run MLGST again but use a DataSet with a lower number of counts
mdl_mle_lowcnts = pygsti.do_iterative_mlgst(dsLowCounts, mdl_clgst, lsgstListOfLists, verbosity=2)
```
## Gauge Optimization
All gauge optimization algorithms perform essentially the same task - to find the model which optimizes some objective function from within the set or space of models that are gauge-equivalent to some starting set. This is accomplished in `pygsti` using the following mechanism:
- one begins with an initial `ExplicitOpModel`, call it `mdl`, to be gauge-optimized.
- a `pygsti.objects.GaugeGroup` instance defines a parameterized group of allowable gauge transformations. This gauge group must be compatible with the `mdl`'s parameterization, so that `mdl.transform` (which calls `LinearOperator.transform` and `SPAMVec.transform`) is able to process elements of the `GaugeGroup` (obtained via a call to `GaugeGroup.get_element(params)`). That is, the gauge transformation must map between models with the *same* parameterization (that give by `mdl`). Because of the close interplay between a model's parameterization and its allowed gauge transformations, `Model` objects can contain a `GaugeGroup` instance as their `default_gauge_group` member. In many circumstances, `mdl.default_gauge_group` is set to the correct gauge group to use for a given `Model`.
- `pygsti.gaugeopt_custom(...)` takes an intial `ExplicitOpModel`, an objective function, and a `GaugeGroup` (along with other optimization parameters) and returns a gauge-optimized `ExplicitOpModel`. Note that if its `gauge_group` argument is left as `None`, then the model's default gauge group is used. And objective function which takes a single `ExplicitOpModel` argument and returns a float can be supplied, giving the user a fair amount of flexiblity.
- since usually the objective function is one which compares the model being optimized to a fixed "target" model, `pygsti.gaugeopt_to_target(...)` is a routine able to perform these common types of gauge optimization. Instead of an objective function, `gaugeopt_to_target` takes a target `ExplicitOpModel` and additional arguments (see below) from which it constructs a objective function and then calls `gaugeopt_custom`. It is essetially a convenience routine for constructing common gauge optimization objective functions. Relevant arguments which affect what objective function is used are:
- `targetModel` : the `ExplicitOpModel` to compare against - i.e., the one you want to gauge optimize toward. **Note that this doesn't have to be a set of ideal gates **- it can be any (imperfect) model that reflects your expectations about what the estimates should look like.
- `itemWeights` : a dictionary of weights allowing different gates and/or SPAM operations to be weighted differently when computing the objective function's value.
- `CPpenalty` : a prefactor multiplying the sum of all the negative Choi-matrix eigenvalues corresponding to each of the gates.
- `TPpenalty` : a prefactor multiplying the sum of absoulte-value differences between the first row of each operation matrix and `[1 0 ... 0 ]` and the discrpance between the first element of each state preparation vector and its expected value.
- `validSpamPenalty` : a prefactor multiplying penalty terms enforcing the non-negativity of state preparation eigenavlues and that POVM effect eigenvalues lie between 0 and 1.
- `gatesMetric` : how to compare corresponding gates in the gauge-optimized and target sets. `"frobenius`" uses the frobenius norm (weighted before taking the final sqrt), `"fidelity"` uses the *squared process infidelity* (squared to avoid negative-infidelity issues in non-TP models), and `"tracedist"` uses the trace distance (weighted after computing the trace distance between corresponding gates).
- `spamMetric` : how to compare corresponding SPAM vectors. `"frobenius"` (the default) should be used here, as `"fidelity"` and `"tracedist"` compare the "SPAM gates" -- the outer product of state prep and POVM effect vectors -- which isn't a meaningful metric.
The cell below demonstrates some of common usages of `gaugeopt_to_target`.
```
mdl = mdl_mle.copy() #we'll use the MLGST result from above as an example
mdl_go1 = pygsti.gaugeopt_to_target(mdl, target_model) # optimization to the perfect target gates
mdl_go2 = pygsti.gaugeopt_to_target(mdl, depol_model) # optimization to a "guess" at what the estimate should be
mdl_go3 = pygsti.gaugeopt_to_target(mdl, target_model, {'gates': 1.0, 'spam': 0.01})
# weight the gates differently from the SPAM operations
mdl_go4 = pygsti.gaugeopt_to_target(mdl, target_model, {'gates': 1.0, 'spam': 0.01, 'Gx': 10.0, 'E0': 0.001})
# weight an individual gate/SPAM separately (note the specific gate/SPAM labels always override
# the more general 'gates' and 'spam' weight values).
mdl_go5 = pygsti.gaugeopt_to_target(mdl, target_model, gatesMetric="tracedist") #use trace distance instead of frobenius
print("Default gauge group = ",type(mdl.default_gauge_group)) # default is FullGaugeGroup
mdl_go6 = pygsti.gaugeopt_to_target(mdl, target_model, gauge_group=pygsti.objects.UnitaryGaugeGroup(mdl.dim, 'pp'))
#gauge optimize only over unitary gauge transformations
print("\ngaugeopt_to_target output:")
mdl_go7 = pygsti.gaugeopt_to_target(mdl, target_model, verbosity=3) # show output
print("Final frobenius distance between mdl_go7 and target_model = ", mdl_go7.frobeniusdist(target_model))
```
## Compare MLGST with MC2GST (after gauge optimization)
Both MLGST and MC2GST use a $\chi^{2}$ optimization procedure for all but the final iteration. For the last set of circuits (the last iteration), MLGST uses a maximum likelihood estimation. Below, we show how close the two estimates are to one another. Before making the comparison, however, we **optimize the gauge** so the estimated gates are as close to the target gates as the gauge degrees of freedom allow.
```
# We optimize over the model gauge
mdl_mle = pygsti.gaugeopt_to_target(mdl_mle,depol_model)
mdl_mle_lowcnts = pygsti.gaugeopt_to_target(mdl_mle_lowcnts,depol_model)
mdl_mc2 = pygsti.gaugeopt_to_target(mdl_mc2,depol_model)
mdl_mc2_lowcnts = pygsti.gaugeopt_to_target(mdl_mc2_lowcnts,depol_model)
print("Frobenius diff btwn MLGST and datagen = {0}".format(round(mdl_mle.frobeniusdist(depol_model), 6)))
print("Frobenius diff btwn MC2GST and datagen = {0}".format(round(mdl_mc2.frobeniusdist(depol_model), 6)))
print("Frobenius diff btwn MLGST and LGST = {0}".format(round(mdl_mle.frobeniusdist(mdl_clgst), 6)))
print("Frobenius diff btwn MLGST and MC2GST = {0}".format(round(mdl_mle.frobeniusdist(mdl_mc2), 6)))
print("Chi^2 ( MC2GST ) = {0}".format(round(pygsti.chi2(mdl_mc2, ds, lsgstListOfLists[-1]), 4)))
print("Chi^2 ( MLGST ) = {0}".format(round(pygsti.chi2(mdl_mle, ds, lsgstListOfLists[-1] ), 4)))
print("LogL ( MC2GST ) = {0}".format(round(pygsti.logl(mdl_mc2, ds, lsgstListOfLists[-1]), 4)))
print("LogL ( MLGST ) = {0}".format(round(pygsti.logl(mdl_mle, ds, lsgstListOfLists[-1]), 4)))
```
Notice that, as expected, the MC2GST estimate has a *slightly* lower $\chi^{2}$ score than the MLGST estimate, and the MLGST estimate has a *slightly* higher loglikelihood than the MC2GST estimate. In addition, _both_ are close (in terms of the Frobenius difference) to the depolarized model. Which is good - it means GST is giving us estimates which are close to the _true_ model used to generate the data. Performing the same analysis with the low-count data shows larger differences between the two, which is expected since the $\chi^2$ and loglikelihood statistics are more similar at large $N$, that is, for large numbers of samples.
```
print("LOW COUNT DATA:")
print("Frobenius diff btwn MLGST and datagen = {0}".format(round(mdl_mle_lowcnts.frobeniusdist(depol_model), 6)))
print("Frobenius diff btwn MC2GST and datagen = {0}".format(round(mdl_mc2_lowcnts.frobeniusdist(depol_model), 6)))
print("Frobenius diff btwn MLGST and LGST = {0}".format(round(mdl_mle_lowcnts.frobeniusdist(mdl_clgst), 6)))
print("Frobenius diff btwn MLGST and MC2GST = {0}".format(round(mdl_mle_lowcnts.frobeniusdist(mdl_mc2), 6)))
print("Chi^2 ( MC2GST ) = {0}".format(round(pygsti.chi2(mdl_mc2_lowcnts, dsLowCounts, lsgstListOfLists[-1]), 4)))
print("Chi^2 ( MLGST ) = {0}".format(round(pygsti.chi2(mdl_mle_lowcnts, dsLowCounts, lsgstListOfLists[-1] ), 4)))
print("LogL ( MC2GST ) = {0}".format(round(pygsti.logl(mdl_mc2_lowcnts, dsLowCounts, lsgstListOfLists[-1]), 4)))
print("LogL ( MLGST ) = {0}".format(round(pygsti.logl(mdl_mle_lowcnts, dsLowCounts, lsgstListOfLists[-1]), 4)))
```
| github_jupyter |
```
from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms, models
from torch.optim.lr_scheduler import StepLR
def cmd_args():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=14, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
args = parser.parse_args()
return args
args = cmd_args()
use_cuda = torch.cuda.is_available()
seed = 42
torch.manual_seed(seed)
device = torch.device("cuda" if use_cuda else "cpu")
batch_size = 32
kwargs = {'batch_size': batch_size}
if use_cuda:
kwargs.update({'num_workers': 1,
'pin_memory': True,
'shuffle': True},
)
# prepare transform
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
# load mnist data
datasets_path = os.path.expanduser("~/.datasets")
mnist_train = datasets.MNIST(
datasets_path, train=True, download=True, transform=transform)
mnist_test = datasets.MNIST(
datasets_path, train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(mnist_train, **kwargs)
test_loader = torch.utils.data.DataLoader(mnist_test, **kwargs)
# choose model: resnet18
resnet18 = models.resnet18(pretrained=True)
resnet18
resnet18.fc
import matplotlib.pyplot as plt
img, label = mnist_train[0]
_img = img.reshape(28, 28)
plt.imshow(_img)
img, label = mnist_train[0]
print(type(img))
print(img.size())
print(label)
resnet18(img)
```
| github_jupyter |
```
import pandas as pd
import numpy as np
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
start_mem = df.memory_usage().sum()
print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col_type = df[col].dtype
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
df[col] = df[col].astype(np.int16)
elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
df[col] = df[col].astype(np.int32)
elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
df[col] = df[col].astype(np.int64)
else:
if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
df[col] = df[col].astype(np.float16)
elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
df[col] = df[col].astype(np.float32)
else:
df[col] = df[col].astype(np.float64)
else:
df[col] = df[col].astype('category')
end_mem = df.memory_usage().sum()
print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
return df
def load_data(path):
user = reduce_mem_usage(pd.read_csv(path + 'user.csv',header=None))
item = reduce_mem_usage(pd.read_csv(path + 'item.csv',header=None))
data = pd.read_csv(path + 'user_behavior.csv',header=None)
data.columns = ['userID','itemID','behavior','timestamp']
data['day'] = data['timestamp'] // 86400
data['hour'] = data['timestamp'] // 3600 % 24
## 生成behavior的onehot
for i in ['pv','fav','cart','buy']:
data[i] = 0
data.loc[data['behavior'] == i, i] = 1
## 生成behavior的加权
data['day_hour'] = data['day'] + data['hour'] / float(24)
data.loc[data['behavior']=='pv','behavior'] = 1
data.loc[data['behavior']=='fav','behavior'] = 2
data.loc[data['behavior']=='cart','behavior'] = 3
data.loc[data['behavior']=='buy','behavior'] = 1
max_day = max(data['day'])
min_day = min(data['day'])
data['behavior'] = (1 - (max_day-data['day_hour']+2)/(max_day-min_day+2)) * data['behavior']
item.columns = ['itemID','category','shop','brand']
user.columns = ['userID','sex','age','ability']
data = reduce_mem_usage(data)
data = pd.merge(left=data, right=item, on='itemID',how='left')
data = pd.merge(left=data, right=user, on='userID',how='left')
return user, item, data
path = '../ECommAI_EUIR_round2_train_20190816/'
user, item, data = load_data(path = path)
```
## 2019/09/21 晚 实验
提取某个商品/店铺/类别/品牌 距离第15 and 16天的最后一次点击
```
train = data[data['day'] < 15]
start_timestamp = max(train['timestamp'])
train['last_time'] = start_timestamp - train['timestamp']
timefeatures = []
for time_feature in ['itemID', 'shop', 'category','brand']:
name = time_feature + '_last_time_underline.csv'
tf = train[['last_time', time_feature]].groupby(
time_feature, as_index=False).agg({'last_time':'min'}).rename(columns={'last_time': time_feature + 'last_time'})
tf[time_feature + 'last_time_hour_ed'] = tf[time_feature + 'last_time'] // 3600 % 24
timefeatures.append((name, tf))
for f in timefeatures:
f[1].to_csv(f[0], index=False)
```
| github_jupyter |
(use/api)=
# Python API
This page outlines how to utilise the cache programatically.
We step throught the three aspects illustrated in the diagram below:
[cacheing](use/api/cache), [staging](use/api/project) and [executing](use/api/execute).
```{figure} images/execution_process.svg
:width: 500 px
Illustration of the execution process.
```
```{note}
The full Jupyter notebook for this page can accessed here; {nb-download}`api.ipynb`.
Try it for yourself!
```
## Initialisation
```
from pathlib import Path
import nbformat as nbf
from jupyter_cache import get_cache
from jupyter_cache.base import CacheBundleIn
from jupyter_cache.executors import load_executor, list_executors
from jupyter_cache.utils import (
tabulate_cache_records,
tabulate_project_records
)
```
First we setup a cache and ensure that it is cleared.
```{important}
Clearing a cache wipes its entire content, including any settings (such as cache limit).
```
```
cache = get_cache(".jupyter_cache")
cache.clear_cache()
cache
print(cache.list_cache_records())
print(cache.list_project_records())
```
(use/api/cache)=
## Cacheing Notebooks
To directly cache a notebook:
```
record = cache.cache_notebook_file(
path=Path("example_nbs", "basic.ipynb")
)
record
```
This will add a physical copy of the notebook to tha cache (stripped of any text cells) and return the record that has been added to the cache database.
```{important}
The returned record is static, as in it will not update if the database is updated.
```
The record stores metadata for the notebook:
```
record.to_dict()
```
```{important}
The URI that the notebook is read from is stored, but does not have an impact on later comparison of notebooks. They are only compared by their internal content.
```
We can retrive cache records by their Primary Key (pk):
```
cache.list_cache_records()
cache.get_cache_record(1)
```
To load the entire notebook that is related to a pk:
```
nb_bundle = cache.get_cache_bundle(1)
nb_bundle
nb_bundle.nb
```
Trying to add a notebook to the cache that matches an existing one will result in a error, since the cache ensures that all notebook hashes are unique:
```
record = cache.cache_notebook_file(
path=Path("example_nbs", "basic.ipynb")
)
```
If we load a notebook external to the cache, then we can try to match it to one
stored inside the cache:
```
notebook = nbf.read(str(Path("example_nbs", "basic.ipynb")), 4)
notebook
cache.match_cache_notebook(notebook)
```
Notebooks are matched by a hash based only on aspects of the notebook that will affect its execution (and hence outputs). So changing text cells will match the cached notebook:
```
notebook.cells[0].source = "change some text"
cache.match_cache_notebook(notebook)
```
But changing code cells will result in a different hash, and so will not be matched:
```
notebook.cells[1].source = "change some source code"
cache.match_cache_notebook(notebook)
```
To understand the difference between an external notebook, and one stored in the cache, we can 'diff' them:
```
print(cache.diff_nbnode_with_cache(1, notebook, as_str=True))
```
If we cache this altered notebook, note that this will not remove the previously cached notebook:
```
nb_bundle = CacheBundleIn(
nb=notebook,
uri=Path("example_nbs", "basic.ipynb"),
data={"tag": "mytag"}
)
cache.cache_notebook_bundle(nb_bundle)
print(tabulate_cache_records(
cache.list_cache_records(), path_length=1, hashkeys=True
))
```
Notebooks are retained in the cache, until the cache limit is reached,
at which point the oldest notebooks are removed.
```
cache.get_cache_limit()
cache.change_cache_limit(100)
```
(use/api/project)=
## Staging Notebooks for Execution
Notebooks can be staged, by adding the path as a stage record.
```{important}
This does not physically add the notebook to the cache,
merely store its URI, for later use.
```
```
record = cache.add_nb_to_project(Path("example_nbs", "basic.ipynb"))
record
record.to_dict()
```
If the staged notbook relates to one in the cache, we will be able to retrieve the cache record:
```
cache.get_cached_project_nb(1)
print(tabulate_project_records(
cache.list_project_records(), path_length=2, cache=cache
))
```
We can also retrieve a *merged* notebook.
This is a copy of the source notebook with the following added to it from the cached notebook:
- Selected notebook metadata keys (generally only those keys that affect its execution)
- All code cells, with their outputs and metadata
(only selected metadata can be merged if `cell_meta` is not `None`)
In this way we create a notebook that is *fully* up-to-date for both its code and textual content:
```
cache.merge_match_into_file(
cache.get_project_record(1).uri,
nb_meta=('kernelspec', 'language_info', 'widgets'),
cell_meta=None
)
```
If we add a notebook that cannot be found in the cache, it will be listed for execution:
```
record = cache.add_nb_to_project(Path("example_nbs", "basic_failing.ipynb"))
record
cache.get_cached_project_nb(2) # returns None
cache.list_unexecuted()
print(tabulate_project_records(
cache.list_project_records(), path_length=2, cache=cache
))
```
To remove a notebook from the staging area:
```
cache.remove_nb_from_project(1)
print(tabulate_project_records(
cache.list_project_records(), path_length=2, cache=cache
))
```
(use/api/execute)=
## Execution
If we have some staged notebooks:
```
cache.clear_cache()
cache.add_nb_to_project(Path("example_nbs", "basic.ipynb"))
cache.add_nb_to_project(Path("example_nbs", "basic_failing.ipynb"))
print(tabulate_project_records(
cache.list_project_records(), path_length=2, cache=cache
))
```
Then we can select an executor (specified as entry points) to execute the notebook.
```{tip}
To view the executors log, make sure logging is enabled,
or you can parse a logger directly to `load_executor()`.
```
```
list_executors()
from logging import basicConfig, INFO
basicConfig(level=INFO)
executor = load_executor("local-serial", cache=cache)
executor
```
Calling `run_and_cache()` will run all staged notebooks that do not already have matches in the cache.
It will return a dictionary with lists for:
- **succeeded**: The notebook was executed successfully with no (or only expected) exceptions
- **excepted**: A notebook cell was encountered that raised an unexpected exception
- **errored**: An exception occured before/after the actual notebook execution
```{tip}
Code cells can be tagged with `raises-exception` to let the executor known that
a cell *may* raise an exception (see [this issue on its behaviour](https://github.com/jupyter/nbconvert/issues/730)).
```
```{note}
You can use the `filter_uris` and/or `filter_pks` options to only run selected staged notebooks.
You can also specify the timeout for execution in seconds using the `timeout` option.
```
```
result = executor.run_and_cache()
result
```
Successfully executed notebooks will be added to the cache, and data about their execution (such as time taken) will be stored in the cache record:
```
cache.list_cache_records()
record = cache.get_cache_record(1)
record.to_dict()
```
Notebooks which failed to run will **not** be added to the cache,
but details about their execution (including the exception traceback)
will be added to the stage record:
```
record = cache.get_project_record(2)
print(record.traceback)
```
We now have two staged records, and one cache record:
```
print(tabulate_project_records(
cache.list_project_records(), path_length=2, cache=cache
))
print(tabulate_cache_records(
cache.list_cache_records(), path_length=1, hashkeys=True
))
```
### Timeout
A **timeout** argument can also be passed to `run_and_cache()` which takes value in seconds.
Alternatively, timeout can also be specified inside the notebook metadata:
```
'execution': {
'timeout': 30
}
```
```{note}
Timeout specified in notebook metadata will take precedence over the one passed as an argument to `run_and_cache()`.
```
| github_jupyter |
# Tutorial 13: Running RLlib experiments on EC2
This tutorial walks through how to run RLlib experiments on an AWS EC2 instance. This assumes that the machine you are using has already been configured for AWS (i.e. `~/.aws/credentials` is properly set up). We HIGHLY RECOMMEND the following as prior reading, as this will be something of an abridged version: https://github.com/ray-project/ray/blob/master/doc/source/autoscaling.rst
While going through the above documentation, you can ignore all instructions on GCP, as GCP will not be covered in this tutorial.
## A brief description of ray_autoscale.yaml
This section explains the most salient components of `/flow/scripts/ray_autoscale.yaml`. We'll go over some of the variables you should change, as well as those that might come in handy for you. A more detailed guide is on deck soon.
* `cluster_name`: (CHANGE ME!) A unique identifier for the head node and workers of this cluster. If you want to set up multiple clusters, `cluster_name` must be changed each time the script is run.
* `AMI`: This specifies which AMI to launch this instance with. We provide a pre-built AMI for usage in flow/ray_autoscale.yaml which is available for usage. For further reading, please check out: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html
* `setup_commands`: This describes the set of commands to run after the instance is up and running in the $HOME directory. Commands can vary widely. If you're running experiments, you're most likely on a branch that is not 'master'. This is the right place to specify which branch you want to sync to EC2.
* To specify a branch from the main flow-project repo will look something like:
`cd flow && git pull && git checkout [YOUR-BRANCH-HERE]`
* To specify a branch from your fork, the command will look something like this:
`git remote add [USER] https://github.com/[USER]/flow && git fetch [USER] && git checkout [USER] [YOUR-BRANCH-HERE]
## Setup and run clusters
1. Once your yaml file is properly configured, start the cluster with:
`ray up ray_autoscale.yaml -y`
* The -y flag is optional, it simply indicates 'yes' to all follow-up questions
2. Use the `ray exec` command to communicate with your cluster.
`ray exec ray_autoscale.yaml "flow/examples/stabilizing_the_ring.py"`
* For a list of options you can provide to this command which will enable a variety of helpful options such as running in tmux or stopping after the command completes, view the link at the beginning of this tutorial.
3. Attach to the cluster via `ray attach`.
`ray attach ray_autoscale.yaml -y`
* This ssh's into the cluster.
Note that the above steps 2-3 can become tedious if you create multiple clusters, and thus there are many versions of ray_autoscale.yaml lying around. For further explanation, read on: ray commands identify clusters according to the cluster_name attribute in ray_autoscale.yaml, so if you create 'test_0', test_1', 'test_2', 'test_3', and 'test_4' by simply erasing 'test_0' and replacing it with 'test_1', and so on, you would have to manually change the cluster_name in ray_autoscale.yaml to specify which cluster you intend to interact with while using `ray attach`, `ray exec`, or other `ray` commands. An alternative is this: when the cluster is created i.e. after `ray up ray_autoscale.yaml -y` is successful, it returns a ssh command to connect to that cluster's IP directly. When running multiple clusters, it can be useful to save these ssh commands.
Note note, that a helpful, streamlined method of starting and executing a cluster in one fell swoop can be done via: <br />
4. `ray exec ray_autoscale.yaml flow/examples/stabilizing_the_ring.py --start`
## Run Experiments
Steps 2 and 4 from the previous section indicate how one may begin RLlib experiments in EC2. This section goes over some caveats to consider while running experiments.
* tmux: Running experiments in tmux within the cluster is highly recommended, as this allows you keep the process running in the background whil you ssh out of the cluster or move around within the cluster. This can be achieved by supplying the `ray exec` command with the `--tmux` flag.
- Or if you want to create a tmux session manually:
- To create a new session: `tmux new [-s] [SESSION_NAME]`
- To list all sessions: `tmux ls`
- To attach to the most recently created session: `tmux a`
- `tmux a #` if multiple sessions exist
- To attach to a specific session: `tmux a -t [SESSION_NO]`
- To detach from a session: ctrl-b + d
- To kill a session: `tmux kill-session -t [SESSION_NO]`
- To scroll within the session: ctrl-b + \[
- To exit scroll mode: `q`
* Information about managing results: As usual, ray results will be automatically written to /$HOME/ray_results. To upload these results to Amazon s3, you should configure this step before running the experiment. An argument should be included within flow_params in the runner script (i.e. stabilizing_the_ring.py) in the following fashion (note the # CHANGE ME!!! comment):
```
if __name__ == "__main__":
alg_run, gym_name, config = setup_exps()
ray.init(num_cpus=N_CPUS + 1)
trials = run_experiments({
flow_params["exp_tag"]: {
"run": alg_run,
"env": gym_name,
"config": {
**config
},
"checkpoint_freq": 20,
"checkpoint_at_end": True,
"max_failures": 999,
"stop": {
"training_iteration": 200,
},
upload_dir: 's3://path/to/your/bucket', # CHANGE ME!!!
}
})
```
## Close Clusters
When you are done with the experiment, it's time to close the cluster. There are a few ways to do this.
* ray down ray_autoscale.yaml -y
* Go to your EC2 instance console and terminate the desired instance
* Run your cluster command with the `--stop` option, so that the cluster will terminate once the command is complete.
| github_jupyter |
# Calibrating single-qubit gates on `ibmq_armonk`
In this tutorial we demonstrate how to calibrate single-qubit gates on `ibmq_armonk` using the calibration framework in qiskit-experiments. We will run experiments to find the qubit frequency, calibrate the amplitude of DRAG pulses and chose the value of the DRAG parameter that minimizes leakage. The calibration framework requires the user to
* setup an instance of `Calibrations`,
* run calibration experiments which can be found in `qiskit_experiments.library.calibration`.
Note that the values of the parameters stored in the instance of the `Calibrations` class will automatically be updated by the calibration experiments. This automatic updating can also be disabled using the `auto_update` flag.
```
import pandas as pd
import numpy as np
import qiskit.pulse as pulse
from qiskit.circuit import Parameter
from qiskit_experiments.calibration_management.calibrations import Calibrations
from qiskit import IBMQ, schedule
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
qubit = 0 # The qubit we will work with
```
The two functions below show how to setup an instance of `Calibrations`. To do this the user defines the template schedules to calibrate. These template schedules are fully parameterized, even the channel indices on which the pulses are played. Furthermore, the name of the parameter in the channel index must follow the convention laid out in the documentation of the calibration module. Note that the parameters in the channel indices are automatically mapped to the channel index when `get_schedule` is called.
```
def setup_cals(backend) -> Calibrations:
"""A function to instantiate calibrations and add a couple of template schedules."""
cals = Calibrations.from_backend(backend)
dur = Parameter("dur")
amp = Parameter("amp")
sigma = Parameter("σ")
beta = Parameter("β")
drive = pulse.DriveChannel(Parameter("ch0"))
# Define and add template schedules.
with pulse.build(name="xp") as xp:
pulse.play(pulse.Drag(dur, amp, sigma, beta), drive)
with pulse.build(name="xm") as xm:
pulse.play(pulse.Drag(dur, -amp, sigma, beta), drive)
with pulse.build(name="x90p") as x90p:
pulse.play(pulse.Drag(dur, Parameter("amp"), sigma, Parameter("β")), drive)
cals.add_schedule(xp, num_qubits=1)
cals.add_schedule(xm, num_qubits=1)
cals.add_schedule(x90p, num_qubits=1)
return cals
def add_parameter_guesses(cals: Calibrations):
"""Add guesses for the parameter values to the calibrations."""
for sched in ["xp", "x90p"]:
cals.add_parameter_value(80, "σ", schedule=sched)
cals.add_parameter_value(0.5, "β", schedule=sched)
cals.add_parameter_value(320, "dur", schedule=sched)
cals.add_parameter_value(0.5, "amp", schedule=sched)
```
When setting up the calibrations we add three pulses: a $\pi$-rotation, with a schedule named `xp`, a schedule `xm` identical to `xp` but with a nagative amplitude, and a $\pi/2$-rotation, with a schedule named `x90p`. Here, we have linked the amplitude of the `xp` and `xm` pulses. Therefore, calibrating the parameters of `xp` will also calibrate the parameters of `xm`.
```
cals = setup_cals(backend)
add_parameter_guesses(cals)
```
A samilar setup is achieved by using a pre-built library of gates. The library of gates provides a standard set of gates and some initial guesses for the value of the parameters in the template schedules. This is shown below using the `FixedFrequencyTransmon` which provides the `x`, `y`, `sx`, and `sy` pulses. Note that in the example below we change the default value of the pulse duration to 320 samples.
```
from qiskit_experiments.calibration_management.basis_gate_library import FixedFrequencyTransmon
library = FixedFrequencyTransmon(default_values={"duration": 320})
cals = Calibrations.from_backend(backend, library)
```
## 1. Finding qubits with spectroscopy
Here, we are using a backend for which we already know the qubit frequency. We will therefore use the spectroscopy experiment to confirm that there is a resonance at the qubit frequency reported by the backend.
```
from qiskit_experiments.library.calibration.rough_frequency import RoughFrequencyCal
```
We first show the contents of the calibrations for qubit 0. Note that the guess values that we added before apply to all qubits on the chip. We see this in the table below as an empty tuple `()` in the qubits column. Observe that the parameter values of `xm` do not appear in this table as they are given by the values of `xp`.
```
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()]))
freq01_estimate = backend.defaults().qubit_freq_est[qubit]
frequencies = np.linspace(freq01_estimate -15e6, freq01_estimate + 15e6, 51)
spec = RoughFrequencyCal(qubit, cals, frequencies, backend=backend)
spec.set_experiment_options(amp=0.1)
circuit = spec.circuits()[0]
circuit.draw(output="mpl")
schedule(circuit, backend).draw()
spec_data = spec.run().block_for_results()
spec_data.figure(0)
print(spec_data.analysis_results("f01"))
```
We now update the instance of `Calibrations` with the value of the frequency that we measured using the `Frequency.update` function. Note that for the remainder of this notebook we use the value of the qubit frequency in the backend as it is not yet possible to updated qubit frequencies with the circuit path.
```
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit]))
```
As seen from the table above the measured frequency has been added to the calibrations.
## 2. Calibrating the pulse amplitudes with a Rabi experiment
In the Rabi experiment we apply a pulse at the frequency of the qubit and scan its amplitude to find the amplitude that creates a rotation of a desired angle. We do this with the calibration experiment `RoughXSXAmplitudeCal`. This is a specialization of the `Rabi` experiment that will update the calibrations for both the `X` pulse and the `SX` pulse using a single experiment.
```
from qiskit_experiments.library.calibration import RoughXSXAmplitudeCal
rabi = RoughXSXAmplitudeCal(qubit, cals, backend=backend)
```
The rough amplitude calibration is therefore a Rabi experiment in which each circuit contains a pulse with a gate. Different circuits correspond to pulses with different amplitudes.
```
rabi.circuits()[0].draw("mpl")
```
After the experiment completes the value of the amplitudes in the calibrations will automatically be updated. This behaviour can be controlled using the `auto_update` argument given to the calibration experiment at initialization.
```
rabi_data = rabi.run().block_for_results()
rabi_data.figure(0)
print(rabi_data.analysis_results("rabi_rate"))
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="amp"))
```
The table above shows that we have now updated the amplitude of our $\pi$-pulse from 0.5 to the value obtained in the most recent Rabi experiment. Importantly, since we linked the amplitudes of the `x` and `y` schedules we will see that the amplitude of the `y` schedule has also been updated as seen when requesting schedules form the `Calibrations` instance. Furthermore, we used the result from the `Rabi` experiment to also update the value of the `sx` pulse. This was achieved by specifying `(np.pi/2, "amp", "sx")` when calling `update`.
```
cals.get_schedule("sx", qubit)
cals.get_schedule("x", qubit)
cals.get_schedule("y", qubit)
```
## 3. Saving and loading calibrations
The values of the calibrated parameters can be saved to a `.csv` file and reloaded at a later point in time.
```
cals.save(file_type="csv", overwrite=True, file_prefix="Armonk")
```
After saving the values of the parameters you may restart your kernel. If you do so, you will only need to run the following cell to recover the state of your calibrations. Since the schedules are currently not stored we need to call our `setup_cals` function to populate an instance of `Calibrations` with the template schedules. By contrast, the value of the parameters will be recovered from the file.
```
cals = Calibrations.from_backend(backend, library)
cals.load_parameter_values(file_name="Armonkparameter_values.csv")
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="amp"))
```
## 4. Calibrating the value of the DRAG coefficient
A Derivative Removal by Adiabatic Gate (DRAG) pulse is designed to minimize leakage
to a neighbouring transition. It is a standard pulse with an additional derivative
component. It is designed to reduce the frequency spectrum of a normal pulse near
the $|1\rangle$ - $|2\rangle$ transition, reducing the chance of leakage
to the $|2\rangle$ state. The optimal value of the DRAG parameter is chosen to
minimize both leakage and phase errors resulting from the AC Stark shift.
The pulse envelope is $f(t) = \Omega_x(t) + j \beta \frac{\rm d}{{\rm d }t} \Omega_x(t)$.
Here, $\Omega_x$ is the envelop of the in-phase component of the pulse and
$\beta$ is the strength of the quadrature which we refer to as the DRAG
parameter and seek to calibrate in this experiment.
The DRAG calibration will run
several series of circuits. In a given circuit a Rp(β) - Rm(β) block is repeated
$N$ times. Here, Rp is a rotation with a positive angle and Rm is the same rotation
with a negative amplitude.
```
from qiskit_experiments.library import RoughDragCal
cal_drag = RoughDragCal(qubit, cals, backend=backend, betas=np.linspace(-20, 20, 25))
cal_drag.set_experiment_options(reps=[3, 5, 7])
cal_drag.circuits()[5].draw(output='mpl')
drag_data = cal_drag.run().block_for_results()
drag_data.figure(0)
print(drag_data.analysis_results("beta"))
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="β"))
```
## 5. Fine amplitude calibration
The `FineAmplitude` calibration experiment repeats $N$ times a gate with a pulse
to amplify the under or over-rotations in the gate to determine the optimal amplitude.
The circuits that are run have a custom gate with the pulse schedule attached to it
through the calibrations.
```
from qiskit_experiments.library.calibration.fine_amplitude import FineXAmplitudeCal
amp_x_cal = FineXAmplitudeCal(qubit, cals, backend=backend, schedule_name="x")
amp_x_cal.circuits()[5].draw(output="mpl")
data_fine = amp_x_cal.run().block_for_results()
data_fine.figure(0)
print(data_fine.analysis_results("d_theta"))
```
The cell below shows how the amplitude is updated based on the error in the rotation angle measured by the `FineXAmplitude` experiment. Note that this calculation is automatically done by the `Amplitude.update` function.
```
dtheta = data_fine.analysis_results("d_theta").value.value
target_angle = np.pi
scale = target_angle / (target_angle + dtheta)
pulse_amp = cals.get_parameter_value("amp", qubit, "x")
print(f"The ideal angle is {target_angle:.2f} rad. We measured a deviation of {dtheta:.3f} rad.")
print(f"Thus, scale the {pulse_amp:.4f} pulse amplitude by {scale:.3f} to obtain {pulse_amp*scale:.5f}.")
```
Observe, once again, that the calibrations have automatically been updated.
```
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="amp"))
```
To check that we have managed to reduce the error in the rotation angle we will run the fine amplitude calibration experiment once again.
```
data_fine2 = amp_x_cal.run().block_for_results()
data_fine2.figure(0)
```
As can be seen from the data above and the analysis result below we have managed to reduce the error in the rotation angle ${\rm d}\theta$.
```
print(data_fine2.analysis_results("d_theta"))
```
### Fine amplitude calibration of the $\pi/2$ rotation
We now wish to calibrate the amplitude of the $\pi/2$ rotation.
```
from qiskit_experiments.library.calibration.fine_amplitude import FineSXAmplitudeCal
amp_sx_cal = FineSXAmplitudeCal(qubit, cals, backend=backend, schedule_name="sx")
amp_sx_cal.circuits()[5].draw(output="mpl")
data_fine_sx = amp_sx_cal.run().block_for_results()
data_fine_sx.figure(0)
print(data_fine_sx.analysis_results(0))
print(data_fine_sx.analysis_results("d_theta"))
```
The parameter value is reflected in the calibrations.
```
pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="amp"))
cals.get_schedule("sx", qubit)
cals.get_schedule("x", qubit)
cals.get_schedule("y", qubit)
import qiskit.tools.jupyter
%qiskit_copyright
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.